| 1 | pub struct List[T] { |
| 2 | pub mut: |
| 3 | head &ListNode[T] = unsafe { nil } |
| 4 | } |
| 5 | |
| 6 | pub struct ListNode[T] { |
| 7 | pub mut: |
| 8 | value T |
| 9 | next &ListNode[T] = unsafe { nil } |
| 10 | } |
| 11 | |
| 12 | pub fn list_new[T]() List[T] { |
| 13 | return List[T]{} |
| 14 | } |
| 15 | |
| 16 | pub fn (mut l List[T]) add(value T) { |
| 17 | mut node := &ListNode[T]{value, unsafe { nil }} |
| 18 | if unsafe { l.head == nil } { |
| 19 | l.head = node |
| 20 | } else { |
| 21 | node.next = l.head |
| 22 | l.head = node |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | fn test_generic_assign_reference_generic_struct() { |
| 27 | mut list1 := list_new[string]() |
| 28 | list1.add('hello') |
| 29 | println(list1.head.value) |
| 30 | assert list1.head.value == 'hello' |
| 31 | |
| 32 | mut list2 := list_new[int]() |
| 33 | list2.add(100) |
| 34 | println(list2.head.value) |
| 35 | assert list2.head.value == 100 |
| 36 | |
| 37 | mut list3 := list_new[f64]() |
| 38 | list3.add(22.2) |
| 39 | println(list3.head.value) |
| 40 | assert list3.head.value == 22.2 |
| 41 | |
| 42 | mut list4 := list_new[bool]() |
| 43 | list4.add(true) |
| 44 | println(list4.head.value) |
| 45 | assert list4.head.value == true |
| 46 | } |
| 47 | |