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.
20 "reflect/internal/example1"
21 "reflect/internal/example2"
35 func TestBool(t *testing.T) {
38 t.Fatal("ValueOf(true).Bool() = false")
50 var _ = T{} == T{} // tests depend on T being comparable
57 func assert(t *testing.T, s, want string) {
59 t.Errorf("have %#q want %#q", s, want)
63 var typeTests = []pair{
64 {struct{ x int }{}, "int"},
65 {struct{ x int8 }{}, "int8"},
66 {struct{ x int16 }{}, "int16"},
67 {struct{ x int32 }{}, "int32"},
68 {struct{ x int64 }{}, "int64"},
69 {struct{ x uint }{}, "uint"},
70 {struct{ x uint8 }{}, "uint8"},
71 {struct{ x uint16 }{}, "uint16"},
72 {struct{ x uint32 }{}, "uint32"},
73 {struct{ x uint64 }{}, "uint64"},
74 {struct{ x float32 }{}, "float32"},
75 {struct{ x float64 }{}, "float64"},
76 {struct{ x int8 }{}, "int8"},
77 {struct{ x (**int8) }{}, "**int8"},
78 {struct{ x (**integer) }{}, "**reflect_test.integer"},
79 {struct{ x ([32]int32) }{}, "[32]int32"},
80 {struct{ x ([]int8) }{}, "[]int8"},
81 {struct{ x (map[string]int32) }{}, "map[string]int32"},
82 {struct{ x (chan<- string) }{}, "chan<- string"},
83 {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
84 {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
85 {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
86 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
93 "struct { c chan *int32; d float32 }",
95 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
98 c func(chan *integer, *int8)
101 "struct { c func(chan *reflect_test.integer, *int8) }",
109 "struct { a int8; b int32 }",
118 "struct { a int8; b int8; c int32 }",
128 "struct { a int8; b int8; c int8; d int32 }",
139 "struct { a int8; b int8; c int8; d int8; e int32 }",
151 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
155 a int8 `reflect:"hi there"`
158 `struct { a int8 "reflect:\"hi there\"" }`,
162 a int8 `reflect:"hi \x00there\t\n\"\\"`
165 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
172 "struct { f func(...int) }",
176 a(func(func(int) int) func(func(int)) int)
180 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
188 "struct { int32; int64 }",
192 var valueTests = []pair{
203 {new(float32), "256.25"},
204 {new(float64), "512.125"},
205 {new(complex64), "532.125+10i"},
206 {new(complex128), "564.25+1i"},
207 {new(string), "stringy cheese"},
209 {new(*int8), "*int8(0)"},
210 {new(**int8), "**int8(0)"},
211 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
212 {new(**integer), "**reflect_test.integer(0)"},
213 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
214 {new(chan<- string), "chan<- string"},
215 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
220 "struct { c chan *int32; d float32 }{chan *int32, 0}",
222 {new(struct{ c func(chan *integer, *int8) }),
223 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
229 "struct { a int8; b int32 }{0, 0}",
236 "struct { a int8; b int8; c int32 }{0, 0, 0}",
240 func testType(t *testing.T, i int, typ Type, want string) {
243 t.Errorf("#%d: have %#q, want %#q", i, s, want)
247 func TestTypes(t *testing.T) {
248 for i, tt := range typeTests {
249 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
253 func TestSet(t *testing.T) {
254 for i, tt := range valueTests {
283 v.SetComplex(532.125 + 10i)
285 v.SetComplex(564.25 + 1i)
287 v.SetString("stringy cheese")
291 s := valueToString(v)
293 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
298 func TestSetValue(t *testing.T) {
299 for i, tt := range valueTests {
300 v := ValueOf(tt.i).Elem()
303 v.Set(ValueOf(int(132)))
305 v.Set(ValueOf(int8(8)))
307 v.Set(ValueOf(int16(16)))
309 v.Set(ValueOf(int32(32)))
311 v.Set(ValueOf(int64(64)))
313 v.Set(ValueOf(uint(132)))
315 v.Set(ValueOf(uint8(8)))
317 v.Set(ValueOf(uint16(16)))
319 v.Set(ValueOf(uint32(32)))
321 v.Set(ValueOf(uint64(64)))
323 v.Set(ValueOf(float32(256.25)))
325 v.Set(ValueOf(512.125))
327 v.Set(ValueOf(complex64(532.125 + 10i)))
329 v.Set(ValueOf(complex128(564.25 + 1i)))
331 v.Set(ValueOf("stringy cheese"))
335 s := valueToString(v)
337 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
342 func TestMapIterSet(t *testing.T) {
343 m := make(map[string]any, len(valueTests))
344 for _, tt := range valueTests {
349 k := New(v.Type().Key()).Elem()
350 e := New(v.Type().Elem()).Elem()
356 want := m[k.String()]
359 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
361 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
362 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
364 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
365 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
369 if testenv.OptimizationOff() {
370 return // no inlining with the noopt builder
373 got := int(testing.AllocsPerRun(10, func() {
380 // Calling MapRange should not allocate even though it returns a *MapIter.
381 // The function is inlineable, so if the local usage does not escape
382 // the *MapIter, it can remain stack allocated.
385 t.Errorf("wanted %d alloc, got %d", want, got)
389 func TestCanIntUintFloatComplex(t *testing.T) {
393 type complex complex128
395 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
397 var testCases = []struct {
402 {132, [...]bool{true, false, false, false}},
403 {int8(8), [...]bool{true, false, false, false}},
404 {int16(16), [...]bool{true, false, false, false}},
405 {int32(32), [...]bool{true, false, false, false}},
406 {int64(64), [...]bool{true, false, false, false}},
408 {uint(132), [...]bool{false, true, false, false}},
409 {uint8(8), [...]bool{false, true, false, false}},
410 {uint16(16), [...]bool{false, true, false, false}},
411 {uint32(32), [...]bool{false, true, false, false}},
412 {uint64(64), [...]bool{false, true, false, false}},
413 {uintptr(0xABCD), [...]bool{false, true, false, false}},
415 {float32(256.25), [...]bool{false, false, true, false}},
416 {float64(512.125), [...]bool{false, false, true, false}},
418 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
419 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
421 {integer(-132), [...]bool{true, false, false, false}},
422 {uinteger(132), [...]bool{false, true, false, false}},
423 {float(256.25), [...]bool{false, false, true, false}},
424 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
426 {"hello world", [...]bool{false, false, false, false}},
427 {new(int), [...]bool{false, false, false, false}},
428 {new(uint), [...]bool{false, false, false, false}},
429 {new(float64), [...]bool{false, false, false, false}},
430 {new(complex64), [...]bool{false, false, false, false}},
431 {new([5]int), [...]bool{false, false, false, false}},
432 {new(integer), [...]bool{false, false, false, false}},
433 {new(map[int]int), [...]bool{false, false, false, false}},
434 {new(chan<- int), [...]bool{false, false, false, false}},
435 {new(func(a int8)), [...]bool{false, false, false, false}},
436 {new(struct{ i int }), [...]bool{false, false, false, false}},
439 for i, tc := range testCases {
441 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
443 for j := range tc.want {
444 if got[j] != tc.want[j] {
446 "#%d: v.%s() returned %t for type %T, want %t",
458 func TestCanSetField(t *testing.T) {
459 type embed struct{ x, X int }
460 type Embed struct{ x, X int }
478 type testCase struct {
479 // -1 means Addr().Elem() of current value
490 {[]int{0, -1}, false},
491 {[]int{0, 0}, false},
492 {[]int{0, 0, -1}, false},
493 {[]int{0, -1, 0}, false},
494 {[]int{0, -1, 0, -1}, false},
496 {[]int{0, 1, -1}, true},
497 {[]int{0, -1, 1}, true},
498 {[]int{0, -1, 1, -1}, true},
500 {[]int{1, -1}, false},
502 {[]int{2, -1}, true},
505 val: ValueOf(&S2{embed: &embed{}}),
508 {[]int{0, -1}, false},
509 {[]int{0, 0}, false},
510 {[]int{0, 0, -1}, false},
511 {[]int{0, -1, 0}, false},
512 {[]int{0, -1, 0, -1}, false},
514 {[]int{0, 1, -1}, true},
515 {[]int{0, -1, 1}, true},
516 {[]int{0, -1, 1, -1}, true},
524 {[]int{0, -1}, true},
525 {[]int{0, 0}, false},
526 {[]int{0, 0, -1}, false},
527 {[]int{0, -1, 0}, false},
528 {[]int{0, -1, 0, -1}, false},
530 {[]int{0, 1, -1}, true},
531 {[]int{0, -1, 1}, true},
532 {[]int{0, -1, 1, -1}, true},
537 val: ValueOf(&S4{Embed: &Embed{}}),
540 {[]int{0, -1}, true},
541 {[]int{0, 0}, false},
542 {[]int{0, 0, -1}, false},
543 {[]int{0, -1, 0}, false},
544 {[]int{0, -1, 0, -1}, false},
546 {[]int{0, 1, -1}, true},
547 {[]int{0, -1, 1}, true},
548 {[]int{0, -1, 1, -1}, true},
554 for _, tt := range tests {
555 t.Run(tt.val.Type().Name(), func(t *testing.T) {
556 for _, tc := range tt.cases {
558 for _, i := range tc.index {
559 if f.Kind() == Pointer {
568 if got := f.CanSet(); got != tc.canSet {
569 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
578 var valueToStringTests = []pair{
583 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
584 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
585 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
586 {&[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})"},
587 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
588 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
591 func TestValueToString(t *testing.T) {
592 for i, test := range valueToStringTests {
593 s := valueToString(ValueOf(test.i))
595 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
600 func TestArrayElemSet(t *testing.T) {
601 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
602 v.Index(4).SetInt(123)
603 s := valueToString(v)
604 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
606 t.Errorf("[10]int: have %#q want %#q", s, want)
609 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
610 v.Index(4).SetInt(123)
612 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
614 t.Errorf("[]int: have %#q want %#q", s, want1)
618 func TestPtrPointTo(t *testing.T) {
622 vi := ValueOf(&i).Elem()
623 vip.Elem().Set(vi.Addr())
625 t.Errorf("got %d, want 1234", *ip)
629 vp := ValueOf(&ip).Elem()
630 vp.Set(Zero(vp.Type()))
632 t.Errorf("got non-nil (%p), want nil", ip)
636 func TestPtrSetNil(t *testing.T) {
640 vip.Elem().Set(Zero(vip.Elem().Type()))
642 t.Errorf("got non-nil (%d), want nil", *ip)
646 func TestMapSetNil(t *testing.T) {
647 m := make(map[string]int)
649 vm.Elem().Set(Zero(vm.Elem().Type()))
651 t.Errorf("got non-nil (%p), want nil", m)
655 func TestAll(t *testing.T) {
656 testType(t, 1, TypeOf((int8)(0)), "int8")
657 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
659 typ := TypeOf((*struct {
663 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
665 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
668 testType(t, 5, f.Type, "chan *int32")
670 f, present := styp.FieldByName("d")
672 t.Errorf("FieldByName says present field is absent")
674 testType(t, 6, f.Type, "float32")
676 f, present = styp.FieldByName("absent")
678 t.Errorf("FieldByName says absent field is present")
681 typ = TypeOf([32]int32{})
682 testType(t, 7, typ, "[32]int32")
683 testType(t, 8, typ.Elem(), "int32")
685 typ = TypeOf((map[string]*int32)(nil))
686 testType(t, 9, typ, "map[string]*int32")
688 testType(t, 10, mtyp.Key(), "string")
689 testType(t, 11, mtyp.Elem(), "*int32")
691 typ = TypeOf((chan<- string)(nil))
692 testType(t, 12, typ, "chan<- string")
693 testType(t, 13, typ.Elem(), "string")
695 // make sure tag strings are not part of element type
696 typ = TypeOf(struct {
697 d []uint32 `reflect:"TAG"`
699 testType(t, 14, typ, "[]uint32")
702 func TestInterfaceGet(t *testing.T) {
707 v1 := ValueOf(&inter)
708 v2 := v1.Elem().Field(0)
709 assert(t, v2.Type().String(), "interface {}")
712 assert(t, v3.Type().String(), "float64")
715 func TestInterfaceValue(t *testing.T) {
720 v1 := ValueOf(&inter)
721 v2 := v1.Elem().Field(0)
722 assert(t, v2.Type().String(), "interface {}")
724 assert(t, v3.Type().String(), "float64")
727 if _, ok := i3.(float64); !ok {
728 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
732 func TestFunctionValue(t *testing.T) {
733 var x any = func() {}
735 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
736 t.Fatalf("TestFunction returned wrong pointer")
738 assert(t, v.Type().String(), "func()")
741 var appendTests = []struct {
744 {make([]int, 2, 4), []int{22}},
745 {make([]int, 2, 4), []int{22, 33, 44}},
748 func sameInts(x, y []int) bool {
749 if len(x) != len(y) {
752 for i, xx := range x {
760 func TestAppend(t *testing.T) {
761 for i, test := range appendTests {
762 origLen, extraLen := len(test.orig), len(test.extra)
763 want := append(test.orig, test.extra...)
764 // Convert extra from []int to []Value.
765 e0 := make([]Value, len(test.extra))
766 for j, e := range test.extra {
769 // Convert extra from []int to *SliceValue.
770 e1 := ValueOf(test.extra)
772 a0 := ValueOf(test.orig)
773 have0 := Append(a0, e0...).Interface().([]int)
774 if !sameInts(have0, want) {
775 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
777 // Check that the orig and extra slices were not modified.
778 if len(test.orig) != origLen {
779 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
781 if len(test.extra) != extraLen {
782 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
785 a1 := ValueOf(test.orig)
786 have1 := AppendSlice(a1, e1).Interface().([]int)
787 if !sameInts(have1, want) {
788 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
790 // Check that the orig and extra slices were not modified.
791 if len(test.orig) != origLen {
792 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
794 if len(test.extra) != extraLen {
795 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
800 func TestCopy(t *testing.T) {
801 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
802 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
803 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
804 for i := 0; i < len(b); i++ {
806 t.Fatalf("b != c before test")
811 aa := ValueOf(&a1).Elem()
812 ab := ValueOf(&b1).Elem()
813 for tocopy := 1; tocopy <= 7; tocopy++ {
817 for i := 0; i < tocopy; i++ {
819 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
820 tocopy, i, a[i], i, b[i])
823 for i := tocopy; i < len(b); i++ {
826 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
827 tocopy, i, a[i], i, b[i], i, c[i])
829 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
830 tocopy, i, b[i], i, c[i])
833 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
839 func TestCopyString(t *testing.T) {
840 t.Run("Slice", func(t *testing.T) {
841 s := bytes.Repeat([]byte{'_'}, 8)
844 n := Copy(val, ValueOf(""))
845 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
846 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
849 n = Copy(val, ValueOf("hello"))
850 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
851 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
854 n = Copy(val, ValueOf("helloworld"))
855 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
856 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
859 t.Run("Array", func(t *testing.T) {
860 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
861 val := ValueOf(&s).Elem()
863 n := Copy(val, ValueOf(""))
864 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
865 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
868 n = Copy(val, ValueOf("hello"))
869 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
870 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
873 n = Copy(val, ValueOf("helloworld"))
874 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
875 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
880 func TestCopyArray(t *testing.T) {
881 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
882 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
884 aa := ValueOf(&a).Elem()
885 ab := ValueOf(&b).Elem()
887 for i := 0; i < len(a); i++ {
889 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
892 for i := len(a); i < len(b); i++ {
894 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
896 t.Logf("elem %d is okay\n", i)
901 func TestBigUnnamedStruct(t *testing.T) {
902 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
904 b1 := v.Interface().(struct {
907 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
908 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
916 func TestBigStruct(t *testing.T) {
917 b := big{1, 2, 3, 4, 5}
919 b1 := v.Interface().(big)
920 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
921 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
932 type DeepEqualTest struct {
937 // Simple functions for DeepEqual tests.
941 fn3 = func() { fn1() } // Not nil.
949 var loop1, loop2 Loop
950 var loopy1, loopy2 Loopy
951 var cycleMap1, cycleMap2, cycleMap3 map[string]any
953 type structWithSelfPtr struct {
965 cycleMap1 = map[string]any{}
966 cycleMap1["cycle"] = cycleMap1
967 cycleMap2 = map[string]any{}
968 cycleMap2["cycle"] = cycleMap2
969 cycleMap3 = map[string]any{}
970 cycleMap3["different"] = cycleMap3
973 var deepEqualTests = []DeepEqualTest{
977 {int32(1), int32(1), true},
979 {float32(0.5), float32(0.5), true},
980 {"hello", "hello", true},
981 {make([]int, 10), make([]int, 10), true},
982 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
983 {Basic{1, 0.5}, Basic{1, 0.5}, true},
984 {error(nil), error(nil), true},
985 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
987 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
988 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
989 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
993 {int32(1), int32(2), false},
995 {float32(0.5), float32(0.6), false},
996 {"hello", "hey", false},
997 {make([]int, 10), make([]int, 11), false},
998 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
999 {Basic{1, 0.5}, Basic{1, 0.6}, false},
1000 {Basic{1, 0}, Basic{2, 0}, false},
1001 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
1002 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
1003 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
1004 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
1009 {[][]int{{1}}, [][]int{{2}}, false},
1010 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1012 // Fun with floating point.
1013 {math.NaN(), math.NaN(), false},
1014 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1015 {&[1]float64{math.NaN()}, self{}, true},
1016 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1017 {[]float64{math.NaN()}, self{}, true},
1018 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1019 {map[float64]float64{math.NaN(): 1}, self{}, true},
1021 // Nil vs empty: not the same.
1022 {[]int{}, []int(nil), false},
1023 {[]int{}, []int{}, true},
1024 {[]int(nil), []int(nil), true},
1025 {map[int]int{}, map[int]int(nil), false},
1026 {map[int]int{}, map[int]int{}, true},
1027 {map[int]int(nil), map[int]int(nil), true},
1031 {int32(1), int64(1), false},
1032 {0.5, "hello", false},
1033 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1034 {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
1035 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1036 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1037 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1038 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1039 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1042 {&loop1, &loop1, true},
1043 {&loop1, &loop2, true},
1044 {&loopy1, &loopy1, true},
1045 {&loopy1, &loopy2, true},
1046 {&cycleMap1, &cycleMap2, true},
1047 {&cycleMap1, &cycleMap3, false},
1050 func TestDeepEqual(t *testing.T) {
1051 for _, test := range deepEqualTests {
1052 if test.b == (self{}) {
1055 if r := DeepEqual(test.a, test.b); r != test.eq {
1056 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1061 func TestTypeOf(t *testing.T) {
1062 // Special case for nil
1063 if typ := TypeOf(nil); typ != nil {
1064 t.Errorf("expected nil type for nil value; got %v", typ)
1066 for _, test := range deepEqualTests {
1067 v := ValueOf(test.a)
1071 typ := TypeOf(test.a)
1072 if typ != v.Type() {
1073 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1078 type Recursive struct {
1083 func TestDeepEqualRecursiveStruct(t *testing.T) {
1084 a, b := new(Recursive), new(Recursive)
1085 *a = Recursive{12, a}
1086 *b = Recursive{12, b}
1087 if !DeepEqual(a, b) {
1088 t.Error("DeepEqual(recursive same) = false, want true")
1092 type _Complex struct {
1096 d map[float64]float64
1099 func TestDeepEqualComplexStruct(t *testing.T) {
1100 m := make(map[float64]float64)
1101 stra, strb := "hello", "hello"
1102 a, b := new(_Complex), new(_Complex)
1103 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1104 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1105 if !DeepEqual(a, b) {
1106 t.Error("DeepEqual(complex same) = false, want true")
1110 func TestDeepEqualComplexStructInequality(t *testing.T) {
1111 m := make(map[float64]float64)
1112 stra, strb := "hello", "helloo" // Difference is here
1113 a, b := new(_Complex), new(_Complex)
1114 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1115 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1116 if DeepEqual(a, b) {
1117 t.Error("DeepEqual(complex different) = true, want false")
1121 type UnexpT struct {
1125 func TestDeepEqualUnexportedMap(t *testing.T) {
1126 // Check that DeepEqual can look at unexported fields.
1127 x1 := UnexpT{map[int]int{1: 2}}
1128 x2 := UnexpT{map[int]int{1: 2}}
1129 if !DeepEqual(&x1, &x2) {
1130 t.Error("DeepEqual(x1, x2) = false, want true")
1133 y1 := UnexpT{map[int]int{2: 3}}
1134 if DeepEqual(&x1, &y1) {
1135 t.Error("DeepEqual(x1, y1) = true, want false")
1139 var deepEqualPerfTests = []struct {
1142 {x: int8(99), y: int8(99)},
1143 {x: []int8{99}, y: []int8{99}},
1144 {x: int16(99), y: int16(99)},
1145 {x: []int16{99}, y: []int16{99}},
1146 {x: int32(99), y: int32(99)},
1147 {x: []int32{99}, y: []int32{99}},
1148 {x: int64(99), y: int64(99)},
1149 {x: []int64{99}, y: []int64{99}},
1150 {x: int(999999), y: int(999999)},
1151 {x: []int{999999}, y: []int{999999}},
1153 {x: uint8(99), y: uint8(99)},
1154 {x: []uint8{99}, y: []uint8{99}},
1155 {x: uint16(99), y: uint16(99)},
1156 {x: []uint16{99}, y: []uint16{99}},
1157 {x: uint32(99), y: uint32(99)},
1158 {x: []uint32{99}, y: []uint32{99}},
1159 {x: uint64(99), y: uint64(99)},
1160 {x: []uint64{99}, y: []uint64{99}},
1161 {x: uint(999999), y: uint(999999)},
1162 {x: []uint{999999}, y: []uint{999999}},
1163 {x: uintptr(999999), y: uintptr(999999)},
1164 {x: []uintptr{999999}, y: []uintptr{999999}},
1166 {x: float32(1.414), y: float32(1.414)},
1167 {x: []float32{1.414}, y: []float32{1.414}},
1168 {x: float64(1.414), y: float64(1.414)},
1169 {x: []float64{1.414}, y: []float64{1.414}},
1171 {x: complex64(1.414), y: complex64(1.414)},
1172 {x: []complex64{1.414}, y: []complex64{1.414}},
1173 {x: complex128(1.414), y: complex128(1.414)},
1174 {x: []complex128{1.414}, y: []complex128{1.414}},
1177 {x: []bool{true}, y: []bool{true}},
1179 {x: "abcdef", y: "abcdef"},
1180 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1182 {x: []byte("abcdef"), y: []byte("abcdef")},
1183 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1185 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1186 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1189 func TestDeepEqualAllocs(t *testing.T) {
1190 for _, tt := range deepEqualPerfTests {
1191 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1192 got := testing.AllocsPerRun(100, func() {
1193 if !DeepEqual(tt.x, tt.y) {
1194 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1198 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1204 func check2ndField(x any, offs uintptr, t *testing.T) {
1206 f := s.Type().Field(1)
1207 if f.Offset != offs {
1208 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1212 // Check that structure alignment & offsets viewed through reflect agree with those
1213 // from the compiler itself.
1214 func TestAlignment(t *testing.T) {
1215 type T1inner struct {
1222 type T2inner struct {
1230 x := T1{T1inner{2}, 17}
1231 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1233 x1 := T2{T2inner{2, 3}, 17}
1234 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1237 func Nil(a any, t *testing.T) {
1238 n := ValueOf(a).Field(0)
1240 t.Errorf("%v should be nil", a)
1244 func NotNil(a any, t *testing.T) {
1245 n := ValueOf(a).Field(0)
1247 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1251 func TestIsNil(t *testing.T) {
1252 // These implement IsNil.
1253 // Wrap in extra struct to hide interface type.
1257 struct{ x map[string]int }{},
1258 struct{ x func() bool }{},
1259 struct{ x chan int }{},
1260 struct{ x []string }{},
1261 struct{ x unsafe.Pointer }{},
1263 for _, ts := range doNil {
1264 ty := TypeOf(ts).Field(0).Type
1266 v.IsNil() // panics if not okay to call
1269 // Check the implementations
1281 si.x = make([]int, 10)
1288 ci.x = make(chan int)
1295 mi.x = make(map[int]int)
1306 x func(t *testing.T)
1313 func TestIsZero(t *testing.T) {
1314 for i, tt := range []struct {
1343 {float32(1.2), false},
1345 {float64(1.2), false},
1346 {math.Copysign(0, -1), false},
1347 {complex64(0), true},
1348 {complex64(1.2), false},
1349 {complex128(0), true},
1350 {complex128(1.2), false},
1351 {complex(math.Copysign(0, -1), 0), false},
1352 {complex(0, math.Copysign(0, -1)), false},
1353 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1355 {uintptr(128), false},
1357 {Zero(TypeOf([5]string{})).Interface(), true},
1358 {[5]string{}, true}, // comparable array
1359 {[5]string{"", "", "", "a", ""}, false}, // comparable array
1360 {[1]*int{}, true}, // direct pointer array
1361 {[1]*int{new(int)}, false}, // direct pointer array
1362 {[3][]int{}, true}, // incomparable array
1363 {[3][]int{{1}}, false}, // incomparable array
1364 {[1 << 12]byte{}, true},
1365 {[1 << 12]byte{1}, false},
1367 {[3]Value{{}, ValueOf(0), {}}, false},
1369 {(chan string)(nil), true},
1370 {make(chan string), false},
1371 {time.After(1), false},
1373 {(func())(nil), true},
1376 {New(TypeOf(new(error)).Elem()).Elem(), true},
1377 {(io.Reader)(strings.NewReader("")), false},
1379 {(map[string]string)(nil), true},
1380 {map[string]string{}, false},
1381 {make(map[string]string), false},
1383 {(*func())(nil), true},
1384 {(*int)(nil), true},
1387 {[]string{}, false},
1388 {([]string)(nil), true},
1389 {make([]string, 0), false},
1392 {"not-zero", false},
1394 {T{}, true}, // comparable struct
1395 {T{123, 456.75, "hello", &_i}, false}, // comparable struct
1396 {struct{ p *int }{}, true}, // direct pointer struct
1397 {struct{ p *int }{new(int)}, false}, // direct pointer struct
1398 {struct{ s []int }{}, true}, // incomparable struct
1399 {struct{ s []int }{[]int{1}}, false}, // incomparable struct
1400 {struct{ Value }{}, true},
1401 {struct{ Value }{ValueOf(0)}, false},
1403 {(unsafe.Pointer)(nil), true},
1404 {(unsafe.Pointer)(new(int)), false},
1407 if v, ok := tt.x.(Value); ok {
1415 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1418 if !Zero(TypeOf(tt.x)).IsZero() {
1419 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1422 p := New(x.Type()).Elem()
1426 t.Errorf("%d: IsZero((%s)(%+v)) is true after SetZero", i, p.Kind(), tt.x)
1432 if r := recover(); r == nil {
1433 t.Error("should panic for invalid value")
1440 func TestInterfaceExtraction(t *testing.T) {
1446 v := Indirect(ValueOf(&s)).Field(0).Interface()
1448 t.Error("Interface() on interface: ", v, s.W)
1452 func TestNilPtrValueSub(t *testing.T) {
1454 if pv := ValueOf(pi); pv.Elem().IsValid() {
1455 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1459 func TestMap(t *testing.T) {
1460 m := map[string]int{"a": 1, "b": 2}
1462 if n := mv.Len(); n != len(m) {
1463 t.Errorf("Len = %d, want %d", n, len(m))
1465 keys := mv.MapKeys()
1466 newmap := MakeMap(mv.Type())
1467 for k, v := range m {
1468 // Check that returned Keys match keys in range.
1469 // These aren't required to be in the same order.
1471 for _, kv := range keys {
1472 if kv.String() == k {
1478 t.Errorf("Missing key %q", k)
1481 // Check that value lookup is correct.
1482 vv := mv.MapIndex(ValueOf(k))
1483 if vi := vv.Int(); vi != int64(v) {
1484 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1487 // Copy into new map.
1488 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1490 vv := mv.MapIndex(ValueOf("not-present"))
1492 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1495 newm := newmap.Interface().(map[string]int)
1496 if len(newm) != len(m) {
1497 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1500 for k, v := range newm {
1503 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1507 newmap.SetMapIndex(ValueOf("a"), Value{})
1510 t.Errorf("newm[\"a\"] = %d after delete", v)
1513 mv = ValueOf(&m).Elem()
1514 mv.Set(Zero(mv.Type()))
1516 t.Errorf("mv.Set(nil) failed")
1520 shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
1521 shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
1524 func TestNilMap(t *testing.T) {
1525 var m map[string]int
1527 keys := mv.MapKeys()
1529 t.Errorf(">0 keys for nil map: %v", keys)
1532 // Check that value for missing key is zero.
1533 x := mv.MapIndex(ValueOf("hello"))
1534 if x.Kind() != Invalid {
1535 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1538 // Check big value too.
1539 var mbig map[string][10 << 20]byte
1540 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1541 if x.Kind() != Invalid {
1542 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1545 // Test that deletes from a nil map succeed.
1546 mv.SetMapIndex(ValueOf("hi"), Value{})
1549 func TestChan(t *testing.T) {
1550 for loop := 0; loop < 2; loop++ {
1554 // check both ways to allocate channels
1557 c = make(chan int, 1)
1560 cv = MakeChan(TypeOf(c), 1)
1561 c = cv.Interface().(chan int)
1566 if i := <-c; i != 2 {
1567 t.Errorf("reflect Send 2, native recv %d", i)
1572 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1573 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1577 val, ok := cv.TryRecv()
1578 if val.IsValid() || ok {
1579 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1584 val, ok = cv.TryRecv()
1586 t.Errorf("TryRecv on ready chan got nil")
1587 } else if i := val.Int(); i != 4 || !ok {
1588 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1593 ok = cv.TrySend(ValueOf(5))
1596 t.Errorf("TrySend on full chan succeeded: value %d", i)
1600 ok = cv.TrySend(ValueOf(6))
1602 t.Errorf("TrySend on empty chan failed")
1605 t.Errorf("TrySend failed but it did send %d", x)
1609 if i = <-c; i != 6 {
1610 t.Errorf("TrySend 6, recv %d", i)
1617 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1618 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1620 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1621 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1625 // check creation of unbuffered channel
1627 cv := MakeChan(TypeOf(c), 0)
1628 c = cv.Interface().(chan int)
1629 if cv.TrySend(ValueOf(7)) {
1630 t.Errorf("TrySend on sync chan succeeded")
1632 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1633 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1637 cv = MakeChan(TypeOf(c), 10)
1638 c = cv.Interface().(chan int)
1639 for i := 0; i < 3; i++ {
1642 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1643 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1647 // caseInfo describes a single case in a select test.
1648 type caseInfo struct {
1657 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1659 func TestSelect(t *testing.T) {
1660 selectWatch.once.Do(func() { go selectWatcher() })
1664 newop := func(n int, cap int) (ch, val Value) {
1667 c := make(chan int, cap)
1671 c := make(chan string, cap)
1673 val = ValueOf(fmt.Sprint(n))
1678 for n := 0; x.Next(); n++ {
1679 if testing.Short() && n >= 1000 {
1682 if n >= 100000 && !*allselect {
1685 if n%100000 == 0 && testing.Verbose() {
1686 println("TestSelect", n)
1688 var cases []SelectCase
1693 ch, val := newop(len(cases), 1)
1694 cases = append(cases, SelectCase{
1699 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1704 ch, val := newop(len(cases), 1)
1706 cases = append(cases, SelectCase{
1710 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1715 ch, val := newop(len(cases), 0)
1716 cases = append(cases, SelectCase{
1723 f := func() { ch.Recv() }
1724 info = append(info, caseInfo{desc: "blocking send", helper: f})
1726 info = append(info, caseInfo{desc: "blocking send"})
1732 ch, val := newop(len(cases), 0)
1733 cases = append(cases, SelectCase{
1739 f := func() { ch.Send(val) }
1740 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1742 info = append(info, caseInfo{desc: "blocking recv"})
1748 // Maybe include value to send.
1753 cases = append(cases, SelectCase{
1757 info = append(info, caseInfo{desc: "zero Chan send"})
1760 // Zero Chan receive.
1762 cases = append(cases, SelectCase{
1765 info = append(info, caseInfo{desc: "zero Chan recv"})
1770 cases = append(cases, SelectCase{
1772 Chan: ValueOf((chan int)(nil)),
1775 info = append(info, caseInfo{desc: "nil Chan send"})
1780 cases = append(cases, SelectCase{
1782 Chan: ValueOf((chan int)(nil)),
1784 info = append(info, caseInfo{desc: "nil Chan recv"})
1787 // closed Chan send.
1789 ch := make(chan int)
1791 cases = append(cases, SelectCase{
1796 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1799 // closed Chan recv.
1801 ch, val := newop(len(cases), 0)
1803 val = Zero(val.Type())
1804 cases = append(cases, SelectCase{
1808 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1811 var helper func() // goroutine to help the select complete
1813 // Add default? Must be last case here, but will permute.
1814 // Add the default if the select would otherwise
1815 // block forever, and maybe add it anyway.
1821 for i, c := range info {
1829 } else if c.helper != nil {
1831 helpers = append(helpers, i)
1834 if !canProceed || x.Maybe() {
1835 cases = append(cases, SelectCase{
1838 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1840 } else if canBlock {
1841 // Select needs to communicate with another goroutine.
1842 cas := &info[helpers[x.Choose(len(helpers))]]
1844 cas.canSelect = true
1848 // Permute cases and case info.
1849 // Doing too much here makes the exhaustive loop
1850 // too exhausting, so just do two swaps.
1851 for loop := 0; loop < 2; loop++ {
1852 i := x.Choose(len(cases))
1853 j := x.Choose(len(cases))
1854 cases[i], cases[j] = cases[j], cases[i]
1855 info[i], info[j] = info[j], info[i]
1859 // We wait before kicking off a goroutine to satisfy a blocked select.
1860 // The pause needs to be big enough to let the select block before
1861 // we run the helper, but if we lose that race once in a while it's okay: the
1862 // select will just proceed immediately. Not a big deal.
1863 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1864 pause := 10 * time.Microsecond
1865 if testing.Short() {
1866 pause = 100 * time.Microsecond
1868 time.AfterFunc(pause, helper)
1872 i, recv, recvOK, panicErr := runSelect(cases, info)
1873 if panicErr != nil && !canPanic {
1874 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1876 if panicErr == nil && canPanic && numCanSelect == 1 {
1877 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1879 if panicErr != nil {
1887 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1889 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1892 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1895 if cases[i].Dir == SelectRecv {
1896 if !recv.IsValid() {
1897 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1899 if !cas.recv.IsValid() {
1900 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1902 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1903 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1904 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1906 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1909 if recv.IsValid() || recvOK {
1910 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1916 func TestSelectMaxCases(t *testing.T) {
1917 var sCases []SelectCase
1918 channel := make(chan int)
1920 for i := 0; i < 65536; i++ {
1921 sCases = append(sCases, SelectCase{
1923 Chan: ValueOf(channel),
1927 _, _, _ = Select(sCases)
1928 sCases = append(sCases, SelectCase{
1930 Chan: ValueOf(channel),
1933 if err := recover(); err != nil {
1934 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1935 t.Fatalf("unexpected error from select call with greater than max supported cases")
1938 t.Fatalf("expected select call to panic with greater than max supported cases")
1942 _, _, _ = Select(sCases)
1945 func TestSelectNop(t *testing.T) {
1946 // "select { default: }" should always return the default case.
1947 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1949 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1953 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1954 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1955 // an error describing the select and panics the entire test binary.
1956 var selectWatch struct {
1963 func selectWatcher() {
1965 time.Sleep(1 * time.Second)
1967 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1968 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1969 panic("select stuck")
1971 selectWatch.Unlock()
1975 // runSelect runs a single select test.
1976 // It returns the values returned by Select but also returns
1977 // a panic value if the Select panics.
1978 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
1980 panicErr = recover()
1983 selectWatch.info = nil
1984 selectWatch.Unlock()
1988 selectWatch.now = time.Now()
1989 selectWatch.info = info
1990 selectWatch.Unlock()
1992 chosen, recv, recvOK = Select(cases)
1996 // fmtSelect formats the information about a single select test.
1997 func fmtSelect(info []caseInfo) string {
1998 var buf strings.Builder
1999 fmt.Fprintf(&buf, "\nselect {\n")
2000 for i, cas := range info {
2001 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2002 if cas.recv.IsValid() {
2003 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2006 fmt.Fprintf(&buf, " canselect")
2009 fmt.Fprintf(&buf, " panic")
2011 fmt.Fprintf(&buf, "\n")
2013 fmt.Fprintf(&buf, "}")
2019 // Difficult test for function call because of
2020 // implicit padding between arguments.
2021 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) {
2022 return b, c, d, e, f, g, h
2025 func TestFunc(t *testing.T) {
2026 ret := ValueOf(dummy).Call([]Value{
2030 ValueOf(two{40, 50}),
2032 ValueOf(float32(70)),
2036 t.Fatalf("Call returned %d values, want 7", len(ret))
2039 i := byte(ret[0].Uint())
2040 j := int(ret[1].Int())
2041 k := byte(ret[2].Uint())
2042 l := ret[3].Interface().(two)
2043 m := byte(ret[4].Uint())
2044 n := float32(ret[5].Float())
2045 o := byte(ret[6].Uint())
2047 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2048 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)
2051 for i, v := range ret {
2053 t.Errorf("result %d is addressable", i)
2058 func TestCallConvert(t *testing.T) {
2059 v := ValueOf(new(io.ReadWriter)).Elem()
2060 f := ValueOf(func(r io.Reader) io.Reader { return r })
2061 out := f.Call([]Value{v})
2062 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2063 t.Errorf("expected [nil], got %v", out)
2067 type emptyStruct struct{}
2069 type nonEmptyStruct struct {
2073 func returnEmpty() emptyStruct {
2074 return emptyStruct{}
2077 func takesEmpty(e emptyStruct) {
2080 func returnNonEmpty(i int) nonEmptyStruct {
2081 return nonEmptyStruct{member: i}
2084 func takesNonEmpty(n nonEmptyStruct) int {
2088 func TestCallWithStruct(t *testing.T) {
2089 r := ValueOf(returnEmpty).Call(nil)
2090 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2091 t.Errorf("returning empty struct returned %#v instead", r)
2093 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2095 t.Errorf("takesEmpty returned values: %#v", r)
2097 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2098 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2099 t.Errorf("returnNonEmpty returned %#v", r)
2101 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2102 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2103 t.Errorf("takesNonEmpty returned %#v", r)
2107 func TestCallReturnsEmpty(t *testing.T) {
2108 // Issue 21717: past-the-end pointer write in Call with
2109 // nonzero-sized frame and zero-sized return value.
2111 var finalized uint32
2112 f := func() (emptyStruct, *[2]int64) {
2113 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2114 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2115 return emptyStruct{}, i
2117 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2118 timeout := time.After(5 * time.Second)
2119 for atomic.LoadUint32(&finalized) == 0 {
2122 t.Fatal("finalizer did not run")
2128 runtime.KeepAlive(v)
2131 func TestMakeFunc(t *testing.T) {
2133 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2134 ValueOf(&f).Elem().Set(fv)
2136 // Call g with small arguments so that there is
2137 // something predictable (and different from the
2138 // correct results) in those positions on the stack.
2140 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2142 // Call constructed function f.
2143 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2144 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2145 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)
2149 func TestMakeFuncInterface(t *testing.T) {
2150 fn := func(i int) int { return i }
2151 incr := func(in []Value) []Value {
2152 return []Value{ValueOf(int(in[0].Int() + 1))}
2154 fv := MakeFunc(TypeOf(fn), incr)
2155 ValueOf(&fn).Elem().Set(fv)
2156 if r := fn(2); r != 3 {
2157 t.Errorf("Call returned %d, want 3", r)
2159 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2160 t.Errorf("Call returned %d, want 15", r)
2162 if r := fv.Interface().(func(int) int)(26); r != 27 {
2163 t.Errorf("Call returned %d, want 27", r)
2167 func TestMakeFuncVariadic(t *testing.T) {
2168 // Test that variadic arguments are packed into a slice and passed as last arg
2169 fn := func(_ int, is ...int) []int { return nil }
2170 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2171 ValueOf(&fn).Elem().Set(fv)
2174 if r[0] != 2 || r[1] != 3 {
2175 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2178 r = fn(1, []int{2, 3}...)
2179 if r[0] != 2 || r[1] != 3 {
2180 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2183 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2184 if r[0] != 2 || r[1] != 3 {
2185 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2188 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2189 if r[0] != 2 || r[1] != 3 {
2190 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2193 f := fv.Interface().(func(int, ...int) []int)
2196 if r[0] != 2 || r[1] != 3 {
2197 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2199 r = f(1, []int{2, 3}...)
2200 if r[0] != 2 || r[1] != 3 {
2201 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2205 // Dummy type that implements io.WriteCloser
2209 func (w *WC) Write(p []byte) (n int, err error) {
2212 func (w *WC) Close() error {
2216 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2217 // reflect.Values returned from the wrapped function should be assignment-converted
2218 // to the types returned by the result of MakeFunc.
2220 // Concrete types should be promotable to interfaces they implement.
2222 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2223 return []Value{ValueOf(io.EOF)}
2224 }).Interface().(func() error)
2227 // Super-interfaces should be promotable to simpler interfaces.
2228 var g func() io.Writer
2229 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2230 var w io.WriteCloser = &WC{}
2231 return []Value{ValueOf(&w).Elem()}
2232 }).Interface().(func() io.Writer)
2235 // Channels should be promotable to directional channels.
2236 var h func() <-chan int
2237 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2238 return []Value{ValueOf(make(chan int))}
2239 }).Interface().(func() <-chan int)
2242 // Unnamed types should be promotable to named types.
2243 type T struct{ a, b, c int }
2245 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2246 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2247 }).Interface().(func() T)
2251 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2252 // Type doesn't implement the required interface.
2253 shouldPanic("", func() {
2255 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2256 return []Value{ValueOf(int(7))}
2257 }).Interface().(func() error)
2260 // Assigning to an interface with additional methods.
2261 shouldPanic("", func() {
2262 var f func() io.ReadWriteCloser
2263 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2264 var w io.WriteCloser = &WC{}
2265 return []Value{ValueOf(&w).Elem()}
2266 }).Interface().(func() io.ReadWriteCloser)
2269 // Directional channels can't be assigned to bidirectional ones.
2270 shouldPanic("", func() {
2271 var f func() chan int
2272 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2273 var c <-chan int = make(chan int)
2274 return []Value{ValueOf(c)}
2275 }).Interface().(func() chan int)
2278 // Two named types which are otherwise identical.
2279 shouldPanic("", func() {
2280 type T struct{ a, b, c int }
2281 type U struct{ a, b, c int }
2283 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2284 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2285 }).Interface().(func() T)
2294 // This will be index 0.
2295 func (p Point) AnotherMethod(scale int) int {
2299 // This will be index 1.
2300 func (p Point) Dist(scale int) int {
2301 //println("Point.Dist", p.x, p.y, scale)
2302 return p.x*p.x*scale + p.y*p.y*scale
2305 // This will be index 2.
2306 func (p Point) GCMethod(k int) int {
2311 // This will be index 3.
2312 func (p Point) NoArgs() {
2313 // Exercise no-argument/no-result paths.
2316 // This will be index 4.
2317 func (p Point) TotalDist(points ...Point) int {
2319 for _, q := range points {
2322 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2328 // This will be index 5.
2329 func (p *Point) Int64Method(x int64) int64 {
2333 // This will be index 6.
2334 func (p *Point) Int32Method(x int32) int32 {
2338 func TestMethod(t *testing.T) {
2339 // Non-curried method of type.
2341 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2343 t.Errorf("Type Method returned %d; want 250", i)
2346 m, ok := TypeOf(p).MethodByName("Dist")
2348 t.Fatalf("method by name failed")
2350 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2352 t.Errorf("Type MethodByName returned %d; want 275", i)
2355 m, ok = TypeOf(p).MethodByName("NoArgs")
2357 t.Fatalf("method by name failed")
2359 n := len(m.Func.Call([]Value{ValueOf(p)}))
2361 t.Errorf("NoArgs returned %d values; want 0", n)
2364 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2366 t.Errorf("Pointer Type Method returned %d; want 300", i)
2369 m, ok = TypeOf(&p).MethodByName("Dist")
2371 t.Fatalf("ptr method by name failed")
2373 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2375 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2378 m, ok = TypeOf(&p).MethodByName("NoArgs")
2380 t.Fatalf("method by name failed")
2382 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2384 t.Errorf("NoArgs returned %d values; want 0", n)
2387 // Curried method of value.
2388 tfunc := TypeOf((func(int) int)(nil))
2389 v := ValueOf(p).Method(1)
2390 if tt := v.Type(); tt != tfunc {
2391 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2393 i = v.Call([]Value{ValueOf(14)})[0].Int()
2395 t.Errorf("Value Method returned %d; want 350", i)
2397 v = ValueOf(p).MethodByName("Dist")
2398 if tt := v.Type(); tt != tfunc {
2399 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2401 i = v.Call([]Value{ValueOf(15)})[0].Int()
2403 t.Errorf("Value MethodByName returned %d; want 375", i)
2405 v = ValueOf(p).MethodByName("NoArgs")
2408 // Curried method of pointer.
2409 v = ValueOf(&p).Method(1)
2410 if tt := v.Type(); tt != tfunc {
2411 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2413 i = v.Call([]Value{ValueOf(16)})[0].Int()
2415 t.Errorf("Pointer Value Method returned %d; want 400", i)
2417 v = ValueOf(&p).MethodByName("Dist")
2418 if tt := v.Type(); tt != tfunc {
2419 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2421 i = v.Call([]Value{ValueOf(17)})[0].Int()
2423 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2425 v = ValueOf(&p).MethodByName("NoArgs")
2428 // Curried method of interface value.
2429 // Have to wrap interface value in a struct to get at it.
2430 // Passing it to ValueOf directly would
2431 // access the underlying Point, not the interface.
2435 pv := ValueOf(&x).Elem()
2437 if tt := v.Type(); tt != tfunc {
2438 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2440 i = v.Call([]Value{ValueOf(18)})[0].Int()
2442 t.Errorf("Interface Method returned %d; want 450", i)
2444 v = pv.MethodByName("Dist")
2445 if tt := v.Type(); tt != tfunc {
2446 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2448 i = v.Call([]Value{ValueOf(19)})[0].Int()
2450 t.Errorf("Interface MethodByName returned %d; want 475", i)
2454 func TestMethodValue(t *testing.T) {
2458 // Check that method value have the same underlying code pointers.
2459 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2460 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2463 // Curried method of value.
2464 tfunc := TypeOf((func(int) int)(nil))
2465 v := ValueOf(p).Method(1)
2466 if tt := v.Type(); tt != tfunc {
2467 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2469 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2471 t.Errorf("Value Method returned %d; want 250", i)
2473 v = ValueOf(p).MethodByName("Dist")
2474 if tt := v.Type(); tt != tfunc {
2475 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2477 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2479 t.Errorf("Value MethodByName returned %d; want 275", i)
2481 v = ValueOf(p).MethodByName("NoArgs")
2482 ValueOf(v.Interface()).Call(nil)
2483 v.Interface().(func())()
2485 // Curried method of pointer.
2486 v = ValueOf(&p).Method(1)
2487 if tt := v.Type(); tt != tfunc {
2488 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2490 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2492 t.Errorf("Pointer Value Method returned %d; want 300", i)
2494 v = ValueOf(&p).MethodByName("Dist")
2495 if tt := v.Type(); tt != tfunc {
2496 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2498 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2500 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2502 v = ValueOf(&p).MethodByName("NoArgs")
2503 ValueOf(v.Interface()).Call(nil)
2504 v.Interface().(func())()
2506 // Curried method of pointer to pointer.
2508 v = ValueOf(&pp).Elem().Method(1)
2509 if tt := v.Type(); tt != tfunc {
2510 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2512 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2514 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2516 v = ValueOf(&pp).Elem().MethodByName("Dist")
2517 if tt := v.Type(); tt != tfunc {
2518 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2520 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2522 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2525 // Curried method of interface value.
2526 // Have to wrap interface value in a struct to get at it.
2527 // Passing it to ValueOf directly would
2528 // access the underlying Point, not the interface.
2534 pv := ValueOf(s).Field(0)
2536 if tt := v.Type(); tt != tfunc {
2537 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2539 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2541 t.Errorf("Interface Method returned %d; want 400", i)
2543 v = pv.MethodByName("Dist")
2544 if tt := v.Type(); tt != tfunc {
2545 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2547 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2549 t.Errorf("Interface MethodByName returned %d; want 425", i)
2552 // For issue #33628: method args are not stored at the right offset
2554 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2555 if x := m64(123); x != 123 {
2556 t.Errorf("Int64Method returned %d; want 123", x)
2558 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2559 if x := m32(456); x != 456 {
2560 t.Errorf("Int32Method returned %d; want 456", x)
2564 func TestVariadicMethodValue(t *testing.T) {
2566 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2567 want := int64(p.TotalDist(points[0], points[1], points[2]))
2569 // Variadic method of type.
2570 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2571 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2572 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2575 // Curried method of value.
2576 tfunc = TypeOf((func(...Point) int)(nil))
2577 v := ValueOf(p).Method(4)
2578 if tt := v.Type(); tt != tfunc {
2579 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2581 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2583 t.Errorf("Variadic Method returned %d; want %d", i, want)
2585 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2587 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2590 f := v.Interface().(func(...Point) int)
2591 i = int64(f(points[0], points[1], points[2]))
2593 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2595 i = int64(f(points...))
2597 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2601 type DirectIfaceT struct {
2605 func (d DirectIfaceT) M() int { return *d.p }
2607 func TestDirectIfaceMethod(t *testing.T) {
2609 v := DirectIfaceT{&x}
2611 m, ok := typ.MethodByName("M")
2613 t.Fatalf("cannot find method M")
2615 in := []Value{ValueOf(v)}
2616 out := m.Func.Call(in)
2617 if got := out[0].Int(); got != 42 {
2618 t.Errorf("Call with value receiver got %d, want 42", got)
2623 m, ok = typ.MethodByName("M")
2625 t.Fatalf("cannot find method M")
2627 in = []Value{ValueOf(pv)}
2628 out = m.Func.Call(in)
2629 if got := out[0].Int(); got != 42 {
2630 t.Errorf("Call with pointer receiver got %d, want 42", got)
2634 // Reflect version of $GOROOT/test/method5.go
2636 // Concrete types implementing M method.
2637 // Smaller than a word, word-sized, larger than a word.
2638 // Value and pointer receivers.
2640 type Tinter interface {
2641 M(int, byte) (byte, int)
2646 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2650 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2654 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2658 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2660 type Tbigv [2]uintptr
2662 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2664 type Tbigp [2]uintptr
2666 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2668 type tinter interface {
2669 m(int, byte) (byte, int)
2672 // Embedding via pointer.
2689 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2691 func TestMethod5(t *testing.T) {
2692 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2694 if b != 99 || x != 1000+inc {
2695 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2699 CheckV := func(name string, i Value, inc int) {
2700 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2701 b := bx[0].Interface()
2702 x := bx[1].Interface()
2703 if b != byte(99) || x != 1000+inc {
2704 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2707 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2710 var TinterType = TypeOf(new(Tinter)).Elem()
2712 CheckI := func(name string, i any, inc int) {
2714 CheckV(name, v, inc)
2715 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2720 CheckI("&sv", &sv, 1)
2723 CheckI("&sp", &sp, 2)
2727 CheckI("&wv", &wv, 3)
2730 CheckI("&wp", &wp, 4)
2732 bv := Tbigv([2]uintptr{5, 6})
2733 CheckI("bv", bv, 11)
2734 CheckI("&bv", &bv, 11)
2736 bp := Tbigp([2]uintptr{7, 8})
2737 CheckI("&bp", &bp, 15)
2743 CheckI("t4", t4, 40)
2744 CheckI("&t4", &t4, 40)
2745 CheckI("t3", t3, 40)
2746 CheckI("&t3", &t3, 40)
2747 CheckI("t2", t2, 40)
2748 CheckI("&t2", &t2, 40)
2749 CheckI("t1", t1, 40)
2750 CheckI("&t1", &t1, 40)
2753 vnil := ValueOf(&tnil).Elem()
2754 shouldPanic("Method", func() { vnil.Method(0) })
2757 func TestInterfaceSet(t *testing.T) {
2766 sv := ValueOf(&s).Elem()
2767 sv.Field(0).Set(ValueOf(p))
2768 if q := s.I.(*Point); q != p {
2769 t.Errorf("i: have %p want %p", q, p)
2774 if q := s.P.(*Point); q != p {
2775 t.Errorf("i: have %p want %p", q, p)
2778 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2780 t.Errorf("Interface Method returned %d; want 250", i)
2789 func TestAnonymousFields(t *testing.T) {
2790 var field StructField
2794 if field, ok = type1.FieldByName("int"); !ok {
2795 t.Fatal("no field 'int'")
2797 if field.Index[0] != 1 {
2798 t.Error("field index should be 1; is", field.Index)
2852 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2874 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2893 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2907 var fieldTests = []FTest{
2908 {struct{}{}, "", nil, 0},
2909 {struct{}{}, "Foo", nil, 0},
2910 {S0{A: 'a'}, "A", []int{0}, 'a'},
2911 {S0{}, "D", nil, 0},
2912 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2913 {S1{B: 'b'}, "B", []int{0}, 'b'},
2914 {S1{}, "S0", []int{1}, 0},
2915 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2916 {S2{A: 'a'}, "A", []int{0}, 'a'},
2917 {S2{}, "S1", []int{1}, 0},
2918 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2919 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2920 {S2{}, "D", nil, 0},
2921 {S3{}, "S1", nil, 0},
2922 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2923 {S3{}, "B", nil, 0},
2924 {S3{D: 'd'}, "D", []int{2}, 0},
2925 {S3{E: 'e'}, "E", []int{3}, 'e'},
2926 {S4{A: 'a'}, "A", []int{1}, 'a'},
2927 {S4{}, "B", nil, 0},
2928 {S5{}, "X", nil, 0},
2929 {S5{}, "Y", []int{2, 0, 1}, 0},
2930 {S10{}, "X", nil, 0},
2931 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2932 {S14{}, "X", nil, 0},
2935 func TestFieldByIndex(t *testing.T) {
2936 for _, test := range fieldTests {
2938 f := s.FieldByIndex(test.index)
2940 if test.index != nil {
2941 if f.Name != test.name {
2942 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2945 t.Errorf("%s.%s found", s.Name(), f.Name)
2947 } else if len(test.index) > 0 {
2948 t.Errorf("%s.%s not found", s.Name(), test.name)
2951 if test.value != 0 {
2952 v := ValueOf(test.s).FieldByIndex(test.index)
2954 if x, ok := v.Interface().(int); ok {
2955 if x != test.value {
2956 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2959 t.Errorf("%s%v value not an int", s.Name(), test.index)
2962 t.Errorf("%s%v value not found", s.Name(), test.index)
2968 func TestFieldByName(t *testing.T) {
2969 for _, test := range fieldTests {
2971 f, found := s.FieldByName(test.name)
2973 if test.index != nil {
2974 // Verify field depth and index.
2975 if len(f.Index) != len(test.index) {
2976 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)
2978 for i, x := range f.Index {
2979 if x != test.index[i] {
2980 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2985 t.Errorf("%s.%s found", s.Name(), f.Name)
2987 } else if len(test.index) > 0 {
2988 t.Errorf("%s.%s not found", s.Name(), test.name)
2991 if test.value != 0 {
2992 v := ValueOf(test.s).FieldByName(test.name)
2994 if x, ok := v.Interface().(int); ok {
2995 if x != test.value {
2996 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2999 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3002 t.Errorf("%s.%s value not found", s.Name(), test.name)
3008 func TestImportPath(t *testing.T) {
3013 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3014 {TypeOf(int(0)), ""},
3015 {TypeOf(int8(0)), ""},
3016 {TypeOf(int16(0)), ""},
3017 {TypeOf(int32(0)), ""},
3018 {TypeOf(int64(0)), ""},
3019 {TypeOf(uint(0)), ""},
3020 {TypeOf(uint8(0)), ""},
3021 {TypeOf(uint16(0)), ""},
3022 {TypeOf(uint32(0)), ""},
3023 {TypeOf(uint64(0)), ""},
3024 {TypeOf(uintptr(0)), ""},
3025 {TypeOf(float32(0)), ""},
3026 {TypeOf(float64(0)), ""},
3027 {TypeOf(complex64(0)), ""},
3028 {TypeOf(complex128(0)), ""},
3029 {TypeOf(byte(0)), ""},
3030 {TypeOf(rune(0)), ""},
3031 {TypeOf([]byte(nil)), ""},
3032 {TypeOf([]rune(nil)), ""},
3033 {TypeOf(string("")), ""},
3034 {TypeOf((*any)(nil)).Elem(), ""},
3035 {TypeOf((*byte)(nil)), ""},
3036 {TypeOf((*rune)(nil)), ""},
3037 {TypeOf((*int64)(nil)), ""},
3038 {TypeOf(map[string]int{}), ""},
3039 {TypeOf((*error)(nil)).Elem(), ""},
3040 {TypeOf((*Point)(nil)), ""},
3041 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3043 for _, test := range tests {
3044 if path := test.t.PkgPath(); path != test.path {
3045 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3050 func TestFieldPkgPath(t *testing.T) {
3052 typ := TypeOf(struct {
3060 type pkgpathTest struct {
3067 checkPkgPath := func(name string, s []pkgpathTest) {
3068 for _, test := range s {
3069 f := typ.FieldByIndex(test.index)
3070 if got, want := f.PkgPath, test.pkgPath; got != want {
3071 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3073 if got, want := f.Anonymous, test.embedded; got != want {
3074 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3076 if got, want := f.IsExported(), test.exported; got != want {
3077 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3082 checkPkgPath("testStruct", []pkgpathTest{
3083 {[]int{0}, "", false, true}, // Exported
3084 {[]int{1}, "reflect_test", false, false}, // unexported
3085 {[]int{2}, "", true, true}, // OtherPkgFields
3086 {[]int{2, 0}, "", false, true}, // OtherExported
3087 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3088 {[]int{3}, "reflect_test", true, false}, // int
3089 {[]int{4}, "reflect_test", true, false}, // *x
3092 type localOtherPkgFields OtherPkgFields
3093 typ = TypeOf(localOtherPkgFields{})
3094 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3095 {[]int{0}, "", false, true}, // OtherExported
3096 {[]int{1}, "reflect", false, false}, // otherUnexported
3100 func TestMethodPkgPath(t *testing.T) {
3105 typ := TypeOf((*interface {
3118 {"x", "reflect_test", false},
3119 {"y", "reflect_test", false},
3122 for _, test := range tests {
3123 m, _ := typ.MethodByName(test.name)
3124 if got, want := m.PkgPath, test.pkgPath; got != want {
3125 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3127 if got, want := m.IsExported(), test.exported; got != want {
3128 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3133 func TestVariadicType(t *testing.T) {
3134 // Test example from Type documentation.
3135 var f func(x int, y ...float64)
3137 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3139 if sl.Kind() == Slice {
3140 if sl.Elem() == TypeOf(0.0) {
3148 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3149 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3150 for i := 0; i < typ.NumIn(); i++ {
3151 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3165 func (*inner) M() {}
3166 func (*outer) M() {}
3168 func TestNestedMethods(t *testing.T) {
3169 typ := TypeOf((*outer)(nil))
3170 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3171 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3172 for i := 0; i < typ.NumMethod(); i++ {
3174 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3181 func (*unexp) f() (int32, int8) { return 7, 7 }
3182 func (*unexp) g() (int64, int8) { return 8, 8 }
3184 type unexpI interface {
3188 var unexpi unexpI = new(unexp)
3190 func TestUnexportedMethods(t *testing.T) {
3191 typ := TypeOf(unexpi)
3193 if got := typ.NumMethod(); got != 0 {
3194 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3198 type InnerInt struct {
3202 type OuterInt struct {
3207 func (i *InnerInt) M() int {
3211 func TestEmbeddedMethods(t *testing.T) {
3212 typ := TypeOf((*OuterInt)(nil))
3213 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3214 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3215 for i := 0; i < typ.NumMethod(); i++ {
3217 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3222 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3223 t.Errorf("i.M() = %d, want 3", v)
3226 o := &OuterInt{1, InnerInt{2}}
3227 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3228 t.Errorf("i.M() = %d, want 2", v)
3232 if v := f(o); v != 2 {
3233 t.Errorf("f(o) = %d, want 2", v)
3237 type FuncDDD func(...any) error
3239 func (f FuncDDD) M() {}
3241 func TestNumMethodOnDDD(t *testing.T) {
3242 rv := ValueOf((FuncDDD)(nil))
3243 if n := rv.NumMethod(); n != 1 {
3244 t.Fatalf("NumMethod()=%d, want 1", n)
3248 func TestPtrTo(t *testing.T) {
3249 // This block of code means that the ptrToThis field of the
3250 // reflect data for *unsafe.Pointer is non zero, see
3251 // https://golang.org/issue/19003
3252 var x unsafe.Pointer
3259 for i = 0; i < 100; i++ {
3260 typ = PointerTo(typ)
3262 for i = 0; i < 100; i++ {
3265 if typ != TypeOf(z) {
3266 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3270 func TestPtrToGC(t *testing.T) {
3272 tt := TypeOf(T(nil))
3276 for i := 0; i < n; i++ {
3281 v.Elem().Set(ValueOf(p).Convert(pt))
3282 x = append(x, v.Interface())
3286 for i, xi := range x {
3287 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3288 if k != uintptr(i) {
3289 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3294 func TestAddr(t *testing.T) {
3306 t.Errorf("Addr.Elem.Set failed to set value")
3309 // Again but take address of the ValueOf value.
3310 // Exercises generation of PtrTypes not present in the binary.
3312 v = ValueOf(&q).Elem()
3321 t.Errorf("Addr.Elem.Set failed to set value")
3324 // Starting without pointer we should get changed value
3327 v = ValueOf(&qq).Elem()
3333 if p.X != 3 { // should be unchanged from last time
3334 t.Errorf("somehow value Set changed original p")
3336 p = v0.Interface().(struct {
3340 t.Errorf("Addr.Elem.Set valued to set value in top value")
3343 // Verify that taking the address of a type gives us a pointer
3344 // which we can convert back using the usual interface
3349 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3350 *(ps.(**bool)) = new(bool)
3352 t.Errorf("Addr.Interface direct assignment failed")
3356 func noAlloc(t *testing.T, n int, f func(int)) {
3357 if testing.Short() {
3358 t.Skip("skipping malloc count in short mode")
3360 if runtime.GOMAXPROCS(0) > 1 {
3361 t.Skip("skipping; GOMAXPROCS>1")
3364 allocs := testing.AllocsPerRun(n, func() {
3369 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3373 func TestAllocations(t *testing.T) {
3374 noAlloc(t, 100, func(j int) {
3378 // We can uncomment this when compiler escape analysis
3379 // is good enough to see that the integer assigned to i
3380 // does not escape and therefore need not be allocated.
3384 // if int(v.Int()) != 42+j {
3385 // panic("wrong int")
3388 i = func(j int) int { return j }
3390 if v.Interface().(func(int) int)(j) != j {
3391 panic("wrong result")
3396 func TestSmallNegativeInt(t *testing.T) {
3400 t.Errorf("int16(-1).Int() returned %v", v.Int())
3404 func TestIndex(t *testing.T) {
3405 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3406 v := ValueOf(xs).Index(3).Interface().(byte)
3408 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3410 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3411 v = ValueOf(xa).Index(2).Interface().(byte)
3413 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3416 v = ValueOf(s).Index(3).Interface().(byte)
3418 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3422 func TestSlice(t *testing.T) {
3423 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3424 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3426 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3429 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3431 if !DeepEqual(v[0:5], xs[3:]) {
3432 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3434 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3435 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3437 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3440 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3442 if !DeepEqual(v[0:6], xa[2:]) {
3443 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3446 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3448 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3451 rv := ValueOf(&xs).Elem()
3453 ptr2 := rv.UnsafePointer()
3455 ptr3 := rv.UnsafePointer()
3457 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3461 func TestSlice3(t *testing.T) {
3462 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3463 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3465 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3468 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3470 if !DeepEqual(v[0:4], xs[3:7:7]) {
3471 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3473 rv := ValueOf(&xs).Elem()
3474 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3475 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3476 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3478 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3479 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3481 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3484 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3486 if !DeepEqual(v[0:4], xa[2:6:6]) {
3487 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3489 rv = ValueOf(&xa).Elem()
3490 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3491 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3492 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3495 rv = ValueOf(&s).Elem()
3496 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3498 rv = ValueOf(&xs).Elem()
3499 rv = rv.Slice3(3, 5, 7)
3500 ptr2 := rv.UnsafePointer()
3501 rv = rv.Slice3(4, 4, 4)
3502 ptr3 := rv.UnsafePointer()
3504 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3508 func TestSetLenCap(t *testing.T) {
3509 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3510 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3512 vs := ValueOf(&xs).Elem()
3513 shouldPanic("SetLen", func() { vs.SetLen(10) })
3514 shouldPanic("SetCap", func() { vs.SetCap(10) })
3515 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3516 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3517 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3519 if len(xs) != 5 || cap(xs) != 8 {
3520 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3523 if len(xs) != 5 || cap(xs) != 6 {
3524 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3527 if len(xs) != 5 || cap(xs) != 5 {
3528 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3530 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3531 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3533 va := ValueOf(&xa).Elem()
3534 shouldPanic("SetLen", func() { va.SetLen(8) })
3535 shouldPanic("SetCap", func() { va.SetCap(8) })
3538 func TestVariadic(t *testing.T) {
3539 var b strings.Builder
3543 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3544 if b.String() != "hello, 42 world" {
3545 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3549 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3550 if b.String() != "hello, 42 world" {
3551 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3555 func TestFuncArg(t *testing.T) {
3556 f1 := func(i int, f func(int) int) int { return f(i) }
3557 f2 := func(i int) int { return i + 1 }
3558 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3559 if r[0].Int() != 101 {
3560 t.Errorf("function returned %d, want 101", r[0].Int())
3564 func TestStructArg(t *testing.T) {
3565 type padded struct {
3572 wantA = padded{"3", 4}
3575 f := func(a padded, b uint32) {
3578 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3579 if gotA != wantA || gotB != wantB {
3580 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3584 var tagGetTests = []struct {
3589 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3590 {`protobuf:"PB(1,2)"`, `foo`, ``},
3591 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3592 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3593 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3594 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3595 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3598 func TestTagGet(t *testing.T) {
3599 for _, tt := range tagGetTests {
3600 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3601 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3606 func TestBytes(t *testing.T) {
3607 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3608 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3612 y := ValueOf(x).Bytes()
3613 if !bytes.Equal(x, y) {
3614 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3617 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3622 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3623 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3624 b := ValueOf(&a).Elem().Bytes()
3625 if !bytes.Equal(a[:], y) {
3626 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3629 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3632 // Per issue #24746, it was decided that Bytes can be called on byte slices
3633 // that normally cannot be converted from per Go language semantics.
3637 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3638 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3639 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3640 ValueOf(new(AB)).Elem().Bytes() // should not panic
3643 func TestSetBytes(t *testing.T) {
3646 y := []byte{1, 2, 3, 4}
3647 ValueOf(&x).Elem().SetBytes(y)
3648 if !bytes.Equal(x, y) {
3649 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3652 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3656 type Private struct {
3662 func (p *Private) m() {
3665 type private struct {
3673 func (p *private) P() {
3676 type Public struct {
3682 func (p *Public) M() {
3685 func TestUnexported(t *testing.T) {
3690 isValid(v.Elem().Field(0))
3691 isValid(v.Elem().Field(1))
3692 isValid(v.Elem().Field(2))
3693 isValid(v.Elem().FieldByName("X"))
3694 isValid(v.Elem().FieldByName("Y"))
3695 isValid(v.Elem().FieldByName("Z"))
3696 isValid(v.Type().Method(0).Func)
3697 m, _ := v.Type().MethodByName("M")
3699 m, _ = v.Type().MethodByName("P")
3701 isNonNil(v.Elem().Field(0).Interface())
3702 isNonNil(v.Elem().Field(1).Interface())
3703 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3704 isNonNil(v.Elem().FieldByName("X").Interface())
3705 isNonNil(v.Elem().FieldByName("Y").Interface())
3706 isNonNil(v.Elem().FieldByName("Z").Interface())
3707 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3708 isNonNil(v.Type().Method(0).Func.Interface())
3709 m, _ = v.Type().MethodByName("P")
3710 isNonNil(m.Func.Interface())
3714 isValid(v.Elem().Field(0))
3715 isValid(v.Elem().Field(1))
3716 isValid(v.Elem().FieldByName("x"))
3717 isValid(v.Elem().FieldByName("y"))
3718 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3719 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3720 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3721 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3722 shouldPanic("Method", func() { v.Type().Method(0) })
3725 func TestSetPanic(t *testing.T) {
3726 ok := func(f func()) { f() }
3727 bad := func(f func()) { shouldPanic("Set", f) }
3728 clear := func(v Value) { v.Set(Zero(v.Type())) }
3756 bad(func() { clear(v.Field(0)) }) // .X
3757 bad(func() { clear(v.Field(1)) }) // .t1
3758 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3759 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3760 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3761 bad(func() { clear(v.Field(2)) }) // .T2
3762 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3763 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3764 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3765 bad(func() { clear(v.Field(3)) }) // .NamedT1
3766 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3767 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3768 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3769 bad(func() { clear(v.Field(4)) }) // .NamedT2
3770 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3771 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3772 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3773 bad(func() { clear(v.Field(5)) }) // .namedT1
3774 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3775 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3776 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3777 bad(func() { clear(v.Field(6)) }) // .namedT2
3778 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3779 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3780 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3783 v = ValueOf(&T{}).Elem()
3784 ok(func() { clear(v.Field(0)) }) // .X
3785 bad(func() { clear(v.Field(1)) }) // .t1
3786 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3787 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3788 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3789 ok(func() { clear(v.Field(2)) }) // .T2
3790 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3791 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3792 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3793 ok(func() { clear(v.Field(3)) }) // .NamedT1
3794 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3795 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3796 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3797 ok(func() { clear(v.Field(4)) }) // .NamedT2
3798 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3799 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3800 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3801 bad(func() { clear(v.Field(5)) }) // .namedT1
3802 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3803 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3804 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3805 bad(func() { clear(v.Field(6)) }) // .namedT2
3806 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3807 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3808 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3813 func (t timp) W() {}
3814 func (t timp) Y() {}
3815 func (t timp) w() {}
3816 func (t timp) y() {}
3818 func TestCallPanic(t *testing.T) {
3843 ok := func(f func()) { f() }
3844 badCall := func(f func()) { shouldPanic("Call", f) }
3845 badMethod := func(f func()) { shouldPanic("Method", f) }
3846 call := func(v Value) { v.Call(nil) }
3849 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3850 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3851 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3852 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3853 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3854 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3855 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3856 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3857 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3859 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3860 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3861 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3862 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3864 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3865 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3866 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3867 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3869 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3870 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3871 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3872 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3874 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3875 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3876 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3877 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3879 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3880 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3881 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3882 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3884 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3885 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3886 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3887 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3890 func TestValuePanic(t *testing.T) {
3892 shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
3893 shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
3894 shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
3895 shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
3896 shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
3897 shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
3898 shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
3899 shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
3900 shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
3901 shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
3902 shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
3903 shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
3904 shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
3905 shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
3906 shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
3907 shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
3908 shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
3909 shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
3910 shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
3911 shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
3912 shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
3913 shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
3914 shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
3915 shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
3916 shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
3917 shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
3918 shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
3919 shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
3920 shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
3921 shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
3922 shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
3923 shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
3924 shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
3925 shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
3926 shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
3927 shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
3928 shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
3929 shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
3930 shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
3931 shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
3932 shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
3935 func shouldPanic(expect string, f func()) {
3939 panic("did not panic")
3943 switch r := r.(type) {
3949 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3951 if !strings.HasPrefix(s, "reflect") {
3952 panic(`panic string does not start with "reflect": ` + s)
3954 if !strings.Contains(s, expect) {
3955 panic(`panic string does not contain "` + expect + `": ` + s)
3962 func isNonNil(x any) {
3964 panic("nil interface")
3968 func isValid(v Value) {
3974 func TestAlias(t *testing.T) {
3975 x := string("hello")
3976 v := ValueOf(&x).Elem()
3977 oldvalue := v.Interface()
3978 v.SetString("world")
3979 newvalue := v.Interface()
3981 if oldvalue != "hello" || newvalue != "world" {
3982 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3988 func EmptyInterfaceV(x any) Value {
3989 return ValueOf(&x).Elem()
3992 func ReaderV(x io.Reader) Value {
3993 return ValueOf(&x).Elem()
3996 func ReadWriterV(x io.ReadWriter) Value {
3997 return ValueOf(&x).Elem()
4001 type MyStruct struct {
4004 type MyStruct1 struct {
4009 type MyStruct2 struct {
4014 type MyString string
4016 type MyBytesArrayPtr0 *[0]byte
4017 type MyBytesArrayPtr *[4]byte
4018 type MyBytesArray0 [0]byte
4019 type MyBytesArray [4]byte
4020 type MyRunes []int32
4024 type IntChan chan int
4025 type IntChanRecv <-chan int
4026 type IntChanSend chan<- int
4027 type BytesChan chan []byte
4028 type BytesChanRecv <-chan []byte
4029 type BytesChanSend chan<- []byte
4031 var convertTests = []struct {
4037 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4043 var numbers = []string{
4044 "int8", "uint8", "int16", "uint16",
4045 "int32", "uint32", "int64", "uint64",
4046 "int", "uint", "uintptr",
4047 "float32", "float64",
4051 // all pairs but in an unusual order,
4052 // to emit all the int8, uint8 cases
4053 // before n grows too big.
4055 for i, f := range numbers {
4056 for _, g := range numbers[i:] {
4057 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4060 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4067 {V(int8(1)), V(int8(1))},
4068 {V(int8(2)), V(uint8(2))},
4069 {V(uint8(3)), V(int8(3))},
4070 {V(int8(4)), V(int16(4))},
4071 {V(int16(5)), V(int8(5))},
4072 {V(int8(6)), V(uint16(6))},
4073 {V(uint16(7)), V(int8(7))},
4074 {V(int8(8)), V(int32(8))},
4075 {V(int32(9)), V(int8(9))},
4076 {V(int8(10)), V(uint32(10))},
4077 {V(uint32(11)), V(int8(11))},
4078 {V(int8(12)), V(int64(12))},
4079 {V(int64(13)), V(int8(13))},
4080 {V(int8(14)), V(uint64(14))},
4081 {V(uint64(15)), V(int8(15))},
4082 {V(int8(16)), V(int(16))},
4083 {V(int(17)), V(int8(17))},
4084 {V(int8(18)), V(uint(18))},
4085 {V(uint(19)), V(int8(19))},
4086 {V(int8(20)), V(uintptr(20))},
4087 {V(uintptr(21)), V(int8(21))},
4088 {V(int8(22)), V(float32(22))},
4089 {V(float32(23)), V(int8(23))},
4090 {V(int8(24)), V(float64(24))},
4091 {V(float64(25)), V(int8(25))},
4092 {V(uint8(26)), V(uint8(26))},
4093 {V(uint8(27)), V(int16(27))},
4094 {V(int16(28)), V(uint8(28))},
4095 {V(uint8(29)), V(uint16(29))},
4096 {V(uint16(30)), V(uint8(30))},
4097 {V(uint8(31)), V(int32(31))},
4098 {V(int32(32)), V(uint8(32))},
4099 {V(uint8(33)), V(uint32(33))},
4100 {V(uint32(34)), V(uint8(34))},
4101 {V(uint8(35)), V(int64(35))},
4102 {V(int64(36)), V(uint8(36))},
4103 {V(uint8(37)), V(uint64(37))},
4104 {V(uint64(38)), V(uint8(38))},
4105 {V(uint8(39)), V(int(39))},
4106 {V(int(40)), V(uint8(40))},
4107 {V(uint8(41)), V(uint(41))},
4108 {V(uint(42)), V(uint8(42))},
4109 {V(uint8(43)), V(uintptr(43))},
4110 {V(uintptr(44)), V(uint8(44))},
4111 {V(uint8(45)), V(float32(45))},
4112 {V(float32(46)), V(uint8(46))},
4113 {V(uint8(47)), V(float64(47))},
4114 {V(float64(48)), V(uint8(48))},
4115 {V(int16(49)), V(int16(49))},
4116 {V(int16(50)), V(uint16(50))},
4117 {V(uint16(51)), V(int16(51))},
4118 {V(int16(52)), V(int32(52))},
4119 {V(int32(53)), V(int16(53))},
4120 {V(int16(54)), V(uint32(54))},
4121 {V(uint32(55)), V(int16(55))},
4122 {V(int16(56)), V(int64(56))},
4123 {V(int64(57)), V(int16(57))},
4124 {V(int16(58)), V(uint64(58))},
4125 {V(uint64(59)), V(int16(59))},
4126 {V(int16(60)), V(int(60))},
4127 {V(int(61)), V(int16(61))},
4128 {V(int16(62)), V(uint(62))},
4129 {V(uint(63)), V(int16(63))},
4130 {V(int16(64)), V(uintptr(64))},
4131 {V(uintptr(65)), V(int16(65))},
4132 {V(int16(66)), V(float32(66))},
4133 {V(float32(67)), V(int16(67))},
4134 {V(int16(68)), V(float64(68))},
4135 {V(float64(69)), V(int16(69))},
4136 {V(uint16(70)), V(uint16(70))},
4137 {V(uint16(71)), V(int32(71))},
4138 {V(int32(72)), V(uint16(72))},
4139 {V(uint16(73)), V(uint32(73))},
4140 {V(uint32(74)), V(uint16(74))},
4141 {V(uint16(75)), V(int64(75))},
4142 {V(int64(76)), V(uint16(76))},
4143 {V(uint16(77)), V(uint64(77))},
4144 {V(uint64(78)), V(uint16(78))},
4145 {V(uint16(79)), V(int(79))},
4146 {V(int(80)), V(uint16(80))},
4147 {V(uint16(81)), V(uint(81))},
4148 {V(uint(82)), V(uint16(82))},
4149 {V(uint16(83)), V(uintptr(83))},
4150 {V(uintptr(84)), V(uint16(84))},
4151 {V(uint16(85)), V(float32(85))},
4152 {V(float32(86)), V(uint16(86))},
4153 {V(uint16(87)), V(float64(87))},
4154 {V(float64(88)), V(uint16(88))},
4155 {V(int32(89)), V(int32(89))},
4156 {V(int32(90)), V(uint32(90))},
4157 {V(uint32(91)), V(int32(91))},
4158 {V(int32(92)), V(int64(92))},
4159 {V(int64(93)), V(int32(93))},
4160 {V(int32(94)), V(uint64(94))},
4161 {V(uint64(95)), V(int32(95))},
4162 {V(int32(96)), V(int(96))},
4163 {V(int(97)), V(int32(97))},
4164 {V(int32(98)), V(uint(98))},
4165 {V(uint(99)), V(int32(99))},
4166 {V(int32(100)), V(uintptr(100))},
4167 {V(uintptr(101)), V(int32(101))},
4168 {V(int32(102)), V(float32(102))},
4169 {V(float32(103)), V(int32(103))},
4170 {V(int32(104)), V(float64(104))},
4171 {V(float64(105)), V(int32(105))},
4172 {V(uint32(106)), V(uint32(106))},
4173 {V(uint32(107)), V(int64(107))},
4174 {V(int64(108)), V(uint32(108))},
4175 {V(uint32(109)), V(uint64(109))},
4176 {V(uint64(110)), V(uint32(110))},
4177 {V(uint32(111)), V(int(111))},
4178 {V(int(112)), V(uint32(112))},
4179 {V(uint32(113)), V(uint(113))},
4180 {V(uint(114)), V(uint32(114))},
4181 {V(uint32(115)), V(uintptr(115))},
4182 {V(uintptr(116)), V(uint32(116))},
4183 {V(uint32(117)), V(float32(117))},
4184 {V(float32(118)), V(uint32(118))},
4185 {V(uint32(119)), V(float64(119))},
4186 {V(float64(120)), V(uint32(120))},
4187 {V(int64(121)), V(int64(121))},
4188 {V(int64(122)), V(uint64(122))},
4189 {V(uint64(123)), V(int64(123))},
4190 {V(int64(124)), V(int(124))},
4191 {V(int(125)), V(int64(125))},
4192 {V(int64(126)), V(uint(126))},
4193 {V(uint(127)), V(int64(127))},
4194 {V(int64(128)), V(uintptr(128))},
4195 {V(uintptr(129)), V(int64(129))},
4196 {V(int64(130)), V(float32(130))},
4197 {V(float32(131)), V(int64(131))},
4198 {V(int64(132)), V(float64(132))},
4199 {V(float64(133)), V(int64(133))},
4200 {V(uint64(134)), V(uint64(134))},
4201 {V(uint64(135)), V(int(135))},
4202 {V(int(136)), V(uint64(136))},
4203 {V(uint64(137)), V(uint(137))},
4204 {V(uint(138)), V(uint64(138))},
4205 {V(uint64(139)), V(uintptr(139))},
4206 {V(uintptr(140)), V(uint64(140))},
4207 {V(uint64(141)), V(float32(141))},
4208 {V(float32(142)), V(uint64(142))},
4209 {V(uint64(143)), V(float64(143))},
4210 {V(float64(144)), V(uint64(144))},
4211 {V(int(145)), V(int(145))},
4212 {V(int(146)), V(uint(146))},
4213 {V(uint(147)), V(int(147))},
4214 {V(int(148)), V(uintptr(148))},
4215 {V(uintptr(149)), V(int(149))},
4216 {V(int(150)), V(float32(150))},
4217 {V(float32(151)), V(int(151))},
4218 {V(int(152)), V(float64(152))},
4219 {V(float64(153)), V(int(153))},
4220 {V(uint(154)), V(uint(154))},
4221 {V(uint(155)), V(uintptr(155))},
4222 {V(uintptr(156)), V(uint(156))},
4223 {V(uint(157)), V(float32(157))},
4224 {V(float32(158)), V(uint(158))},
4225 {V(uint(159)), V(float64(159))},
4226 {V(float64(160)), V(uint(160))},
4227 {V(uintptr(161)), V(uintptr(161))},
4228 {V(uintptr(162)), V(float32(162))},
4229 {V(float32(163)), V(uintptr(163))},
4230 {V(uintptr(164)), V(float64(164))},
4231 {V(float64(165)), V(uintptr(165))},
4232 {V(float32(166)), V(float32(166))},
4233 {V(float32(167)), V(float64(167))},
4234 {V(float64(168)), V(float32(168))},
4235 {V(float64(169)), V(float64(169))},
4238 {V(float64(1.5)), V(int(1))},
4241 {V(complex64(1i)), V(complex64(1i))},
4242 {V(complex64(2i)), V(complex128(2i))},
4243 {V(complex128(3i)), V(complex64(3i))},
4244 {V(complex128(4i)), V(complex128(4i))},
4247 {V(string("hello")), V(string("hello"))},
4248 {V(string("bytes1")), V([]byte("bytes1"))},
4249 {V([]byte("bytes2")), V(string("bytes2"))},
4250 {V([]byte("bytes3")), V([]byte("bytes3"))},
4251 {V(string("runes♝")), V([]rune("runes♝"))},
4252 {V([]rune("runes♕")), V(string("runes♕"))},
4253 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4254 {V(int('a')), V(string("a"))},
4255 {V(int8('a')), V(string("a"))},
4256 {V(int16('a')), V(string("a"))},
4257 {V(int32('a')), V(string("a"))},
4258 {V(int64('a')), V(string("a"))},
4259 {V(uint('a')), V(string("a"))},
4260 {V(uint8('a')), V(string("a"))},
4261 {V(uint16('a')), V(string("a"))},
4262 {V(uint32('a')), V(string("a"))},
4263 {V(uint64('a')), V(string("a"))},
4264 {V(uintptr('a')), V(string("a"))},
4265 {V(int(-1)), V(string("\uFFFD"))},
4266 {V(int8(-2)), V(string("\uFFFD"))},
4267 {V(int16(-3)), V(string("\uFFFD"))},
4268 {V(int32(-4)), V(string("\uFFFD"))},
4269 {V(int64(-5)), V(string("\uFFFD"))},
4270 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4271 {V(int64(1 << 32)), V(string("\uFFFD"))},
4272 {V(uint(0x110001)), V(string("\uFFFD"))},
4273 {V(uint32(0x110002)), V(string("\uFFFD"))},
4274 {V(uint64(0x110003)), V(string("\uFFFD"))},
4275 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4276 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4279 {V(MyString("hello")), V(string("hello"))},
4280 {V(string("hello")), V(MyString("hello"))},
4281 {V(string("hello")), V(string("hello"))},
4282 {V(MyString("hello")), V(MyString("hello"))},
4283 {V(MyString("bytes1")), V([]byte("bytes1"))},
4284 {V([]byte("bytes2")), V(MyString("bytes2"))},
4285 {V([]byte("bytes3")), V([]byte("bytes3"))},
4286 {V(MyString("runes♝")), V([]rune("runes♝"))},
4287 {V([]rune("runes♕")), V(MyString("runes♕"))},
4288 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4289 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4290 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4291 {V(int('a')), V(MyString("a"))},
4292 {V(int8('a')), V(MyString("a"))},
4293 {V(int16('a')), V(MyString("a"))},
4294 {V(int32('a')), V(MyString("a"))},
4295 {V(int64('a')), V(MyString("a"))},
4296 {V(uint('a')), V(MyString("a"))},
4297 {V(uint8('a')), V(MyString("a"))},
4298 {V(uint16('a')), V(MyString("a"))},
4299 {V(uint32('a')), V(MyString("a"))},
4300 {V(uint64('a')), V(MyString("a"))},
4301 {V(uintptr('a')), V(MyString("a"))},
4302 {V(int(-1)), V(MyString("\uFFFD"))},
4303 {V(int8(-2)), V(MyString("\uFFFD"))},
4304 {V(int16(-3)), V(MyString("\uFFFD"))},
4305 {V(int32(-4)), V(MyString("\uFFFD"))},
4306 {V(int64(-5)), V(MyString("\uFFFD"))},
4307 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4308 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4309 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4310 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4313 {V(string("bytes1")), V(MyBytes("bytes1"))},
4314 {V(MyBytes("bytes2")), V(string("bytes2"))},
4315 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4316 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4317 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4320 {V(string("runes♝")), V(MyRunes("runes♝"))},
4321 {V(MyRunes("runes♕")), V(string("runes♕"))},
4322 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4323 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4324 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4326 // slice to array pointer
4327 {V([]byte(nil)), V((*[0]byte)(nil))},
4328 {V([]byte{}), V(new([0]byte))},
4329 {V([]byte{7}), V(&[1]byte{7})},
4330 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4331 {V(MyBytes([]byte{})), V(new([0]byte))},
4332 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4333 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4334 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4335 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4336 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4337 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4339 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4340 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4341 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4342 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4343 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4344 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4345 {V(new([0]byte)), V(new(MyBytesArray0))},
4346 {V(new(MyBytesArray0)), V(new([0]byte))},
4347 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4348 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4350 // named types and equal underlying types
4351 {V(new(int)), V(new(integer))},
4352 {V(new(integer)), V(new(int))},
4353 {V(Empty{}), V(struct{}{})},
4354 {V(new(Empty)), V(new(struct{}))},
4355 {V(struct{}{}), V(Empty{})},
4356 {V(new(struct{})), V(new(Empty))},
4357 {V(Empty{}), V(Empty{})},
4358 {V(MyBytes{}), V([]byte{})},
4359 {V([]byte{}), V(MyBytes{})},
4360 {V((func())(nil)), V(MyFunc(nil))},
4361 {V((MyFunc)(nil)), V((func())(nil))},
4363 // structs with different tags
4376 {V(MyStruct{}), V(struct {
4382 }{}), V(MyStruct{})},
4384 {V(MyStruct{}), V(struct {
4390 }{}), V(MyStruct{})},
4392 {V(MyStruct1{}), V(MyStruct2{})},
4393 {V(MyStruct2{}), V(MyStruct1{})},
4395 // can convert *byte and *MyByte
4396 {V((*byte)(nil)), V((*MyByte)(nil))},
4397 {V((*MyByte)(nil)), V((*byte)(nil))},
4399 // cannot convert mismatched array sizes
4400 {V([2]byte{}), V([2]byte{})},
4401 {V([3]byte{}), V([3]byte{})},
4403 // cannot convert other instances
4404 {V((**byte)(nil)), V((**byte)(nil))},
4405 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4406 {V((chan byte)(nil)), V((chan byte)(nil))},
4407 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4408 {V(([]byte)(nil)), V(([]byte)(nil))},
4409 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4410 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4411 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4412 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4413 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4414 {V([2]byte{}), V([2]byte{})},
4415 {V([2]MyByte{}), V([2]MyByte{})},
4418 {V((***int)(nil)), V((***int)(nil))},
4419 {V((***byte)(nil)), V((***byte)(nil))},
4420 {V((***int32)(nil)), V((***int32)(nil))},
4421 {V((***int64)(nil)), V((***int64)(nil))},
4422 {V((chan byte)(nil)), V((chan byte)(nil))},
4423 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4424 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4425 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4426 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4427 {V([]uint(nil)), V([]uint(nil))},
4428 {V([]int(nil)), V([]int(nil))},
4429 {V(new(any)), V(new(any))},
4430 {V(new(io.Reader)), V(new(io.Reader))},
4431 {V(new(io.Writer)), V(new(io.Writer))},
4434 {V(IntChan(nil)), V((chan<- int)(nil))},
4435 {V(IntChan(nil)), V((<-chan int)(nil))},
4436 {V((chan int)(nil)), V(IntChanRecv(nil))},
4437 {V((chan int)(nil)), V(IntChanSend(nil))},
4438 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4439 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4440 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4441 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4442 {V(IntChan(nil)), V((chan int)(nil))},
4443 {V((chan int)(nil)), V(IntChan(nil))},
4444 {V((chan int)(nil)), V((<-chan int)(nil))},
4445 {V((chan int)(nil)), V((chan<- int)(nil))},
4446 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4447 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4448 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4449 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4450 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4451 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4452 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4453 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4454 {V(BytesChan(nil)), V((chan []byte)(nil))},
4455 {V((chan []byte)(nil)), V(BytesChan(nil))},
4456 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4457 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4459 // cannot convert other instances (channels)
4460 {V(IntChan(nil)), V(IntChan(nil))},
4461 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4462 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4463 {V(BytesChan(nil)), V(BytesChan(nil))},
4464 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4465 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4468 {V(int(1)), EmptyInterfaceV(int(1))},
4469 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4470 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4471 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4472 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4475 func TestConvert(t *testing.T) {
4476 canConvert := map[[2]Type]bool{}
4477 all := map[Type]bool{}
4479 for _, tt := range convertTests {
4481 if !t1.ConvertibleTo(t1) {
4482 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4487 if !t1.ConvertibleTo(t2) {
4488 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4494 canConvert[[2]Type{t1, t2}] = true
4496 // vout1 represents the in value converted to the in type.
4498 if !v1.CanConvert(t1) {
4499 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4501 vout1 := v1.Convert(t1)
4502 out1 := vout1.Interface()
4503 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4504 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4507 // vout2 represents the in value converted to the out type.
4508 if !v1.CanConvert(t2) {
4509 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4511 vout2 := v1.Convert(t2)
4512 out2 := vout2.Interface()
4513 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4514 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4516 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4517 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4520 // vout3 represents a new value of the out type, set to vout2. This makes
4521 // sure the converted value vout2 is really usable as a regular value.
4522 vout3 := New(t2).Elem()
4524 out3 := vout3.Interface()
4525 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4526 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4530 t.Errorf("table entry %v is RO, should not be", v1)
4533 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4536 t.Errorf("conversion output %v is RO, should not be", vout2)
4539 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4541 if !IsRO(MakeRO(v1).Convert(t1)) {
4542 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4544 if !IsRO(MakeRO(v1).Convert(t2)) {
4545 t.Errorf("RO conversion output %v is not RO, should be", v1)
4549 // Assume that of all the types we saw during the tests,
4550 // if there wasn't an explicit entry for a conversion between
4551 // a pair of types, then it's not to be allowed. This checks for
4552 // things like 'int64' converting to '*int'.
4553 for t1 := range all {
4554 for t2 := range all {
4555 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4556 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4557 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4563 func TestConvertPanic(t *testing.T) {
4564 s := make([]byte, 4)
4568 if !v.Type().ConvertibleTo(pt) {
4569 t.Errorf("[]byte should be convertible to *[8]byte")
4571 if v.CanConvert(pt) {
4572 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4574 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4579 var gFloat32 float32
4581 const snan uint32 = 0x7f800001
4583 func TestConvertNaNs(t *testing.T) {
4584 // Test to see if a store followed by a load of a signaling NaN
4585 // maintains the signaling bit. (This used to fail on the 387 port.)
4586 gFloat32 = math.Float32frombits(snan)
4587 runtime.Gosched() // make sure we don't optimize the store/load away
4588 if got := math.Float32bits(gFloat32); got != snan {
4589 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4591 // Test reflect's conversion between float32s. See issue 36400.
4592 type myFloat32 float32
4593 x := V(myFloat32(math.Float32frombits(snan)))
4594 y := x.Convert(TypeOf(float32(0)))
4595 z := y.Interface().(float32)
4596 if got := math.Float32bits(z); got != snan {
4597 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4601 type ComparableStruct struct {
4605 type NonComparableStruct struct {
4610 var comparableTests = []struct {
4615 {TypeOf("hello"), true},
4616 {TypeOf(new(byte)), true},
4617 {TypeOf((func())(nil)), false},
4618 {TypeOf([]byte{}), false},
4619 {TypeOf(map[string]int{}), false},
4620 {TypeOf(make(chan int)), true},
4621 {TypeOf(1.5), true},
4622 {TypeOf(false), true},
4624 {TypeOf(ComparableStruct{}), true},
4625 {TypeOf(NonComparableStruct{}), false},
4626 {TypeOf([10]map[string]int{}), false},
4627 {TypeOf([10]string{}), true},
4628 {TypeOf(new(any)).Elem(), true},
4631 func TestComparable(t *testing.T) {
4632 for _, tt := range comparableTests {
4633 if ok := tt.typ.Comparable(); ok != tt.ok {
4634 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4639 func TestOverflow(t *testing.T) {
4640 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4641 t.Errorf("%v wrongly overflows float64", 1e300)
4644 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4645 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4646 t.Errorf("%v wrongly overflows float32", maxFloat32)
4648 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4649 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4650 t.Errorf("%v should overflow float32", ovfFloat32)
4652 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4653 t.Errorf("%v should overflow float32", -ovfFloat32)
4656 maxInt32 := int64(0x7fffffff)
4657 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4658 t.Errorf("%v wrongly overflows int32", maxInt32)
4660 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4661 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4663 ovfInt32 := int64(1 << 31)
4664 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4665 t.Errorf("%v should overflow int32", ovfInt32)
4668 maxUint32 := uint64(0xffffffff)
4669 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4670 t.Errorf("%v wrongly overflows uint32", maxUint32)
4672 ovfUint32 := uint64(1 << 32)
4673 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4674 t.Errorf("%v should overflow uint32", ovfUint32)
4678 func checkSameType(t *testing.T, x Type, y any) {
4679 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4680 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4684 func TestArrayOf(t *testing.T) {
4685 // check construction and use of type not in binary
4688 value func(i int) any
4694 value: func(i int) any { type Tint int; return Tint(i) },
4700 value: func(i int) any { type Tint int; return Tint(i) },
4702 want: "[0 1 2 3 4 5 6 7 8 9]",
4706 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4708 want: "[0 1 2 3 4 5 6 7 8 9]",
4712 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4714 want: "[0 1 2 3 4 5 6 7 8 9]",
4718 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4720 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4724 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4726 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4730 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4732 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4736 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4738 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4742 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4744 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4748 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4750 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4754 value: func(i int) any {
4755 type TstructUV struct {
4759 return TstructUV{i, float64(i)}
4762 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4766 for _, table := range tests {
4767 at := ArrayOf(table.n, TypeOf(table.value(0)))
4769 vok := New(at).Elem()
4770 vnot := New(at).Elem()
4771 for i := 0; i < v.Len(); i++ {
4772 v.Index(i).Set(ValueOf(table.value(i)))
4773 vok.Index(i).Set(ValueOf(table.value(i)))
4778 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4780 s := fmt.Sprint(v.Interface())
4781 if s != table.want {
4782 t.Errorf("constructed array = %s, want %s", s, table.want)
4785 if table.comparable != at.Comparable() {
4786 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4788 if table.comparable {
4790 if DeepEqual(vnot.Interface(), v.Interface()) {
4792 "arrays (%#v) compare ok (but should not)",
4797 if !DeepEqual(vok.Interface(), v.Interface()) {
4799 "arrays (%#v) compare NOT-ok (but should)",
4806 // check that type already in binary is found
4808 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4811 func TestArrayOfGC(t *testing.T) {
4813 tt := TypeOf(T(nil))
4816 for i := 0; i < n; i++ {
4817 v := New(ArrayOf(n, tt)).Elem()
4818 for j := 0; j < v.Len(); j++ {
4820 *p = uintptr(i*n + j)
4821 v.Index(j).Set(ValueOf(p).Convert(tt))
4823 x = append(x, v.Interface())
4827 for i, xi := range x {
4829 for j := 0; j < v.Len(); j++ {
4830 k := v.Index(j).Elem().Interface()
4831 if k != uintptr(i*n+j) {
4832 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4838 func TestArrayOfAlg(t *testing.T) {
4839 at := ArrayOf(6, TypeOf(byte(0)))
4840 v1 := New(at).Elem()
4841 v2 := New(at).Elem()
4842 if v1.Interface() != v1.Interface() {
4843 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4845 v1.Index(5).Set(ValueOf(byte(1)))
4846 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4847 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4850 at = ArrayOf(6, TypeOf([]int(nil)))
4852 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4855 func TestArrayOfGenericAlg(t *testing.T) {
4856 at1 := ArrayOf(5, TypeOf(string("")))
4857 at := ArrayOf(6, at1)
4858 v1 := New(at).Elem()
4859 v2 := New(at).Elem()
4860 if v1.Interface() != v1.Interface() {
4861 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4864 v1.Index(0).Index(0).Set(ValueOf("abc"))
4865 v2.Index(0).Index(0).Set(ValueOf("efg"))
4866 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4867 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4870 v1.Index(0).Index(0).Set(ValueOf("abc"))
4871 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4872 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4873 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4877 m := MakeMap(MapOf(at, TypeOf(int(0))))
4878 m.SetMapIndex(v1, ValueOf(1))
4879 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4880 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4884 func TestArrayOfDirectIface(t *testing.T) {
4887 i1 := Zero(TypeOf(T{})).Interface()
4888 v1 := ValueOf(&i1).Elem()
4889 p1 := v1.InterfaceData()[1]
4891 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
4892 v2 := ValueOf(&i2).Elem()
4893 p2 := v2.InterfaceData()[1]
4896 t.Errorf("got p1=%v. want=%v", p1, nil)
4900 t.Errorf("got p2=%v. want=%v", p2, nil)
4905 i1 := Zero(TypeOf(T{})).Interface()
4906 v1 := ValueOf(&i1).Elem()
4907 p1 := v1.InterfaceData()[1]
4909 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
4910 v2 := ValueOf(&i2).Elem()
4911 p2 := v2.InterfaceData()[1]
4914 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4918 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4923 // Ensure passing in negative lengths panics.
4924 // See https://golang.org/issue/43603
4925 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4926 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4927 ArrayOf(-1, TypeOf(byte(0)))
4931 func TestSliceOf(t *testing.T) {
4932 // check construction and use of type not in binary
4934 st := SliceOf(TypeOf(T(1)))
4935 if got, want := st.String(), "[]reflect_test.T"; got != want {
4936 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4938 v := MakeSlice(st, 10, 10)
4940 for i := 0; i < v.Len(); i++ {
4941 v.Index(i).Set(ValueOf(T(i)))
4944 s := fmt.Sprint(v.Interface())
4945 want := "[0 1 2 3 4 5 6 7 8 9]"
4947 t.Errorf("constructed slice = %s, want %s", s, want)
4950 // check that type already in binary is found
4952 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4955 func TestSliceOverflow(t *testing.T) {
4956 // check that MakeSlice panics when size of slice overflows uint
4959 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4961 t.Fatal("slice size does not overflow")
4964 st := SliceOf(TypeOf(x))
4968 t.Fatal("slice overflow does not panic")
4971 MakeSlice(st, int(l), int(l))
4974 func TestSliceOfGC(t *testing.T) {
4976 tt := TypeOf(T(nil))
4980 for i := 0; i < n; i++ {
4981 v := MakeSlice(st, n, n)
4982 for j := 0; j < v.Len(); j++ {
4984 *p = uintptr(i*n + j)
4985 v.Index(j).Set(ValueOf(p).Convert(tt))
4987 x = append(x, v.Interface())
4991 for i, xi := range x {
4993 for j := 0; j < v.Len(); j++ {
4994 k := v.Index(j).Elem().Interface()
4995 if k != uintptr(i*n+j) {
4996 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5002 func TestStructOfFieldName(t *testing.T) {
5003 // invalid field name "1nvalid"
5004 shouldPanic("has invalid name", func() {
5005 StructOf([]StructField{
5006 {Name: "Valid", Type: TypeOf("")},
5007 {Name: "1nvalid", Type: TypeOf("")},
5011 // invalid field name "+"
5012 shouldPanic("has invalid name", func() {
5013 StructOf([]StructField{
5014 {Name: "Val1d", Type: TypeOf("")},
5015 {Name: "+", Type: TypeOf("")},
5020 shouldPanic("has no name", func() {
5021 StructOf([]StructField{
5022 {Name: "", Type: TypeOf("")},
5026 // verify creation of a struct with valid struct fields
5027 validFields := []StructField{
5042 validStruct := StructOf(validFields)
5044 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5045 if got, want := validStruct.String(), structStr; got != want {
5046 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5050 func TestStructOf(t *testing.T) {
5051 // check construction and use of type not in binary
5052 fields := []StructField{
5061 Type: TypeOf(byte(0)),
5065 Type: TypeOf(uint64(0)),
5069 Type: TypeOf([3]uint16{}),
5073 st := StructOf(fields)
5076 v.FieldByName("X").Set(ValueOf(byte(2)))
5077 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5080 s := fmt.Sprint(v.Interface())
5081 want := `{ 1 0 [0 0 0]}`
5083 t.Errorf("constructed struct = %s, want %s", s, want)
5085 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5086 if got, want := st.String(), stStr; got != want {
5087 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5090 // check the size, alignment and field offsets
5091 stt := TypeOf(struct {
5097 if st.Size() != stt.Size() {
5098 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5100 if st.Align() != stt.Align() {
5101 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5103 if st.FieldAlign() != stt.FieldAlign() {
5104 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5106 for i := 0; i < st.NumField(); i++ {
5107 o1 := st.Field(i).Offset
5108 o2 := stt.Field(i).Offset
5110 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5114 // Check size and alignment with a trailing zero-sized field.
5115 st = StructOf([]StructField{
5118 Type: TypeOf(byte(0)),
5122 Type: TypeOf([0]*byte{}),
5125 stt = TypeOf(struct {
5129 if st.Size() != stt.Size() {
5130 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5132 if st.Align() != stt.Align() {
5133 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5135 if st.FieldAlign() != stt.FieldAlign() {
5136 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5138 for i := 0; i < st.NumField(); i++ {
5139 o1 := st.Field(i).Offset
5140 o2 := stt.Field(i).Offset
5142 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5146 // check duplicate names
5147 shouldPanic("duplicate field", func() {
5148 StructOf([]StructField{
5149 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5150 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5153 shouldPanic("has no name", func() {
5154 StructOf([]StructField{
5156 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5159 shouldPanic("has no name", func() {
5160 StructOf([]StructField{
5165 // check that type already in binary is found
5166 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5168 // gccgo used to fail this test.
5169 type structFieldType any
5171 StructOf([]StructField{
5174 Type: TypeOf((*structFieldType)(nil)).Elem(),
5177 struct{ F structFieldType }{})
5180 func TestStructOfExportRules(t *testing.T) {
5186 testPanic := func(i int, mustPanic bool, f func()) {
5189 if err == nil && mustPanic {
5190 t.Errorf("test-%d did not panic", i)
5192 if err != nil && !mustPanic {
5193 t.Errorf("test-%d panicked: %v\n", i, err)
5205 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5209 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5213 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5217 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5221 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5225 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5229 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5233 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5237 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5241 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5245 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5248 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5251 field: StructField{Name: "S", Type: TypeOf(S1{})},
5255 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5259 field: StructField{Name: "S", Type: TypeOf(s2{})},
5263 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5267 field: StructField{Name: "s", Type: TypeOf(S1{})},
5271 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5275 field: StructField{Name: "s", Type: TypeOf(s2{})},
5279 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5283 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5286 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5289 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5292 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5295 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5299 field: StructField{Name: "", Type: TypeOf(φType{})},
5303 field: StructField{Name: "Φ", Type: TypeOf(0)},
5307 field: StructField{Name: "φ", Type: TypeOf(0)},
5312 for i, test := range tests {
5313 testPanic(i, test.mustPanic, func() {
5314 typ := StructOf([]StructField{test.field})
5316 t.Errorf("test-%d: error creating struct type", i)
5319 field := typ.Field(0)
5322 panic("field.Name must not be empty")
5324 exported := token.IsExported(n)
5325 if exported != test.exported {
5326 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5328 if field.PkgPath != test.field.PkgPath {
5329 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5335 func TestStructOfGC(t *testing.T) {
5337 tt := TypeOf(T(nil))
5338 fields := []StructField{
5339 {Name: "X", Type: tt},
5340 {Name: "Y", Type: tt},
5342 st := StructOf(fields)
5346 for i := 0; i < n; i++ {
5348 for j := 0; j < v.NumField(); j++ {
5350 *p = uintptr(i*n + j)
5351 v.Field(j).Set(ValueOf(p).Convert(tt))
5353 x = append(x, v.Interface())
5357 for i, xi := range x {
5359 for j := 0; j < v.NumField(); j++ {
5360 k := v.Field(j).Elem().Interface()
5361 if k != uintptr(i*n+j) {
5362 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5368 func TestStructOfAlg(t *testing.T) {
5369 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5370 v1 := New(st).Elem()
5371 v2 := New(st).Elem()
5372 if !DeepEqual(v1.Interface(), v1.Interface()) {
5373 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5375 v1.FieldByName("X").Set(ValueOf(int(1)))
5376 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5377 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5380 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5382 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5385 func TestStructOfGenericAlg(t *testing.T) {
5386 st1 := StructOf([]StructField{
5387 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5388 {Name: "Y", Type: TypeOf(string(""))},
5390 st := StructOf([]StructField{
5391 {Name: "S0", Type: st1},
5392 {Name: "S1", Type: st1},
5410 {Name: "XX", Type: TypeOf([0]int{})},
5411 {Name: "YY", Type: TypeOf("")},
5419 {Name: "XX", Type: TypeOf([0]int{})},
5420 {Name: "YY", Type: TypeOf("")},
5421 {Name: "ZZ", Type: TypeOf([2]int{})},
5429 {Name: "XX", Type: TypeOf([1]int{})},
5430 {Name: "YY", Type: TypeOf("")},
5438 {Name: "XX", Type: TypeOf([1]int{})},
5439 {Name: "YY", Type: TypeOf("")},
5440 {Name: "ZZ", Type: TypeOf([1]int{})},
5448 {Name: "XX", Type: TypeOf([2]int{})},
5449 {Name: "YY", Type: TypeOf("")},
5450 {Name: "ZZ", Type: TypeOf([2]int{})},
5458 {Name: "XX", Type: TypeOf(int64(0))},
5459 {Name: "YY", Type: TypeOf(byte(0))},
5460 {Name: "ZZ", Type: TypeOf("")},
5468 {Name: "XX", Type: TypeOf(int64(0))},
5469 {Name: "YY", Type: TypeOf(int64(0))},
5470 {Name: "ZZ", Type: TypeOf("")},
5471 {Name: "AA", Type: TypeOf([1]int64{})},
5478 for _, table := range tests {
5479 v1 := New(table.rt).Elem()
5480 v2 := New(table.rt).Elem()
5482 if !DeepEqual(v1.Interface(), v1.Interface()) {
5483 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5486 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5487 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5488 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5489 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5493 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5494 val := "+" + abc + "-"
5495 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5496 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5497 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5501 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5502 m.SetMapIndex(v1, ValueOf(1))
5503 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5504 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5507 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5508 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5509 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5512 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5513 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5518 func TestStructOfDirectIface(t *testing.T) {
5520 type T struct{ X [1]*byte }
5521 i1 := Zero(TypeOf(T{})).Interface()
5522 v1 := ValueOf(&i1).Elem()
5523 p1 := v1.InterfaceData()[1]
5525 i2 := Zero(StructOf([]StructField{
5528 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5531 v2 := ValueOf(&i2).Elem()
5532 p2 := v2.InterfaceData()[1]
5535 t.Errorf("got p1=%v. want=%v", p1, nil)
5539 t.Errorf("got p2=%v. want=%v", p2, nil)
5543 type T struct{ X [0]*byte }
5544 i1 := Zero(TypeOf(T{})).Interface()
5545 v1 := ValueOf(&i1).Elem()
5546 p1 := v1.InterfaceData()[1]
5548 i2 := Zero(StructOf([]StructField{
5551 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5554 v2 := ValueOf(&i2).Elem()
5555 p2 := v2.InterfaceData()[1]
5558 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5562 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5569 func (i StructI) Get() int { return int(i) }
5573 func (i *StructIPtr) Get() int { return int(*i) }
5574 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5576 type SettableStruct struct {
5580 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5582 type SettablePointer struct {
5586 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5588 func TestStructOfWithInterface(t *testing.T) {
5590 type Iface interface {
5593 type IfaceSet interface {
5604 typ: TypeOf(StructI(want)),
5605 val: ValueOf(StructI(want)),
5610 typ: PointerTo(TypeOf(StructI(want))),
5611 val: ValueOf(func() any {
5619 typ: PointerTo(TypeOf(StructIPtr(want))),
5620 val: ValueOf(func() any {
5621 v := StructIPtr(want)
5628 typ: TypeOf(StructIPtr(want)),
5629 val: ValueOf(StructIPtr(want)),
5633 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5634 // val: ValueOf(StructI(want)),
5639 for i, table := range tests {
5640 for j := 0; j < 2; j++ {
5641 var fields []StructField
5643 fields = append(fields, StructField{
5646 Type: TypeOf(int(0)),
5649 fields = append(fields, StructField{
5656 // We currently do not correctly implement methods
5657 // for embedded fields other than the first.
5658 // Therefore, for now, we expect those methods
5659 // to not exist. See issues 15924 and 20824.
5660 // When those issues are fixed, this test of panic
5661 // should be removed.
5662 if j == 1 && table.impl {
5665 if err := recover(); err == nil {
5666 t.Errorf("test-%d-%d did not panic", i, j)
5669 _ = StructOf(fields)
5674 rt := StructOf(fields)
5675 rv := New(rt).Elem()
5676 rv.Field(j).Set(table.val)
5678 if _, ok := rv.Interface().(Iface); ok != table.impl {
5680 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5682 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5691 v := rv.Interface().(Iface).Get()
5693 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5696 fct := rv.MethodByName("Get")
5697 out := fct.Call(nil)
5698 if !DeepEqual(out[0].Interface(), want) {
5699 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5704 // Test an embedded nil pointer with pointer methods.
5705 fields := []StructField{{
5708 Type: PointerTo(TypeOf(StructIPtr(want))),
5710 rt := StructOf(fields)
5711 rv := New(rt).Elem()
5712 // This should panic since the pointer is nil.
5713 shouldPanic("", func() {
5714 rv.Interface().(IfaceSet).Set(want)
5717 // Test an embedded nil pointer to a struct with pointer methods.
5719 fields = []StructField{{
5720 Name: "SettableStruct",
5722 Type: PointerTo(TypeOf(SettableStruct{})),
5724 rt = StructOf(fields)
5726 // This should panic since the pointer is nil.
5727 shouldPanic("", func() {
5728 rv.Interface().(IfaceSet).Set(want)
5731 // The behavior is different if there is a second field,
5732 // since now an interface value holds a pointer to the struct
5733 // rather than just holding a copy of the struct.
5734 fields = []StructField{
5736 Name: "SettableStruct",
5738 Type: PointerTo(TypeOf(SettableStruct{})),
5741 Name: "EmptyStruct",
5743 Type: StructOf(nil),
5746 // With the current implementation this is expected to panic.
5747 // Ideally it should work and we should be able to see a panic
5748 // if we call the Set method.
5749 shouldPanic("", func() {
5753 // Embed a field that can be stored directly in an interface,
5754 // with a second field.
5755 fields = []StructField{
5757 Name: "SettablePointer",
5759 Type: TypeOf(SettablePointer{}),
5762 Name: "EmptyStruct",
5764 Type: StructOf(nil),
5767 // With the current implementation this is expected to panic.
5768 // Ideally it should work and we should be able to call the
5769 // Set and Get methods.
5770 shouldPanic("", func() {
5775 func TestStructOfTooManyFields(t *testing.T) {
5776 // Bug Fix: #25402 - this should not panic
5777 tt := StructOf([]StructField{
5778 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5781 if _, present := tt.MethodByName("After"); !present {
5782 t.Errorf("Expected method `After` to be found")
5786 func TestStructOfDifferentPkgPath(t *testing.T) {
5787 fields := []StructField{
5791 Type: TypeOf(int(0)),
5796 Type: TypeOf(int(0)),
5799 shouldPanic("different PkgPath", func() {
5804 func TestStructOfTooLarge(t *testing.T) {
5805 t1 := TypeOf(byte(0))
5806 t2 := TypeOf(int16(0))
5807 t4 := TypeOf(int32(0))
5808 t0 := ArrayOf(0, t1)
5810 // 2^64-3 sized type (or 2^32-3 on 32-bit archs)
5811 bigType := StructOf([]StructField{
5812 {Name: "F1", Type: ArrayOf(int(^uintptr(0)>>1), t1)},
5813 {Name: "F2", Type: ArrayOf(int(^uintptr(0)>>1-1), t1)},
5818 fields []StructField
5823 shouldPanic: false, // 2^64-1, ok
5824 fields: []StructField{
5825 {Name: "F1", Type: bigType},
5826 {Name: "F2", Type: ArrayOf(2, t1)},
5830 shouldPanic: true, // overflow in total size
5831 fields: []StructField{
5832 {Name: "F1", Type: bigType},
5833 {Name: "F2", Type: ArrayOf(3, t1)},
5837 shouldPanic: true, // overflow while aligning F2
5838 fields: []StructField{
5839 {Name: "F1", Type: bigType},
5840 {Name: "F2", Type: t4},
5844 shouldPanic: true, // overflow while adding trailing byte for zero-sized fields
5845 fields: []StructField{
5846 {Name: "F1", Type: bigType},
5847 {Name: "F2", Type: ArrayOf(2, t1)},
5848 {Name: "F3", Type: t0},
5852 shouldPanic: true, // overflow while aligning total size
5853 fields: []StructField{
5854 {Name: "F1", Type: t2},
5855 {Name: "F2", Type: bigType},
5860 for i, tt := range tests {
5864 if !tt.shouldPanic {
5866 t.Errorf("test %d should not panic, got %s", i, err)
5871 t.Errorf("test %d expected to panic", i)
5874 s := fmt.Sprintf("%s", err)
5875 if s != "reflect.StructOf: struct size would exceed virtual address space" {
5876 t.Errorf("test %d wrong panic message: %s", i, s)
5880 _ = StructOf(tt.fields)
5885 func TestChanOf(t *testing.T) {
5886 // check construction and use of type not in binary
5888 ct := ChanOf(BothDir, TypeOf(T("")))
5889 v := MakeChan(ct, 2)
5891 v.Send(ValueOf(T("hello")))
5893 v.Send(ValueOf(T("world")))
5900 if s1 != "hello" || s2 != "world" {
5901 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5904 // check that type already in binary is found
5906 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5908 // Check arrow token association in undefined chan types.
5909 var left chan<- chan T
5910 var right chan (<-chan T)
5911 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5912 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5913 if tLeft != TypeOf(left) {
5914 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5916 if tRight != TypeOf(right) {
5917 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5921 func TestChanOfDir(t *testing.T) {
5922 // check construction and use of type not in binary
5924 crt := ChanOf(RecvDir, TypeOf(T("")))
5925 cst := ChanOf(SendDir, TypeOf(T("")))
5927 // check that type already in binary is found
5929 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5930 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5932 // check String form of ChanDir
5933 if crt.ChanDir().String() != "<-chan" {
5934 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5936 if cst.ChanDir().String() != "chan<-" {
5937 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5941 func TestChanOfGC(t *testing.T) {
5942 done := make(chan bool, 1)
5946 case <-time.After(5 * time.Second):
5947 panic("deadlock in TestChanOfGC")
5956 tt := TypeOf(T(nil))
5957 ct := ChanOf(BothDir, tt)
5959 // NOTE: The garbage collector handles allocated channels specially,
5960 // so we have to save pointers to channels in x; the pointer code will
5961 // use the gc info in the newly constructed chan type.
5964 for i := 0; i < n; i++ {
5965 v := MakeChan(ct, n)
5966 for j := 0; j < n; j++ {
5968 *p = uintptr(i*n + j)
5969 v.Send(ValueOf(p).Convert(tt))
5973 x = append(x, pv.Interface())
5977 for i, xi := range x {
5978 v := ValueOf(xi).Elem()
5979 for j := 0; j < n; j++ {
5981 k := pv.Elem().Interface()
5982 if k != uintptr(i*n+j) {
5983 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5989 func TestMapOf(t *testing.T) {
5990 // check construction and use of type not in binary
5994 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5996 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5999 s := fmt.Sprint(v.Interface())
6002 t.Errorf("constructed map = %s, want %s", s, want)
6005 // check that type already in binary is found
6006 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
6008 // check that invalid key type panics
6009 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
6012 func TestMapOfGCKeys(t *testing.T) {
6014 tt := TypeOf(T(nil))
6015 mt := MapOf(tt, TypeOf(false))
6017 // NOTE: The garbage collector handles allocated maps specially,
6018 // so we have to save pointers to maps in x; the pointer code will
6019 // use the gc info in the newly constructed map type.
6022 for i := 0; i < n; i++ {
6024 for j := 0; j < n; j++ {
6026 *p = uintptr(i*n + j)
6027 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
6031 x = append(x, pv.Interface())
6035 for i, xi := range x {
6036 v := ValueOf(xi).Elem()
6038 for _, kv := range v.MapKeys() {
6039 out = append(out, int(kv.Elem().Interface().(uintptr)))
6042 for j, k := range out {
6044 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6050 func TestMapOfGCValues(t *testing.T) {
6052 tt := TypeOf(T(nil))
6053 mt := MapOf(TypeOf(1), tt)
6055 // NOTE: The garbage collector handles allocated maps specially,
6056 // so we have to save pointers to maps in x; the pointer code will
6057 // use the gc info in the newly constructed map type.
6060 for i := 0; i < n; i++ {
6062 for j := 0; j < n; j++ {
6064 *p = uintptr(i*n + j)
6065 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6069 x = append(x, pv.Interface())
6073 for i, xi := range x {
6074 v := ValueOf(xi).Elem()
6075 for j := 0; j < n; j++ {
6076 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6077 if k != uintptr(i*n+j) {
6078 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6084 func TestTypelinksSorted(t *testing.T) {
6086 for i, n := range TypeLinks() {
6088 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6094 func TestFuncOf(t *testing.T) {
6095 // check construction and use of type not in binary
6099 fn := func(args []Value) []Value {
6101 t.Errorf("args == %v, want exactly one arg", args)
6102 } else if args[0].Type() != TypeOf(K("")) {
6103 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6104 } else if args[0].String() != "gopher" {
6105 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6107 return []Value{ValueOf(V(3.14))}
6109 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6111 outs := v.Call([]Value{ValueOf(K("gopher"))})
6113 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6114 } else if outs[0].Type() != TypeOf(V(0)) {
6115 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6117 f := outs[0].Float()
6119 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6122 // check that types already in binary are found
6124 testCases := []struct {
6129 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6130 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6131 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6132 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6133 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6135 for _, tt := range testCases {
6136 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6139 // check that variadic requires last element be a slice.
6140 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6141 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6142 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6144 //testcase for #54669
6146 for i := 0; i < 51; i++ {
6147 in = append(in, TypeOf(1))
6149 FuncOf(in, nil, false)
6222 func TestEmbed(t *testing.T) {
6224 f, ok := typ.FieldByName("X")
6226 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6230 func TestAllocsInterfaceBig(t *testing.T) {
6231 if testing.Short() {
6232 t.Skip("skipping malloc count in short mode")
6235 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6236 t.Error("allocs:", allocs)
6240 func TestAllocsInterfaceSmall(t *testing.T) {
6241 if testing.Short() {
6242 t.Skip("skipping malloc count in short mode")
6244 v := ValueOf(int64(0))
6245 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6246 t.Error("allocs:", allocs)
6250 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6251 // The basic usage is:
6254 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6257 // Each iteration of the loop returns a different set of results, until all
6258 // possible result sets have been explored. It is okay for different code paths
6259 // to make different method call sequences on x, but there must be no
6260 // other source of non-determinism in the call sequences.
6262 // When faced with a new decision, x chooses randomly. Future explorations
6263 // of that path will choose successive values for the result. Thus, stopping
6264 // the loop after a fixed number of iterations gives somewhat stochastic
6270 // v := make([]bool, x.Choose(4))
6271 // for i := range v {
6277 // prints (in some order):
6286 // [false false false]
6289 // [false false false false]
6291 // [true true true true]
6292 type exhaustive struct {
6298 type choice struct {
6304 func (x *exhaustive) Next() bool {
6306 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6313 for i := len(x.last) - 1; i >= 0; i-- {
6317 x.last = x.last[:i+1]
6324 func (x *exhaustive) Choose(max int) int {
6325 if x.pos >= len(x.last) {
6326 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6331 panic("inconsistent use of exhaustive tester")
6333 return (c.n + c.off) % max
6336 func (x *exhaustive) Maybe() bool {
6337 return x.Choose(2) == 1
6340 func GCFunc(args []Value) []Value {
6345 func TestReflectFuncTraceback(t *testing.T) {
6346 f := MakeFunc(TypeOf(func() {}), GCFunc)
6350 func TestReflectMethodTraceback(t *testing.T) {
6352 m := ValueOf(p).MethodByName("GCMethod")
6353 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6355 t.Errorf("Call returned %d; want 8", i)
6359 func TestSmallZero(t *testing.T) {
6362 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6363 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6367 func TestBigZero(t *testing.T) {
6368 const size = 1 << 10
6370 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6371 for i := 0; i < size; i++ {
6373 t.Fatalf("Zero object not all zero, index %d", i)
6378 func TestZeroSet(t *testing.T) {
6386 a: 0xaaaaaaaaaaaaaaaa,
6387 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6388 b: 0xbbbbbbbbbbbbbbbb,
6390 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6392 a: 0xaaaaaaaaaaaaaaaa,
6393 b: 0xbbbbbbbbbbbbbbbb,
6395 t.Fatalf("Setting a field to a Zero value didn't work")
6399 func TestFieldByIndexNil(t *testing.T) {
6408 v.FieldByName("P") // should be fine
6411 if err := recover(); err == nil {
6412 t.Fatalf("no error")
6413 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6414 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6417 v.FieldByName("F") // should panic
6419 t.Fatalf("did not panic")
6423 // type Outer struct {
6427 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6428 // The implementation is logically:
6429 // func (p *Outer) M() {
6432 // but since the only change here is the replacement of one pointer receiver with another,
6433 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6434 // then jumps to the M method expecting the *Inner receiver.
6436 // During reflect.Value.Call, we create an argument frame and the associated data structures
6437 // to describe it to the garbage collector, populate the frame, call reflect.call to
6438 // run a function call using that frame, and then copy the results back out of the frame.
6439 // The reflect.call function does a memmove of the frame structure onto the
6440 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6441 // the frame structure (to preserve the outputs).
6443 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6444 // were for the full stack frame. However, in the case where the called function was
6445 // one of these wrappers, the rewritten receiver is almost certainly a different type
6446 // than the original receiver. This is not a problem on the stack, where we use the
6447 // program counter to determine the type information and understand that
6448 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6449 // memory word is now an *Inner. But in the statically typed argument frame created
6450 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6451 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6452 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6453 // memory as if it were an *Outer. If the two have different memory layouts, the
6454 // collection will interpret the memory incorrectly.
6456 // One such possible incorrect interpretation is to treat two arbitrary memory words
6457 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6458 // an interface requires dereferencing the itab word, the misinterpretation will try to
6459 // deference Inner.P1, causing a crash during garbage collection.
6461 // This came up in a real program in issue 7725.
6474 func (pi *Inner) M() {
6475 // Clear references to pi so that the only way the
6476 // garbage collection will find the pointer is in the
6477 // argument frame, typed as a *Outer.
6480 // Set up an interface value that will cause a crash.
6481 // P1 = 1 is a non-zero, so the interface looks non-nil.
6482 // P2 = pi ensures that the data word points into the
6483 // allocated heap; if not the collection skips the interface
6484 // value as irrelevant, without dereferencing P1.
6486 pi.P2 = uintptr(unsafe.Pointer(pi))
6489 func TestCallMethodJump(t *testing.T) {
6490 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6491 // returns but before the args frame has been discarded.
6492 // This is a little clumsy but makes the failure repeatable.
6495 p := &Outer{Inner: new(Inner)}
6497 ValueOf(p).Method(0).Call(nil)
6499 // Stop garbage collecting during reflect.call.
6503 func TestCallArgLive(t *testing.T) {
6504 type T struct{ X, Y *string } // pointerful aggregate
6506 F := func(t T) { *t.X = "ok" }
6508 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6509 // between marshaling argument and the actual call.
6513 runtime.SetFinalizer(x, func(p *string) {
6515 t.Errorf("x dead prematurely")
6520 ValueOf(F).Call([]Value{ValueOf(v)})
6522 // Stop garbage collecting during reflect.call.
6526 func TestMakeFuncStackCopy(t *testing.T) {
6527 target := func(in []Value) []Value {
6530 return []Value{ValueOf(9)}
6533 var concrete func(*int, int) int
6534 fn := MakeFunc(ValueOf(concrete).Type(), target)
6535 ValueOf(&concrete).Elem().Set(fn)
6536 x := concrete(nil, 7)
6538 t.Errorf("have %#q want 9", x)
6542 // use about n KB of stack
6543 func useStack(n int) {
6547 var b [1024]byte // makes frame about 1KB
6548 useStack(n - 1 + int(b[99]))
6555 func TestValueString(t *testing.T) {
6556 rv := ValueOf(Impl{})
6557 if rv.String() != "<reflect_test.Impl Value>" {
6558 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6561 method := rv.Method(0)
6562 if method.String() != "<func() Value>" {
6563 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6567 func TestInvalid(t *testing.T) {
6568 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6569 type T struct{ v any }
6571 v := ValueOf(T{}).Field(0)
6572 if v.IsValid() != true || v.Kind() != Interface {
6573 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6576 if v.IsValid() != false || v.Kind() != Invalid {
6577 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6582 func TestLargeGCProg(t *testing.T) {
6583 fv := ValueOf(func([256]*byte) {})
6584 fv.Call([]Value{ValueOf([256]*byte{})})
6587 func fieldIndexRecover(t Type, i int) (recovered any) {
6589 recovered = recover()
6597 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6598 typ := TypeOf(struct{ X int }{10})
6599 testIndices := [...]struct {
6608 for i, tt := range testIndices {
6609 recoveredErr := fieldIndexRecover(typ, tt.i)
6611 if recoveredErr == nil {
6612 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6615 if recoveredErr != nil {
6616 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6623 func TestCallGC(t *testing.T) {
6624 f := func(a, b, c, d, e string) {
6626 g := func(in []Value) []Value {
6630 typ := ValueOf(f).Type()
6631 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6632 f2("four", "five5", "six666", "seven77", "eight888")
6635 // Issue 18635 (function version).
6636 func TestKeepFuncLive(t *testing.T) {
6637 // Test that we keep makeFuncImpl live as long as it is
6638 // referenced on the stack.
6639 typ := TypeOf(func(i int) {})
6640 var f, g func(in []Value) []Value
6641 f = func(in []Value) []Value {
6643 i := int(in[0].Int())
6645 // We can't use Value.Call here because
6646 // runtime.call* will keep the makeFuncImpl
6647 // alive. However, by converting it to an
6648 // interface value and calling that,
6649 // reflect.callReflect is the only thing that
6650 // can keep the makeFuncImpl live.
6652 // Alternate between f and g so that if we do
6653 // reuse the memory prematurely it's more
6654 // likely to get obviously corrupted.
6655 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6659 g = func(in []Value) []Value {
6661 i := int(in[0].Int())
6662 MakeFunc(typ, f).Interface().(func(i int))(i)
6665 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6668 type UnExportedFirst int
6670 func (i UnExportedFirst) ΦExported() {}
6671 func (i UnExportedFirst) unexported() {}
6674 func TestMethodByNameUnExportedFirst(t *testing.T) {
6676 if recover() != nil {
6677 t.Errorf("should not panic")
6680 typ := TypeOf(UnExportedFirst(0))
6681 m, _ := typ.MethodByName("ΦExported")
6682 if m.Name != "ΦExported" {
6683 t.Errorf("got %s, expected ΦExported", m.Name)
6687 // Issue 18635 (method version).
6688 type KeepMethodLive struct{}
6690 func (k KeepMethodLive) Method1(i int) {
6693 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6697 func (k KeepMethodLive) Method2(i int) {
6699 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6702 func TestKeepMethodLive(t *testing.T) {
6703 // Test that we keep methodValue live as long as it is
6704 // referenced on the stack.
6705 KeepMethodLive{}.Method1(10)
6708 // clobber tries to clobber unreachable memory.
6711 for i := 1; i < 32; i++ {
6712 for j := 0; j < 10; j++ {
6713 obj := make([]*byte, i)
6720 func TestFuncLayout(t *testing.T) {
6721 align := func(x uintptr) uintptr {
6722 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6725 if goarch.PtrSize == 4 {
6726 r = []byte{0, 0, 0, 1}
6738 size, argsize, retOffset uintptr
6739 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6740 intRegs, floatRegs int
6741 floatRegSize uintptr
6745 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6746 size: 6 * goarch.PtrSize,
6747 argsize: 4 * goarch.PtrSize,
6748 retOffset: 4 * goarch.PtrSize,
6749 stack: []byte{1, 0, 1, 0, 1},
6750 gc: []byte{1, 0, 1, 0, 1},
6753 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6754 size: align(align(3*4) + goarch.PtrSize + 2),
6755 argsize: align(3*4) + goarch.PtrSize + 2,
6756 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6761 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6762 size: 4 * goarch.PtrSize,
6763 argsize: 4 * goarch.PtrSize,
6764 retOffset: 4 * goarch.PtrSize,
6765 stack: []byte{1, 0, 1, 1},
6766 gc: []byte{1, 0, 1, 1},
6769 typ: ValueOf(func(a S) {}).Type(),
6770 size: 4 * goarch.PtrSize,
6771 argsize: 4 * goarch.PtrSize,
6772 retOffset: 4 * goarch.PtrSize,
6773 stack: []byte{0, 0, 1, 1},
6774 gc: []byte{0, 0, 1, 1},
6777 rcvr: ValueOf((*byte)(nil)).Type(),
6778 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6779 size: 3 * goarch.PtrSize,
6780 argsize: 3 * goarch.PtrSize,
6781 retOffset: 3 * goarch.PtrSize,
6782 stack: []byte{1, 0, 1},
6783 gc: []byte{1, 0, 1},
6786 typ: ValueOf(func(a uintptr) {}).Type(),
6787 size: goarch.PtrSize,
6788 argsize: goarch.PtrSize,
6789 retOffset: goarch.PtrSize,
6794 typ: ValueOf(func() uintptr { return 0 }).Type(),
6795 size: goarch.PtrSize,
6802 rcvr: ValueOf(uintptr(0)).Type(),
6803 typ: ValueOf(func(a uintptr) {}).Type(),
6804 size: 2 * goarch.PtrSize,
6805 argsize: 2 * goarch.PtrSize,
6806 retOffset: 2 * goarch.PtrSize,
6809 // Note: this one is tricky, as the receiver is not a pointer. But we
6810 // pass the receiver by reference to the autogenerated pointer-receiver
6811 // version of the function.
6813 // TODO(mknyszek): Add tests for non-zero register count.
6815 for _, lt := range tests {
6816 name := lt.typ.String()
6818 name = lt.rcvr.String() + "." + name
6820 t.Run(name, func(t *testing.T) {
6821 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6823 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6824 if typ.Size() != lt.size {
6825 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6827 if argsize != lt.argsize {
6828 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6830 if retOffset != lt.retOffset {
6831 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6833 if !bytes.Equal(stack, lt.stack) {
6834 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6836 if !bytes.Equal(gc, lt.gc) {
6837 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6839 if !bytes.Equal(inRegs, lt.inRegs) {
6840 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6842 if !bytes.Equal(outRegs, lt.outRegs) {
6843 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6845 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6846 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6852 // trimBitmap removes trailing 0 elements from b and returns the result.
6853 func trimBitmap(b []byte) []byte {
6854 for len(b) > 0 && b[len(b)-1] == 0 {
6860 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6861 heapBits := GCBits(New(typ).Interface())
6863 // Trim scalars at the end, as bits might end in zero,
6864 // e.g. with rep(2, lit(1, 0)).
6865 bits = trimBitmap(bits)
6867 if !bytes.Equal(heapBits, bits) {
6868 _, _, line, _ := runtime.Caller(1)
6869 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6873 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6874 // Creating a slice causes the runtime to repeat a bitmap,
6875 // which exercises a different path from making the compiler
6876 // repeat a bitmap for a small array or executing a repeat in
6878 val := MakeSlice(typ, 0, cap)
6879 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
6880 heapBits := GCBits(data.Interface())
6881 // Repeat the bitmap for the slice size, trimming scalars in
6882 // the last element.
6883 bits = trimBitmap(rep(cap, bits))
6884 if !bytes.Equal(heapBits, bits) {
6885 _, _, line, _ := runtime.Caller(1)
6886 t.Errorf("line %d: heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", line, typ, cap, heapBits, bits)
6890 func TestGCBits(t *testing.T) {
6891 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6893 // Building blocks for types seen by the compiler (like [2]Xscalar).
6894 // The compiler will create the type structures for the derived types,
6895 // including their GC metadata.
6896 type Xscalar struct{ x uintptr }
6897 type Xptr struct{ x *byte }
6898 type Xptrscalar struct {
6902 type Xscalarptr struct {
6906 type Xbigptrscalar struct {
6911 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6913 // Building blocks for types constructed by reflect.
6914 // This code is in a separate block so that code below
6915 // cannot accidentally refer to these.
6916 // The compiler must NOT see types derived from these
6917 // (for example, [2]Scalar must NOT appear in the program),
6918 // or else reflect will use it instead of having to construct one.
6919 // The goal is to test the construction.
6920 type Scalar struct{ x uintptr }
6921 type Ptr struct{ x *byte }
6922 type Ptrscalar struct {
6926 type Scalarptr struct {
6930 type Bigptrscalar struct {
6935 Tscalar = TypeOf(Scalar{})
6936 Tint64 = TypeOf(Int64(0))
6937 Tptr = TypeOf(Ptr{})
6938 Tscalarptr = TypeOf(Scalarptr{})
6939 Tptrscalar = TypeOf(Ptrscalar{})
6940 Tbigptrscalar = TypeOf(Bigptrscalar{})
6945 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6946 verifyGCBits(t, Tscalar, empty)
6947 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6948 verifyGCBits(t, Tptr, lit(1))
6949 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6950 verifyGCBits(t, Tscalarptr, lit(0, 1))
6951 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6952 verifyGCBits(t, Tptrscalar, lit(1))
6954 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6955 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6956 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6957 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6958 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6959 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6960 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6961 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6962 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6963 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6964 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6965 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6966 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6967 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6968 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6969 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6970 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6971 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6972 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6973 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6974 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6975 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6976 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6977 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6978 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6979 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6981 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6982 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6983 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6984 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6985 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6986 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6987 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6988 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6989 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6990 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6991 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6992 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6993 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6994 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6995 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6996 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6997 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6998 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6999 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
7000 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7001 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7002 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7003 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7004 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7005 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7006 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7008 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7009 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7011 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7012 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7014 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7015 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7017 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7018 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7020 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7021 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7023 hdr := make([]byte, 8/goarch.PtrSize)
7025 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7026 verifyGCBits(t, MapBucketOf(k, e), want)
7027 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7031 map[Xscalar]Xptr(nil),
7032 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7035 map[Xscalarptr]Xptr(nil),
7036 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7037 verifyMapBucket(t, Tint64, Tptr,
7038 map[int64]Xptr(nil),
7039 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7042 map[Xscalar]Xscalar(nil),
7045 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7046 map[[2]Xscalarptr][3]Xptrscalar(nil),
7047 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7049 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7050 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7051 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7053 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7054 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7055 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7057 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7058 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7059 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7061 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7062 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7063 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7066 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7067 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7068 func lit(x ...byte) []byte { return x }
7070 func TestTypeOfTypeOf(t *testing.T) {
7071 // Check that all the type constructors return concrete *rtype implementations.
7072 // It's difficult to test directly because the reflect package is only at arm's length.
7073 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7074 check := func(name string, typ Type) {
7075 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7076 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7080 type T struct{ int }
7081 check("TypeOf", TypeOf(T{}))
7083 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7084 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7085 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7086 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7087 check("PtrTo", PointerTo(TypeOf(T{})))
7088 check("SliceOf", SliceOf(TypeOf(T{})))
7091 type XM struct{ _ bool }
7093 func (*XM) String() string { return "" }
7095 func TestPtrToMethods(t *testing.T) {
7097 yp := New(TypeOf(y)).Interface()
7098 _, ok := yp.(fmt.Stringer)
7100 t.Fatal("does not implement Stringer, but should")
7104 func TestMapAlloc(t *testing.T) {
7105 m := ValueOf(make(map[int]int, 10))
7108 allocs := testing.AllocsPerRun(100, func() {
7112 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7117 val := ValueOf(&tmp).Elem()
7118 allocs = testing.AllocsPerRun(100, func() {
7119 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7120 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7121 for i := 0; i < size/2; i++ {
7122 val.SetInt(int64(i))
7123 mv.SetMapIndex(val, val)
7127 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7129 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7130 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7131 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7134 func TestChanAlloc(t *testing.T) {
7135 // Note: for a chan int, the return Value must be allocated, so we
7136 // use a chan *int instead.
7137 c := ValueOf(make(chan *int, 1))
7138 v := ValueOf(new(int))
7139 allocs := testing.AllocsPerRun(100, func() {
7143 if allocs < 0.5 || allocs > 1.5 {
7144 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7146 // Note: there is one allocation in reflect.recv which seems to be
7147 // a limitation of escape analysis. If that is ever fixed the
7148 // allocs < 0.5 condition will trigger and this test should be fixed.
7151 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7153 type nameTest struct {
7158 var nameTests = []nameTest{
7159 {(*int32)(nil), "int32"},
7162 {(*chan D1)(nil), ""},
7163 {(*func() D1)(nil), ""},
7164 {(*<-chan D1)(nil), ""},
7165 {(*chan<- D1)(nil), ""},
7170 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7173 func TestNames(t *testing.T) {
7174 for _, test := range nameTests {
7175 typ := TypeOf(test.v).Elem()
7176 if got := typ.Name(); got != test.want {
7177 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7182 func TestExported(t *testing.T) {
7183 type ΦExported struct{}
7184 type φUnexported struct{}
7191 type exportTest struct {
7195 exportTests := []exportTest{
7199 {(*big)(nil), false},
7200 {(BigP)(nil), true},
7201 {(*BigP)(nil), true},
7202 {ΦExported{}, true},
7203 {φUnexported{}, false},
7210 for i, test := range exportTests {
7211 typ := TypeOf(test.v)
7212 if got := IsExported(typ); got != test.want {
7213 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7218 func TestTypeStrings(t *testing.T) {
7219 type stringTest struct {
7223 stringTests := []stringTest{
7224 {TypeOf(func(int) {}), "func(int)"},
7225 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7226 {TypeOf(XM{}), "reflect_test.XM"},
7227 {TypeOf(new(XM)), "*reflect_test.XM"},
7228 {TypeOf(new(XM).String), "func() string"},
7229 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7230 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7231 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7232 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7233 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7236 for i, test := range stringTests {
7237 if got, want := test.typ.String(), test.want; got != want {
7238 t.Errorf("type %d String()=%q, want %q", i, got, want)
7243 func TestOffsetLock(t *testing.T) {
7244 var wg sync.WaitGroup
7245 for i := 0; i < 4; i++ {
7249 for j := 0; j < 50; j++ {
7250 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
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)
7705 // Make sure we panic assigning from an unexported field.
7706 m = ValueOf(struct{ m map[string]int }{data}).Field(0)
7707 for iter := m.MapRange(); iter.Next(); {
7708 shouldPanic("using value obtained using unexported field", func() {
7711 shouldPanic("using value obtained using unexported field", func() {
7712 v.SetIterValue(iter)
7717 func TestMethodCallValueCodePtr(t *testing.T) {
7718 m := ValueOf(Point{}).Method(1)
7719 want := MethodValueCallCodePtr()
7720 if got := uintptr(m.UnsafePointer()); got != want {
7721 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7723 if got := m.Pointer(); got != want {
7724 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7729 type B[T any] struct{}
7731 func TestIssue50208(t *testing.T) {
7732 want1 := "B[reflect_test.A]"
7733 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7734 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7736 want2 := "B[reflect_test.B[reflect_test.A]]"
7737 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7738 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7742 func TestNegativeKindString(t *testing.T) {
7744 s := Kind(x).String()
7747 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
7756 func TestValue_Cap(t *testing.T) {
7757 a := &[3]int{1, 2, 3}
7759 if v.Cap() != cap(a) {
7760 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7765 if v.Cap() != cap(a) {
7766 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7769 getError := func(f func()) (errorStr string) {
7772 if str, ok := e.(string); ok {
7779 e := getError(func() {
7783 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
7785 t.Errorf("error is %q, want %q", e, wantStr)
7789 func TestValue_Len(t *testing.T) {
7790 a := &[3]int{1, 2, 3}
7792 if v.Len() != len(a) {
7793 t.Errorf("Len = %d want %d", v.Len(), len(a))
7798 if v.Len() != len(a) {
7799 t.Errorf("Len = %d want %d", v.Len(), len(a))
7802 getError := func(f func()) (errorStr string) {
7805 if str, ok := e.(string); ok {
7812 e := getError(func() {
7816 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
7818 t.Errorf("error is %q, want %q", e, wantStr)
7822 func TestValue_Comparable(t *testing.T) {
7825 var i interface{} = a
7826 var iSlice interface{} = s
7827 var iArrayFalse interface{} = [2]interface{}{1, map[int]int{}}
7828 var iArrayTrue interface{} = [2]interface{}{1, struct{ I interface{} }{1}}
7829 var testcases = []struct {
7880 ValueOf(float32(1)),
7885 ValueOf(float64(1)),
7890 ValueOf(complex(float32(1), float32(1))),
7895 ValueOf(complex(float64(1), float64(1))),
7910 ValueOf(map[int]int{}),
7950 ValueOf([2]map[int]int{}),
7955 ValueOf([0]func(){}),
7960 ValueOf([2]struct{ I interface{} }{{1}, {1}}),
7965 ValueOf([2]struct{ I interface{} }{{[]int{}}, {1}}),
7970 ValueOf([2]interface{}{1, struct{ I int }{1}}),
7975 ValueOf([2]interface{}{[1]interface{}{map[int]int{}}, struct{ I int }{1}}),
7980 ValueOf(&iArrayFalse),
7985 ValueOf(&iArrayTrue),
7991 for _, cas := range testcases {
7996 got := v.Comparable()
7997 if got != cas.comparable {
7998 t.Errorf("%T.Comparable = %t, want %t", v, got, cas.comparable)
8003 type ValueEqualTest struct {
8009 var equalI interface{} = 1
8010 var equalSlice interface{} = []int{1}
8011 var nilInterface interface{}
8012 var mapInterface interface{} = map[int]int{}
8014 var valueEqualTests = []ValueEqualTest{
8061 uint16(1), uint16(1),
8066 uint32(1), uint32(1),
8071 uint64(1), uint64(1),
8076 float32(1), float32(1),
8081 float64(1), float64(1),
8086 complex(1, 1), complex(1, 1),
8091 complex128(1 + 1i), complex128(1 + 1i),
8106 &equalSlice, []int{1},
8111 map[int]int{}, map[int]int{},
8116 (chan int)(nil), nil,
8121 (chan int)(nil), (chan int)(nil),
8131 struct{ i int }{1}, struct{ i int }{1},
8136 struct{ i int }{1}, struct{ i int }{2},
8141 &nilInterface, &nilInterface,
8146 1, ValueOf(struct{ i int }{1}).Field(0),
8151 &mapInterface, &mapInterface,
8157 func TestValue_Equal(t *testing.T) {
8158 for _, test := range valueEqualTests {
8160 if vv, ok := test.v.(Value); ok {
8166 if uu, ok := test.u.(Value); ok {
8179 if r := v.Equal(u); r != test.eq {
8180 t.Errorf("%s == %s got %t, want %t", v.Type(), u.Type(), r, test.eq)