|
| 1 | +package main |
| 2 | + |
| 3 | +// Regression test for https://github.com/goplus/llgo/issues/1608 |
| 4 | +// and https://github.com/goplus/llgo/issues/1604 |
| 5 | +// |
| 6 | +// When returning a slice that was read from a struct field, |
| 7 | +// and the field is modified before return, the original value |
| 8 | +// should be returned, not the modified value. |
| 9 | + |
| 10 | +type T struct { |
| 11 | + data []int |
| 12 | +} |
| 13 | + |
| 14 | +// Single return value - was buggy before fix |
| 15 | +func a() []int { |
| 16 | + var t = T{data: []int{1, 2}} |
| 17 | + a := t.data |
| 18 | + t.data = []int{1, 2, 3} |
| 19 | + return a |
| 20 | +} |
| 21 | + |
| 22 | +// Multiple return values - always worked |
| 23 | +func b() ([]int, bool) { |
| 24 | + var t = T{data: []int{1, 2}} |
| 25 | + a := t.data |
| 26 | + t.data = []int{1, 2, 3} |
| 27 | + return a, true |
| 28 | +} |
| 29 | + |
| 30 | +func main() { |
| 31 | + // Test single return value |
| 32 | + resultA := a() |
| 33 | + if len(resultA) != 2 { |
| 34 | + panic("a(): expected len=2, got " + itoa(len(resultA))) |
| 35 | + } |
| 36 | + if resultA[0] != 1 { |
| 37 | + panic("a(): expected [0]=1, got " + itoa(resultA[0])) |
| 38 | + } |
| 39 | + if resultA[1] != 2 { |
| 40 | + panic("a(): expected [1]=2, got " + itoa(resultA[1])) |
| 41 | + } |
| 42 | + println("a() passed: len=2, elements=[1, 2]") |
| 43 | + |
| 44 | + // Test multiple return values |
| 45 | + resultB, ok := b() |
| 46 | + if !ok { |
| 47 | + panic("b(): expected ok=true") |
| 48 | + } |
| 49 | + if len(resultB) != 2 { |
| 50 | + panic("b(): expected len=2, got " + itoa(len(resultB))) |
| 51 | + } |
| 52 | + if resultB[0] != 1 { |
| 53 | + panic("b(): expected [0]=1, got " + itoa(resultB[0])) |
| 54 | + } |
| 55 | + if resultB[1] != 2 { |
| 56 | + panic("b(): expected [1]=2, got " + itoa(resultB[1])) |
| 57 | + } |
| 58 | + println("b() passed: len=2, elements=[1, 2]") |
| 59 | + |
| 60 | + println("\n✅ All tests passed!") |
| 61 | +} |
| 62 | + |
| 63 | +func itoa(n int) string { |
| 64 | + if n == 0 { |
| 65 | + return "0" |
| 66 | + } |
| 67 | + if n < 0 { |
| 68 | + return "-" + itoa(-n) |
| 69 | + } |
| 70 | + var buf [20]byte |
| 71 | + i := len(buf) |
| 72 | + for n > 0 { |
| 73 | + i-- |
| 74 | + buf[i] = byte('0' + n%10) |
| 75 | + n /= 10 |
| 76 | + } |
| 77 | + return string(buf[i:]) |
| 78 | +} |
0 commit comments