| 1 | struct Bar { |
| 2 | value int |
| 3 | } |
| 4 | |
| 5 | struct Foo1 { |
| 6 | mut: |
| 7 | name &string |
| 8 | } |
| 9 | |
| 10 | struct Foo2 { |
| 11 | mut: |
| 12 | name ?&string |
| 13 | } |
| 14 | |
| 15 | struct Foo3 { |
| 16 | mut: |
| 17 | bar &Bar |
| 18 | } |
| 19 | |
| 20 | fn main() { |
| 21 | // Basic test of assigning nil to a string pointer |
| 22 | mut str := 'hi!' |
| 23 | mut str_ptr := &str |
| 24 | unsafe { |
| 25 | str_ptr = nil |
| 26 | } |
| 27 | println(str_ptr) // should print '&nil' |
| 28 | assert str_ptr == unsafe { nil } |
| 29 | |
| 30 | // Test initializing a pointer field with nil |
| 31 | f1 := Foo1{ |
| 32 | name: unsafe { nil } |
| 33 | } |
| 34 | assert f1.name == unsafe { nil } |
| 35 | |
| 36 | // Test assigning nil to an optional pointer field |
| 37 | mut f2 := Foo2{} |
| 38 | unsafe { |
| 39 | f2.name = nil |
| 40 | } |
| 41 | if f2.name != none { |
| 42 | assert f2.name == unsafe { nil } |
| 43 | } else { |
| 44 | assert false |
| 45 | } |
| 46 | |
| 47 | // Test assigning a non-nil pointer to an optional pointer field after init |
| 48 | mut f2_non_nil := Foo2{} |
| 49 | boo := 'boo!' |
| 50 | f2_non_nil.name = &boo |
| 51 | assert f2_non_nil.name != none |
| 52 | |
| 53 | // Test assigning nil to a struct pointer |
| 54 | mut f3 := &Foo2{} |
| 55 | unsafe { |
| 56 | f3 = nil |
| 57 | } |
| 58 | assert f3 == unsafe { nil } |
| 59 | |
| 60 | // Test with custom struct fields |
| 61 | mut f4 := Foo3{ |
| 62 | bar: &Bar{42} |
| 63 | } |
| 64 | unsafe { |
| 65 | f4.bar = nil |
| 66 | } |
| 67 | assert f4.bar == unsafe { nil } |
| 68 | |
| 69 | // Test with nil pointers in arrays |
| 70 | mut ptrs := []&string{len: 3, init: unsafe { nil }} |
| 71 | p0, p1 := 'hello', 'world' |
| 72 | ptrs[0] = &p0 |
| 73 | ptrs[1] = &p1 |
| 74 | unsafe { |
| 75 | ptrs[2] = nil |
| 76 | } |
| 77 | assert ptrs[0] != unsafe { nil } |
| 78 | assert ptrs[1] != unsafe { nil } |
| 79 | assert ptrs[2] == unsafe { nil } |
| 80 | } |
| 81 | |