github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/tests/copy_test.go (about) 1 package tests 2 3 import ( 4 "reflect" 5 "testing" 6 ) 7 8 type S struct { 9 x int 10 } 11 12 func (a S) test(b S) { 13 a.x = 0 14 b.x = 0 15 } 16 17 type A [1]int 18 19 func (a A) test(b A) { 20 a[0] = 0 21 b[0] = 0 22 } 23 24 func TestCopyOnCall(t *testing.T) { 25 { 26 a := S{1} 27 b := S{2} 28 29 a.test(b) 30 func() { 31 defer a.test(b) 32 }() 33 34 if a.x != 1 { 35 t.Error("a.x != 1") 36 } 37 if b.x != 2 { 38 t.Error("b.x != 2") 39 } 40 } 41 { 42 a := A{1} 43 b := A{2} 44 45 a.test(b) 46 func() { 47 defer a.test(b) 48 }() 49 50 if a[0] != 1 { 51 t.Error("a[0] != 1") 52 } 53 if b[0] != 2 { 54 t.Error("b[0] != 2") 55 } 56 } 57 } 58 59 func TestSwap(t *testing.T) { 60 { 61 a := S{1} 62 b := S{2} 63 a, b = b, a 64 if a.x != 2 || b.x != 1 { 65 t.Fail() 66 } 67 } 68 { 69 a := A{1} 70 b := A{2} 71 a, b = b, a 72 if a[0] != 2 || b[0] != 1 { 73 t.Fail() 74 } 75 } 76 } 77 78 func TestComposite(t *testing.T) { 79 { 80 a := S{1} 81 s := []S{a} 82 s[0].x = 0 83 if a.x != 1 { 84 t.Fail() 85 } 86 } 87 { 88 a := A{1} 89 s := []A{a} 90 s[0][0] = 0 91 if a[0] != 1 { 92 t.Fail() 93 } 94 } 95 } 96 97 func TestAppend(t *testing.T) { 98 { 99 s := append(make([]S, 3), S{}) // cap(s) == 6 100 s = s[:6] 101 if s[5].x != 0 { 102 t.Fail() 103 } 104 } 105 106 { 107 a := S{1} 108 b := []S{{2}} 109 s := append([]S{}, b...) 110 s[0].x = 0 111 if a.x != 1 || b[0].x != 2 { 112 t.Fail() 113 } 114 } 115 } 116 117 type I interface { 118 M() int 119 } 120 121 type T S 122 123 func (t T) M() int { 124 return t.x 125 } 126 127 func TestExplicitConversion(t *testing.T) { 128 coolGuy := S{x: 42} 129 var i I 130 i = T(coolGuy) 131 if i.M() != 42 { 132 t.Fail() 133 } 134 } 135 136 func TestCopyStructByReflect(t *testing.T) { 137 // https://github.com/gopherjs/gopherjs/issues/1156 138 type Info struct { 139 name string 140 } 141 a := []Info{{"A"}, {"B"}, {"C"}} 142 v := reflect.ValueOf(a) 143 i := v.Index(0).Interface() 144 a[0] = Info{"X"} 145 if got := i.(Info).name; got != "A" { 146 t.Fatalf(`bad copy struct got %q, want "A"`, got) 147 } 148 }