-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
struct ArrayList[T] { | ||
mut: | ||
size usize | ||
items []&T | ||
} | ||
|
||
fn new_array_list[T]() ArrayList[T] { | ||
return ArrayList[T]{} | ||
} | ||
|
||
fn (li ArrayList[T]) is_empty() bool { | ||
return li.size == 0 | ||
} | ||
|
||
fn (mut li ArrayList[T]) add(item &T) { | ||
li.items << item | ||
li.size += 1 | ||
} | ||
|
||
fn (mut li ArrayList[T]) pop() ?&T { | ||
if li.is_empty() { | ||
return none | ||
} else { | ||
item := li.items.last() | ||
li.items.delete_last() | ||
li.size -= 1 | ||
return item | ||
} | ||
} | ||
|
||
struct Student { | ||
name string | ||
mut: | ||
age u8 | ||
} | ||
|
||
fn (mut s Student) grow() { | ||
s.age += 1 | ||
} | ||
|
||
fn test_main() { | ||
mut list := new_array_list[Student]() | ||
assert list.is_empty() && list.size == 0 | ||
|
||
mut stu := Student{'Tom', 16} | ||
list.add(&stu) | ||
assert !list.is_empty() && list.size == 1 | ||
stu.grow() | ||
assert stu.age == 17 | ||
|
||
tom := list.pop()? | ||
assert list.is_empty() && list.size == 0 | ||
assert tom == stu | ||
assert tom.age == 17 | ||
} |