1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
19 "reflect/internal/example1"
20 "reflect/internal/example2"
34 func TestBool(t *testing.T) {
37 t.Fatal("ValueOf(true).Bool() = false")
54 func assert(t *testing.T, s, want string) {
56 t.Errorf("have %#q want %#q", s, want)
60 var typeTests = []pair{
61 {struct{ x int }{}, "int"},
62 {struct{ x int8 }{}, "int8"},
63 {struct{ x int16 }{}, "int16"},
64 {struct{ x int32 }{}, "int32"},
65 {struct{ x int64 }{}, "int64"},
66 {struct{ x uint }{}, "uint"},
67 {struct{ x uint8 }{}, "uint8"},
68 {struct{ x uint16 }{}, "uint16"},
69 {struct{ x uint32 }{}, "uint32"},
70 {struct{ x uint64 }{}, "uint64"},
71 {struct{ x float32 }{}, "float32"},
72 {struct{ x float64 }{}, "float64"},
73 {struct{ x int8 }{}, "int8"},
74 {struct{ x (**int8) }{}, "**int8"},
75 {struct{ x (**integer) }{}, "**reflect_test.integer"},
76 {struct{ x ([32]int32) }{}, "[32]int32"},
77 {struct{ x ([]int8) }{}, "[]int8"},
78 {struct{ x (map[string]int32) }{}, "map[string]int32"},
79 {struct{ x (chan<- string) }{}, "chan<- string"},
80 {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
81 {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
82 {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
83 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
90 "struct { c chan *int32; d float32 }",
92 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
95 c func(chan *integer, *int8)
98 "struct { c func(chan *reflect_test.integer, *int8) }",
106 "struct { a int8; b int32 }",
115 "struct { a int8; b int8; c int32 }",
125 "struct { a int8; b int8; c int8; d int32 }",
136 "struct { a int8; b int8; c int8; d int8; e int32 }",
148 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
152 a int8 `reflect:"hi there"`
155 `struct { a int8 "reflect:\"hi there\"" }`,
159 a int8 `reflect:"hi \x00there\t\n\"\\"`
162 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
169 "struct { f func(...int) }",
173 a(func(func(int) int) func(func(int)) int)
177 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
185 "struct { int32; int64 }",
189 var valueTests = []pair{
200 {new(float32), "256.25"},
201 {new(float64), "512.125"},
202 {new(complex64), "532.125+10i"},
203 {new(complex128), "564.25+1i"},
204 {new(string), "stringy cheese"},
206 {new(*int8), "*int8(0)"},
207 {new(**int8), "**int8(0)"},
208 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
209 {new(**integer), "**reflect_test.integer(0)"},
210 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
211 {new(chan<- string), "chan<- string"},
212 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
217 "struct { c chan *int32; d float32 }{chan *int32, 0}",
219 {new(struct{ c func(chan *integer, *int8) }),
220 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
226 "struct { a int8; b int32 }{0, 0}",
233 "struct { a int8; b int8; c int32 }{0, 0, 0}",
237 func testType(t *testing.T, i int, typ Type, want string) {
240 t.Errorf("#%d: have %#q, want %#q", i, s, want)
244 func TestTypes(t *testing.T) {
245 for i, tt := range typeTests {
246 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
250 func TestSet(t *testing.T) {
251 for i, tt := range valueTests {
280 v.SetComplex(532.125 + 10i)
282 v.SetComplex(564.25 + 1i)
284 v.SetString("stringy cheese")
288 s := valueToString(v)
290 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
295 func TestSetValue(t *testing.T) {
296 for i, tt := range valueTests {
297 v := ValueOf(tt.i).Elem()
300 v.Set(ValueOf(int(132)))
302 v.Set(ValueOf(int8(8)))
304 v.Set(ValueOf(int16(16)))
306 v.Set(ValueOf(int32(32)))
308 v.Set(ValueOf(int64(64)))
310 v.Set(ValueOf(uint(132)))
312 v.Set(ValueOf(uint8(8)))
314 v.Set(ValueOf(uint16(16)))
316 v.Set(ValueOf(uint32(32)))
318 v.Set(ValueOf(uint64(64)))
320 v.Set(ValueOf(float32(256.25)))
322 v.Set(ValueOf(512.125))
324 v.Set(ValueOf(complex64(532.125 + 10i)))
326 v.Set(ValueOf(complex128(564.25 + 1i)))
328 v.Set(ValueOf("stringy cheese"))
332 s := valueToString(v)
334 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
339 func TestMapIterSet(t *testing.T) {
340 m := make(map[string]interface{}, len(valueTests))
341 for _, tt := range valueTests {
346 k := New(v.Type().Key()).Elem()
347 e := New(v.Type().Elem()).Elem()
353 want := m[k.String()]
356 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
358 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
359 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
361 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
362 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
366 got := int(testing.AllocsPerRun(10, func() {
373 // Making a *MapIter allocates. This should be the only allocation.
375 t.Errorf("wanted 1 alloc, got %d", got)
379 func TestCanIntUintFloatComplex(t *testing.T) {
383 type complex complex128
385 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
387 var testCases = []struct {
392 {132, [...]bool{true, false, false, false}},
393 {int8(8), [...]bool{true, false, false, false}},
394 {int16(16), [...]bool{true, false, false, false}},
395 {int32(32), [...]bool{true, false, false, false}},
396 {int64(64), [...]bool{true, false, false, false}},
398 {uint(132), [...]bool{false, true, false, false}},
399 {uint8(8), [...]bool{false, true, false, false}},
400 {uint16(16), [...]bool{false, true, false, false}},
401 {uint32(32), [...]bool{false, true, false, false}},
402 {uint64(64), [...]bool{false, true, false, false}},
403 {uintptr(0xABCD), [...]bool{false, true, false, false}},
405 {float32(256.25), [...]bool{false, false, true, false}},
406 {float64(512.125), [...]bool{false, false, true, false}},
408 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
409 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
411 {integer(-132), [...]bool{true, false, false, false}},
412 {uinteger(132), [...]bool{false, true, false, false}},
413 {float(256.25), [...]bool{false, false, true, false}},
414 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
416 {"hello world", [...]bool{false, false, false, false}},
417 {new(int), [...]bool{false, false, false, false}},
418 {new(uint), [...]bool{false, false, false, false}},
419 {new(float64), [...]bool{false, false, false, false}},
420 {new(complex64), [...]bool{false, false, false, false}},
421 {new([5]int), [...]bool{false, false, false, false}},
422 {new(integer), [...]bool{false, false, false, false}},
423 {new(map[int]int), [...]bool{false, false, false, false}},
424 {new(chan<- int), [...]bool{false, false, false, false}},
425 {new(func(a int8)), [...]bool{false, false, false, false}},
426 {new(struct{ i int }), [...]bool{false, false, false, false}},
429 for i, tc := range testCases {
431 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
433 for j := range tc.want {
434 if got[j] != tc.want[j] {
436 "#%d: v.%s() returned %t for type %T, want %t",
448 func TestCanSetField(t *testing.T) {
449 type embed struct{ x, X int }
450 type Embed struct{ x, X int }
468 type testCase struct {
469 // -1 means Addr().Elem() of current value
480 {[]int{0, -1}, false},
481 {[]int{0, 0}, false},
482 {[]int{0, 0, -1}, false},
483 {[]int{0, -1, 0}, false},
484 {[]int{0, -1, 0, -1}, false},
486 {[]int{0, 1, -1}, true},
487 {[]int{0, -1, 1}, true},
488 {[]int{0, -1, 1, -1}, true},
490 {[]int{1, -1}, false},
492 {[]int{2, -1}, true},
495 val: ValueOf(&S2{embed: &embed{}}),
498 {[]int{0, -1}, false},
499 {[]int{0, 0}, false},
500 {[]int{0, 0, -1}, false},
501 {[]int{0, -1, 0}, false},
502 {[]int{0, -1, 0, -1}, false},
504 {[]int{0, 1, -1}, true},
505 {[]int{0, -1, 1}, true},
506 {[]int{0, -1, 1, -1}, true},
514 {[]int{0, -1}, true},
515 {[]int{0, 0}, false},
516 {[]int{0, 0, -1}, false},
517 {[]int{0, -1, 0}, false},
518 {[]int{0, -1, 0, -1}, false},
520 {[]int{0, 1, -1}, true},
521 {[]int{0, -1, 1}, true},
522 {[]int{0, -1, 1, -1}, true},
527 val: ValueOf(&S4{Embed: &Embed{}}),
530 {[]int{0, -1}, true},
531 {[]int{0, 0}, false},
532 {[]int{0, 0, -1}, false},
533 {[]int{0, -1, 0}, false},
534 {[]int{0, -1, 0, -1}, false},
536 {[]int{0, 1, -1}, true},
537 {[]int{0, -1, 1}, true},
538 {[]int{0, -1, 1, -1}, true},
544 for _, tt := range tests {
545 t.Run(tt.val.Type().Name(), func(t *testing.T) {
546 for _, tc := range tt.cases {
548 for _, i := range tc.index {
558 if got := f.CanSet(); got != tc.canSet {
559 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
568 var valueToStringTests = []pair{
573 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
574 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
575 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
576 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
577 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
578 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
581 func TestValueToString(t *testing.T) {
582 for i, test := range valueToStringTests {
583 s := valueToString(ValueOf(test.i))
585 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
590 func TestArrayElemSet(t *testing.T) {
591 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
592 v.Index(4).SetInt(123)
593 s := valueToString(v)
594 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
596 t.Errorf("[10]int: have %#q want %#q", s, want)
599 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
600 v.Index(4).SetInt(123)
602 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
604 t.Errorf("[]int: have %#q want %#q", s, want1)
608 func TestPtrPointTo(t *testing.T) {
612 vi := ValueOf(&i).Elem()
613 vip.Elem().Set(vi.Addr())
615 t.Errorf("got %d, want 1234", *ip)
619 vp := ValueOf(&ip).Elem()
620 vp.Set(Zero(vp.Type()))
622 t.Errorf("got non-nil (%p), want nil", ip)
626 func TestPtrSetNil(t *testing.T) {
630 vip.Elem().Set(Zero(vip.Elem().Type()))
632 t.Errorf("got non-nil (%d), want nil", *ip)
636 func TestMapSetNil(t *testing.T) {
637 m := make(map[string]int)
639 vm.Elem().Set(Zero(vm.Elem().Type()))
641 t.Errorf("got non-nil (%p), want nil", m)
645 func TestAll(t *testing.T) {
646 testType(t, 1, TypeOf((int8)(0)), "int8")
647 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
649 typ := TypeOf((*struct {
653 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
655 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
658 testType(t, 5, f.Type, "chan *int32")
660 f, present := styp.FieldByName("d")
662 t.Errorf("FieldByName says present field is absent")
664 testType(t, 6, f.Type, "float32")
666 f, present = styp.FieldByName("absent")
668 t.Errorf("FieldByName says absent field is present")
671 typ = TypeOf([32]int32{})
672 testType(t, 7, typ, "[32]int32")
673 testType(t, 8, typ.Elem(), "int32")
675 typ = TypeOf((map[string]*int32)(nil))
676 testType(t, 9, typ, "map[string]*int32")
678 testType(t, 10, mtyp.Key(), "string")
679 testType(t, 11, mtyp.Elem(), "*int32")
681 typ = TypeOf((chan<- string)(nil))
682 testType(t, 12, typ, "chan<- string")
683 testType(t, 13, typ.Elem(), "string")
685 // make sure tag strings are not part of element type
686 typ = TypeOf(struct {
687 d []uint32 `reflect:"TAG"`
689 testType(t, 14, typ, "[]uint32")
692 func TestInterfaceGet(t *testing.T) {
697 v1 := ValueOf(&inter)
698 v2 := v1.Elem().Field(0)
699 assert(t, v2.Type().String(), "interface {}")
702 assert(t, v3.Type().String(), "float64")
705 func TestInterfaceValue(t *testing.T) {
710 v1 := ValueOf(&inter)
711 v2 := v1.Elem().Field(0)
712 assert(t, v2.Type().String(), "interface {}")
714 assert(t, v3.Type().String(), "float64")
717 if _, ok := i3.(float64); !ok {
718 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
722 func TestFunctionValue(t *testing.T) {
723 var x interface{} = func() {}
725 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
726 t.Fatalf("TestFunction returned wrong pointer")
728 assert(t, v.Type().String(), "func()")
731 var appendTests = []struct {
734 {make([]int, 2, 4), []int{22}},
735 {make([]int, 2, 4), []int{22, 33, 44}},
738 func sameInts(x, y []int) bool {
739 if len(x) != len(y) {
742 for i, xx := range x {
750 func TestAppend(t *testing.T) {
751 for i, test := range appendTests {
752 origLen, extraLen := len(test.orig), len(test.extra)
753 want := append(test.orig, test.extra...)
754 // Convert extra from []int to []Value.
755 e0 := make([]Value, len(test.extra))
756 for j, e := range test.extra {
759 // Convert extra from []int to *SliceValue.
760 e1 := ValueOf(test.extra)
762 a0 := ValueOf(test.orig)
763 have0 := Append(a0, e0...).Interface().([]int)
764 if !sameInts(have0, want) {
765 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
767 // Check that the orig and extra slices were not modified.
768 if len(test.orig) != origLen {
769 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
771 if len(test.extra) != extraLen {
772 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
775 a1 := ValueOf(test.orig)
776 have1 := AppendSlice(a1, e1).Interface().([]int)
777 if !sameInts(have1, want) {
778 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
780 // Check that the orig and extra slices were not modified.
781 if len(test.orig) != origLen {
782 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
784 if len(test.extra) != extraLen {
785 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
790 func TestCopy(t *testing.T) {
791 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
792 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
793 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
794 for i := 0; i < len(b); i++ {
796 t.Fatalf("b != c before test")
801 aa := ValueOf(&a1).Elem()
802 ab := ValueOf(&b1).Elem()
803 for tocopy := 1; tocopy <= 7; tocopy++ {
807 for i := 0; i < tocopy; i++ {
809 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
810 tocopy, i, a[i], i, b[i])
813 for i := tocopy; i < len(b); i++ {
816 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
817 tocopy, i, a[i], i, b[i], i, c[i])
819 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
820 tocopy, i, b[i], i, c[i])
823 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
829 func TestCopyString(t *testing.T) {
830 t.Run("Slice", func(t *testing.T) {
831 s := bytes.Repeat([]byte{'_'}, 8)
834 n := Copy(val, ValueOf(""))
835 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
836 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
839 n = Copy(val, ValueOf("hello"))
840 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
841 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
844 n = Copy(val, ValueOf("helloworld"))
845 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
846 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
849 t.Run("Array", func(t *testing.T) {
850 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
851 val := ValueOf(&s).Elem()
853 n := Copy(val, ValueOf(""))
854 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
855 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
858 n = Copy(val, ValueOf("hello"))
859 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
860 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
863 n = Copy(val, ValueOf("helloworld"))
864 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
865 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
870 func TestCopyArray(t *testing.T) {
871 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
872 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
874 aa := ValueOf(&a).Elem()
875 ab := ValueOf(&b).Elem()
877 for i := 0; i < len(a); i++ {
879 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
882 for i := len(a); i < len(b); i++ {
884 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
886 t.Logf("elem %d is okay\n", i)
891 func TestBigUnnamedStruct(t *testing.T) {
892 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
894 b1 := v.Interface().(struct {
897 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
898 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
906 func TestBigStruct(t *testing.T) {
907 b := big{1, 2, 3, 4, 5}
909 b1 := v.Interface().(big)
910 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
911 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
922 type DeepEqualTest struct {
927 // Simple functions for DeepEqual tests.
931 fn3 = func() { fn1() } // Not nil.
937 type Loopy interface{}
939 var loop1, loop2 Loop
940 var loopy1, loopy2 Loopy
941 var cycleMap1, cycleMap2, cycleMap3 map[string]interface{}
943 type structWithSelfPtr struct {
955 cycleMap1 = map[string]interface{}{}
956 cycleMap1["cycle"] = cycleMap1
957 cycleMap2 = map[string]interface{}{}
958 cycleMap2["cycle"] = cycleMap2
959 cycleMap3 = map[string]interface{}{}
960 cycleMap3["different"] = cycleMap3
963 var deepEqualTests = []DeepEqualTest{
967 {int32(1), int32(1), true},
969 {float32(0.5), float32(0.5), true},
970 {"hello", "hello", true},
971 {make([]int, 10), make([]int, 10), true},
972 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
973 {Basic{1, 0.5}, Basic{1, 0.5}, true},
974 {error(nil), error(nil), true},
975 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
977 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
978 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
979 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
983 {int32(1), int32(2), false},
985 {float32(0.5), float32(0.6), false},
986 {"hello", "hey", false},
987 {make([]int, 10), make([]int, 11), false},
988 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
989 {Basic{1, 0.5}, Basic{1, 0.6}, false},
990 {Basic{1, 0}, Basic{2, 0}, false},
991 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
992 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
993 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
994 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
999 {[][]int{{1}}, [][]int{{2}}, false},
1000 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1002 // Fun with floating point.
1003 {math.NaN(), math.NaN(), false},
1004 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1005 {&[1]float64{math.NaN()}, self{}, true},
1006 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1007 {[]float64{math.NaN()}, self{}, true},
1008 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1009 {map[float64]float64{math.NaN(): 1}, self{}, true},
1011 // Nil vs empty: not the same.
1012 {[]int{}, []int(nil), false},
1013 {[]int{}, []int{}, true},
1014 {[]int(nil), []int(nil), true},
1015 {map[int]int{}, map[int]int(nil), false},
1016 {map[int]int{}, map[int]int{}, true},
1017 {map[int]int(nil), map[int]int(nil), true},
1021 {int32(1), int64(1), false},
1022 {0.5, "hello", false},
1023 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1024 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
1025 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1026 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1027 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1028 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1029 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1032 {&loop1, &loop1, true},
1033 {&loop1, &loop2, true},
1034 {&loopy1, &loopy1, true},
1035 {&loopy1, &loopy2, true},
1036 {&cycleMap1, &cycleMap2, true},
1037 {&cycleMap1, &cycleMap3, false},
1040 func TestDeepEqual(t *testing.T) {
1041 for _, test := range deepEqualTests {
1042 if test.b == (self{}) {
1045 if r := DeepEqual(test.a, test.b); r != test.eq {
1046 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1051 func TestTypeOf(t *testing.T) {
1052 // Special case for nil
1053 if typ := TypeOf(nil); typ != nil {
1054 t.Errorf("expected nil type for nil value; got %v", typ)
1056 for _, test := range deepEqualTests {
1057 v := ValueOf(test.a)
1061 typ := TypeOf(test.a)
1062 if typ != v.Type() {
1063 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1068 type Recursive struct {
1073 func TestDeepEqualRecursiveStruct(t *testing.T) {
1074 a, b := new(Recursive), new(Recursive)
1075 *a = Recursive{12, a}
1076 *b = Recursive{12, b}
1077 if !DeepEqual(a, b) {
1078 t.Error("DeepEqual(recursive same) = false, want true")
1082 type _Complex struct {
1086 d map[float64]float64
1089 func TestDeepEqualComplexStruct(t *testing.T) {
1090 m := make(map[float64]float64)
1091 stra, strb := "hello", "hello"
1092 a, b := new(_Complex), new(_Complex)
1093 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1094 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1095 if !DeepEqual(a, b) {
1096 t.Error("DeepEqual(complex same) = false, want true")
1100 func TestDeepEqualComplexStructInequality(t *testing.T) {
1101 m := make(map[float64]float64)
1102 stra, strb := "hello", "helloo" // Difference is here
1103 a, b := new(_Complex), new(_Complex)
1104 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1105 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1106 if DeepEqual(a, b) {
1107 t.Error("DeepEqual(complex different) = true, want false")
1111 type UnexpT struct {
1115 func TestDeepEqualUnexportedMap(t *testing.T) {
1116 // Check that DeepEqual can look at unexported fields.
1117 x1 := UnexpT{map[int]int{1: 2}}
1118 x2 := UnexpT{map[int]int{1: 2}}
1119 if !DeepEqual(&x1, &x2) {
1120 t.Error("DeepEqual(x1, x2) = false, want true")
1123 y1 := UnexpT{map[int]int{2: 3}}
1124 if DeepEqual(&x1, &y1) {
1125 t.Error("DeepEqual(x1, y1) = true, want false")
1129 var deepEqualPerfTests = []struct {
1132 {x: int8(99), y: int8(99)},
1133 {x: []int8{99}, y: []int8{99}},
1134 {x: int16(99), y: int16(99)},
1135 {x: []int16{99}, y: []int16{99}},
1136 {x: int32(99), y: int32(99)},
1137 {x: []int32{99}, y: []int32{99}},
1138 {x: int64(99), y: int64(99)},
1139 {x: []int64{99}, y: []int64{99}},
1140 {x: int(999999), y: int(999999)},
1141 {x: []int{999999}, y: []int{999999}},
1143 {x: uint8(99), y: uint8(99)},
1144 {x: []uint8{99}, y: []uint8{99}},
1145 {x: uint16(99), y: uint16(99)},
1146 {x: []uint16{99}, y: []uint16{99}},
1147 {x: uint32(99), y: uint32(99)},
1148 {x: []uint32{99}, y: []uint32{99}},
1149 {x: uint64(99), y: uint64(99)},
1150 {x: []uint64{99}, y: []uint64{99}},
1151 {x: uint(999999), y: uint(999999)},
1152 {x: []uint{999999}, y: []uint{999999}},
1153 {x: uintptr(999999), y: uintptr(999999)},
1154 {x: []uintptr{999999}, y: []uintptr{999999}},
1156 {x: float32(1.414), y: float32(1.414)},
1157 {x: []float32{1.414}, y: []float32{1.414}},
1158 {x: float64(1.414), y: float64(1.414)},
1159 {x: []float64{1.414}, y: []float64{1.414}},
1161 {x: complex64(1.414), y: complex64(1.414)},
1162 {x: []complex64{1.414}, y: []complex64{1.414}},
1163 {x: complex128(1.414), y: complex128(1.414)},
1164 {x: []complex128{1.414}, y: []complex128{1.414}},
1167 {x: []bool{true}, y: []bool{true}},
1169 {x: "abcdef", y: "abcdef"},
1170 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1172 {x: []byte("abcdef"), y: []byte("abcdef")},
1173 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1175 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1176 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1179 func TestDeepEqualAllocs(t *testing.T) {
1180 for _, tt := range deepEqualPerfTests {
1181 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1182 got := testing.AllocsPerRun(100, func() {
1183 if !DeepEqual(tt.x, tt.y) {
1184 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1188 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1194 func BenchmarkDeepEqual(b *testing.B) {
1195 for _, bb := range deepEqualPerfTests {
1196 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1198 for i := 0; i < b.N; i++ {
1199 sink = DeepEqual(bb.x, bb.y)
1205 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
1207 f := s.Type().Field(1)
1208 if f.Offset != offs {
1209 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1213 // Check that structure alignment & offsets viewed through reflect agree with those
1214 // from the compiler itself.
1215 func TestAlignment(t *testing.T) {
1216 type T1inner struct {
1223 type T2inner struct {
1231 x := T1{T1inner{2}, 17}
1232 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1234 x1 := T2{T2inner{2, 3}, 17}
1235 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1238 func Nil(a interface{}, t *testing.T) {
1239 n := ValueOf(a).Field(0)
1241 t.Errorf("%v should be nil", a)
1245 func NotNil(a interface{}, t *testing.T) {
1246 n := ValueOf(a).Field(0)
1248 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1252 func TestIsNil(t *testing.T) {
1253 // These implement IsNil.
1254 // Wrap in extra struct to hide interface type.
1255 doNil := []interface{}{
1257 struct{ x interface{} }{},
1258 struct{ x map[string]int }{},
1259 struct{ x func() bool }{},
1260 struct{ x chan int }{},
1261 struct{ x []string }{},
1262 struct{ x unsafe.Pointer }{},
1264 for _, ts := range doNil {
1265 ty := TypeOf(ts).Field(0).Type
1267 v.IsNil() // panics if not okay to call
1270 // Check the implementations
1282 si.x = make([]int, 10)
1289 ci.x = make(chan int)
1296 mi.x = make(map[int]int)
1307 x func(t *testing.T)
1314 func TestIsZero(t *testing.T) {
1315 for i, tt := range []struct {
1344 {float32(1.2), false},
1346 {float64(1.2), false},
1347 {math.Copysign(0, -1), false},
1348 {complex64(0), true},
1349 {complex64(1.2), false},
1350 {complex128(0), true},
1351 {complex128(1.2), false},
1352 {complex(math.Copysign(0, -1), 0), false},
1353 {complex(0, math.Copysign(0, -1)), false},
1354 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1356 {uintptr(128), false},
1358 {Zero(TypeOf([5]string{})).Interface(), true},
1359 {[5]string{"", "", "", "", ""}, true},
1360 {[5]string{}, true},
1361 {[5]string{"", "", "", "a", ""}, false},
1363 {(chan string)(nil), true},
1364 {make(chan string), false},
1365 {time.After(1), false},
1367 {(func())(nil), true},
1370 {New(TypeOf(new(error)).Elem()).Elem(), true},
1371 {(io.Reader)(strings.NewReader("")), false},
1373 {(map[string]string)(nil), true},
1374 {map[string]string{}, false},
1375 {make(map[string]string), false},
1377 {(*func())(nil), true},
1378 {(*int)(nil), true},
1381 {[]string{}, false},
1382 {([]string)(nil), true},
1383 {make([]string, 0), false},
1386 {"not-zero", false},
1389 {T{123, 456.75, "hello", &_i}, false},
1391 {(unsafe.Pointer)(nil), true},
1392 {(unsafe.Pointer)(new(int)), false},
1395 if v, ok := tt.x.(Value); ok {
1403 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1406 if !Zero(TypeOf(tt.x)).IsZero() {
1407 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1413 if r := recover(); r == nil {
1414 t.Error("should panic for invalid value")
1421 func TestInterfaceExtraction(t *testing.T) {
1427 v := Indirect(ValueOf(&s)).Field(0).Interface()
1428 if v != s.W.(interface{}) {
1429 t.Error("Interface() on interface: ", v, s.W)
1433 func TestNilPtrValueSub(t *testing.T) {
1435 if pv := ValueOf(pi); pv.Elem().IsValid() {
1436 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1440 func TestMap(t *testing.T) {
1441 m := map[string]int{"a": 1, "b": 2}
1443 if n := mv.Len(); n != len(m) {
1444 t.Errorf("Len = %d, want %d", n, len(m))
1446 keys := mv.MapKeys()
1447 newmap := MakeMap(mv.Type())
1448 for k, v := range m {
1449 // Check that returned Keys match keys in range.
1450 // These aren't required to be in the same order.
1452 for _, kv := range keys {
1453 if kv.String() == k {
1459 t.Errorf("Missing key %q", k)
1462 // Check that value lookup is correct.
1463 vv := mv.MapIndex(ValueOf(k))
1464 if vi := vv.Int(); vi != int64(v) {
1465 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1468 // Copy into new map.
1469 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1471 vv := mv.MapIndex(ValueOf("not-present"))
1473 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1476 newm := newmap.Interface().(map[string]int)
1477 if len(newm) != len(m) {
1478 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1481 for k, v := range newm {
1484 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1488 newmap.SetMapIndex(ValueOf("a"), Value{})
1491 t.Errorf("newm[\"a\"] = %d after delete", v)
1494 mv = ValueOf(&m).Elem()
1495 mv.Set(Zero(mv.Type()))
1497 t.Errorf("mv.Set(nil) failed")
1501 func TestNilMap(t *testing.T) {
1502 var m map[string]int
1504 keys := mv.MapKeys()
1506 t.Errorf(">0 keys for nil map: %v", keys)
1509 // Check that value for missing key is zero.
1510 x := mv.MapIndex(ValueOf("hello"))
1511 if x.Kind() != Invalid {
1512 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1515 // Check big value too.
1516 var mbig map[string][10 << 20]byte
1517 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1518 if x.Kind() != Invalid {
1519 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1522 // Test that deletes from a nil map succeed.
1523 mv.SetMapIndex(ValueOf("hi"), Value{})
1526 func TestChan(t *testing.T) {
1527 for loop := 0; loop < 2; loop++ {
1531 // check both ways to allocate channels
1534 c = make(chan int, 1)
1537 cv = MakeChan(TypeOf(c), 1)
1538 c = cv.Interface().(chan int)
1543 if i := <-c; i != 2 {
1544 t.Errorf("reflect Send 2, native recv %d", i)
1549 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1550 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1554 val, ok := cv.TryRecv()
1555 if val.IsValid() || ok {
1556 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1561 val, ok = cv.TryRecv()
1563 t.Errorf("TryRecv on ready chan got nil")
1564 } else if i := val.Int(); i != 4 || !ok {
1565 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1570 ok = cv.TrySend(ValueOf(5))
1573 t.Errorf("TrySend on full chan succeeded: value %d", i)
1577 ok = cv.TrySend(ValueOf(6))
1579 t.Errorf("TrySend on empty chan failed")
1582 t.Errorf("TrySend failed but it did send %d", x)
1586 if i = <-c; i != 6 {
1587 t.Errorf("TrySend 6, recv %d", i)
1594 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1595 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1597 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1598 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1602 // check creation of unbuffered channel
1604 cv := MakeChan(TypeOf(c), 0)
1605 c = cv.Interface().(chan int)
1606 if cv.TrySend(ValueOf(7)) {
1607 t.Errorf("TrySend on sync chan succeeded")
1609 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1610 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1614 cv = MakeChan(TypeOf(c), 10)
1615 c = cv.Interface().(chan int)
1616 for i := 0; i < 3; i++ {
1619 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1620 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1624 // caseInfo describes a single case in a select test.
1625 type caseInfo struct {
1634 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1636 func TestSelect(t *testing.T) {
1637 selectWatch.once.Do(func() { go selectWatcher() })
1641 newop := func(n int, cap int) (ch, val Value) {
1644 c := make(chan int, cap)
1648 c := make(chan string, cap)
1650 val = ValueOf(fmt.Sprint(n))
1655 for n := 0; x.Next(); n++ {
1656 if testing.Short() && n >= 1000 {
1659 if n >= 100000 && !*allselect {
1662 if n%100000 == 0 && testing.Verbose() {
1663 println("TestSelect", n)
1665 var cases []SelectCase
1670 ch, val := newop(len(cases), 1)
1671 cases = append(cases, SelectCase{
1676 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1681 ch, val := newop(len(cases), 1)
1683 cases = append(cases, SelectCase{
1687 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1692 ch, val := newop(len(cases), 0)
1693 cases = append(cases, SelectCase{
1700 f := func() { ch.Recv() }
1701 info = append(info, caseInfo{desc: "blocking send", helper: f})
1703 info = append(info, caseInfo{desc: "blocking send"})
1709 ch, val := newop(len(cases), 0)
1710 cases = append(cases, SelectCase{
1716 f := func() { ch.Send(val) }
1717 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1719 info = append(info, caseInfo{desc: "blocking recv"})
1725 // Maybe include value to send.
1730 cases = append(cases, SelectCase{
1734 info = append(info, caseInfo{desc: "zero Chan send"})
1737 // Zero Chan receive.
1739 cases = append(cases, SelectCase{
1742 info = append(info, caseInfo{desc: "zero Chan recv"})
1747 cases = append(cases, SelectCase{
1749 Chan: ValueOf((chan int)(nil)),
1752 info = append(info, caseInfo{desc: "nil Chan send"})
1757 cases = append(cases, SelectCase{
1759 Chan: ValueOf((chan int)(nil)),
1761 info = append(info, caseInfo{desc: "nil Chan recv"})
1764 // closed Chan send.
1766 ch := make(chan int)
1768 cases = append(cases, SelectCase{
1773 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1776 // closed Chan recv.
1778 ch, val := newop(len(cases), 0)
1780 val = Zero(val.Type())
1781 cases = append(cases, SelectCase{
1785 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1788 var helper func() // goroutine to help the select complete
1790 // Add default? Must be last case here, but will permute.
1791 // Add the default if the select would otherwise
1792 // block forever, and maybe add it anyway.
1798 for i, c := range info {
1806 } else if c.helper != nil {
1808 helpers = append(helpers, i)
1811 if !canProceed || x.Maybe() {
1812 cases = append(cases, SelectCase{
1815 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1817 } else if canBlock {
1818 // Select needs to communicate with another goroutine.
1819 cas := &info[helpers[x.Choose(len(helpers))]]
1821 cas.canSelect = true
1825 // Permute cases and case info.
1826 // Doing too much here makes the exhaustive loop
1827 // too exhausting, so just do two swaps.
1828 for loop := 0; loop < 2; loop++ {
1829 i := x.Choose(len(cases))
1830 j := x.Choose(len(cases))
1831 cases[i], cases[j] = cases[j], cases[i]
1832 info[i], info[j] = info[j], info[i]
1836 // We wait before kicking off a goroutine to satisfy a blocked select.
1837 // The pause needs to be big enough to let the select block before
1838 // we run the helper, but if we lose that race once in a while it's okay: the
1839 // select will just proceed immediately. Not a big deal.
1840 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1841 pause := 10 * time.Microsecond
1842 if testing.Short() {
1843 pause = 100 * time.Microsecond
1845 time.AfterFunc(pause, helper)
1849 i, recv, recvOK, panicErr := runSelect(cases, info)
1850 if panicErr != nil && !canPanic {
1851 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1853 if panicErr == nil && canPanic && numCanSelect == 1 {
1854 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1856 if panicErr != nil {
1864 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1866 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1870 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1874 if cases[i].Dir == SelectRecv {
1875 if !recv.IsValid() {
1876 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1878 if !cas.recv.IsValid() {
1879 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1881 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1882 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1883 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1885 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1888 if recv.IsValid() || recvOK {
1889 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1895 func TestSelectMaxCases(t *testing.T) {
1896 var sCases []SelectCase
1897 channel := make(chan int)
1899 for i := 0; i < 65536; i++ {
1900 sCases = append(sCases, SelectCase{
1902 Chan: ValueOf(channel),
1906 _, _, _ = Select(sCases)
1907 sCases = append(sCases, SelectCase{
1909 Chan: ValueOf(channel),
1912 if err := recover(); err != nil {
1913 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1914 t.Fatalf("unexpected error from select call with greater than max supported cases")
1917 t.Fatalf("expected select call to panic with greater than max supported cases")
1921 _, _, _ = Select(sCases)
1924 func TestSelectNop(t *testing.T) {
1925 // "select { default: }" should always return the default case.
1926 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1928 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1932 func BenchmarkSelect(b *testing.B) {
1933 channel := make(chan int)
1935 var cases []SelectCase
1936 for i := 0; i < 8; i++ {
1937 cases = append(cases, SelectCase{
1939 Chan: ValueOf(channel),
1942 for _, numCases := range []int{1, 4, 8} {
1943 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1945 for i := 0; i < b.N; i++ {
1946 _, _, _ = Select(cases[:numCases])
1952 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1953 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1954 // an error describing the select and panics the entire test binary.
1955 var selectWatch struct {
1962 func selectWatcher() {
1964 time.Sleep(1 * time.Second)
1966 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1967 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1968 panic("select stuck")
1970 selectWatch.Unlock()
1974 // runSelect runs a single select test.
1975 // It returns the values returned by Select but also returns
1976 // a panic value if the Select panics.
1977 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1979 panicErr = recover()
1982 selectWatch.info = nil
1983 selectWatch.Unlock()
1987 selectWatch.now = time.Now()
1988 selectWatch.info = info
1989 selectWatch.Unlock()
1991 chosen, recv, recvOK = Select(cases)
1995 // fmtSelect formats the information about a single select test.
1996 func fmtSelect(info []caseInfo) string {
1997 var buf bytes.Buffer
1998 fmt.Fprintf(&buf, "\nselect {\n")
1999 for i, cas := range info {
2000 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2001 if cas.recv.IsValid() {
2002 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2005 fmt.Fprintf(&buf, " canselect")
2008 fmt.Fprintf(&buf, " panic")
2010 fmt.Fprintf(&buf, "\n")
2012 fmt.Fprintf(&buf, "}")
2018 // Difficult test for function call because of
2019 // implicit padding between arguments.
2020 func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
2021 return b, c, d, e, f, g, h
2024 func TestFunc(t *testing.T) {
2025 ret := ValueOf(dummy).Call([]Value{
2029 ValueOf(two{40, 50}),
2031 ValueOf(float32(70)),
2035 t.Fatalf("Call returned %d values, want 7", len(ret))
2038 i := byte(ret[0].Uint())
2039 j := int(ret[1].Int())
2040 k := byte(ret[2].Uint())
2041 l := ret[3].Interface().(two)
2042 m := byte(ret[4].Uint())
2043 n := float32(ret[5].Float())
2044 o := byte(ret[6].Uint())
2046 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2047 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
2050 for i, v := range ret {
2052 t.Errorf("result %d is addressable", i)
2057 func TestCallConvert(t *testing.T) {
2058 v := ValueOf(new(io.ReadWriter)).Elem()
2059 f := ValueOf(func(r io.Reader) io.Reader { return r })
2060 out := f.Call([]Value{v})
2061 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2062 t.Errorf("expected [nil], got %v", out)
2066 type emptyStruct struct{}
2068 type nonEmptyStruct struct {
2072 func returnEmpty() emptyStruct {
2073 return emptyStruct{}
2076 func takesEmpty(e emptyStruct) {
2079 func returnNonEmpty(i int) nonEmptyStruct {
2080 return nonEmptyStruct{member: i}
2083 func takesNonEmpty(n nonEmptyStruct) int {
2087 func TestCallWithStruct(t *testing.T) {
2088 r := ValueOf(returnEmpty).Call(nil)
2089 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2090 t.Errorf("returning empty struct returned %#v instead", r)
2092 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2094 t.Errorf("takesEmpty returned values: %#v", r)
2096 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2097 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2098 t.Errorf("returnNonEmpty returned %#v", r)
2100 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2101 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2102 t.Errorf("takesNonEmpty returned %#v", r)
2106 func TestCallReturnsEmpty(t *testing.T) {
2107 // Issue 21717: past-the-end pointer write in Call with
2108 // nonzero-sized frame and zero-sized return value.
2110 var finalized uint32
2111 f := func() (emptyStruct, *[2]int64) {
2112 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2113 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2114 return emptyStruct{}, i
2116 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2117 timeout := time.After(5 * time.Second)
2118 for atomic.LoadUint32(&finalized) == 0 {
2121 t.Fatal("finalizer did not run")
2127 runtime.KeepAlive(v)
2130 func BenchmarkCall(b *testing.B) {
2131 fv := ValueOf(func(a, b string) {})
2133 b.RunParallel(func(pb *testing.PB) {
2134 args := []Value{ValueOf("a"), ValueOf("b")}
2143 func (i *myint) inc() {
2147 func BenchmarkCallMethod(b *testing.B) {
2152 for i := 0; i < b.N; i++ {
2157 func BenchmarkCallArgCopy(b *testing.B) {
2158 byteArray := func(n int) Value {
2159 return Zero(ArrayOf(n, TypeOf(byte(0))))
2161 sizes := [...]struct {
2165 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2166 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2167 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2168 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2169 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2171 for _, size := range sizes {
2172 bench := func(b *testing.B) {
2173 args := []Value{size.arg}
2174 b.SetBytes(int64(size.arg.Len()))
2176 b.RunParallel(func(pb *testing.PB) {
2182 name := fmt.Sprintf("size=%v", size.arg.Len())
2187 func TestMakeFunc(t *testing.T) {
2189 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2190 ValueOf(&f).Elem().Set(fv)
2192 // Call g with small arguments so that there is
2193 // something predictable (and different from the
2194 // correct results) in those positions on the stack.
2196 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2198 // Call constructed function f.
2199 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2200 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2201 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
2205 func TestMakeFuncInterface(t *testing.T) {
2206 fn := func(i int) int { return i }
2207 incr := func(in []Value) []Value {
2208 return []Value{ValueOf(int(in[0].Int() + 1))}
2210 fv := MakeFunc(TypeOf(fn), incr)
2211 ValueOf(&fn).Elem().Set(fv)
2212 if r := fn(2); r != 3 {
2213 t.Errorf("Call returned %d, want 3", r)
2215 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2216 t.Errorf("Call returned %d, want 15", r)
2218 if r := fv.Interface().(func(int) int)(26); r != 27 {
2219 t.Errorf("Call returned %d, want 27", r)
2223 func TestMakeFuncVariadic(t *testing.T) {
2224 // Test that variadic arguments are packed into a slice and passed as last arg
2225 fn := func(_ int, is ...int) []int { return nil }
2226 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2227 ValueOf(&fn).Elem().Set(fv)
2230 if r[0] != 2 || r[1] != 3 {
2231 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2234 r = fn(1, []int{2, 3}...)
2235 if r[0] != 2 || r[1] != 3 {
2236 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2239 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2240 if r[0] != 2 || r[1] != 3 {
2241 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2244 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2245 if r[0] != 2 || r[1] != 3 {
2246 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2249 f := fv.Interface().(func(int, ...int) []int)
2252 if r[0] != 2 || r[1] != 3 {
2253 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2255 r = f(1, []int{2, 3}...)
2256 if r[0] != 2 || r[1] != 3 {
2257 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2261 // Dummy type that implements io.WriteCloser
2265 func (w *WC) Write(p []byte) (n int, err error) {
2268 func (w *WC) Close() error {
2272 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2273 // reflect.Values returned from the wrapped function should be assignment-converted
2274 // to the types returned by the result of MakeFunc.
2276 // Concrete types should be promotable to interfaces they implement.
2278 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2279 return []Value{ValueOf(io.EOF)}
2280 }).Interface().(func() error)
2283 // Super-interfaces should be promotable to simpler interfaces.
2284 var g func() io.Writer
2285 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2286 var w io.WriteCloser = &WC{}
2287 return []Value{ValueOf(&w).Elem()}
2288 }).Interface().(func() io.Writer)
2291 // Channels should be promotable to directional channels.
2292 var h func() <-chan int
2293 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2294 return []Value{ValueOf(make(chan int))}
2295 }).Interface().(func() <-chan int)
2298 // Unnamed types should be promotable to named types.
2299 type T struct{ a, b, c int }
2301 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2302 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2303 }).Interface().(func() T)
2307 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2308 // Type doesn't implement the required interface.
2309 shouldPanic("", func() {
2311 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2312 return []Value{ValueOf(int(7))}
2313 }).Interface().(func() error)
2316 // Assigning to an interface with additional methods.
2317 shouldPanic("", func() {
2318 var f func() io.ReadWriteCloser
2319 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2320 var w io.WriteCloser = &WC{}
2321 return []Value{ValueOf(&w).Elem()}
2322 }).Interface().(func() io.ReadWriteCloser)
2325 // Directional channels can't be assigned to bidirectional ones.
2326 shouldPanic("", func() {
2327 var f func() chan int
2328 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2329 var c <-chan int = make(chan int)
2330 return []Value{ValueOf(c)}
2331 }).Interface().(func() chan int)
2334 // Two named types which are otherwise identical.
2335 shouldPanic("", func() {
2336 type T struct{ a, b, c int }
2337 type U struct{ a, b, c int }
2339 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2340 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2341 }).Interface().(func() T)
2350 // This will be index 0.
2351 func (p Point) AnotherMethod(scale int) int {
2355 // This will be index 1.
2356 func (p Point) Dist(scale int) int {
2357 //println("Point.Dist", p.x, p.y, scale)
2358 return p.x*p.x*scale + p.y*p.y*scale
2361 // This will be index 2.
2362 func (p Point) GCMethod(k int) int {
2367 // This will be index 3.
2368 func (p Point) NoArgs() {
2369 // Exercise no-argument/no-result paths.
2372 // This will be index 4.
2373 func (p Point) TotalDist(points ...Point) int {
2375 for _, q := range points {
2378 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2384 // This will be index 5.
2385 func (p *Point) Int64Method(x int64) int64 {
2389 // This will be index 6.
2390 func (p *Point) Int32Method(x int32) int32 {
2394 func TestMethod(t *testing.T) {
2395 // Non-curried method of type.
2397 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2399 t.Errorf("Type Method returned %d; want 250", i)
2402 m, ok := TypeOf(p).MethodByName("Dist")
2404 t.Fatalf("method by name failed")
2406 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2408 t.Errorf("Type MethodByName returned %d; want 275", i)
2411 m, ok = TypeOf(p).MethodByName("NoArgs")
2413 t.Fatalf("method by name failed")
2415 n := len(m.Func.Call([]Value{ValueOf(p)}))
2417 t.Errorf("NoArgs returned %d values; want 0", n)
2420 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2422 t.Errorf("Pointer Type Method returned %d; want 300", i)
2425 m, ok = TypeOf(&p).MethodByName("Dist")
2427 t.Fatalf("ptr method by name failed")
2429 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2431 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2434 m, ok = TypeOf(&p).MethodByName("NoArgs")
2436 t.Fatalf("method by name failed")
2438 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2440 t.Errorf("NoArgs returned %d values; want 0", n)
2443 // Curried method of value.
2444 tfunc := TypeOf((func(int) int)(nil))
2445 v := ValueOf(p).Method(1)
2446 if tt := v.Type(); tt != tfunc {
2447 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2449 i = v.Call([]Value{ValueOf(14)})[0].Int()
2451 t.Errorf("Value Method returned %d; want 350", i)
2453 v = ValueOf(p).MethodByName("Dist")
2454 if tt := v.Type(); tt != tfunc {
2455 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2457 i = v.Call([]Value{ValueOf(15)})[0].Int()
2459 t.Errorf("Value MethodByName returned %d; want 375", i)
2461 v = ValueOf(p).MethodByName("NoArgs")
2464 // Curried method of pointer.
2465 v = ValueOf(&p).Method(1)
2466 if tt := v.Type(); tt != tfunc {
2467 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2469 i = v.Call([]Value{ValueOf(16)})[0].Int()
2471 t.Errorf("Pointer Value Method returned %d; want 400", i)
2473 v = ValueOf(&p).MethodByName("Dist")
2474 if tt := v.Type(); tt != tfunc {
2475 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2477 i = v.Call([]Value{ValueOf(17)})[0].Int()
2479 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2481 v = ValueOf(&p).MethodByName("NoArgs")
2484 // Curried method of interface value.
2485 // Have to wrap interface value in a struct to get at it.
2486 // Passing it to ValueOf directly would
2487 // access the underlying Point, not the interface.
2491 pv := ValueOf(&x).Elem()
2493 if tt := v.Type(); tt != tfunc {
2494 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2496 i = v.Call([]Value{ValueOf(18)})[0].Int()
2498 t.Errorf("Interface Method returned %d; want 450", i)
2500 v = pv.MethodByName("Dist")
2501 if tt := v.Type(); tt != tfunc {
2502 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2504 i = v.Call([]Value{ValueOf(19)})[0].Int()
2506 t.Errorf("Interface MethodByName returned %d; want 475", i)
2510 func TestMethodValue(t *testing.T) {
2514 // Check that method value have the same underlying code pointers.
2515 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2516 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2519 // Curried method of value.
2520 tfunc := TypeOf((func(int) int)(nil))
2521 v := ValueOf(p).Method(1)
2522 if tt := v.Type(); tt != tfunc {
2523 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2525 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2527 t.Errorf("Value Method returned %d; want 250", i)
2529 v = ValueOf(p).MethodByName("Dist")
2530 if tt := v.Type(); tt != tfunc {
2531 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2533 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2535 t.Errorf("Value MethodByName returned %d; want 275", i)
2537 v = ValueOf(p).MethodByName("NoArgs")
2538 ValueOf(v.Interface()).Call(nil)
2539 v.Interface().(func())()
2541 // Curried method of pointer.
2542 v = ValueOf(&p).Method(1)
2543 if tt := v.Type(); tt != tfunc {
2544 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2546 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2548 t.Errorf("Pointer Value Method returned %d; want 300", i)
2550 v = ValueOf(&p).MethodByName("Dist")
2551 if tt := v.Type(); tt != tfunc {
2552 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2554 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2556 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2558 v = ValueOf(&p).MethodByName("NoArgs")
2559 ValueOf(v.Interface()).Call(nil)
2560 v.Interface().(func())()
2562 // Curried method of pointer to pointer.
2564 v = ValueOf(&pp).Elem().Method(1)
2565 if tt := v.Type(); tt != tfunc {
2566 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2568 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2570 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2572 v = ValueOf(&pp).Elem().MethodByName("Dist")
2573 if tt := v.Type(); tt != tfunc {
2574 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2576 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2578 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2581 // Curried method of interface value.
2582 // Have to wrap interface value in a struct to get at it.
2583 // Passing it to ValueOf directly would
2584 // access the underlying Point, not the interface.
2590 pv := ValueOf(s).Field(0)
2592 if tt := v.Type(); tt != tfunc {
2593 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2595 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2597 t.Errorf("Interface Method returned %d; want 400", i)
2599 v = pv.MethodByName("Dist")
2600 if tt := v.Type(); tt != tfunc {
2601 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2603 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2605 t.Errorf("Interface MethodByName returned %d; want 425", i)
2608 // For issue #33628: method args are not stored at the right offset
2610 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2611 if x := m64(123); x != 123 {
2612 t.Errorf("Int64Method returned %d; want 123", x)
2614 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2615 if x := m32(456); x != 456 {
2616 t.Errorf("Int32Method returned %d; want 456", x)
2620 func TestVariadicMethodValue(t *testing.T) {
2622 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2623 want := int64(p.TotalDist(points[0], points[1], points[2]))
2625 // Variadic method of type.
2626 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2627 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2628 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2631 // Curried method of value.
2632 tfunc = TypeOf((func(...Point) int)(nil))
2633 v := ValueOf(p).Method(4)
2634 if tt := v.Type(); tt != tfunc {
2635 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2637 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2639 t.Errorf("Variadic Method returned %d; want %d", i, want)
2641 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2643 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2646 f := v.Interface().(func(...Point) int)
2647 i = int64(f(points[0], points[1], points[2]))
2649 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2651 i = int64(f(points...))
2653 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2657 type DirectIfaceT struct {
2661 func (d DirectIfaceT) M() int { return *d.p }
2663 func TestDirectIfaceMethod(t *testing.T) {
2665 v := DirectIfaceT{&x}
2667 m, ok := typ.MethodByName("M")
2669 t.Fatalf("cannot find method M")
2671 in := []Value{ValueOf(v)}
2672 out := m.Func.Call(in)
2673 if got := out[0].Int(); got != 42 {
2674 t.Errorf("Call with value receiver got %d, want 42", got)
2679 m, ok = typ.MethodByName("M")
2681 t.Fatalf("cannot find method M")
2683 in = []Value{ValueOf(pv)}
2684 out = m.Func.Call(in)
2685 if got := out[0].Int(); got != 42 {
2686 t.Errorf("Call with pointer receiver got %d, want 42", got)
2690 // Reflect version of $GOROOT/test/method5.go
2692 // Concrete types implementing M method.
2693 // Smaller than a word, word-sized, larger than a word.
2694 // Value and pointer receivers.
2696 type Tinter interface {
2697 M(int, byte) (byte, int)
2702 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2706 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2710 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2714 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2716 type Tbigv [2]uintptr
2718 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2720 type Tbigp [2]uintptr
2722 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2724 type tinter interface {
2725 m(int, byte) (byte, int)
2728 // Embedding via pointer.
2745 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2747 func TestMethod5(t *testing.T) {
2748 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2750 if b != 99 || x != 1000+inc {
2751 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2755 CheckV := func(name string, i Value, inc int) {
2756 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2757 b := bx[0].Interface()
2758 x := bx[1].Interface()
2759 if b != byte(99) || x != 1000+inc {
2760 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2763 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2766 var TinterType = TypeOf(new(Tinter)).Elem()
2768 CheckI := func(name string, i interface{}, inc int) {
2770 CheckV(name, v, inc)
2771 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2776 CheckI("&sv", &sv, 1)
2779 CheckI("&sp", &sp, 2)
2783 CheckI("&wv", &wv, 3)
2786 CheckI("&wp", &wp, 4)
2788 bv := Tbigv([2]uintptr{5, 6})
2789 CheckI("bv", bv, 11)
2790 CheckI("&bv", &bv, 11)
2792 bp := Tbigp([2]uintptr{7, 8})
2793 CheckI("&bp", &bp, 15)
2799 CheckI("t4", t4, 40)
2800 CheckI("&t4", &t4, 40)
2801 CheckI("t3", t3, 40)
2802 CheckI("&t3", &t3, 40)
2803 CheckI("t2", t2, 40)
2804 CheckI("&t2", &t2, 40)
2805 CheckI("t1", t1, 40)
2806 CheckI("&t1", &t1, 40)
2809 vnil := ValueOf(&tnil).Elem()
2810 shouldPanic("Method", func() { vnil.Method(0) })
2813 func TestInterfaceSet(t *testing.T) {
2822 sv := ValueOf(&s).Elem()
2823 sv.Field(0).Set(ValueOf(p))
2824 if q := s.I.(*Point); q != p {
2825 t.Errorf("i: have %p want %p", q, p)
2830 if q := s.P.(*Point); q != p {
2831 t.Errorf("i: have %p want %p", q, p)
2834 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2836 t.Errorf("Interface Method returned %d; want 250", i)
2845 func TestAnonymousFields(t *testing.T) {
2846 var field StructField
2850 if field, ok = type1.FieldByName("int"); !ok {
2851 t.Fatal("no field 'int'")
2853 if field.Index[0] != 1 {
2854 t.Error("field index should be 1; is", field.Index)
2908 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2930 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2949 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2963 var fieldTests = []FTest{
2964 {struct{}{}, "", nil, 0},
2965 {struct{}{}, "Foo", nil, 0},
2966 {S0{A: 'a'}, "A", []int{0}, 'a'},
2967 {S0{}, "D", nil, 0},
2968 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2969 {S1{B: 'b'}, "B", []int{0}, 'b'},
2970 {S1{}, "S0", []int{1}, 0},
2971 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2972 {S2{A: 'a'}, "A", []int{0}, 'a'},
2973 {S2{}, "S1", []int{1}, 0},
2974 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2975 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2976 {S2{}, "D", nil, 0},
2977 {S3{}, "S1", nil, 0},
2978 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2979 {S3{}, "B", nil, 0},
2980 {S3{D: 'd'}, "D", []int{2}, 0},
2981 {S3{E: 'e'}, "E", []int{3}, 'e'},
2982 {S4{A: 'a'}, "A", []int{1}, 'a'},
2983 {S4{}, "B", nil, 0},
2984 {S5{}, "X", nil, 0},
2985 {S5{}, "Y", []int{2, 0, 1}, 0},
2986 {S10{}, "X", nil, 0},
2987 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2988 {S14{}, "X", nil, 0},
2991 func TestFieldByIndex(t *testing.T) {
2992 for _, test := range fieldTests {
2994 f := s.FieldByIndex(test.index)
2996 if test.index != nil {
2997 if f.Name != test.name {
2998 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3001 t.Errorf("%s.%s found", s.Name(), f.Name)
3003 } else if len(test.index) > 0 {
3004 t.Errorf("%s.%s not found", s.Name(), test.name)
3007 if test.value != 0 {
3008 v := ValueOf(test.s).FieldByIndex(test.index)
3010 if x, ok := v.Interface().(int); ok {
3011 if x != test.value {
3012 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3015 t.Errorf("%s%v value not an int", s.Name(), test.index)
3018 t.Errorf("%s%v value not found", s.Name(), test.index)
3024 func TestFieldByName(t *testing.T) {
3025 for _, test := range fieldTests {
3027 f, found := s.FieldByName(test.name)
3029 if test.index != nil {
3030 // Verify field depth and index.
3031 if len(f.Index) != len(test.index) {
3032 t.Errorf("%s.%s depth %d; want %d: %v vs %v", s.Name(), test.name, len(f.Index), len(test.index), f.Index, test.index)
3034 for i, x := range f.Index {
3035 if x != test.index[i] {
3036 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3041 t.Errorf("%s.%s found", s.Name(), f.Name)
3043 } else if len(test.index) > 0 {
3044 t.Errorf("%s.%s not found", s.Name(), test.name)
3047 if test.value != 0 {
3048 v := ValueOf(test.s).FieldByName(test.name)
3050 if x, ok := v.Interface().(int); ok {
3051 if x != test.value {
3052 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3055 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3058 t.Errorf("%s.%s value not found", s.Name(), test.name)
3064 func TestImportPath(t *testing.T) {
3069 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3070 {TypeOf(int(0)), ""},
3071 {TypeOf(int8(0)), ""},
3072 {TypeOf(int16(0)), ""},
3073 {TypeOf(int32(0)), ""},
3074 {TypeOf(int64(0)), ""},
3075 {TypeOf(uint(0)), ""},
3076 {TypeOf(uint8(0)), ""},
3077 {TypeOf(uint16(0)), ""},
3078 {TypeOf(uint32(0)), ""},
3079 {TypeOf(uint64(0)), ""},
3080 {TypeOf(uintptr(0)), ""},
3081 {TypeOf(float32(0)), ""},
3082 {TypeOf(float64(0)), ""},
3083 {TypeOf(complex64(0)), ""},
3084 {TypeOf(complex128(0)), ""},
3085 {TypeOf(byte(0)), ""},
3086 {TypeOf(rune(0)), ""},
3087 {TypeOf([]byte(nil)), ""},
3088 {TypeOf([]rune(nil)), ""},
3089 {TypeOf(string("")), ""},
3090 {TypeOf((*interface{})(nil)).Elem(), ""},
3091 {TypeOf((*byte)(nil)), ""},
3092 {TypeOf((*rune)(nil)), ""},
3093 {TypeOf((*int64)(nil)), ""},
3094 {TypeOf(map[string]int{}), ""},
3095 {TypeOf((*error)(nil)).Elem(), ""},
3096 {TypeOf((*Point)(nil)), ""},
3097 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3099 for _, test := range tests {
3100 if path := test.t.PkgPath(); path != test.path {
3101 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3106 func TestFieldPkgPath(t *testing.T) {
3108 typ := TypeOf(struct {
3116 type pkgpathTest struct {
3123 checkPkgPath := func(name string, s []pkgpathTest) {
3124 for _, test := range s {
3125 f := typ.FieldByIndex(test.index)
3126 if got, want := f.PkgPath, test.pkgPath; got != want {
3127 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3129 if got, want := f.Anonymous, test.embedded; got != want {
3130 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3132 if got, want := f.IsExported(), test.exported; got != want {
3133 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3138 checkPkgPath("testStruct", []pkgpathTest{
3139 {[]int{0}, "", false, true}, // Exported
3140 {[]int{1}, "reflect_test", false, false}, // unexported
3141 {[]int{2}, "", true, true}, // OtherPkgFields
3142 {[]int{2, 0}, "", false, true}, // OtherExported
3143 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3144 {[]int{3}, "reflect_test", true, false}, // int
3145 {[]int{4}, "reflect_test", true, false}, // *x
3148 type localOtherPkgFields OtherPkgFields
3149 typ = TypeOf(localOtherPkgFields{})
3150 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3151 {[]int{0}, "", false, true}, // OtherExported
3152 {[]int{1}, "reflect", false, false}, // otherUnexported
3156 func TestMethodPkgPath(t *testing.T) {
3161 typ := TypeOf((*interface {
3174 {"x", "reflect_test", false},
3175 {"y", "reflect_test", false},
3178 for _, test := range tests {
3179 m, _ := typ.MethodByName(test.name)
3180 if got, want := m.PkgPath, test.pkgPath; got != want {
3181 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3183 if got, want := m.IsExported(), test.exported; got != want {
3184 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3189 func TestVariadicType(t *testing.T) {
3190 // Test example from Type documentation.
3191 var f func(x int, y ...float64)
3193 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3195 if sl.Kind() == Slice {
3196 if sl.Elem() == TypeOf(0.0) {
3204 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3205 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3206 for i := 0; i < typ.NumIn(); i++ {
3207 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3221 func (*inner) M() {}
3222 func (*outer) M() {}
3224 func TestNestedMethods(t *testing.T) {
3225 typ := TypeOf((*outer)(nil))
3226 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3227 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3228 for i := 0; i < typ.NumMethod(); i++ {
3230 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3237 func (*unexp) f() (int32, int8) { return 7, 7 }
3238 func (*unexp) g() (int64, int8) { return 8, 8 }
3240 type unexpI interface {
3244 var unexpi unexpI = new(unexp)
3246 func TestUnexportedMethods(t *testing.T) {
3247 typ := TypeOf(unexpi)
3249 if got := typ.NumMethod(); got != 0 {
3250 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3254 type InnerInt struct {
3258 type OuterInt struct {
3263 func (i *InnerInt) M() int {
3267 func TestEmbeddedMethods(t *testing.T) {
3268 typ := TypeOf((*OuterInt)(nil))
3269 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3270 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3271 for i := 0; i < typ.NumMethod(); i++ {
3273 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3278 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3279 t.Errorf("i.M() = %d, want 3", v)
3282 o := &OuterInt{1, InnerInt{2}}
3283 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3284 t.Errorf("i.M() = %d, want 2", v)
3288 if v := f(o); v != 2 {
3289 t.Errorf("f(o) = %d, want 2", v)
3293 type FuncDDD func(...interface{}) error
3295 func (f FuncDDD) M() {}
3297 func TestNumMethodOnDDD(t *testing.T) {
3298 rv := ValueOf((FuncDDD)(nil))
3299 if n := rv.NumMethod(); n != 1 {
3300 t.Fatalf("NumMethod()=%d, want 1", n)
3304 func TestPtrTo(t *testing.T) {
3305 // This block of code means that the ptrToThis field of the
3306 // reflect data for *unsafe.Pointer is non zero, see
3307 // https://golang.org/issue/19003
3308 var x unsafe.Pointer
3315 for i = 0; i < 100; i++ {
3318 for i = 0; i < 100; i++ {
3321 if typ != TypeOf(z) {
3322 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
3326 func TestPtrToGC(t *testing.T) {
3328 tt := TypeOf(T(nil))
3332 for i := 0; i < n; i++ {
3337 v.Elem().Set(ValueOf(p).Convert(pt))
3338 x = append(x, v.Interface())
3342 for i, xi := range x {
3343 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3344 if k != uintptr(i) {
3345 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3350 func BenchmarkPtrTo(b *testing.B) {
3351 // Construct a type with a zero ptrToThis.
3352 type T struct{ int }
3353 t := SliceOf(TypeOf(T{}))
3354 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3355 if !ptrToThis.IsValid() {
3356 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3358 if ptrToThis.Int() != 0 {
3359 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3363 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
3365 b.RunParallel(func(pb *testing.PB) {
3372 func TestAddr(t *testing.T) {
3384 t.Errorf("Addr.Elem.Set failed to set value")
3387 // Again but take address of the ValueOf value.
3388 // Exercises generation of PtrTypes not present in the binary.
3390 v = ValueOf(&q).Elem()
3399 t.Errorf("Addr.Elem.Set failed to set value")
3402 // Starting without pointer we should get changed value
3405 v = ValueOf(&qq).Elem()
3411 if p.X != 3 { // should be unchanged from last time
3412 t.Errorf("somehow value Set changed original p")
3414 p = v0.Interface().(struct {
3418 t.Errorf("Addr.Elem.Set valued to set value in top value")
3421 // Verify that taking the address of a type gives us a pointer
3422 // which we can convert back using the usual interface
3427 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3428 *(ps.(**bool)) = new(bool)
3430 t.Errorf("Addr.Interface direct assignment failed")
3434 func noAlloc(t *testing.T, n int, f func(int)) {
3435 if testing.Short() {
3436 t.Skip("skipping malloc count in short mode")
3438 if runtime.GOMAXPROCS(0) > 1 {
3439 t.Skip("skipping; GOMAXPROCS>1")
3442 allocs := testing.AllocsPerRun(n, func() {
3447 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3451 func TestAllocations(t *testing.T) {
3452 noAlloc(t, 100, func(j int) {
3456 // We can uncomment this when compiler escape analysis
3457 // is good enough to see that the integer assigned to i
3458 // does not escape and therefore need not be allocated.
3462 // if int(v.Int()) != 42+j {
3463 // panic("wrong int")
3466 i = func(j int) int { return j }
3468 if v.Interface().(func(int) int)(j) != j {
3469 panic("wrong result")
3474 func TestSmallNegativeInt(t *testing.T) {
3478 t.Errorf("int16(-1).Int() returned %v", v.Int())
3482 func TestIndex(t *testing.T) {
3483 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3484 v := ValueOf(xs).Index(3).Interface().(byte)
3486 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3488 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3489 v = ValueOf(xa).Index(2).Interface().(byte)
3491 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3494 v = ValueOf(s).Index(3).Interface().(byte)
3496 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3500 func TestSlice(t *testing.T) {
3501 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3502 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3504 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3507 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3509 if !DeepEqual(v[0:5], xs[3:]) {
3510 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3512 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3513 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3515 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3518 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3520 if !DeepEqual(v[0:6], xa[2:]) {
3521 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3524 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3526 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3529 rv := ValueOf(&xs).Elem()
3531 ptr2 := rv.UnsafePointer()
3533 ptr3 := rv.UnsafePointer()
3535 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3539 func TestSlice3(t *testing.T) {
3540 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3541 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3543 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3546 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3548 if !DeepEqual(v[0:4], xs[3:7:7]) {
3549 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3551 rv := ValueOf(&xs).Elem()
3552 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3553 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3554 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3556 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3557 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3559 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3562 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3564 if !DeepEqual(v[0:4], xa[2:6:6]) {
3565 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3567 rv = ValueOf(&xa).Elem()
3568 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3569 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3570 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3573 rv = ValueOf(&s).Elem()
3574 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3576 rv = ValueOf(&xs).Elem()
3577 rv = rv.Slice3(3, 5, 7)
3578 ptr2 := rv.UnsafePointer()
3579 rv = rv.Slice3(4, 4, 4)
3580 ptr3 := rv.UnsafePointer()
3582 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3586 func TestSetLenCap(t *testing.T) {
3587 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3588 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3590 vs := ValueOf(&xs).Elem()
3591 shouldPanic("SetLen", func() { vs.SetLen(10) })
3592 shouldPanic("SetCap", func() { vs.SetCap(10) })
3593 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3594 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3595 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3597 if len(xs) != 5 || cap(xs) != 8 {
3598 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3601 if len(xs) != 5 || cap(xs) != 6 {
3602 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3605 if len(xs) != 5 || cap(xs) != 5 {
3606 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3608 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3609 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3611 va := ValueOf(&xa).Elem()
3612 shouldPanic("SetLen", func() { va.SetLen(8) })
3613 shouldPanic("SetCap", func() { va.SetCap(8) })
3616 func TestVariadic(t *testing.T) {
3621 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3622 if b.String() != "hello, 42 world" {
3623 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3627 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3628 if b.String() != "hello, 42 world" {
3629 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3633 func TestFuncArg(t *testing.T) {
3634 f1 := func(i int, f func(int) int) int { return f(i) }
3635 f2 := func(i int) int { return i + 1 }
3636 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3637 if r[0].Int() != 101 {
3638 t.Errorf("function returned %d, want 101", r[0].Int())
3642 func TestStructArg(t *testing.T) {
3643 type padded struct {
3650 wantA = padded{"3", 4}
3653 f := func(a padded, b uint32) {
3656 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3657 if gotA != wantA || gotB != wantB {
3658 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3662 var tagGetTests = []struct {
3667 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3668 {`protobuf:"PB(1,2)"`, `foo`, ``},
3669 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3670 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3671 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3672 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3673 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3676 func TestTagGet(t *testing.T) {
3677 for _, tt := range tagGetTests {
3678 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3679 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3684 func TestBytes(t *testing.T) {
3687 y := ValueOf(x).Bytes()
3688 if !bytes.Equal(x, y) {
3689 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3692 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3696 func TestSetBytes(t *testing.T) {
3699 y := []byte{1, 2, 3, 4}
3700 ValueOf(&x).Elem().SetBytes(y)
3701 if !bytes.Equal(x, y) {
3702 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3705 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3709 type Private struct {
3715 func (p *Private) m() {
3718 type private struct {
3726 func (p *private) P() {
3729 type Public struct {
3735 func (p *Public) M() {
3738 func TestUnexported(t *testing.T) {
3743 isValid(v.Elem().Field(0))
3744 isValid(v.Elem().Field(1))
3745 isValid(v.Elem().Field(2))
3746 isValid(v.Elem().FieldByName("X"))
3747 isValid(v.Elem().FieldByName("Y"))
3748 isValid(v.Elem().FieldByName("Z"))
3749 isValid(v.Type().Method(0).Func)
3750 m, _ := v.Type().MethodByName("M")
3752 m, _ = v.Type().MethodByName("P")
3754 isNonNil(v.Elem().Field(0).Interface())
3755 isNonNil(v.Elem().Field(1).Interface())
3756 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3757 isNonNil(v.Elem().FieldByName("X").Interface())
3758 isNonNil(v.Elem().FieldByName("Y").Interface())
3759 isNonNil(v.Elem().FieldByName("Z").Interface())
3760 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3761 isNonNil(v.Type().Method(0).Func.Interface())
3762 m, _ = v.Type().MethodByName("P")
3763 isNonNil(m.Func.Interface())
3767 isValid(v.Elem().Field(0))
3768 isValid(v.Elem().Field(1))
3769 isValid(v.Elem().FieldByName("x"))
3770 isValid(v.Elem().FieldByName("y"))
3771 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3772 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3773 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3774 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3775 shouldPanic("Method", func() { v.Type().Method(0) })
3778 func TestSetPanic(t *testing.T) {
3779 ok := func(f func()) { f() }
3780 bad := func(f func()) { shouldPanic("Set", f) }
3781 clear := func(v Value) { v.Set(Zero(v.Type())) }
3809 bad(func() { clear(v.Field(0)) }) // .X
3810 bad(func() { clear(v.Field(1)) }) // .t1
3811 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3812 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3813 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3814 bad(func() { clear(v.Field(2)) }) // .T2
3815 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3816 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3817 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3818 bad(func() { clear(v.Field(3)) }) // .NamedT1
3819 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3820 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3821 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3822 bad(func() { clear(v.Field(4)) }) // .NamedT2
3823 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3824 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3825 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3826 bad(func() { clear(v.Field(5)) }) // .namedT1
3827 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3828 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3829 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3830 bad(func() { clear(v.Field(6)) }) // .namedT2
3831 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3832 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3833 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3836 v = ValueOf(&T{}).Elem()
3837 ok(func() { clear(v.Field(0)) }) // .X
3838 bad(func() { clear(v.Field(1)) }) // .t1
3839 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3840 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3841 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3842 ok(func() { clear(v.Field(2)) }) // .T2
3843 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3844 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3845 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3846 ok(func() { clear(v.Field(3)) }) // .NamedT1
3847 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3848 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3849 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3850 ok(func() { clear(v.Field(4)) }) // .NamedT2
3851 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3852 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3853 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3854 bad(func() { clear(v.Field(5)) }) // .namedT1
3855 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3856 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3857 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3858 bad(func() { clear(v.Field(6)) }) // .namedT2
3859 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3860 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3861 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3866 func (t timp) W() {}
3867 func (t timp) Y() {}
3868 func (t timp) w() {}
3869 func (t timp) y() {}
3871 func TestCallPanic(t *testing.T) {
3896 ok := func(f func()) { f() }
3897 badCall := func(f func()) { shouldPanic("Call", f) }
3898 badMethod := func(f func()) { shouldPanic("Method", f) }
3899 call := func(v Value) { v.Call(nil) }
3902 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3903 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3904 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3905 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3906 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3907 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3908 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3909 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3910 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3912 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3913 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3914 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3915 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3917 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3918 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3919 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3920 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3922 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3923 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3924 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3925 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3927 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3928 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3929 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3930 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3932 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3933 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3934 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3935 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3937 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3938 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3939 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3940 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3943 func shouldPanic(expect string, f func()) {
3947 panic("did not panic")
3951 switch r := r.(type) {
3957 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3959 if !strings.HasPrefix(s, "reflect") {
3960 panic(`panic string does not start with "reflect": ` + s)
3962 if !strings.Contains(s, expect) {
3963 panic(`panic string does not contain "` + expect + `": ` + s)
3970 func isNonNil(x interface{}) {
3972 panic("nil interface")
3976 func isValid(v Value) {
3982 func TestAlias(t *testing.T) {
3983 x := string("hello")
3984 v := ValueOf(&x).Elem()
3985 oldvalue := v.Interface()
3986 v.SetString("world")
3987 newvalue := v.Interface()
3989 if oldvalue != "hello" || newvalue != "world" {
3990 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3996 func EmptyInterfaceV(x interface{}) Value {
3997 return ValueOf(&x).Elem()
4000 func ReaderV(x io.Reader) Value {
4001 return ValueOf(&x).Elem()
4004 func ReadWriterV(x io.ReadWriter) Value {
4005 return ValueOf(&x).Elem()
4009 type MyStruct struct {
4012 type MyStruct1 struct {
4017 type MyStruct2 struct {
4022 type MyString string
4024 type MyBytesArrayPtr0 *[0]byte
4025 type MyBytesArrayPtr *[4]byte
4026 type MyBytesArray0 [0]byte
4027 type MyBytesArray [4]byte
4028 type MyRunes []int32
4032 type IntChan chan int
4033 type IntChanRecv <-chan int
4034 type IntChanSend chan<- int
4035 type BytesChan chan []byte
4036 type BytesChanRecv <-chan []byte
4037 type BytesChanSend chan<- []byte
4039 var convertTests = []struct {
4045 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4051 var numbers = []string{
4052 "int8", "uint8", "int16", "uint16",
4053 "int32", "uint32", "int64", "uint64",
4054 "int", "uint", "uintptr",
4055 "float32", "float64",
4059 // all pairs but in an unusual order,
4060 // to emit all the int8, uint8 cases
4061 // before n grows too big.
4063 for i, f := range numbers {
4064 for _, g := range numbers[i:] {
4065 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4068 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4075 {V(int8(1)), V(int8(1))},
4076 {V(int8(2)), V(uint8(2))},
4077 {V(uint8(3)), V(int8(3))},
4078 {V(int8(4)), V(int16(4))},
4079 {V(int16(5)), V(int8(5))},
4080 {V(int8(6)), V(uint16(6))},
4081 {V(uint16(7)), V(int8(7))},
4082 {V(int8(8)), V(int32(8))},
4083 {V(int32(9)), V(int8(9))},
4084 {V(int8(10)), V(uint32(10))},
4085 {V(uint32(11)), V(int8(11))},
4086 {V(int8(12)), V(int64(12))},
4087 {V(int64(13)), V(int8(13))},
4088 {V(int8(14)), V(uint64(14))},
4089 {V(uint64(15)), V(int8(15))},
4090 {V(int8(16)), V(int(16))},
4091 {V(int(17)), V(int8(17))},
4092 {V(int8(18)), V(uint(18))},
4093 {V(uint(19)), V(int8(19))},
4094 {V(int8(20)), V(uintptr(20))},
4095 {V(uintptr(21)), V(int8(21))},
4096 {V(int8(22)), V(float32(22))},
4097 {V(float32(23)), V(int8(23))},
4098 {V(int8(24)), V(float64(24))},
4099 {V(float64(25)), V(int8(25))},
4100 {V(uint8(26)), V(uint8(26))},
4101 {V(uint8(27)), V(int16(27))},
4102 {V(int16(28)), V(uint8(28))},
4103 {V(uint8(29)), V(uint16(29))},
4104 {V(uint16(30)), V(uint8(30))},
4105 {V(uint8(31)), V(int32(31))},
4106 {V(int32(32)), V(uint8(32))},
4107 {V(uint8(33)), V(uint32(33))},
4108 {V(uint32(34)), V(uint8(34))},
4109 {V(uint8(35)), V(int64(35))},
4110 {V(int64(36)), V(uint8(36))},
4111 {V(uint8(37)), V(uint64(37))},
4112 {V(uint64(38)), V(uint8(38))},
4113 {V(uint8(39)), V(int(39))},
4114 {V(int(40)), V(uint8(40))},
4115 {V(uint8(41)), V(uint(41))},
4116 {V(uint(42)), V(uint8(42))},
4117 {V(uint8(43)), V(uintptr(43))},
4118 {V(uintptr(44)), V(uint8(44))},
4119 {V(uint8(45)), V(float32(45))},
4120 {V(float32(46)), V(uint8(46))},
4121 {V(uint8(47)), V(float64(47))},
4122 {V(float64(48)), V(uint8(48))},
4123 {V(int16(49)), V(int16(49))},
4124 {V(int16(50)), V(uint16(50))},
4125 {V(uint16(51)), V(int16(51))},
4126 {V(int16(52)), V(int32(52))},
4127 {V(int32(53)), V(int16(53))},
4128 {V(int16(54)), V(uint32(54))},
4129 {V(uint32(55)), V(int16(55))},
4130 {V(int16(56)), V(int64(56))},
4131 {V(int64(57)), V(int16(57))},
4132 {V(int16(58)), V(uint64(58))},
4133 {V(uint64(59)), V(int16(59))},
4134 {V(int16(60)), V(int(60))},
4135 {V(int(61)), V(int16(61))},
4136 {V(int16(62)), V(uint(62))},
4137 {V(uint(63)), V(int16(63))},
4138 {V(int16(64)), V(uintptr(64))},
4139 {V(uintptr(65)), V(int16(65))},
4140 {V(int16(66)), V(float32(66))},
4141 {V(float32(67)), V(int16(67))},
4142 {V(int16(68)), V(float64(68))},
4143 {V(float64(69)), V(int16(69))},
4144 {V(uint16(70)), V(uint16(70))},
4145 {V(uint16(71)), V(int32(71))},
4146 {V(int32(72)), V(uint16(72))},
4147 {V(uint16(73)), V(uint32(73))},
4148 {V(uint32(74)), V(uint16(74))},
4149 {V(uint16(75)), V(int64(75))},
4150 {V(int64(76)), V(uint16(76))},
4151 {V(uint16(77)), V(uint64(77))},
4152 {V(uint64(78)), V(uint16(78))},
4153 {V(uint16(79)), V(int(79))},
4154 {V(int(80)), V(uint16(80))},
4155 {V(uint16(81)), V(uint(81))},
4156 {V(uint(82)), V(uint16(82))},
4157 {V(uint16(83)), V(uintptr(83))},
4158 {V(uintptr(84)), V(uint16(84))},
4159 {V(uint16(85)), V(float32(85))},
4160 {V(float32(86)), V(uint16(86))},
4161 {V(uint16(87)), V(float64(87))},
4162 {V(float64(88)), V(uint16(88))},
4163 {V(int32(89)), V(int32(89))},
4164 {V(int32(90)), V(uint32(90))},
4165 {V(uint32(91)), V(int32(91))},
4166 {V(int32(92)), V(int64(92))},
4167 {V(int64(93)), V(int32(93))},
4168 {V(int32(94)), V(uint64(94))},
4169 {V(uint64(95)), V(int32(95))},
4170 {V(int32(96)), V(int(96))},
4171 {V(int(97)), V(int32(97))},
4172 {V(int32(98)), V(uint(98))},
4173 {V(uint(99)), V(int32(99))},
4174 {V(int32(100)), V(uintptr(100))},
4175 {V(uintptr(101)), V(int32(101))},
4176 {V(int32(102)), V(float32(102))},
4177 {V(float32(103)), V(int32(103))},
4178 {V(int32(104)), V(float64(104))},
4179 {V(float64(105)), V(int32(105))},
4180 {V(uint32(106)), V(uint32(106))},
4181 {V(uint32(107)), V(int64(107))},
4182 {V(int64(108)), V(uint32(108))},
4183 {V(uint32(109)), V(uint64(109))},
4184 {V(uint64(110)), V(uint32(110))},
4185 {V(uint32(111)), V(int(111))},
4186 {V(int(112)), V(uint32(112))},
4187 {V(uint32(113)), V(uint(113))},
4188 {V(uint(114)), V(uint32(114))},
4189 {V(uint32(115)), V(uintptr(115))},
4190 {V(uintptr(116)), V(uint32(116))},
4191 {V(uint32(117)), V(float32(117))},
4192 {V(float32(118)), V(uint32(118))},
4193 {V(uint32(119)), V(float64(119))},
4194 {V(float64(120)), V(uint32(120))},
4195 {V(int64(121)), V(int64(121))},
4196 {V(int64(122)), V(uint64(122))},
4197 {V(uint64(123)), V(int64(123))},
4198 {V(int64(124)), V(int(124))},
4199 {V(int(125)), V(int64(125))},
4200 {V(int64(126)), V(uint(126))},
4201 {V(uint(127)), V(int64(127))},
4202 {V(int64(128)), V(uintptr(128))},
4203 {V(uintptr(129)), V(int64(129))},
4204 {V(int64(130)), V(float32(130))},
4205 {V(float32(131)), V(int64(131))},
4206 {V(int64(132)), V(float64(132))},
4207 {V(float64(133)), V(int64(133))},
4208 {V(uint64(134)), V(uint64(134))},
4209 {V(uint64(135)), V(int(135))},
4210 {V(int(136)), V(uint64(136))},
4211 {V(uint64(137)), V(uint(137))},
4212 {V(uint(138)), V(uint64(138))},
4213 {V(uint64(139)), V(uintptr(139))},
4214 {V(uintptr(140)), V(uint64(140))},
4215 {V(uint64(141)), V(float32(141))},
4216 {V(float32(142)), V(uint64(142))},
4217 {V(uint64(143)), V(float64(143))},
4218 {V(float64(144)), V(uint64(144))},
4219 {V(int(145)), V(int(145))},
4220 {V(int(146)), V(uint(146))},
4221 {V(uint(147)), V(int(147))},
4222 {V(int(148)), V(uintptr(148))},
4223 {V(uintptr(149)), V(int(149))},
4224 {V(int(150)), V(float32(150))},
4225 {V(float32(151)), V(int(151))},
4226 {V(int(152)), V(float64(152))},
4227 {V(float64(153)), V(int(153))},
4228 {V(uint(154)), V(uint(154))},
4229 {V(uint(155)), V(uintptr(155))},
4230 {V(uintptr(156)), V(uint(156))},
4231 {V(uint(157)), V(float32(157))},
4232 {V(float32(158)), V(uint(158))},
4233 {V(uint(159)), V(float64(159))},
4234 {V(float64(160)), V(uint(160))},
4235 {V(uintptr(161)), V(uintptr(161))},
4236 {V(uintptr(162)), V(float32(162))},
4237 {V(float32(163)), V(uintptr(163))},
4238 {V(uintptr(164)), V(float64(164))},
4239 {V(float64(165)), V(uintptr(165))},
4240 {V(float32(166)), V(float32(166))},
4241 {V(float32(167)), V(float64(167))},
4242 {V(float64(168)), V(float32(168))},
4243 {V(float64(169)), V(float64(169))},
4246 {V(float64(1.5)), V(int(1))},
4249 {V(complex64(1i)), V(complex64(1i))},
4250 {V(complex64(2i)), V(complex128(2i))},
4251 {V(complex128(3i)), V(complex64(3i))},
4252 {V(complex128(4i)), V(complex128(4i))},
4255 {V(string("hello")), V(string("hello"))},
4256 {V(string("bytes1")), V([]byte("bytes1"))},
4257 {V([]byte("bytes2")), V(string("bytes2"))},
4258 {V([]byte("bytes3")), V([]byte("bytes3"))},
4259 {V(string("runes♝")), V([]rune("runes♝"))},
4260 {V([]rune("runes♕")), V(string("runes♕"))},
4261 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4262 {V(int('a')), V(string("a"))},
4263 {V(int8('a')), V(string("a"))},
4264 {V(int16('a')), V(string("a"))},
4265 {V(int32('a')), V(string("a"))},
4266 {V(int64('a')), V(string("a"))},
4267 {V(uint('a')), V(string("a"))},
4268 {V(uint8('a')), V(string("a"))},
4269 {V(uint16('a')), V(string("a"))},
4270 {V(uint32('a')), V(string("a"))},
4271 {V(uint64('a')), V(string("a"))},
4272 {V(uintptr('a')), V(string("a"))},
4273 {V(int(-1)), V(string("\uFFFD"))},
4274 {V(int8(-2)), V(string("\uFFFD"))},
4275 {V(int16(-3)), V(string("\uFFFD"))},
4276 {V(int32(-4)), V(string("\uFFFD"))},
4277 {V(int64(-5)), V(string("\uFFFD"))},
4278 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4279 {V(int64(1 << 32)), V(string("\uFFFD"))},
4280 {V(uint(0x110001)), V(string("\uFFFD"))},
4281 {V(uint32(0x110002)), V(string("\uFFFD"))},
4282 {V(uint64(0x110003)), V(string("\uFFFD"))},
4283 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4284 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4287 {V(MyString("hello")), V(string("hello"))},
4288 {V(string("hello")), V(MyString("hello"))},
4289 {V(string("hello")), V(string("hello"))},
4290 {V(MyString("hello")), V(MyString("hello"))},
4291 {V(MyString("bytes1")), V([]byte("bytes1"))},
4292 {V([]byte("bytes2")), V(MyString("bytes2"))},
4293 {V([]byte("bytes3")), V([]byte("bytes3"))},
4294 {V(MyString("runes♝")), V([]rune("runes♝"))},
4295 {V([]rune("runes♕")), V(MyString("runes♕"))},
4296 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4297 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4298 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4299 {V(int('a')), V(MyString("a"))},
4300 {V(int8('a')), V(MyString("a"))},
4301 {V(int16('a')), V(MyString("a"))},
4302 {V(int32('a')), V(MyString("a"))},
4303 {V(int64('a')), V(MyString("a"))},
4304 {V(uint('a')), V(MyString("a"))},
4305 {V(uint8('a')), V(MyString("a"))},
4306 {V(uint16('a')), V(MyString("a"))},
4307 {V(uint32('a')), V(MyString("a"))},
4308 {V(uint64('a')), V(MyString("a"))},
4309 {V(uintptr('a')), V(MyString("a"))},
4310 {V(int(-1)), V(MyString("\uFFFD"))},
4311 {V(int8(-2)), V(MyString("\uFFFD"))},
4312 {V(int16(-3)), V(MyString("\uFFFD"))},
4313 {V(int32(-4)), V(MyString("\uFFFD"))},
4314 {V(int64(-5)), V(MyString("\uFFFD"))},
4315 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4316 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4317 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4318 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4321 {V(string("bytes1")), V(MyBytes("bytes1"))},
4322 {V(MyBytes("bytes2")), V(string("bytes2"))},
4323 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4324 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4325 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4328 {V(string("runes♝")), V(MyRunes("runes♝"))},
4329 {V(MyRunes("runes♕")), V(string("runes♕"))},
4330 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4331 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4332 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4334 // slice to array pointer
4335 {V([]byte(nil)), V((*[0]byte)(nil))},
4336 {V([]byte{}), V(new([0]byte))},
4337 {V([]byte{7}), V(&[1]byte{7})},
4338 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4339 {V(MyBytes([]byte{})), V(new([0]byte))},
4340 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4341 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4342 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4343 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4344 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4345 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4347 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4348 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4349 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4350 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4351 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4352 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4353 {V(new([0]byte)), V(new(MyBytesArray0))},
4354 {V(new(MyBytesArray0)), V(new([0]byte))},
4355 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4356 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4358 // named types and equal underlying types
4359 {V(new(int)), V(new(integer))},
4360 {V(new(integer)), V(new(int))},
4361 {V(Empty{}), V(struct{}{})},
4362 {V(new(Empty)), V(new(struct{}))},
4363 {V(struct{}{}), V(Empty{})},
4364 {V(new(struct{})), V(new(Empty))},
4365 {V(Empty{}), V(Empty{})},
4366 {V(MyBytes{}), V([]byte{})},
4367 {V([]byte{}), V(MyBytes{})},
4368 {V((func())(nil)), V(MyFunc(nil))},
4369 {V((MyFunc)(nil)), V((func())(nil))},
4371 // structs with different tags
4384 {V(MyStruct{}), V(struct {
4390 }{}), V(MyStruct{})},
4392 {V(MyStruct{}), V(struct {
4398 }{}), V(MyStruct{})},
4400 {V(MyStruct1{}), V(MyStruct2{})},
4401 {V(MyStruct2{}), V(MyStruct1{})},
4403 // can convert *byte and *MyByte
4404 {V((*byte)(nil)), V((*MyByte)(nil))},
4405 {V((*MyByte)(nil)), V((*byte)(nil))},
4407 // cannot convert mismatched array sizes
4408 {V([2]byte{}), V([2]byte{})},
4409 {V([3]byte{}), V([3]byte{})},
4411 // cannot convert other instances
4412 {V((**byte)(nil)), V((**byte)(nil))},
4413 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4414 {V((chan byte)(nil)), V((chan byte)(nil))},
4415 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4416 {V(([]byte)(nil)), V(([]byte)(nil))},
4417 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4418 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4419 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4420 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4421 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4422 {V([2]byte{}), V([2]byte{})},
4423 {V([2]MyByte{}), V([2]MyByte{})},
4426 {V((***int)(nil)), V((***int)(nil))},
4427 {V((***byte)(nil)), V((***byte)(nil))},
4428 {V((***int32)(nil)), V((***int32)(nil))},
4429 {V((***int64)(nil)), V((***int64)(nil))},
4430 {V((chan byte)(nil)), V((chan byte)(nil))},
4431 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4432 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4433 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4434 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4435 {V([]uint(nil)), V([]uint(nil))},
4436 {V([]int(nil)), V([]int(nil))},
4437 {V(new(interface{})), V(new(interface{}))},
4438 {V(new(io.Reader)), V(new(io.Reader))},
4439 {V(new(io.Writer)), V(new(io.Writer))},
4442 {V(IntChan(nil)), V((chan<- int)(nil))},
4443 {V(IntChan(nil)), V((<-chan int)(nil))},
4444 {V((chan int)(nil)), V(IntChanRecv(nil))},
4445 {V((chan int)(nil)), V(IntChanSend(nil))},
4446 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4447 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4448 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4449 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4450 {V(IntChan(nil)), V((chan int)(nil))},
4451 {V((chan int)(nil)), V(IntChan(nil))},
4452 {V((chan int)(nil)), V((<-chan int)(nil))},
4453 {V((chan int)(nil)), V((chan<- int)(nil))},
4454 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4455 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4456 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4457 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4458 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4459 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4460 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4461 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4462 {V(BytesChan(nil)), V((chan []byte)(nil))},
4463 {V((chan []byte)(nil)), V(BytesChan(nil))},
4464 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4465 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4467 // cannot convert other instances (channels)
4468 {V(IntChan(nil)), V(IntChan(nil))},
4469 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4470 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4471 {V(BytesChan(nil)), V(BytesChan(nil))},
4472 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4473 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4476 {V(int(1)), EmptyInterfaceV(int(1))},
4477 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4478 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4479 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4480 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4483 func TestConvert(t *testing.T) {
4484 canConvert := map[[2]Type]bool{}
4485 all := map[Type]bool{}
4487 for _, tt := range convertTests {
4489 if !t1.ConvertibleTo(t1) {
4490 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4495 if !t1.ConvertibleTo(t2) {
4496 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4502 canConvert[[2]Type{t1, t2}] = true
4504 // vout1 represents the in value converted to the in type.
4506 if !v1.CanConvert(t1) {
4507 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4509 vout1 := v1.Convert(t1)
4510 out1 := vout1.Interface()
4511 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4512 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4515 // vout2 represents the in value converted to the out type.
4516 if !v1.CanConvert(t2) {
4517 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4519 vout2 := v1.Convert(t2)
4520 out2 := vout2.Interface()
4521 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4522 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4524 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4525 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4528 // vout3 represents a new value of the out type, set to vout2. This makes
4529 // sure the converted value vout2 is really usable as a regular value.
4530 vout3 := New(t2).Elem()
4532 out3 := vout3.Interface()
4533 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4534 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4538 t.Errorf("table entry %v is RO, should not be", v1)
4541 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4544 t.Errorf("conversion output %v is RO, should not be", vout2)
4547 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4549 if !IsRO(MakeRO(v1).Convert(t1)) {
4550 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4552 if !IsRO(MakeRO(v1).Convert(t2)) {
4553 t.Errorf("RO conversion output %v is not RO, should be", v1)
4557 // Assume that of all the types we saw during the tests,
4558 // if there wasn't an explicit entry for a conversion between
4559 // a pair of types, then it's not to be allowed. This checks for
4560 // things like 'int64' converting to '*int'.
4561 for t1 := range all {
4562 for t2 := range all {
4563 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4564 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4565 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4571 func TestConvertPanic(t *testing.T) {
4572 s := make([]byte, 4)
4576 if !v.Type().ConvertibleTo(pt) {
4577 t.Errorf("[]byte should be convertible to *[8]byte")
4579 if v.CanConvert(pt) {
4580 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4582 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4587 var gFloat32 float32
4589 const snan uint32 = 0x7f800001
4591 func TestConvertNaNs(t *testing.T) {
4592 // Test to see if a store followed by a load of a signaling NaN
4593 // maintains the signaling bit. (This used to fail on the 387 port.)
4594 gFloat32 = math.Float32frombits(snan)
4595 runtime.Gosched() // make sure we don't optimize the store/load away
4596 if got := math.Float32bits(gFloat32); got != snan {
4597 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4599 // Test reflect's conversion between float32s. See issue 36400.
4600 type myFloat32 float32
4601 x := V(myFloat32(math.Float32frombits(snan)))
4602 y := x.Convert(TypeOf(float32(0)))
4603 z := y.Interface().(float32)
4604 if got := math.Float32bits(z); got != snan {
4605 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4609 type ComparableStruct struct {
4613 type NonComparableStruct struct {
4618 var comparableTests = []struct {
4623 {TypeOf("hello"), true},
4624 {TypeOf(new(byte)), true},
4625 {TypeOf((func())(nil)), false},
4626 {TypeOf([]byte{}), false},
4627 {TypeOf(map[string]int{}), false},
4628 {TypeOf(make(chan int)), true},
4629 {TypeOf(1.5), true},
4630 {TypeOf(false), true},
4632 {TypeOf(ComparableStruct{}), true},
4633 {TypeOf(NonComparableStruct{}), false},
4634 {TypeOf([10]map[string]int{}), false},
4635 {TypeOf([10]string{}), true},
4636 {TypeOf(new(interface{})).Elem(), true},
4639 func TestComparable(t *testing.T) {
4640 for _, tt := range comparableTests {
4641 if ok := tt.typ.Comparable(); ok != tt.ok {
4642 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4647 func TestOverflow(t *testing.T) {
4648 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4649 t.Errorf("%v wrongly overflows float64", 1e300)
4652 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4653 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4654 t.Errorf("%v wrongly overflows float32", maxFloat32)
4656 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4657 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4658 t.Errorf("%v should overflow float32", ovfFloat32)
4660 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4661 t.Errorf("%v should overflow float32", -ovfFloat32)
4664 maxInt32 := int64(0x7fffffff)
4665 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4666 t.Errorf("%v wrongly overflows int32", maxInt32)
4668 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4669 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4671 ovfInt32 := int64(1 << 31)
4672 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4673 t.Errorf("%v should overflow int32", ovfInt32)
4676 maxUint32 := uint64(0xffffffff)
4677 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4678 t.Errorf("%v wrongly overflows uint32", maxUint32)
4680 ovfUint32 := uint64(1 << 32)
4681 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4682 t.Errorf("%v should overflow uint32", ovfUint32)
4686 func checkSameType(t *testing.T, x Type, y interface{}) {
4687 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4688 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4692 func TestArrayOf(t *testing.T) {
4693 // check construction and use of type not in binary
4696 value func(i int) interface{}
4702 value: func(i int) interface{} { type Tint int; return Tint(i) },
4708 value: func(i int) interface{} { type Tint int; return Tint(i) },
4710 want: "[0 1 2 3 4 5 6 7 8 9]",
4714 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
4716 want: "[0 1 2 3 4 5 6 7 8 9]",
4720 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
4722 want: "[0 1 2 3 4 5 6 7 8 9]",
4726 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
4728 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4732 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
4734 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4738 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
4740 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4744 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4746 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4750 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4752 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4756 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4758 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4762 value: func(i int) interface{} {
4763 type TstructUV struct {
4767 return TstructUV{i, float64(i)}
4770 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4774 for _, table := range tests {
4775 at := ArrayOf(table.n, TypeOf(table.value(0)))
4777 vok := New(at).Elem()
4778 vnot := New(at).Elem()
4779 for i := 0; i < v.Len(); i++ {
4780 v.Index(i).Set(ValueOf(table.value(i)))
4781 vok.Index(i).Set(ValueOf(table.value(i)))
4786 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4788 s := fmt.Sprint(v.Interface())
4789 if s != table.want {
4790 t.Errorf("constructed array = %s, want %s", s, table.want)
4793 if table.comparable != at.Comparable() {
4794 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4796 if table.comparable {
4798 if DeepEqual(vnot.Interface(), v.Interface()) {
4800 "arrays (%#v) compare ok (but should not)",
4805 if !DeepEqual(vok.Interface(), v.Interface()) {
4807 "arrays (%#v) compare NOT-ok (but should)",
4814 // check that type already in binary is found
4816 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4819 func TestArrayOfGC(t *testing.T) {
4821 tt := TypeOf(T(nil))
4824 for i := 0; i < n; i++ {
4825 v := New(ArrayOf(n, tt)).Elem()
4826 for j := 0; j < v.Len(); j++ {
4828 *p = uintptr(i*n + j)
4829 v.Index(j).Set(ValueOf(p).Convert(tt))
4831 x = append(x, v.Interface())
4835 for i, xi := range x {
4837 for j := 0; j < v.Len(); j++ {
4838 k := v.Index(j).Elem().Interface()
4839 if k != uintptr(i*n+j) {
4840 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4846 func TestArrayOfAlg(t *testing.T) {
4847 at := ArrayOf(6, TypeOf(byte(0)))
4848 v1 := New(at).Elem()
4849 v2 := New(at).Elem()
4850 if v1.Interface() != v1.Interface() {
4851 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4853 v1.Index(5).Set(ValueOf(byte(1)))
4854 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4855 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4858 at = ArrayOf(6, TypeOf([]int(nil)))
4860 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4863 func TestArrayOfGenericAlg(t *testing.T) {
4864 at1 := ArrayOf(5, TypeOf(string("")))
4865 at := ArrayOf(6, at1)
4866 v1 := New(at).Elem()
4867 v2 := New(at).Elem()
4868 if v1.Interface() != v1.Interface() {
4869 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4872 v1.Index(0).Index(0).Set(ValueOf("abc"))
4873 v2.Index(0).Index(0).Set(ValueOf("efg"))
4874 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4875 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4878 v1.Index(0).Index(0).Set(ValueOf("abc"))
4879 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4880 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4881 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4885 m := MakeMap(MapOf(at, TypeOf(int(0))))
4886 m.SetMapIndex(v1, ValueOf(1))
4887 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4888 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4892 func TestArrayOfDirectIface(t *testing.T) {
4895 i1 := Zero(TypeOf(T{})).Interface()
4896 v1 := ValueOf(&i1).Elem()
4897 p1 := v1.InterfaceData()[1]
4899 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4900 v2 := ValueOf(&i2).Elem()
4901 p2 := v2.InterfaceData()[1]
4904 t.Errorf("got p1=%v. want=%v", p1, nil)
4908 t.Errorf("got p2=%v. want=%v", p2, nil)
4913 i1 := Zero(TypeOf(T{})).Interface()
4914 v1 := ValueOf(&i1).Elem()
4915 p1 := v1.InterfaceData()[1]
4917 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4918 v2 := ValueOf(&i2).Elem()
4919 p2 := v2.InterfaceData()[1]
4922 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4926 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4931 // Ensure passing in negative lengths panics.
4932 // See https://golang.org/issue/43603
4933 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4934 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4935 ArrayOf(-1, TypeOf(byte(0)))
4939 func TestSliceOf(t *testing.T) {
4940 // check construction and use of type not in binary
4942 st := SliceOf(TypeOf(T(1)))
4943 if got, want := st.String(), "[]reflect_test.T"; got != want {
4944 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4946 v := MakeSlice(st, 10, 10)
4948 for i := 0; i < v.Len(); i++ {
4949 v.Index(i).Set(ValueOf(T(i)))
4952 s := fmt.Sprint(v.Interface())
4953 want := "[0 1 2 3 4 5 6 7 8 9]"
4955 t.Errorf("constructed slice = %s, want %s", s, want)
4958 // check that type already in binary is found
4960 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4963 func TestSliceOverflow(t *testing.T) {
4964 // check that MakeSlice panics when size of slice overflows uint
4967 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4969 t.Fatal("slice size does not overflow")
4972 st := SliceOf(TypeOf(x))
4976 t.Fatal("slice overflow does not panic")
4979 MakeSlice(st, int(l), int(l))
4982 func TestSliceOfGC(t *testing.T) {
4984 tt := TypeOf(T(nil))
4988 for i := 0; i < n; i++ {
4989 v := MakeSlice(st, n, n)
4990 for j := 0; j < v.Len(); j++ {
4992 *p = uintptr(i*n + j)
4993 v.Index(j).Set(ValueOf(p).Convert(tt))
4995 x = append(x, v.Interface())
4999 for i, xi := range x {
5001 for j := 0; j < v.Len(); j++ {
5002 k := v.Index(j).Elem().Interface()
5003 if k != uintptr(i*n+j) {
5004 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5010 func TestStructOfFieldName(t *testing.T) {
5011 // invalid field name "1nvalid"
5012 shouldPanic("has invalid name", func() {
5013 StructOf([]StructField{
5014 {Name: "Valid", Type: TypeOf("")},
5015 {Name: "1nvalid", Type: TypeOf("")},
5019 // invalid field name "+"
5020 shouldPanic("has invalid name", func() {
5021 StructOf([]StructField{
5022 {Name: "Val1d", Type: TypeOf("")},
5023 {Name: "+", Type: TypeOf("")},
5028 shouldPanic("has no name", func() {
5029 StructOf([]StructField{
5030 {Name: "", Type: TypeOf("")},
5034 // verify creation of a struct with valid struct fields
5035 validFields := []StructField{
5050 validStruct := StructOf(validFields)
5052 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5053 if got, want := validStruct.String(), structStr; got != want {
5054 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5058 func TestStructOf(t *testing.T) {
5059 // check construction and use of type not in binary
5060 fields := []StructField{
5069 Type: TypeOf(byte(0)),
5073 Type: TypeOf(uint64(0)),
5077 Type: TypeOf([3]uint16{}),
5081 st := StructOf(fields)
5084 v.FieldByName("X").Set(ValueOf(byte(2)))
5085 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5088 s := fmt.Sprint(v.Interface())
5089 want := `{ 1 0 [0 0 0]}`
5091 t.Errorf("constructed struct = %s, want %s", s, want)
5093 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5094 if got, want := st.String(), stStr; got != want {
5095 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5098 // check the size, alignment and field offsets
5099 stt := TypeOf(struct {
5105 if st.Size() != stt.Size() {
5106 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5108 if st.Align() != stt.Align() {
5109 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5111 if st.FieldAlign() != stt.FieldAlign() {
5112 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5114 for i := 0; i < st.NumField(); i++ {
5115 o1 := st.Field(i).Offset
5116 o2 := stt.Field(i).Offset
5118 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5122 // Check size and alignment with a trailing zero-sized field.
5123 st = StructOf([]StructField{
5126 Type: TypeOf(byte(0)),
5130 Type: TypeOf([0]*byte{}),
5133 stt = TypeOf(struct {
5137 if st.Size() != stt.Size() {
5138 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5140 if st.Align() != stt.Align() {
5141 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5143 if st.FieldAlign() != stt.FieldAlign() {
5144 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5146 for i := 0; i < st.NumField(); i++ {
5147 o1 := st.Field(i).Offset
5148 o2 := stt.Field(i).Offset
5150 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5154 // check duplicate names
5155 shouldPanic("duplicate field", func() {
5156 StructOf([]StructField{
5157 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5158 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5161 shouldPanic("has no name", func() {
5162 StructOf([]StructField{
5164 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5167 shouldPanic("has no name", func() {
5168 StructOf([]StructField{
5173 // check that type already in binary is found
5174 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5176 // gccgo used to fail this test.
5177 type structFieldType interface{}
5179 StructOf([]StructField{
5182 Type: TypeOf((*structFieldType)(nil)).Elem(),
5185 struct{ F structFieldType }{})
5188 func TestStructOfExportRules(t *testing.T) {
5194 testPanic := func(i int, mustPanic bool, f func()) {
5197 if err == nil && mustPanic {
5198 t.Errorf("test-%d did not panic", i)
5200 if err != nil && !mustPanic {
5201 t.Errorf("test-%d panicked: %v\n", i, err)
5213 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5217 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5221 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5225 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5229 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5233 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5237 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5241 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5245 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5249 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5253 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5256 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5259 field: StructField{Name: "S", Type: TypeOf(S1{})},
5263 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5267 field: StructField{Name: "S", Type: TypeOf(s2{})},
5271 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5275 field: StructField{Name: "s", Type: TypeOf(S1{})},
5279 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5283 field: StructField{Name: "s", Type: TypeOf(s2{})},
5287 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5291 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5294 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5297 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5300 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5303 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5307 field: StructField{Name: "", Type: TypeOf(φType{})},
5311 field: StructField{Name: "Φ", Type: TypeOf(0)},
5315 field: StructField{Name: "φ", Type: TypeOf(0)},
5320 for i, test := range tests {
5321 testPanic(i, test.mustPanic, func() {
5322 typ := StructOf([]StructField{test.field})
5324 t.Errorf("test-%d: error creating struct type", i)
5327 field := typ.Field(0)
5330 panic("field.Name must not be empty")
5332 exported := token.IsExported(n)
5333 if exported != test.exported {
5334 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5336 if field.PkgPath != test.field.PkgPath {
5337 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5343 func TestStructOfGC(t *testing.T) {
5345 tt := TypeOf(T(nil))
5346 fields := []StructField{
5347 {Name: "X", Type: tt},
5348 {Name: "Y", Type: tt},
5350 st := StructOf(fields)
5354 for i := 0; i < n; i++ {
5356 for j := 0; j < v.NumField(); j++ {
5358 *p = uintptr(i*n + j)
5359 v.Field(j).Set(ValueOf(p).Convert(tt))
5361 x = append(x, v.Interface())
5365 for i, xi := range x {
5367 for j := 0; j < v.NumField(); j++ {
5368 k := v.Field(j).Elem().Interface()
5369 if k != uintptr(i*n+j) {
5370 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5376 func TestStructOfAlg(t *testing.T) {
5377 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5378 v1 := New(st).Elem()
5379 v2 := New(st).Elem()
5380 if !DeepEqual(v1.Interface(), v1.Interface()) {
5381 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5383 v1.FieldByName("X").Set(ValueOf(int(1)))
5384 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5385 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5388 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5390 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5393 func TestStructOfGenericAlg(t *testing.T) {
5394 st1 := StructOf([]StructField{
5395 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5396 {Name: "Y", Type: TypeOf(string(""))},
5398 st := StructOf([]StructField{
5399 {Name: "S0", Type: st1},
5400 {Name: "S1", Type: st1},
5418 {Name: "XX", Type: TypeOf([0]int{})},
5419 {Name: "YY", Type: TypeOf("")},
5427 {Name: "XX", Type: TypeOf([0]int{})},
5428 {Name: "YY", Type: TypeOf("")},
5429 {Name: "ZZ", Type: TypeOf([2]int{})},
5437 {Name: "XX", Type: TypeOf([1]int{})},
5438 {Name: "YY", Type: TypeOf("")},
5446 {Name: "XX", Type: TypeOf([1]int{})},
5447 {Name: "YY", Type: TypeOf("")},
5448 {Name: "ZZ", Type: TypeOf([1]int{})},
5456 {Name: "XX", Type: TypeOf([2]int{})},
5457 {Name: "YY", Type: TypeOf("")},
5458 {Name: "ZZ", Type: TypeOf([2]int{})},
5466 {Name: "XX", Type: TypeOf(int64(0))},
5467 {Name: "YY", Type: TypeOf(byte(0))},
5468 {Name: "ZZ", Type: TypeOf("")},
5476 {Name: "XX", Type: TypeOf(int64(0))},
5477 {Name: "YY", Type: TypeOf(int64(0))},
5478 {Name: "ZZ", Type: TypeOf("")},
5479 {Name: "AA", Type: TypeOf([1]int64{})},
5486 for _, table := range tests {
5487 v1 := New(table.rt).Elem()
5488 v2 := New(table.rt).Elem()
5490 if !DeepEqual(v1.Interface(), v1.Interface()) {
5491 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5494 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5495 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5496 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5497 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5501 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5502 val := "+" + abc + "-"
5503 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5504 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5505 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5509 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5510 m.SetMapIndex(v1, ValueOf(1))
5511 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5512 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5515 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5516 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5517 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5520 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5521 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5526 func TestStructOfDirectIface(t *testing.T) {
5528 type T struct{ X [1]*byte }
5529 i1 := Zero(TypeOf(T{})).Interface()
5530 v1 := ValueOf(&i1).Elem()
5531 p1 := v1.InterfaceData()[1]
5533 i2 := Zero(StructOf([]StructField{
5536 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5539 v2 := ValueOf(&i2).Elem()
5540 p2 := v2.InterfaceData()[1]
5543 t.Errorf("got p1=%v. want=%v", p1, nil)
5547 t.Errorf("got p2=%v. want=%v", p2, nil)
5551 type T struct{ X [0]*byte }
5552 i1 := Zero(TypeOf(T{})).Interface()
5553 v1 := ValueOf(&i1).Elem()
5554 p1 := v1.InterfaceData()[1]
5556 i2 := Zero(StructOf([]StructField{
5559 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5562 v2 := ValueOf(&i2).Elem()
5563 p2 := v2.InterfaceData()[1]
5566 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5570 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5577 func (i StructI) Get() int { return int(i) }
5581 func (i *StructIPtr) Get() int { return int(*i) }
5582 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5584 type SettableStruct struct {
5588 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5590 type SettablePointer struct {
5594 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5596 func TestStructOfWithInterface(t *testing.T) {
5598 type Iface interface {
5601 type IfaceSet interface {
5612 typ: TypeOf(StructI(want)),
5613 val: ValueOf(StructI(want)),
5618 typ: PtrTo(TypeOf(StructI(want))),
5619 val: ValueOf(func() interface{} {
5627 typ: PtrTo(TypeOf(StructIPtr(want))),
5628 val: ValueOf(func() interface{} {
5629 v := StructIPtr(want)
5636 typ: TypeOf(StructIPtr(want)),
5637 val: ValueOf(StructIPtr(want)),
5641 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5642 // val: ValueOf(StructI(want)),
5647 for i, table := range tests {
5648 for j := 0; j < 2; j++ {
5649 var fields []StructField
5651 fields = append(fields, StructField{
5654 Type: TypeOf(int(0)),
5657 fields = append(fields, StructField{
5664 // We currently do not correctly implement methods
5665 // for embedded fields other than the first.
5666 // Therefore, for now, we expect those methods
5667 // to not exist. See issues 15924 and 20824.
5668 // When those issues are fixed, this test of panic
5669 // should be removed.
5670 if j == 1 && table.impl {
5673 if err := recover(); err == nil {
5674 t.Errorf("test-%d-%d did not panic", i, j)
5677 _ = StructOf(fields)
5682 rt := StructOf(fields)
5683 rv := New(rt).Elem()
5684 rv.Field(j).Set(table.val)
5686 if _, ok := rv.Interface().(Iface); ok != table.impl {
5688 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5690 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5699 v := rv.Interface().(Iface).Get()
5701 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5704 fct := rv.MethodByName("Get")
5705 out := fct.Call(nil)
5706 if !DeepEqual(out[0].Interface(), want) {
5707 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5712 // Test an embedded nil pointer with pointer methods.
5713 fields := []StructField{{
5716 Type: PtrTo(TypeOf(StructIPtr(want))),
5718 rt := StructOf(fields)
5719 rv := New(rt).Elem()
5720 // This should panic since the pointer is nil.
5721 shouldPanic("", func() {
5722 rv.Interface().(IfaceSet).Set(want)
5725 // Test an embedded nil pointer to a struct with pointer methods.
5727 fields = []StructField{{
5728 Name: "SettableStruct",
5730 Type: PtrTo(TypeOf(SettableStruct{})),
5732 rt = StructOf(fields)
5734 // This should panic since the pointer is nil.
5735 shouldPanic("", func() {
5736 rv.Interface().(IfaceSet).Set(want)
5739 // The behavior is different if there is a second field,
5740 // since now an interface value holds a pointer to the struct
5741 // rather than just holding a copy of the struct.
5742 fields = []StructField{
5744 Name: "SettableStruct",
5746 Type: PtrTo(TypeOf(SettableStruct{})),
5749 Name: "EmptyStruct",
5751 Type: StructOf(nil),
5754 // With the current implementation this is expected to panic.
5755 // Ideally it should work and we should be able to see a panic
5756 // if we call the Set method.
5757 shouldPanic("", func() {
5761 // Embed a field that can be stored directly in an interface,
5762 // with a second field.
5763 fields = []StructField{
5765 Name: "SettablePointer",
5767 Type: TypeOf(SettablePointer{}),
5770 Name: "EmptyStruct",
5772 Type: StructOf(nil),
5775 // With the current implementation this is expected to panic.
5776 // Ideally it should work and we should be able to call the
5777 // Set and Get methods.
5778 shouldPanic("", func() {
5783 func TestStructOfTooManyFields(t *testing.T) {
5784 // Bug Fix: #25402 - this should not panic
5785 tt := StructOf([]StructField{
5786 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5789 if _, present := tt.MethodByName("After"); !present {
5790 t.Errorf("Expected method `After` to be found")
5794 func TestStructOfDifferentPkgPath(t *testing.T) {
5795 fields := []StructField{
5799 Type: TypeOf(int(0)),
5804 Type: TypeOf(int(0)),
5807 shouldPanic("different PkgPath", func() {
5812 func TestChanOf(t *testing.T) {
5813 // check construction and use of type not in binary
5815 ct := ChanOf(BothDir, TypeOf(T("")))
5816 v := MakeChan(ct, 2)
5818 v.Send(ValueOf(T("hello")))
5820 v.Send(ValueOf(T("world")))
5827 if s1 != "hello" || s2 != "world" {
5828 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5831 // check that type already in binary is found
5833 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5835 // Check arrow token association in undefined chan types.
5836 var left chan<- chan T
5837 var right chan (<-chan T)
5838 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5839 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5840 if tLeft != TypeOf(left) {
5841 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5843 if tRight != TypeOf(right) {
5844 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5848 func TestChanOfDir(t *testing.T) {
5849 // check construction and use of type not in binary
5851 crt := ChanOf(RecvDir, TypeOf(T("")))
5852 cst := ChanOf(SendDir, TypeOf(T("")))
5854 // check that type already in binary is found
5856 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5857 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5859 // check String form of ChanDir
5860 if crt.ChanDir().String() != "<-chan" {
5861 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5863 if cst.ChanDir().String() != "chan<-" {
5864 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5868 func TestChanOfGC(t *testing.T) {
5869 done := make(chan bool, 1)
5873 case <-time.After(5 * time.Second):
5874 panic("deadlock in TestChanOfGC")
5883 tt := TypeOf(T(nil))
5884 ct := ChanOf(BothDir, tt)
5886 // NOTE: The garbage collector handles allocated channels specially,
5887 // so we have to save pointers to channels in x; the pointer code will
5888 // use the gc info in the newly constructed chan type.
5891 for i := 0; i < n; i++ {
5892 v := MakeChan(ct, n)
5893 for j := 0; j < n; j++ {
5895 *p = uintptr(i*n + j)
5896 v.Send(ValueOf(p).Convert(tt))
5900 x = append(x, pv.Interface())
5904 for i, xi := range x {
5905 v := ValueOf(xi).Elem()
5906 for j := 0; j < n; j++ {
5908 k := pv.Elem().Interface()
5909 if k != uintptr(i*n+j) {
5910 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5916 func TestMapOf(t *testing.T) {
5917 // check construction and use of type not in binary
5921 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5923 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5926 s := fmt.Sprint(v.Interface())
5929 t.Errorf("constructed map = %s, want %s", s, want)
5932 // check that type already in binary is found
5933 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5935 // check that invalid key type panics
5936 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5939 func TestMapOfGCKeys(t *testing.T) {
5941 tt := TypeOf(T(nil))
5942 mt := MapOf(tt, TypeOf(false))
5944 // NOTE: The garbage collector handles allocated maps specially,
5945 // so we have to save pointers to maps in x; the pointer code will
5946 // use the gc info in the newly constructed map type.
5949 for i := 0; i < n; i++ {
5951 for j := 0; j < n; j++ {
5953 *p = uintptr(i*n + j)
5954 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5958 x = append(x, pv.Interface())
5962 for i, xi := range x {
5963 v := ValueOf(xi).Elem()
5965 for _, kv := range v.MapKeys() {
5966 out = append(out, int(kv.Elem().Interface().(uintptr)))
5969 for j, k := range out {
5971 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5977 func TestMapOfGCValues(t *testing.T) {
5979 tt := TypeOf(T(nil))
5980 mt := MapOf(TypeOf(1), tt)
5982 // NOTE: The garbage collector handles allocated maps specially,
5983 // so we have to save pointers to maps in x; the pointer code will
5984 // use the gc info in the newly constructed map type.
5987 for i := 0; i < n; i++ {
5989 for j := 0; j < n; j++ {
5991 *p = uintptr(i*n + j)
5992 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5996 x = append(x, pv.Interface())
6000 for i, xi := range x {
6001 v := ValueOf(xi).Elem()
6002 for j := 0; j < n; j++ {
6003 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6004 if k != uintptr(i*n+j) {
6005 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6011 func TestTypelinksSorted(t *testing.T) {
6013 for i, n := range TypeLinks() {
6015 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6021 func TestFuncOf(t *testing.T) {
6022 // check construction and use of type not in binary
6026 fn := func(args []Value) []Value {
6028 t.Errorf("args == %v, want exactly one arg", args)
6029 } else if args[0].Type() != TypeOf(K("")) {
6030 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6031 } else if args[0].String() != "gopher" {
6032 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6034 return []Value{ValueOf(V(3.14))}
6036 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6038 outs := v.Call([]Value{ValueOf(K("gopher"))})
6040 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6041 } else if outs[0].Type() != TypeOf(V(0)) {
6042 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6044 f := outs[0].Float()
6046 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6049 // check that types already in binary are found
6051 testCases := []struct {
6056 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6057 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6058 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6059 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6060 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6062 for _, tt := range testCases {
6063 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6066 // check that variadic requires last element be a slice.
6067 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6068 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6069 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6078 func BenchmarkFieldByName1(b *testing.B) {
6080 b.RunParallel(func(pb *testing.PB) {
6087 func BenchmarkFieldByName2(b *testing.B) {
6089 b.RunParallel(func(pb *testing.PB) {
6166 func TestEmbed(t *testing.T) {
6168 f, ok := typ.FieldByName("X")
6170 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6174 func BenchmarkFieldByName3(b *testing.B) {
6176 b.RunParallel(func(pb *testing.PB) {
6188 func BenchmarkInterfaceBig(b *testing.B) {
6190 b.RunParallel(func(pb *testing.PB) {
6198 func TestAllocsInterfaceBig(t *testing.T) {
6199 if testing.Short() {
6200 t.Skip("skipping malloc count in short mode")
6203 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6204 t.Error("allocs:", allocs)
6208 func BenchmarkInterfaceSmall(b *testing.B) {
6209 v := ValueOf(int64(0))
6210 b.RunParallel(func(pb *testing.PB) {
6217 func TestAllocsInterfaceSmall(t *testing.T) {
6218 if testing.Short() {
6219 t.Skip("skipping malloc count in short mode")
6221 v := ValueOf(int64(0))
6222 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6223 t.Error("allocs:", allocs)
6227 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6228 // The basic usage is:
6231 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6234 // Each iteration of the loop returns a different set of results, until all
6235 // possible result sets have been explored. It is okay for different code paths
6236 // to make different method call sequences on x, but there must be no
6237 // other source of non-determinism in the call sequences.
6239 // When faced with a new decision, x chooses randomly. Future explorations
6240 // of that path will choose successive values for the result. Thus, stopping
6241 // the loop after a fixed number of iterations gives somewhat stochastic
6247 // v := make([]bool, x.Choose(4))
6248 // for i := range v {
6254 // prints (in some order):
6263 // [false false false]
6266 // [false false false false]
6268 // [true true true true]
6270 type exhaustive struct {
6276 type choice struct {
6282 func (x *exhaustive) Next() bool {
6284 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6291 for i := len(x.last) - 1; i >= 0; i-- {
6295 x.last = x.last[:i+1]
6302 func (x *exhaustive) Choose(max int) int {
6303 if x.pos >= len(x.last) {
6304 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6309 panic("inconsistent use of exhaustive tester")
6311 return (c.n + c.off) % max
6314 func (x *exhaustive) Maybe() bool {
6315 return x.Choose(2) == 1
6318 func GCFunc(args []Value) []Value {
6323 func TestReflectFuncTraceback(t *testing.T) {
6324 f := MakeFunc(TypeOf(func() {}), GCFunc)
6328 func TestReflectMethodTraceback(t *testing.T) {
6330 m := ValueOf(p).MethodByName("GCMethod")
6331 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6333 t.Errorf("Call returned %d; want 8", i)
6337 func TestSmallZero(t *testing.T) {
6340 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6341 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6345 func TestBigZero(t *testing.T) {
6346 const size = 1 << 10
6348 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6349 for i := 0; i < size; i++ {
6351 t.Fatalf("Zero object not all zero, index %d", i)
6356 func TestZeroSet(t *testing.T) {
6364 a: 0xaaaaaaaaaaaaaaaa,
6365 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6366 b: 0xbbbbbbbbbbbbbbbb,
6368 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6370 a: 0xaaaaaaaaaaaaaaaa,
6371 b: 0xbbbbbbbbbbbbbbbb,
6373 t.Fatalf("Setting a field to a Zero value didn't work")
6377 func TestFieldByIndexNil(t *testing.T) {
6386 v.FieldByName("P") // should be fine
6389 if err := recover(); err == nil {
6390 t.Fatalf("no error")
6391 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6392 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6395 v.FieldByName("F") // should panic
6397 t.Fatalf("did not panic")
6401 // type Outer struct {
6405 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6406 // The implementation is logically:
6407 // func (p *Outer) M() {
6410 // but since the only change here is the replacement of one pointer receiver with another,
6411 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6412 // then jumps to the M method expecting the *Inner receiver.
6414 // During reflect.Value.Call, we create an argument frame and the associated data structures
6415 // to describe it to the garbage collector, populate the frame, call reflect.call to
6416 // run a function call using that frame, and then copy the results back out of the frame.
6417 // The reflect.call function does a memmove of the frame structure onto the
6418 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6419 // the frame structure (to preserve the outputs).
6421 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6422 // were for the full stack frame. However, in the case where the called function was
6423 // one of these wrappers, the rewritten receiver is almost certainly a different type
6424 // than the original receiver. This is not a problem on the stack, where we use the
6425 // program counter to determine the type information and understand that
6426 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6427 // memory word is now an *Inner. But in the statically typed argument frame created
6428 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6429 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6430 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6431 // memory as if it were an *Outer. If the two have different memory layouts, the
6432 // collection will interpret the memory incorrectly.
6434 // One such possible incorrect interpretation is to treat two arbitrary memory words
6435 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6436 // an interface requires dereferencing the itab word, the misinterpretation will try to
6437 // deference Inner.P1, causing a crash during garbage collection.
6439 // This came up in a real program in issue 7725.
6452 func (pi *Inner) M() {
6453 // Clear references to pi so that the only way the
6454 // garbage collection will find the pointer is in the
6455 // argument frame, typed as a *Outer.
6458 // Set up an interface value that will cause a crash.
6459 // P1 = 1 is a non-zero, so the interface looks non-nil.
6460 // P2 = pi ensures that the data word points into the
6461 // allocated heap; if not the collection skips the interface
6462 // value as irrelevant, without dereferencing P1.
6464 pi.P2 = uintptr(unsafe.Pointer(pi))
6467 func TestCallMethodJump(t *testing.T) {
6468 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6469 // returns but before the args frame has been discarded.
6470 // This is a little clumsy but makes the failure repeatable.
6473 p := &Outer{Inner: new(Inner)}
6475 ValueOf(p).Method(0).Call(nil)
6477 // Stop garbage collecting during reflect.call.
6481 func TestMakeFuncStackCopy(t *testing.T) {
6482 target := func(in []Value) []Value {
6485 return []Value{ValueOf(9)}
6488 var concrete func(*int, int) int
6489 fn := MakeFunc(ValueOf(concrete).Type(), target)
6490 ValueOf(&concrete).Elem().Set(fn)
6491 x := concrete(nil, 7)
6493 t.Errorf("have %#q want 9", x)
6497 // use about n KB of stack
6498 func useStack(n int) {
6502 var b [1024]byte // makes frame about 1KB
6503 useStack(n - 1 + int(b[99]))
6510 func TestValueString(t *testing.T) {
6511 rv := ValueOf(Impl{})
6512 if rv.String() != "<reflect_test.Impl Value>" {
6513 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6516 method := rv.Method(0)
6517 if method.String() != "<func() Value>" {
6518 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6522 func TestInvalid(t *testing.T) {
6523 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6524 type T struct{ v interface{} }
6526 v := ValueOf(T{}).Field(0)
6527 if v.IsValid() != true || v.Kind() != Interface {
6528 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6531 if v.IsValid() != false || v.Kind() != Invalid {
6532 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6537 func TestLargeGCProg(t *testing.T) {
6538 fv := ValueOf(func([256]*byte) {})
6539 fv.Call([]Value{ValueOf([256]*byte{})})
6542 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
6544 recovered = recover()
6552 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6553 typ := TypeOf(struct{ X int }{10})
6554 testIndices := [...]struct {
6563 for i, tt := range testIndices {
6564 recoveredErr := fieldIndexRecover(typ, tt.i)
6566 if recoveredErr == nil {
6567 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6570 if recoveredErr != nil {
6571 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6578 func TestCallGC(t *testing.T) {
6579 f := func(a, b, c, d, e string) {
6581 g := func(in []Value) []Value {
6585 typ := ValueOf(f).Type()
6586 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6587 f2("four", "five5", "six666", "seven77", "eight888")
6590 // Issue 18635 (function version).
6591 func TestKeepFuncLive(t *testing.T) {
6592 // Test that we keep makeFuncImpl live as long as it is
6593 // referenced on the stack.
6594 typ := TypeOf(func(i int) {})
6595 var f, g func(in []Value) []Value
6596 f = func(in []Value) []Value {
6598 i := int(in[0].Int())
6600 // We can't use Value.Call here because
6601 // runtime.call* will keep the makeFuncImpl
6602 // alive. However, by converting it to an
6603 // interface value and calling that,
6604 // reflect.callReflect is the only thing that
6605 // can keep the makeFuncImpl live.
6607 // Alternate between f and g so that if we do
6608 // reuse the memory prematurely it's more
6609 // likely to get obviously corrupted.
6610 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6614 g = func(in []Value) []Value {
6616 i := int(in[0].Int())
6617 MakeFunc(typ, f).Interface().(func(i int))(i)
6620 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6623 type UnExportedFirst int
6625 func (i UnExportedFirst) ΦExported() {}
6626 func (i UnExportedFirst) unexported() {}
6629 func TestMethodByNameUnExportedFirst(t *testing.T) {
6631 if recover() != nil {
6632 t.Errorf("should not panic")
6635 typ := TypeOf(UnExportedFirst(0))
6636 m, _ := typ.MethodByName("ΦExported")
6637 if m.Name != "ΦExported" {
6638 t.Errorf("got %s, expected ΦExported", m.Name)
6642 // Issue 18635 (method version).
6643 type KeepMethodLive struct{}
6645 func (k KeepMethodLive) Method1(i int) {
6648 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6652 func (k KeepMethodLive) Method2(i int) {
6654 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6657 func TestKeepMethodLive(t *testing.T) {
6658 // Test that we keep methodValue live as long as it is
6659 // referenced on the stack.
6660 KeepMethodLive{}.Method1(10)
6663 // clobber tries to clobber unreachable memory.
6666 for i := 1; i < 32; i++ {
6667 for j := 0; j < 10; j++ {
6668 obj := make([]*byte, i)
6675 func TestFuncLayout(t *testing.T) {
6676 align := func(x uintptr) uintptr {
6677 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6680 if goarch.PtrSize == 4 {
6681 r = []byte{0, 0, 0, 1}
6693 size, argsize, retOffset uintptr
6694 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6695 intRegs, floatRegs int
6696 floatRegSize uintptr
6700 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6701 size: 6 * goarch.PtrSize,
6702 argsize: 4 * goarch.PtrSize,
6703 retOffset: 4 * goarch.PtrSize,
6704 stack: []byte{1, 0, 1, 0, 1},
6705 gc: []byte{1, 0, 1, 0, 1},
6708 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6709 size: align(align(3*4) + goarch.PtrSize + 2),
6710 argsize: align(3*4) + goarch.PtrSize + 2,
6711 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6716 typ: ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
6717 size: 4 * goarch.PtrSize,
6718 argsize: 4 * goarch.PtrSize,
6719 retOffset: 4 * goarch.PtrSize,
6720 stack: []byte{1, 0, 1, 1},
6721 gc: []byte{1, 0, 1, 1},
6724 typ: ValueOf(func(a S) {}).Type(),
6725 size: 4 * goarch.PtrSize,
6726 argsize: 4 * goarch.PtrSize,
6727 retOffset: 4 * goarch.PtrSize,
6728 stack: []byte{0, 0, 1, 1},
6729 gc: []byte{0, 0, 1, 1},
6732 rcvr: ValueOf((*byte)(nil)).Type(),
6733 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6734 size: 3 * goarch.PtrSize,
6735 argsize: 3 * goarch.PtrSize,
6736 retOffset: 3 * goarch.PtrSize,
6737 stack: []byte{1, 0, 1},
6738 gc: []byte{1, 0, 1},
6741 typ: ValueOf(func(a uintptr) {}).Type(),
6742 size: goarch.PtrSize,
6743 argsize: goarch.PtrSize,
6744 retOffset: goarch.PtrSize,
6749 typ: ValueOf(func() uintptr { return 0 }).Type(),
6750 size: goarch.PtrSize,
6757 rcvr: ValueOf(uintptr(0)).Type(),
6758 typ: ValueOf(func(a uintptr) {}).Type(),
6759 size: 2 * goarch.PtrSize,
6760 argsize: 2 * goarch.PtrSize,
6761 retOffset: 2 * goarch.PtrSize,
6764 // Note: this one is tricky, as the receiver is not a pointer. But we
6765 // pass the receiver by reference to the autogenerated pointer-receiver
6766 // version of the function.
6768 // TODO(mknyszek): Add tests for non-zero register count.
6770 for _, lt := range tests {
6771 name := lt.typ.String()
6773 name = lt.rcvr.String() + "." + name
6775 t.Run(name, func(t *testing.T) {
6776 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6778 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6779 if typ.Size() != lt.size {
6780 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6782 if argsize != lt.argsize {
6783 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6785 if retOffset != lt.retOffset {
6786 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6788 if !bytes.Equal(stack, lt.stack) {
6789 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6791 if !bytes.Equal(gc, lt.gc) {
6792 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6794 if !bytes.Equal(inRegs, lt.inRegs) {
6795 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6797 if !bytes.Equal(outRegs, lt.outRegs) {
6798 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6800 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6801 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6807 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6808 heapBits := GCBits(New(typ).Interface())
6809 if !bytes.Equal(heapBits, bits) {
6810 _, _, line, _ := runtime.Caller(1)
6811 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6815 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6816 // Creating a slice causes the runtime to repeat a bitmap,
6817 // which exercises a different path from making the compiler
6818 // repeat a bitmap for a small array or executing a repeat in
6820 val := MakeSlice(typ, 0, cap)
6821 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
6822 heapBits := GCBits(data.Interface())
6823 // Repeat the bitmap for the slice size, trimming scalars in
6824 // the last element.
6825 bits = rep(cap, bits)
6826 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6827 bits = bits[:len(bits)-1]
6829 if !bytes.Equal(heapBits, bits) {
6830 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6834 func TestGCBits(t *testing.T) {
6835 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6837 // Building blocks for types seen by the compiler (like [2]Xscalar).
6838 // The compiler will create the type structures for the derived types,
6839 // including their GC metadata.
6840 type Xscalar struct{ x uintptr }
6841 type Xptr struct{ x *byte }
6842 type Xptrscalar struct {
6846 type Xscalarptr struct {
6850 type Xbigptrscalar struct {
6855 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6857 // Building blocks for types constructed by reflect.
6858 // This code is in a separate block so that code below
6859 // cannot accidentally refer to these.
6860 // The compiler must NOT see types derived from these
6861 // (for example, [2]Scalar must NOT appear in the program),
6862 // or else reflect will use it instead of having to construct one.
6863 // The goal is to test the construction.
6864 type Scalar struct{ x uintptr }
6865 type Ptr struct{ x *byte }
6866 type Ptrscalar struct {
6870 type Scalarptr struct {
6874 type Bigptrscalar struct {
6879 Tscalar = TypeOf(Scalar{})
6880 Tint64 = TypeOf(Int64(0))
6881 Tptr = TypeOf(Ptr{})
6882 Tscalarptr = TypeOf(Scalarptr{})
6883 Tptrscalar = TypeOf(Ptrscalar{})
6884 Tbigptrscalar = TypeOf(Bigptrscalar{})
6889 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6890 verifyGCBits(t, Tscalar, empty)
6891 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6892 verifyGCBits(t, Tptr, lit(1))
6893 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6894 verifyGCBits(t, Tscalarptr, lit(0, 1))
6895 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6896 verifyGCBits(t, Tptrscalar, lit(1))
6898 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6899 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6900 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6901 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6902 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6903 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6904 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6905 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6906 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6907 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6908 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6909 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6910 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6911 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6912 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6913 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6914 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6915 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6916 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6917 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6918 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6919 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6920 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6921 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6922 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6923 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6925 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6926 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6927 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6928 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6929 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6930 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6931 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6932 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6933 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6934 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6935 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6936 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6937 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6938 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6939 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6940 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6941 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6942 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6943 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6944 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6945 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6946 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6947 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6948 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6949 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6950 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6952 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6953 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6955 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6956 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6958 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6959 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6961 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6962 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6964 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6965 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6967 hdr := make([]byte, 8/goarch.PtrSize)
6969 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6970 verifyGCBits(t, MapBucketOf(k, e), want)
6971 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6975 map[Xscalar]Xptr(nil),
6976 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6979 map[Xscalarptr]Xptr(nil),
6980 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6981 verifyMapBucket(t, Tint64, Tptr,
6982 map[int64]Xptr(nil),
6983 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
6986 map[Xscalar]Xscalar(nil),
6989 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6990 map[[2]Xscalarptr][3]Xptrscalar(nil),
6991 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6993 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6994 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6995 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6997 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6998 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6999 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7001 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7002 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7003 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7005 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7006 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7007 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7010 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7011 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7012 func lit(x ...byte) []byte { return x }
7014 func TestTypeOfTypeOf(t *testing.T) {
7015 // Check that all the type constructors return concrete *rtype implementations.
7016 // It's difficult to test directly because the reflect package is only at arm's length.
7017 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7018 check := func(name string, typ Type) {
7019 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7020 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7024 type T struct{ int }
7025 check("TypeOf", TypeOf(T{}))
7027 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7028 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7029 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7030 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7031 check("PtrTo", PtrTo(TypeOf(T{})))
7032 check("SliceOf", SliceOf(TypeOf(T{})))
7035 type XM struct{ _ bool }
7037 func (*XM) String() string { return "" }
7039 func TestPtrToMethods(t *testing.T) {
7041 yp := New(TypeOf(y)).Interface()
7042 _, ok := yp.(fmt.Stringer)
7044 t.Fatal("does not implement Stringer, but should")
7048 func TestMapAlloc(t *testing.T) {
7049 m := ValueOf(make(map[int]int, 10))
7052 allocs := testing.AllocsPerRun(100, func() {
7056 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7061 val := ValueOf(&tmp).Elem()
7062 allocs = testing.AllocsPerRun(100, func() {
7063 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7064 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7065 for i := 0; i < size/2; i++ {
7066 val.SetInt(int64(i))
7067 mv.SetMapIndex(val, val)
7071 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7073 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7074 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7075 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7078 func TestChanAlloc(t *testing.T) {
7079 // Note: for a chan int, the return Value must be allocated, so we
7080 // use a chan *int instead.
7081 c := ValueOf(make(chan *int, 1))
7082 v := ValueOf(new(int))
7083 allocs := testing.AllocsPerRun(100, func() {
7087 if allocs < 0.5 || allocs > 1.5 {
7088 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7090 // Note: there is one allocation in reflect.recv which seems to be
7091 // a limitation of escape analysis. If that is ever fixed the
7092 // allocs < 0.5 condition will trigger and this test should be fixed.
7095 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7097 type nameTest struct {
7102 var nameTests = []nameTest{
7103 {(*int32)(nil), "int32"},
7106 {(*chan D1)(nil), ""},
7107 {(*func() D1)(nil), ""},
7108 {(*<-chan D1)(nil), ""},
7109 {(*chan<- D1)(nil), ""},
7110 {(*interface{})(nil), ""},
7114 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7117 func TestNames(t *testing.T) {
7118 for _, test := range nameTests {
7119 typ := TypeOf(test.v).Elem()
7120 if got := typ.Name(); got != test.want {
7121 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7126 func TestExported(t *testing.T) {
7127 type ΦExported struct{}
7128 type φUnexported struct{}
7135 type exportTest struct {
7139 exportTests := []exportTest{
7143 {(*big)(nil), false},
7144 {(BigP)(nil), true},
7145 {(*BigP)(nil), true},
7146 {ΦExported{}, true},
7147 {φUnexported{}, false},
7154 for i, test := range exportTests {
7155 typ := TypeOf(test.v)
7156 if got := IsExported(typ); got != test.want {
7157 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7162 func TestTypeStrings(t *testing.T) {
7163 type stringTest struct {
7167 stringTests := []stringTest{
7168 {TypeOf(func(int) {}), "func(int)"},
7169 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7170 {TypeOf(XM{}), "reflect_test.XM"},
7171 {TypeOf(new(XM)), "*reflect_test.XM"},
7172 {TypeOf(new(XM).String), "func() string"},
7173 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7174 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7175 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7176 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7177 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7180 for i, test := range stringTests {
7181 if got, want := test.typ.String(), test.want; got != want {
7182 t.Errorf("type %d String()=%q, want %q", i, got, want)
7187 func TestOffsetLock(t *testing.T) {
7188 var wg sync.WaitGroup
7189 for i := 0; i < 4; i++ {
7193 for j := 0; j < 50; j++ {
7194 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7202 func BenchmarkNew(b *testing.B) {
7204 b.RunParallel(func(pb *testing.PB) {
7211 func BenchmarkMap(b *testing.B) {
7213 value := ValueOf((V)(nil))
7214 stringKeys := []string{}
7215 mapOfStrings := map[string]V{}
7216 uint64Keys := []uint64{}
7217 mapOfUint64s := map[uint64]V{}
7218 for i := 0; i < 100; i++ {
7219 stringKey := fmt.Sprintf("key%d", i)
7220 stringKeys = append(stringKeys, stringKey)
7221 mapOfStrings[stringKey] = nil
7223 uint64Key := uint64(i)
7224 uint64Keys = append(uint64Keys, uint64Key)
7225 mapOfUint64s[uint64Key] = nil
7230 m, keys, value Value
7232 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7233 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7236 for _, tt := range tests {
7237 b.Run(tt.label, func(b *testing.B) {
7238 b.Run("MapIndex", func(b *testing.B) {
7240 for i := 0; i < b.N; i++ {
7241 for j := tt.keys.Len() - 1; j >= 0; j-- {
7242 tt.m.MapIndex(tt.keys.Index(j))
7246 b.Run("SetMapIndex", func(b *testing.B) {
7248 for i := 0; i < b.N; i++ {
7249 for j := tt.keys.Len() - 1; j >= 0; j-- {
7250 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7258 func TestSwapper(t *testing.T) {
7264 type pairPtr struct {
7276 in: []int{1, 20, 300},
7279 want: []int{300, 20, 1},
7282 in: []uintptr{1, 20, 300},
7285 want: []uintptr{300, 20, 1},
7288 in: []int16{1, 20, 300},
7291 want: []int16{300, 20, 1},
7294 in: []int8{1, 20, 100},
7297 want: []int8{100, 20, 1},
7300 in: []*I{&a, &b, &c},
7303 want: []*I{&c, &b, &a},
7306 in: []string{"eric", "sergey", "larry"},
7309 want: []string{"larry", "sergey", "eric"},
7312 in: []S{"eric", "sergey", "larry"},
7315 want: []S{"larry", "sergey", "eric"},
7318 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7321 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7324 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7327 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7331 for i, tt := range tests {
7332 inStr := fmt.Sprint(tt.in)
7333 Swapper(tt.in)(tt.i, tt.j)
7334 if !DeepEqual(tt.in, tt.want) {
7335 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7340 // TestUnaddressableField tests that the reflect package will not allow
7341 // a type from another package to be used as a named type with an
7342 // unexported field.
7344 // This ensures that unexported fields cannot be modified by other packages.
7345 func TestUnaddressableField(t *testing.T) {
7346 var b Buffer // type defined in reflect, a different package
7347 var localBuffer struct {
7350 lv := ValueOf(&localBuffer).Elem()
7352 shouldPanic("Set", func() {
7361 type Talias1 struct {
7369 type Talias2 struct {
7374 func TestAliasNames(t *testing.T) {
7375 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7376 out := fmt.Sprintf("%#v", t1)
7377 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7379 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7382 t2 := Talias2{Tint: 1, Tint2: 2}
7383 out = fmt.Sprintf("%#v", t2)
7384 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7386 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7390 func TestIssue22031(t *testing.T) {
7391 type s []struct{ C int }
7394 type t2 struct{ f s }
7397 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7398 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7401 for i, test := range tests {
7403 t.Errorf("%d: CanSet: got true, want false", i)
7408 type NonExportedFirst int
7410 func (i NonExportedFirst) ΦExported() {}
7411 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7413 func TestIssue22073(t *testing.T) {
7414 m := ValueOf(NonExportedFirst(0)).Method(0)
7416 if got := m.Type().NumOut(); got != 0 {
7417 t.Errorf("NumOut: got %v, want 0", got)
7424 func TestMapIterNonEmptyMap(t *testing.T) {
7425 m := map[string]int{"one": 1, "two": 2, "three": 3}
7426 iter := ValueOf(m).MapRange()
7427 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7428 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7432 func TestMapIterNilMap(t *testing.T) {
7433 var m map[string]int
7434 iter := ValueOf(m).MapRange()
7435 if got, want := iterateToString(iter), `[]`; got != want {
7436 t.Errorf("non-empty result iteratoring nil map: %s", got)
7440 func TestMapIterReset(t *testing.T) {
7441 iter := new(MapIter)
7443 // Use of zero iterator should panic.
7445 defer func() { recover() }()
7447 t.Error("Next did not panic")
7450 // Reset to new Map should work.
7451 m := map[string]int{"one": 1, "two": 2, "three": 3}
7452 iter.Reset(ValueOf(m))
7453 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7454 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7457 // Reset to Zero value should work, but iterating over it should panic.
7460 defer func() { recover() }()
7462 t.Error("Next did not panic")
7465 // Reset to a different Map with different types should work.
7466 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7467 iter.Reset(ValueOf(m2))
7468 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7469 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7472 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7473 m3 := map[uint64]uint64{
7478 kv := New(TypeOf(uint64(0))).Elem()
7479 for i := 0; i < 5; i++ {
7480 var seenk, seenv uint64
7481 iter.Reset(ValueOf(m3))
7485 kv.SetIterValue(iter)
7489 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7491 if seenv != 0b1110 {
7492 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7496 // Reset should not allocate.
7497 n := int(testing.AllocsPerRun(10, func() {
7498 iter.Reset(ValueOf(m2))
7502 t.Errorf("MapIter.Reset allocated %d times", n)
7506 func TestMapIterSafety(t *testing.T) {
7507 // Using a zero MapIter causes a panic, but not a crash.
7509 defer func() { recover() }()
7511 t.Fatal("Key did not panic")
7514 defer func() { recover() }()
7515 new(MapIter).Value()
7516 t.Fatal("Value did not panic")
7519 defer func() { recover() }()
7521 t.Fatal("Next did not panic")
7524 // Calling Key/Value on a MapIter before Next
7525 // causes a panic, but not a crash.
7526 var m map[string]int
7527 iter := ValueOf(m).MapRange()
7530 defer func() { recover() }()
7532 t.Fatal("Key did not panic")
7535 defer func() { recover() }()
7537 t.Fatal("Value did not panic")
7540 // Calling Next, Key, or Value on an exhausted iterator
7541 // causes a panic, but not a crash.
7542 iter.Next() // -> false
7544 defer func() { recover() }()
7546 t.Fatal("Key did not panic")
7549 defer func() { recover() }()
7551 t.Fatal("Value did not panic")
7554 defer func() { recover() }()
7556 t.Fatal("Next did not panic")
7560 func TestMapIterNext(t *testing.T) {
7561 // The first call to Next should reflect any
7562 // insertions to the map since the iterator was created.
7563 m := map[string]int{}
7564 iter := ValueOf(m).MapRange()
7566 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7567 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7571 func TestMapIterDelete0(t *testing.T) {
7572 // Delete all elements before first iteration.
7573 m := map[string]int{"one": 1, "two": 2, "three": 3}
7574 iter := ValueOf(m).MapRange()
7578 if got, want := iterateToString(iter), `[]`; got != want {
7579 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7583 func TestMapIterDelete1(t *testing.T) {
7584 // Delete all elements after first iteration.
7585 m := map[string]int{"one": 1, "two": 2, "three": 3}
7586 iter := ValueOf(m).MapRange()
7589 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7595 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7599 // iterateToString returns the set of elements
7600 // returned by an iterator in readable form.
7601 func iterateToString(it *MapIter) string {
7604 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7605 got = append(got, line)
7608 return "[" + strings.Join(got, ", ") + "]"
7611 func TestConvertibleTo(t *testing.T) {
7612 t1 := ValueOf(example1.MyStruct{}).Type()
7613 t2 := ValueOf(example2.MyStruct{}).Type()
7615 // Shouldn't raise stack overflow
7616 if t1.ConvertibleTo(t2) {
7617 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7620 t3 := ValueOf([]example1.MyStruct{}).Type()
7621 t4 := ValueOf([]example2.MyStruct{}).Type()
7623 if t3.ConvertibleTo(t4) {
7624 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7628 func TestSetIter(t *testing.T) {
7629 data := map[string]int{
7637 k := New(TypeOf("")).Elem()
7638 v := New(TypeOf(0)).Elem()
7639 shouldPanic("Value.SetIterKey called before Next", func() {
7642 shouldPanic("Value.SetIterValue called before Next", func() {
7645 data2 := map[string]int{}
7649 data2[k.Interface().(string)] = v.Interface().(int)
7651 if !DeepEqual(data, data2) {
7652 t.Errorf("maps not equal, got %v want %v", data2, data)
7654 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7657 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7663 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7664 ValueOf("").SetIterKey(i)
7666 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7667 ValueOf(0).SetIterValue(i)
7669 shouldPanic("value of type string is not assignable to type int", func() {
7670 New(TypeOf(0)).Elem().SetIterKey(i)
7672 shouldPanic("value of type int is not assignable to type string", func() {
7673 New(TypeOf("")).Elem().SetIterValue(i)
7676 // Make sure assignment conversion works.
7678 y := ValueOf(&x).Elem()
7680 if _, ok := data[x.(string)]; !ok {
7681 t.Errorf("got key %s which is not in map", x)
7684 if x.(int) < 1 || x.(int) > 3 {
7685 t.Errorf("got value %d which is not in map", x)
7688 // Try some key/value types which are direct interfaces.
7691 pp := map[*int]*int{
7694 i = ValueOf(pp).MapRange()
7697 if got := *y.Interface().(*int); got != a {
7698 t.Errorf("pointer incorrect: got %d want %d", got, a)
7701 if got := *y.Interface().(*int); got != b {
7702 t.Errorf("pointer incorrect: got %d want %d", got, b)
7707 type nih struct{ x int }
7709 var global_nih = nih{x: 7}
7711 func TestNotInHeapDeref(t *testing.T) {
7713 v := ValueOf((*nih)(nil))
7715 shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
7717 v = ValueOf(&global_nih)
7718 if got := v.Elem().Field(0).Int(); got != 7 {
7719 t.Fatalf("got %d, want 7", got)
7722 v = ValueOf((*nih)(unsafe.Pointer(new(int))))
7723 shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
7726 func TestMethodCallValueCodePtr(t *testing.T) {
7727 m := ValueOf(Point{}).Method(1)
7728 want := MethodValueCallCodePtr()
7729 if got := uintptr(m.UnsafePointer()); got != want {
7730 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7732 if got := m.Pointer(); got != want {
7733 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)