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 BenchmarkDeepEqual(b *testing.B) {
1205 for _, bb := range deepEqualPerfTests {
1206 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1208 for i := 0; i < b.N; i++ {
1209 sink = DeepEqual(bb.x, bb.y)
1215 func check2ndField(x any, offs uintptr, t *testing.T) {
1217 f := s.Type().Field(1)
1218 if f.Offset != offs {
1219 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1223 // Check that structure alignment & offsets viewed through reflect agree with those
1224 // from the compiler itself.
1225 func TestAlignment(t *testing.T) {
1226 type T1inner struct {
1233 type T2inner struct {
1241 x := T1{T1inner{2}, 17}
1242 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1244 x1 := T2{T2inner{2, 3}, 17}
1245 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1248 func Nil(a any, t *testing.T) {
1249 n := ValueOf(a).Field(0)
1251 t.Errorf("%v should be nil", a)
1255 func NotNil(a any, t *testing.T) {
1256 n := ValueOf(a).Field(0)
1258 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1262 func TestIsNil(t *testing.T) {
1263 // These implement IsNil.
1264 // Wrap in extra struct to hide interface type.
1268 struct{ x map[string]int }{},
1269 struct{ x func() bool }{},
1270 struct{ x chan int }{},
1271 struct{ x []string }{},
1272 struct{ x unsafe.Pointer }{},
1274 for _, ts := range doNil {
1275 ty := TypeOf(ts).Field(0).Type
1277 v.IsNil() // panics if not okay to call
1280 // Check the implementations
1292 si.x = make([]int, 10)
1299 ci.x = make(chan int)
1306 mi.x = make(map[int]int)
1317 x func(t *testing.T)
1324 func TestIsZero(t *testing.T) {
1325 for i, tt := range []struct {
1354 {float32(1.2), false},
1356 {float64(1.2), false},
1357 {math.Copysign(0, -1), false},
1358 {complex64(0), true},
1359 {complex64(1.2), false},
1360 {complex128(0), true},
1361 {complex128(1.2), false},
1362 {complex(math.Copysign(0, -1), 0), false},
1363 {complex(0, math.Copysign(0, -1)), false},
1364 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1366 {uintptr(128), false},
1368 {Zero(TypeOf([5]string{})).Interface(), true},
1369 {[5]string{}, true}, // comparable array
1370 {[5]string{"", "", "", "a", ""}, false}, // comparable array
1371 {[1]*int{}, true}, // direct pointer array
1372 {[1]*int{new(int)}, false}, // direct pointer array
1373 {[3][]int{}, true}, // incomparable array
1374 {[3][]int{{1}}, false}, // incomparable array
1375 {[1 << 12]byte{}, true},
1376 {[1 << 12]byte{1}, false},
1378 {(chan string)(nil), true},
1379 {make(chan string), false},
1380 {time.After(1), false},
1382 {(func())(nil), true},
1385 {New(TypeOf(new(error)).Elem()).Elem(), true},
1386 {(io.Reader)(strings.NewReader("")), false},
1388 {(map[string]string)(nil), true},
1389 {map[string]string{}, false},
1390 {make(map[string]string), false},
1392 {(*func())(nil), true},
1393 {(*int)(nil), true},
1396 {[]string{}, false},
1397 {([]string)(nil), true},
1398 {make([]string, 0), false},
1401 {"not-zero", false},
1403 {T{}, true}, // comparable struct
1404 {T{123, 456.75, "hello", &_i}, false}, // comparable struct
1405 {struct{ p *int }{}, true}, // direct pointer struct
1406 {struct{ p *int }{new(int)}, false}, // direct pointer struct
1407 {struct{ s []int }{}, true}, // incomparable struct
1408 {struct{ s []int }{[]int{1}}, false}, // incomparable struct
1410 {(unsafe.Pointer)(nil), true},
1411 {(unsafe.Pointer)(new(int)), false},
1414 if v, ok := tt.x.(Value); ok {
1422 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1425 if !Zero(TypeOf(tt.x)).IsZero() {
1426 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1432 if r := recover(); r == nil {
1433 t.Error("should panic for invalid value")
1440 func BenchmarkIsZero(b *testing.B) {
1441 source := ValueOf(struct {
1442 ArrayComparable [4]T
1443 ArrayIncomparable [4]_Complex
1445 StructIncomparable _Complex
1448 for i := 0; i < source.NumField(); i++ {
1449 name := source.Type().Field(i).Name
1450 value := source.Field(i)
1451 b.Run(name, func(b *testing.B) {
1452 for i := 0; i < b.N; i++ {
1453 sink = value.IsZero()
1459 func TestInterfaceExtraction(t *testing.T) {
1465 v := Indirect(ValueOf(&s)).Field(0).Interface()
1467 t.Error("Interface() on interface: ", v, s.W)
1471 func TestNilPtrValueSub(t *testing.T) {
1473 if pv := ValueOf(pi); pv.Elem().IsValid() {
1474 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1478 func TestMap(t *testing.T) {
1479 m := map[string]int{"a": 1, "b": 2}
1481 if n := mv.Len(); n != len(m) {
1482 t.Errorf("Len = %d, want %d", n, len(m))
1484 keys := mv.MapKeys()
1485 newmap := MakeMap(mv.Type())
1486 for k, v := range m {
1487 // Check that returned Keys match keys in range.
1488 // These aren't required to be in the same order.
1490 for _, kv := range keys {
1491 if kv.String() == k {
1497 t.Errorf("Missing key %q", k)
1500 // Check that value lookup is correct.
1501 vv := mv.MapIndex(ValueOf(k))
1502 if vi := vv.Int(); vi != int64(v) {
1503 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1506 // Copy into new map.
1507 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1509 vv := mv.MapIndex(ValueOf("not-present"))
1511 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1514 newm := newmap.Interface().(map[string]int)
1515 if len(newm) != len(m) {
1516 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1519 for k, v := range newm {
1522 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1526 newmap.SetMapIndex(ValueOf("a"), Value{})
1529 t.Errorf("newm[\"a\"] = %d after delete", v)
1532 mv = ValueOf(&m).Elem()
1533 mv.Set(Zero(mv.Type()))
1535 t.Errorf("mv.Set(nil) failed")
1539 shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
1540 shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
1543 func TestNilMap(t *testing.T) {
1544 var m map[string]int
1546 keys := mv.MapKeys()
1548 t.Errorf(">0 keys for nil map: %v", keys)
1551 // Check that value for missing key is zero.
1552 x := mv.MapIndex(ValueOf("hello"))
1553 if x.Kind() != Invalid {
1554 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1557 // Check big value too.
1558 var mbig map[string][10 << 20]byte
1559 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1560 if x.Kind() != Invalid {
1561 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1564 // Test that deletes from a nil map succeed.
1565 mv.SetMapIndex(ValueOf("hi"), Value{})
1568 func TestChan(t *testing.T) {
1569 for loop := 0; loop < 2; loop++ {
1573 // check both ways to allocate channels
1576 c = make(chan int, 1)
1579 cv = MakeChan(TypeOf(c), 1)
1580 c = cv.Interface().(chan int)
1585 if i := <-c; i != 2 {
1586 t.Errorf("reflect Send 2, native recv %d", i)
1591 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1592 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1596 val, ok := cv.TryRecv()
1597 if val.IsValid() || ok {
1598 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1603 val, ok = cv.TryRecv()
1605 t.Errorf("TryRecv on ready chan got nil")
1606 } else if i := val.Int(); i != 4 || !ok {
1607 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1612 ok = cv.TrySend(ValueOf(5))
1615 t.Errorf("TrySend on full chan succeeded: value %d", i)
1619 ok = cv.TrySend(ValueOf(6))
1621 t.Errorf("TrySend on empty chan failed")
1624 t.Errorf("TrySend failed but it did send %d", x)
1628 if i = <-c; i != 6 {
1629 t.Errorf("TrySend 6, recv %d", i)
1636 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1637 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1639 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1640 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1644 // check creation of unbuffered channel
1646 cv := MakeChan(TypeOf(c), 0)
1647 c = cv.Interface().(chan int)
1648 if cv.TrySend(ValueOf(7)) {
1649 t.Errorf("TrySend on sync chan succeeded")
1651 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1652 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1656 cv = MakeChan(TypeOf(c), 10)
1657 c = cv.Interface().(chan int)
1658 for i := 0; i < 3; i++ {
1661 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1662 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1666 // caseInfo describes a single case in a select test.
1667 type caseInfo struct {
1676 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1678 func TestSelect(t *testing.T) {
1679 selectWatch.once.Do(func() { go selectWatcher() })
1683 newop := func(n int, cap int) (ch, val Value) {
1686 c := make(chan int, cap)
1690 c := make(chan string, cap)
1692 val = ValueOf(fmt.Sprint(n))
1697 for n := 0; x.Next(); n++ {
1698 if testing.Short() && n >= 1000 {
1701 if n >= 100000 && !*allselect {
1704 if n%100000 == 0 && testing.Verbose() {
1705 println("TestSelect", n)
1707 var cases []SelectCase
1712 ch, val := newop(len(cases), 1)
1713 cases = append(cases, SelectCase{
1718 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1723 ch, val := newop(len(cases), 1)
1725 cases = append(cases, SelectCase{
1729 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1734 ch, val := newop(len(cases), 0)
1735 cases = append(cases, SelectCase{
1742 f := func() { ch.Recv() }
1743 info = append(info, caseInfo{desc: "blocking send", helper: f})
1745 info = append(info, caseInfo{desc: "blocking send"})
1751 ch, val := newop(len(cases), 0)
1752 cases = append(cases, SelectCase{
1758 f := func() { ch.Send(val) }
1759 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1761 info = append(info, caseInfo{desc: "blocking recv"})
1767 // Maybe include value to send.
1772 cases = append(cases, SelectCase{
1776 info = append(info, caseInfo{desc: "zero Chan send"})
1779 // Zero Chan receive.
1781 cases = append(cases, SelectCase{
1784 info = append(info, caseInfo{desc: "zero Chan recv"})
1789 cases = append(cases, SelectCase{
1791 Chan: ValueOf((chan int)(nil)),
1794 info = append(info, caseInfo{desc: "nil Chan send"})
1799 cases = append(cases, SelectCase{
1801 Chan: ValueOf((chan int)(nil)),
1803 info = append(info, caseInfo{desc: "nil Chan recv"})
1806 // closed Chan send.
1808 ch := make(chan int)
1810 cases = append(cases, SelectCase{
1815 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1818 // closed Chan recv.
1820 ch, val := newop(len(cases), 0)
1822 val = Zero(val.Type())
1823 cases = append(cases, SelectCase{
1827 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1830 var helper func() // goroutine to help the select complete
1832 // Add default? Must be last case here, but will permute.
1833 // Add the default if the select would otherwise
1834 // block forever, and maybe add it anyway.
1840 for i, c := range info {
1848 } else if c.helper != nil {
1850 helpers = append(helpers, i)
1853 if !canProceed || x.Maybe() {
1854 cases = append(cases, SelectCase{
1857 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1859 } else if canBlock {
1860 // Select needs to communicate with another goroutine.
1861 cas := &info[helpers[x.Choose(len(helpers))]]
1863 cas.canSelect = true
1867 // Permute cases and case info.
1868 // Doing too much here makes the exhaustive loop
1869 // too exhausting, so just do two swaps.
1870 for loop := 0; loop < 2; loop++ {
1871 i := x.Choose(len(cases))
1872 j := x.Choose(len(cases))
1873 cases[i], cases[j] = cases[j], cases[i]
1874 info[i], info[j] = info[j], info[i]
1878 // We wait before kicking off a goroutine to satisfy a blocked select.
1879 // The pause needs to be big enough to let the select block before
1880 // we run the helper, but if we lose that race once in a while it's okay: the
1881 // select will just proceed immediately. Not a big deal.
1882 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1883 pause := 10 * time.Microsecond
1884 if testing.Short() {
1885 pause = 100 * time.Microsecond
1887 time.AfterFunc(pause, helper)
1891 i, recv, recvOK, panicErr := runSelect(cases, info)
1892 if panicErr != nil && !canPanic {
1893 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1895 if panicErr == nil && canPanic && numCanSelect == 1 {
1896 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1898 if panicErr != nil {
1906 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1908 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1911 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1914 if cases[i].Dir == SelectRecv {
1915 if !recv.IsValid() {
1916 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1918 if !cas.recv.IsValid() {
1919 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1921 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1922 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1923 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1925 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1928 if recv.IsValid() || recvOK {
1929 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1935 func TestSelectMaxCases(t *testing.T) {
1936 var sCases []SelectCase
1937 channel := make(chan int)
1939 for i := 0; i < 65536; i++ {
1940 sCases = append(sCases, SelectCase{
1942 Chan: ValueOf(channel),
1946 _, _, _ = Select(sCases)
1947 sCases = append(sCases, SelectCase{
1949 Chan: ValueOf(channel),
1952 if err := recover(); err != nil {
1953 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1954 t.Fatalf("unexpected error from select call with greater than max supported cases")
1957 t.Fatalf("expected select call to panic with greater than max supported cases")
1961 _, _, _ = Select(sCases)
1964 func TestSelectNop(t *testing.T) {
1965 // "select { default: }" should always return the default case.
1966 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1968 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1972 func BenchmarkSelect(b *testing.B) {
1973 channel := make(chan int)
1975 var cases []SelectCase
1976 for i := 0; i < 8; i++ {
1977 cases = append(cases, SelectCase{
1979 Chan: ValueOf(channel),
1982 for _, numCases := range []int{1, 4, 8} {
1983 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1985 for i := 0; i < b.N; i++ {
1986 _, _, _ = Select(cases[:numCases])
1992 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1993 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1994 // an error describing the select and panics the entire test binary.
1995 var selectWatch struct {
2002 func selectWatcher() {
2004 time.Sleep(1 * time.Second)
2006 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
2007 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
2008 panic("select stuck")
2010 selectWatch.Unlock()
2014 // runSelect runs a single select test.
2015 // It returns the values returned by Select but also returns
2016 // a panic value if the Select panics.
2017 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
2019 panicErr = recover()
2022 selectWatch.info = nil
2023 selectWatch.Unlock()
2027 selectWatch.now = time.Now()
2028 selectWatch.info = info
2029 selectWatch.Unlock()
2031 chosen, recv, recvOK = Select(cases)
2035 // fmtSelect formats the information about a single select test.
2036 func fmtSelect(info []caseInfo) string {
2037 var buf bytes.Buffer
2038 fmt.Fprintf(&buf, "\nselect {\n")
2039 for i, cas := range info {
2040 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2041 if cas.recv.IsValid() {
2042 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2045 fmt.Fprintf(&buf, " canselect")
2048 fmt.Fprintf(&buf, " panic")
2050 fmt.Fprintf(&buf, "\n")
2052 fmt.Fprintf(&buf, "}")
2058 // Difficult test for function call because of
2059 // implicit padding between arguments.
2060 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) {
2061 return b, c, d, e, f, g, h
2064 func TestFunc(t *testing.T) {
2065 ret := ValueOf(dummy).Call([]Value{
2069 ValueOf(two{40, 50}),
2071 ValueOf(float32(70)),
2075 t.Fatalf("Call returned %d values, want 7", len(ret))
2078 i := byte(ret[0].Uint())
2079 j := int(ret[1].Int())
2080 k := byte(ret[2].Uint())
2081 l := ret[3].Interface().(two)
2082 m := byte(ret[4].Uint())
2083 n := float32(ret[5].Float())
2084 o := byte(ret[6].Uint())
2086 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2087 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)
2090 for i, v := range ret {
2092 t.Errorf("result %d is addressable", i)
2097 func TestCallConvert(t *testing.T) {
2098 v := ValueOf(new(io.ReadWriter)).Elem()
2099 f := ValueOf(func(r io.Reader) io.Reader { return r })
2100 out := f.Call([]Value{v})
2101 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2102 t.Errorf("expected [nil], got %v", out)
2106 type emptyStruct struct{}
2108 type nonEmptyStruct struct {
2112 func returnEmpty() emptyStruct {
2113 return emptyStruct{}
2116 func takesEmpty(e emptyStruct) {
2119 func returnNonEmpty(i int) nonEmptyStruct {
2120 return nonEmptyStruct{member: i}
2123 func takesNonEmpty(n nonEmptyStruct) int {
2127 func TestCallWithStruct(t *testing.T) {
2128 r := ValueOf(returnEmpty).Call(nil)
2129 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2130 t.Errorf("returning empty struct returned %#v instead", r)
2132 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2134 t.Errorf("takesEmpty returned values: %#v", r)
2136 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2137 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2138 t.Errorf("returnNonEmpty returned %#v", r)
2140 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2141 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2142 t.Errorf("takesNonEmpty returned %#v", r)
2146 func TestCallReturnsEmpty(t *testing.T) {
2147 // Issue 21717: past-the-end pointer write in Call with
2148 // nonzero-sized frame and zero-sized return value.
2150 var finalized uint32
2151 f := func() (emptyStruct, *[2]int64) {
2152 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2153 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2154 return emptyStruct{}, i
2156 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2157 timeout := time.After(5 * time.Second)
2158 for atomic.LoadUint32(&finalized) == 0 {
2161 t.Fatal("finalizer did not run")
2167 runtime.KeepAlive(v)
2170 func BenchmarkCall(b *testing.B) {
2171 fv := ValueOf(func(a, b string) {})
2173 b.RunParallel(func(pb *testing.PB) {
2174 args := []Value{ValueOf("a"), ValueOf("b")}
2183 func (i *myint) inc() {
2187 func BenchmarkCallMethod(b *testing.B) {
2192 for i := 0; i < b.N; i++ {
2197 func BenchmarkCallArgCopy(b *testing.B) {
2198 byteArray := func(n int) Value {
2199 return Zero(ArrayOf(n, TypeOf(byte(0))))
2201 sizes := [...]struct {
2205 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2206 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2207 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2208 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2209 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2211 for _, size := range sizes {
2212 bench := func(b *testing.B) {
2213 args := []Value{size.arg}
2214 b.SetBytes(int64(size.arg.Len()))
2216 b.RunParallel(func(pb *testing.PB) {
2222 name := fmt.Sprintf("size=%v", size.arg.Len())
2227 func TestMakeFunc(t *testing.T) {
2229 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2230 ValueOf(&f).Elem().Set(fv)
2232 // Call g with small arguments so that there is
2233 // something predictable (and different from the
2234 // correct results) in those positions on the stack.
2236 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2238 // Call constructed function f.
2239 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2240 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2241 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)
2245 func TestMakeFuncInterface(t *testing.T) {
2246 fn := func(i int) int { return i }
2247 incr := func(in []Value) []Value {
2248 return []Value{ValueOf(int(in[0].Int() + 1))}
2250 fv := MakeFunc(TypeOf(fn), incr)
2251 ValueOf(&fn).Elem().Set(fv)
2252 if r := fn(2); r != 3 {
2253 t.Errorf("Call returned %d, want 3", r)
2255 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2256 t.Errorf("Call returned %d, want 15", r)
2258 if r := fv.Interface().(func(int) int)(26); r != 27 {
2259 t.Errorf("Call returned %d, want 27", r)
2263 func TestMakeFuncVariadic(t *testing.T) {
2264 // Test that variadic arguments are packed into a slice and passed as last arg
2265 fn := func(_ int, is ...int) []int { return nil }
2266 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2267 ValueOf(&fn).Elem().Set(fv)
2270 if r[0] != 2 || r[1] != 3 {
2271 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2274 r = fn(1, []int{2, 3}...)
2275 if r[0] != 2 || r[1] != 3 {
2276 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2279 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2280 if r[0] != 2 || r[1] != 3 {
2281 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2284 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2285 if r[0] != 2 || r[1] != 3 {
2286 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2289 f := fv.Interface().(func(int, ...int) []int)
2292 if r[0] != 2 || r[1] != 3 {
2293 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2295 r = f(1, []int{2, 3}...)
2296 if r[0] != 2 || r[1] != 3 {
2297 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2301 // Dummy type that implements io.WriteCloser
2305 func (w *WC) Write(p []byte) (n int, err error) {
2308 func (w *WC) Close() error {
2312 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2313 // reflect.Values returned from the wrapped function should be assignment-converted
2314 // to the types returned by the result of MakeFunc.
2316 // Concrete types should be promotable to interfaces they implement.
2318 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2319 return []Value{ValueOf(io.EOF)}
2320 }).Interface().(func() error)
2323 // Super-interfaces should be promotable to simpler interfaces.
2324 var g func() io.Writer
2325 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2326 var w io.WriteCloser = &WC{}
2327 return []Value{ValueOf(&w).Elem()}
2328 }).Interface().(func() io.Writer)
2331 // Channels should be promotable to directional channels.
2332 var h func() <-chan int
2333 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2334 return []Value{ValueOf(make(chan int))}
2335 }).Interface().(func() <-chan int)
2338 // Unnamed types should be promotable to named types.
2339 type T struct{ a, b, c int }
2341 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2342 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2343 }).Interface().(func() T)
2347 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2348 // Type doesn't implement the required interface.
2349 shouldPanic("", func() {
2351 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2352 return []Value{ValueOf(int(7))}
2353 }).Interface().(func() error)
2356 // Assigning to an interface with additional methods.
2357 shouldPanic("", func() {
2358 var f func() io.ReadWriteCloser
2359 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2360 var w io.WriteCloser = &WC{}
2361 return []Value{ValueOf(&w).Elem()}
2362 }).Interface().(func() io.ReadWriteCloser)
2365 // Directional channels can't be assigned to bidirectional ones.
2366 shouldPanic("", func() {
2367 var f func() chan int
2368 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2369 var c <-chan int = make(chan int)
2370 return []Value{ValueOf(c)}
2371 }).Interface().(func() chan int)
2374 // Two named types which are otherwise identical.
2375 shouldPanic("", func() {
2376 type T struct{ a, b, c int }
2377 type U struct{ a, b, c int }
2379 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2380 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2381 }).Interface().(func() T)
2390 // This will be index 0.
2391 func (p Point) AnotherMethod(scale int) int {
2395 // This will be index 1.
2396 func (p Point) Dist(scale int) int {
2397 //println("Point.Dist", p.x, p.y, scale)
2398 return p.x*p.x*scale + p.y*p.y*scale
2401 // This will be index 2.
2402 func (p Point) GCMethod(k int) int {
2407 // This will be index 3.
2408 func (p Point) NoArgs() {
2409 // Exercise no-argument/no-result paths.
2412 // This will be index 4.
2413 func (p Point) TotalDist(points ...Point) int {
2415 for _, q := range points {
2418 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2424 // This will be index 5.
2425 func (p *Point) Int64Method(x int64) int64 {
2429 // This will be index 6.
2430 func (p *Point) Int32Method(x int32) int32 {
2434 func TestMethod(t *testing.T) {
2435 // Non-curried method of type.
2437 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2439 t.Errorf("Type Method returned %d; want 250", i)
2442 m, ok := TypeOf(p).MethodByName("Dist")
2444 t.Fatalf("method by name failed")
2446 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2448 t.Errorf("Type MethodByName returned %d; want 275", i)
2451 m, ok = TypeOf(p).MethodByName("NoArgs")
2453 t.Fatalf("method by name failed")
2455 n := len(m.Func.Call([]Value{ValueOf(p)}))
2457 t.Errorf("NoArgs returned %d values; want 0", n)
2460 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2462 t.Errorf("Pointer Type Method returned %d; want 300", i)
2465 m, ok = TypeOf(&p).MethodByName("Dist")
2467 t.Fatalf("ptr method by name failed")
2469 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2471 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2474 m, ok = TypeOf(&p).MethodByName("NoArgs")
2476 t.Fatalf("method by name failed")
2478 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2480 t.Errorf("NoArgs returned %d values; want 0", n)
2483 // Curried method of value.
2484 tfunc := TypeOf((func(int) int)(nil))
2485 v := ValueOf(p).Method(1)
2486 if tt := v.Type(); tt != tfunc {
2487 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2489 i = v.Call([]Value{ValueOf(14)})[0].Int()
2491 t.Errorf("Value Method returned %d; want 350", i)
2493 v = ValueOf(p).MethodByName("Dist")
2494 if tt := v.Type(); tt != tfunc {
2495 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2497 i = v.Call([]Value{ValueOf(15)})[0].Int()
2499 t.Errorf("Value MethodByName returned %d; want 375", i)
2501 v = ValueOf(p).MethodByName("NoArgs")
2504 // Curried method of pointer.
2505 v = ValueOf(&p).Method(1)
2506 if tt := v.Type(); tt != tfunc {
2507 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2509 i = v.Call([]Value{ValueOf(16)})[0].Int()
2511 t.Errorf("Pointer Value Method returned %d; want 400", i)
2513 v = ValueOf(&p).MethodByName("Dist")
2514 if tt := v.Type(); tt != tfunc {
2515 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2517 i = v.Call([]Value{ValueOf(17)})[0].Int()
2519 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2521 v = ValueOf(&p).MethodByName("NoArgs")
2524 // Curried method of interface value.
2525 // Have to wrap interface value in a struct to get at it.
2526 // Passing it to ValueOf directly would
2527 // access the underlying Point, not the interface.
2531 pv := ValueOf(&x).Elem()
2533 if tt := v.Type(); tt != tfunc {
2534 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2536 i = v.Call([]Value{ValueOf(18)})[0].Int()
2538 t.Errorf("Interface Method returned %d; want 450", i)
2540 v = pv.MethodByName("Dist")
2541 if tt := v.Type(); tt != tfunc {
2542 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2544 i = v.Call([]Value{ValueOf(19)})[0].Int()
2546 t.Errorf("Interface MethodByName returned %d; want 475", i)
2550 func TestMethodValue(t *testing.T) {
2554 // Check that method value have the same underlying code pointers.
2555 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2556 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2559 // Curried method of value.
2560 tfunc := TypeOf((func(int) int)(nil))
2561 v := ValueOf(p).Method(1)
2562 if tt := v.Type(); tt != tfunc {
2563 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2565 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2567 t.Errorf("Value Method returned %d; want 250", i)
2569 v = ValueOf(p).MethodByName("Dist")
2570 if tt := v.Type(); tt != tfunc {
2571 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2573 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2575 t.Errorf("Value MethodByName returned %d; want 275", i)
2577 v = ValueOf(p).MethodByName("NoArgs")
2578 ValueOf(v.Interface()).Call(nil)
2579 v.Interface().(func())()
2581 // Curried method of pointer.
2582 v = ValueOf(&p).Method(1)
2583 if tt := v.Type(); tt != tfunc {
2584 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2586 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2588 t.Errorf("Pointer Value Method returned %d; want 300", i)
2590 v = ValueOf(&p).MethodByName("Dist")
2591 if tt := v.Type(); tt != tfunc {
2592 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2594 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2596 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2598 v = ValueOf(&p).MethodByName("NoArgs")
2599 ValueOf(v.Interface()).Call(nil)
2600 v.Interface().(func())()
2602 // Curried method of pointer to pointer.
2604 v = ValueOf(&pp).Elem().Method(1)
2605 if tt := v.Type(); tt != tfunc {
2606 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2608 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2610 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2612 v = ValueOf(&pp).Elem().MethodByName("Dist")
2613 if tt := v.Type(); tt != tfunc {
2614 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2616 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2618 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2621 // Curried method of interface value.
2622 // Have to wrap interface value in a struct to get at it.
2623 // Passing it to ValueOf directly would
2624 // access the underlying Point, not the interface.
2630 pv := ValueOf(s).Field(0)
2632 if tt := v.Type(); tt != tfunc {
2633 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2635 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2637 t.Errorf("Interface Method returned %d; want 400", i)
2639 v = pv.MethodByName("Dist")
2640 if tt := v.Type(); tt != tfunc {
2641 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2643 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2645 t.Errorf("Interface MethodByName returned %d; want 425", i)
2648 // For issue #33628: method args are not stored at the right offset
2650 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2651 if x := m64(123); x != 123 {
2652 t.Errorf("Int64Method returned %d; want 123", x)
2654 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2655 if x := m32(456); x != 456 {
2656 t.Errorf("Int32Method returned %d; want 456", x)
2660 func TestVariadicMethodValue(t *testing.T) {
2662 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2663 want := int64(p.TotalDist(points[0], points[1], points[2]))
2665 // Variadic method of type.
2666 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2667 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2668 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2671 // Curried method of value.
2672 tfunc = TypeOf((func(...Point) int)(nil))
2673 v := ValueOf(p).Method(4)
2674 if tt := v.Type(); tt != tfunc {
2675 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2677 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2679 t.Errorf("Variadic Method returned %d; want %d", i, want)
2681 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2683 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2686 f := v.Interface().(func(...Point) int)
2687 i = int64(f(points[0], points[1], points[2]))
2689 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2691 i = int64(f(points...))
2693 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2697 type DirectIfaceT struct {
2701 func (d DirectIfaceT) M() int { return *d.p }
2703 func TestDirectIfaceMethod(t *testing.T) {
2705 v := DirectIfaceT{&x}
2707 m, ok := typ.MethodByName("M")
2709 t.Fatalf("cannot find method M")
2711 in := []Value{ValueOf(v)}
2712 out := m.Func.Call(in)
2713 if got := out[0].Int(); got != 42 {
2714 t.Errorf("Call with value receiver got %d, want 42", got)
2719 m, ok = typ.MethodByName("M")
2721 t.Fatalf("cannot find method M")
2723 in = []Value{ValueOf(pv)}
2724 out = m.Func.Call(in)
2725 if got := out[0].Int(); got != 42 {
2726 t.Errorf("Call with pointer receiver got %d, want 42", got)
2730 // Reflect version of $GOROOT/test/method5.go
2732 // Concrete types implementing M method.
2733 // Smaller than a word, word-sized, larger than a word.
2734 // Value and pointer receivers.
2736 type Tinter interface {
2737 M(int, byte) (byte, int)
2742 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2746 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2750 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2754 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2756 type Tbigv [2]uintptr
2758 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2760 type Tbigp [2]uintptr
2762 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2764 type tinter interface {
2765 m(int, byte) (byte, int)
2768 // Embedding via pointer.
2785 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2787 func TestMethod5(t *testing.T) {
2788 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2790 if b != 99 || x != 1000+inc {
2791 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2795 CheckV := func(name string, i Value, inc int) {
2796 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2797 b := bx[0].Interface()
2798 x := bx[1].Interface()
2799 if b != byte(99) || x != 1000+inc {
2800 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2803 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2806 var TinterType = TypeOf(new(Tinter)).Elem()
2808 CheckI := func(name string, i any, inc int) {
2810 CheckV(name, v, inc)
2811 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2816 CheckI("&sv", &sv, 1)
2819 CheckI("&sp", &sp, 2)
2823 CheckI("&wv", &wv, 3)
2826 CheckI("&wp", &wp, 4)
2828 bv := Tbigv([2]uintptr{5, 6})
2829 CheckI("bv", bv, 11)
2830 CheckI("&bv", &bv, 11)
2832 bp := Tbigp([2]uintptr{7, 8})
2833 CheckI("&bp", &bp, 15)
2839 CheckI("t4", t4, 40)
2840 CheckI("&t4", &t4, 40)
2841 CheckI("t3", t3, 40)
2842 CheckI("&t3", &t3, 40)
2843 CheckI("t2", t2, 40)
2844 CheckI("&t2", &t2, 40)
2845 CheckI("t1", t1, 40)
2846 CheckI("&t1", &t1, 40)
2849 vnil := ValueOf(&tnil).Elem()
2850 shouldPanic("Method", func() { vnil.Method(0) })
2853 func TestInterfaceSet(t *testing.T) {
2862 sv := ValueOf(&s).Elem()
2863 sv.Field(0).Set(ValueOf(p))
2864 if q := s.I.(*Point); q != p {
2865 t.Errorf("i: have %p want %p", q, p)
2870 if q := s.P.(*Point); q != p {
2871 t.Errorf("i: have %p want %p", q, p)
2874 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2876 t.Errorf("Interface Method returned %d; want 250", i)
2885 func TestAnonymousFields(t *testing.T) {
2886 var field StructField
2890 if field, ok = type1.FieldByName("int"); !ok {
2891 t.Fatal("no field 'int'")
2893 if field.Index[0] != 1 {
2894 t.Error("field index should be 1; is", field.Index)
2948 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2970 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2989 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
3003 var fieldTests = []FTest{
3004 {struct{}{}, "", nil, 0},
3005 {struct{}{}, "Foo", nil, 0},
3006 {S0{A: 'a'}, "A", []int{0}, 'a'},
3007 {S0{}, "D", nil, 0},
3008 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
3009 {S1{B: 'b'}, "B", []int{0}, 'b'},
3010 {S1{}, "S0", []int{1}, 0},
3011 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
3012 {S2{A: 'a'}, "A", []int{0}, 'a'},
3013 {S2{}, "S1", []int{1}, 0},
3014 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
3015 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
3016 {S2{}, "D", nil, 0},
3017 {S3{}, "S1", nil, 0},
3018 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
3019 {S3{}, "B", nil, 0},
3020 {S3{D: 'd'}, "D", []int{2}, 0},
3021 {S3{E: 'e'}, "E", []int{3}, 'e'},
3022 {S4{A: 'a'}, "A", []int{1}, 'a'},
3023 {S4{}, "B", nil, 0},
3024 {S5{}, "X", nil, 0},
3025 {S5{}, "Y", []int{2, 0, 1}, 0},
3026 {S10{}, "X", nil, 0},
3027 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
3028 {S14{}, "X", nil, 0},
3031 func TestFieldByIndex(t *testing.T) {
3032 for _, test := range fieldTests {
3034 f := s.FieldByIndex(test.index)
3036 if test.index != nil {
3037 if f.Name != test.name {
3038 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3041 t.Errorf("%s.%s found", s.Name(), f.Name)
3043 } else if len(test.index) > 0 {
3044 t.Errorf("%s.%s not found", s.Name(), test.name)
3047 if test.value != 0 {
3048 v := ValueOf(test.s).FieldByIndex(test.index)
3050 if x, ok := v.Interface().(int); ok {
3051 if x != test.value {
3052 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3055 t.Errorf("%s%v value not an int", s.Name(), test.index)
3058 t.Errorf("%s%v value not found", s.Name(), test.index)
3064 func TestFieldByName(t *testing.T) {
3065 for _, test := range fieldTests {
3067 f, found := s.FieldByName(test.name)
3069 if test.index != nil {
3070 // Verify field depth and index.
3071 if len(f.Index) != len(test.index) {
3072 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)
3074 for i, x := range f.Index {
3075 if x != test.index[i] {
3076 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3081 t.Errorf("%s.%s found", s.Name(), f.Name)
3083 } else if len(test.index) > 0 {
3084 t.Errorf("%s.%s not found", s.Name(), test.name)
3087 if test.value != 0 {
3088 v := ValueOf(test.s).FieldByName(test.name)
3090 if x, ok := v.Interface().(int); ok {
3091 if x != test.value {
3092 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3095 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3098 t.Errorf("%s.%s value not found", s.Name(), test.name)
3104 func TestImportPath(t *testing.T) {
3109 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3110 {TypeOf(int(0)), ""},
3111 {TypeOf(int8(0)), ""},
3112 {TypeOf(int16(0)), ""},
3113 {TypeOf(int32(0)), ""},
3114 {TypeOf(int64(0)), ""},
3115 {TypeOf(uint(0)), ""},
3116 {TypeOf(uint8(0)), ""},
3117 {TypeOf(uint16(0)), ""},
3118 {TypeOf(uint32(0)), ""},
3119 {TypeOf(uint64(0)), ""},
3120 {TypeOf(uintptr(0)), ""},
3121 {TypeOf(float32(0)), ""},
3122 {TypeOf(float64(0)), ""},
3123 {TypeOf(complex64(0)), ""},
3124 {TypeOf(complex128(0)), ""},
3125 {TypeOf(byte(0)), ""},
3126 {TypeOf(rune(0)), ""},
3127 {TypeOf([]byte(nil)), ""},
3128 {TypeOf([]rune(nil)), ""},
3129 {TypeOf(string("")), ""},
3130 {TypeOf((*any)(nil)).Elem(), ""},
3131 {TypeOf((*byte)(nil)), ""},
3132 {TypeOf((*rune)(nil)), ""},
3133 {TypeOf((*int64)(nil)), ""},
3134 {TypeOf(map[string]int{}), ""},
3135 {TypeOf((*error)(nil)).Elem(), ""},
3136 {TypeOf((*Point)(nil)), ""},
3137 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3139 for _, test := range tests {
3140 if path := test.t.PkgPath(); path != test.path {
3141 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3146 func TestFieldPkgPath(t *testing.T) {
3148 typ := TypeOf(struct {
3156 type pkgpathTest struct {
3163 checkPkgPath := func(name string, s []pkgpathTest) {
3164 for _, test := range s {
3165 f := typ.FieldByIndex(test.index)
3166 if got, want := f.PkgPath, test.pkgPath; got != want {
3167 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3169 if got, want := f.Anonymous, test.embedded; got != want {
3170 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3172 if got, want := f.IsExported(), test.exported; got != want {
3173 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3178 checkPkgPath("testStruct", []pkgpathTest{
3179 {[]int{0}, "", false, true}, // Exported
3180 {[]int{1}, "reflect_test", false, false}, // unexported
3181 {[]int{2}, "", true, true}, // OtherPkgFields
3182 {[]int{2, 0}, "", false, true}, // OtherExported
3183 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3184 {[]int{3}, "reflect_test", true, false}, // int
3185 {[]int{4}, "reflect_test", true, false}, // *x
3188 type localOtherPkgFields OtherPkgFields
3189 typ = TypeOf(localOtherPkgFields{})
3190 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3191 {[]int{0}, "", false, true}, // OtherExported
3192 {[]int{1}, "reflect", false, false}, // otherUnexported
3196 func TestMethodPkgPath(t *testing.T) {
3201 typ := TypeOf((*interface {
3214 {"x", "reflect_test", false},
3215 {"y", "reflect_test", false},
3218 for _, test := range tests {
3219 m, _ := typ.MethodByName(test.name)
3220 if got, want := m.PkgPath, test.pkgPath; got != want {
3221 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3223 if got, want := m.IsExported(), test.exported; got != want {
3224 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3229 func TestVariadicType(t *testing.T) {
3230 // Test example from Type documentation.
3231 var f func(x int, y ...float64)
3233 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3235 if sl.Kind() == Slice {
3236 if sl.Elem() == TypeOf(0.0) {
3244 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3245 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3246 for i := 0; i < typ.NumIn(); i++ {
3247 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3261 func (*inner) M() {}
3262 func (*outer) M() {}
3264 func TestNestedMethods(t *testing.T) {
3265 typ := TypeOf((*outer)(nil))
3266 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3267 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3268 for i := 0; i < typ.NumMethod(); i++ {
3270 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3277 func (*unexp) f() (int32, int8) { return 7, 7 }
3278 func (*unexp) g() (int64, int8) { return 8, 8 }
3280 type unexpI interface {
3284 var unexpi unexpI = new(unexp)
3286 func TestUnexportedMethods(t *testing.T) {
3287 typ := TypeOf(unexpi)
3289 if got := typ.NumMethod(); got != 0 {
3290 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3294 type InnerInt struct {
3298 type OuterInt struct {
3303 func (i *InnerInt) M() int {
3307 func TestEmbeddedMethods(t *testing.T) {
3308 typ := TypeOf((*OuterInt)(nil))
3309 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3310 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3311 for i := 0; i < typ.NumMethod(); i++ {
3313 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3318 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3319 t.Errorf("i.M() = %d, want 3", v)
3322 o := &OuterInt{1, InnerInt{2}}
3323 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3324 t.Errorf("i.M() = %d, want 2", v)
3328 if v := f(o); v != 2 {
3329 t.Errorf("f(o) = %d, want 2", v)
3333 type FuncDDD func(...any) error
3335 func (f FuncDDD) M() {}
3337 func TestNumMethodOnDDD(t *testing.T) {
3338 rv := ValueOf((FuncDDD)(nil))
3339 if n := rv.NumMethod(); n != 1 {
3340 t.Fatalf("NumMethod()=%d, want 1", n)
3344 func TestPtrTo(t *testing.T) {
3345 // This block of code means that the ptrToThis field of the
3346 // reflect data for *unsafe.Pointer is non zero, see
3347 // https://golang.org/issue/19003
3348 var x unsafe.Pointer
3355 for i = 0; i < 100; i++ {
3356 typ = PointerTo(typ)
3358 for i = 0; i < 100; i++ {
3361 if typ != TypeOf(z) {
3362 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3366 func TestPtrToGC(t *testing.T) {
3368 tt := TypeOf(T(nil))
3372 for i := 0; i < n; i++ {
3377 v.Elem().Set(ValueOf(p).Convert(pt))
3378 x = append(x, v.Interface())
3382 for i, xi := range x {
3383 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3384 if k != uintptr(i) {
3385 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3390 func BenchmarkPtrTo(b *testing.B) {
3391 // Construct a type with a zero ptrToThis.
3392 type T struct{ int }
3393 t := SliceOf(TypeOf(T{}))
3394 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3395 if !ptrToThis.IsValid() {
3396 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3398 if ptrToThis.Int() != 0 {
3399 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3403 // Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on
3405 b.RunParallel(func(pb *testing.PB) {
3412 func TestAddr(t *testing.T) {
3424 t.Errorf("Addr.Elem.Set failed to set value")
3427 // Again but take address of the ValueOf value.
3428 // Exercises generation of PtrTypes not present in the binary.
3430 v = ValueOf(&q).Elem()
3439 t.Errorf("Addr.Elem.Set failed to set value")
3442 // Starting without pointer we should get changed value
3445 v = ValueOf(&qq).Elem()
3451 if p.X != 3 { // should be unchanged from last time
3452 t.Errorf("somehow value Set changed original p")
3454 p = v0.Interface().(struct {
3458 t.Errorf("Addr.Elem.Set valued to set value in top value")
3461 // Verify that taking the address of a type gives us a pointer
3462 // which we can convert back using the usual interface
3467 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3468 *(ps.(**bool)) = new(bool)
3470 t.Errorf("Addr.Interface direct assignment failed")
3474 func noAlloc(t *testing.T, n int, f func(int)) {
3475 if testing.Short() {
3476 t.Skip("skipping malloc count in short mode")
3478 if runtime.GOMAXPROCS(0) > 1 {
3479 t.Skip("skipping; GOMAXPROCS>1")
3482 allocs := testing.AllocsPerRun(n, func() {
3487 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3491 func TestAllocations(t *testing.T) {
3492 noAlloc(t, 100, func(j int) {
3496 // We can uncomment this when compiler escape analysis
3497 // is good enough to see that the integer assigned to i
3498 // does not escape and therefore need not be allocated.
3502 // if int(v.Int()) != 42+j {
3503 // panic("wrong int")
3506 i = func(j int) int { return j }
3508 if v.Interface().(func(int) int)(j) != j {
3509 panic("wrong result")
3514 func TestSmallNegativeInt(t *testing.T) {
3518 t.Errorf("int16(-1).Int() returned %v", v.Int())
3522 func TestIndex(t *testing.T) {
3523 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3524 v := ValueOf(xs).Index(3).Interface().(byte)
3526 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3528 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3529 v = ValueOf(xa).Index(2).Interface().(byte)
3531 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3534 v = ValueOf(s).Index(3).Interface().(byte)
3536 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3540 func TestSlice(t *testing.T) {
3541 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3542 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3544 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3547 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3549 if !DeepEqual(v[0:5], xs[3:]) {
3550 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3552 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3553 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3555 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3558 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3560 if !DeepEqual(v[0:6], xa[2:]) {
3561 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3564 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3566 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3569 rv := ValueOf(&xs).Elem()
3571 ptr2 := rv.UnsafePointer()
3573 ptr3 := rv.UnsafePointer()
3575 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3579 func TestSlice3(t *testing.T) {
3580 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3581 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3583 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3586 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3588 if !DeepEqual(v[0:4], xs[3:7:7]) {
3589 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3591 rv := ValueOf(&xs).Elem()
3592 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3593 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3594 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3596 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3597 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3599 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3602 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3604 if !DeepEqual(v[0:4], xa[2:6:6]) {
3605 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3607 rv = ValueOf(&xa).Elem()
3608 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3609 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3610 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3613 rv = ValueOf(&s).Elem()
3614 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3616 rv = ValueOf(&xs).Elem()
3617 rv = rv.Slice3(3, 5, 7)
3618 ptr2 := rv.UnsafePointer()
3619 rv = rv.Slice3(4, 4, 4)
3620 ptr3 := rv.UnsafePointer()
3622 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3626 func TestSetLenCap(t *testing.T) {
3627 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3628 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3630 vs := ValueOf(&xs).Elem()
3631 shouldPanic("SetLen", func() { vs.SetLen(10) })
3632 shouldPanic("SetCap", func() { vs.SetCap(10) })
3633 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3634 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3635 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3637 if len(xs) != 5 || cap(xs) != 8 {
3638 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3641 if len(xs) != 5 || cap(xs) != 6 {
3642 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3645 if len(xs) != 5 || cap(xs) != 5 {
3646 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3648 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3649 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3651 va := ValueOf(&xa).Elem()
3652 shouldPanic("SetLen", func() { va.SetLen(8) })
3653 shouldPanic("SetCap", func() { va.SetCap(8) })
3656 func TestVariadic(t *testing.T) {
3661 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3662 if b.String() != "hello, 42 world" {
3663 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3667 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3668 if b.String() != "hello, 42 world" {
3669 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3673 func TestFuncArg(t *testing.T) {
3674 f1 := func(i int, f func(int) int) int { return f(i) }
3675 f2 := func(i int) int { return i + 1 }
3676 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3677 if r[0].Int() != 101 {
3678 t.Errorf("function returned %d, want 101", r[0].Int())
3682 func TestStructArg(t *testing.T) {
3683 type padded struct {
3690 wantA = padded{"3", 4}
3693 f := func(a padded, b uint32) {
3696 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3697 if gotA != wantA || gotB != wantB {
3698 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3702 var tagGetTests = []struct {
3707 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3708 {`protobuf:"PB(1,2)"`, `foo`, ``},
3709 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3710 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3711 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3712 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3713 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3716 func TestTagGet(t *testing.T) {
3717 for _, tt := range tagGetTests {
3718 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3719 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3724 func TestBytes(t *testing.T) {
3725 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3726 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3730 y := ValueOf(x).Bytes()
3731 if !bytes.Equal(x, y) {
3732 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3735 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3740 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3741 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3742 b := ValueOf(&a).Elem().Bytes()
3743 if !bytes.Equal(a[:], y) {
3744 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3747 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3750 // Per issue #24746, it was decided that Bytes can be called on byte slices
3751 // that normally cannot be converted from per Go language semantics.
3755 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3756 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3757 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3758 ValueOf(new(AB)).Elem().Bytes() // should not panic
3761 func TestSetBytes(t *testing.T) {
3764 y := []byte{1, 2, 3, 4}
3765 ValueOf(&x).Elem().SetBytes(y)
3766 if !bytes.Equal(x, y) {
3767 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3770 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3774 type Private struct {
3780 func (p *Private) m() {
3783 type private struct {
3791 func (p *private) P() {
3794 type Public struct {
3800 func (p *Public) M() {
3803 func TestUnexported(t *testing.T) {
3808 isValid(v.Elem().Field(0))
3809 isValid(v.Elem().Field(1))
3810 isValid(v.Elem().Field(2))
3811 isValid(v.Elem().FieldByName("X"))
3812 isValid(v.Elem().FieldByName("Y"))
3813 isValid(v.Elem().FieldByName("Z"))
3814 isValid(v.Type().Method(0).Func)
3815 m, _ := v.Type().MethodByName("M")
3817 m, _ = v.Type().MethodByName("P")
3819 isNonNil(v.Elem().Field(0).Interface())
3820 isNonNil(v.Elem().Field(1).Interface())
3821 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3822 isNonNil(v.Elem().FieldByName("X").Interface())
3823 isNonNil(v.Elem().FieldByName("Y").Interface())
3824 isNonNil(v.Elem().FieldByName("Z").Interface())
3825 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3826 isNonNil(v.Type().Method(0).Func.Interface())
3827 m, _ = v.Type().MethodByName("P")
3828 isNonNil(m.Func.Interface())
3832 isValid(v.Elem().Field(0))
3833 isValid(v.Elem().Field(1))
3834 isValid(v.Elem().FieldByName("x"))
3835 isValid(v.Elem().FieldByName("y"))
3836 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3837 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3838 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3839 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3840 shouldPanic("Method", func() { v.Type().Method(0) })
3843 func TestSetPanic(t *testing.T) {
3844 ok := func(f func()) { f() }
3845 bad := func(f func()) { shouldPanic("Set", f) }
3846 clear := func(v Value) { v.Set(Zero(v.Type())) }
3874 bad(func() { clear(v.Field(0)) }) // .X
3875 bad(func() { clear(v.Field(1)) }) // .t1
3876 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3877 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3878 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3879 bad(func() { clear(v.Field(2)) }) // .T2
3880 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3881 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3882 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3883 bad(func() { clear(v.Field(3)) }) // .NamedT1
3884 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3885 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3886 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3887 bad(func() { clear(v.Field(4)) }) // .NamedT2
3888 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3889 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3890 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3891 bad(func() { clear(v.Field(5)) }) // .namedT1
3892 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3893 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3894 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3895 bad(func() { clear(v.Field(6)) }) // .namedT2
3896 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3897 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3898 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3901 v = ValueOf(&T{}).Elem()
3902 ok(func() { clear(v.Field(0)) }) // .X
3903 bad(func() { clear(v.Field(1)) }) // .t1
3904 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3905 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3906 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3907 ok(func() { clear(v.Field(2)) }) // .T2
3908 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3909 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3910 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3911 ok(func() { clear(v.Field(3)) }) // .NamedT1
3912 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3913 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3914 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3915 ok(func() { clear(v.Field(4)) }) // .NamedT2
3916 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3917 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3918 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3919 bad(func() { clear(v.Field(5)) }) // .namedT1
3920 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3921 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3922 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3923 bad(func() { clear(v.Field(6)) }) // .namedT2
3924 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3925 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3926 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3931 func (t timp) W() {}
3932 func (t timp) Y() {}
3933 func (t timp) w() {}
3934 func (t timp) y() {}
3936 func TestCallPanic(t *testing.T) {
3961 ok := func(f func()) { f() }
3962 badCall := func(f func()) { shouldPanic("Call", f) }
3963 badMethod := func(f func()) { shouldPanic("Method", f) }
3964 call := func(v Value) { v.Call(nil) }
3967 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3968 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3969 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3970 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3971 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3972 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3973 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3974 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3975 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3977 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3978 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3979 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3980 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3982 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3983 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3984 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3985 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3987 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3988 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3989 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3990 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3992 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3993 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3994 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3995 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3997 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3998 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3999 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
4000 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
4002 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
4003 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
4004 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
4005 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
4008 func TestValuePanic(t *testing.T) {
4010 shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
4011 shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
4012 shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
4013 shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
4014 shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
4015 shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
4016 shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
4017 shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
4018 shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
4019 shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
4020 shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
4021 shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
4022 shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
4023 shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
4024 shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
4025 shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
4026 shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
4027 shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
4028 shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
4029 shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
4030 shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
4031 shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
4032 shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
4033 shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
4034 shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
4035 shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
4036 shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
4037 shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
4038 shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
4039 shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
4040 shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
4041 shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
4042 shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
4043 shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
4044 shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
4045 shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
4046 shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
4047 shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
4048 shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
4049 shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
4050 shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
4053 func shouldPanic(expect string, f func()) {
4057 panic("did not panic")
4061 switch r := r.(type) {
4067 panic(fmt.Sprintf("panicked with unexpected type %T", r))
4069 if !strings.HasPrefix(s, "reflect") {
4070 panic(`panic string does not start with "reflect": ` + s)
4072 if !strings.Contains(s, expect) {
4073 panic(`panic string does not contain "` + expect + `": ` + s)
4080 func isNonNil(x any) {
4082 panic("nil interface")
4086 func isValid(v Value) {
4092 func TestAlias(t *testing.T) {
4093 x := string("hello")
4094 v := ValueOf(&x).Elem()
4095 oldvalue := v.Interface()
4096 v.SetString("world")
4097 newvalue := v.Interface()
4099 if oldvalue != "hello" || newvalue != "world" {
4100 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
4106 func EmptyInterfaceV(x any) Value {
4107 return ValueOf(&x).Elem()
4110 func ReaderV(x io.Reader) Value {
4111 return ValueOf(&x).Elem()
4114 func ReadWriterV(x io.ReadWriter) Value {
4115 return ValueOf(&x).Elem()
4119 type MyStruct struct {
4122 type MyStruct1 struct {
4127 type MyStruct2 struct {
4132 type MyString string
4134 type MyBytesArrayPtr0 *[0]byte
4135 type MyBytesArrayPtr *[4]byte
4136 type MyBytesArray0 [0]byte
4137 type MyBytesArray [4]byte
4138 type MyRunes []int32
4142 type IntChan chan int
4143 type IntChanRecv <-chan int
4144 type IntChanSend chan<- int
4145 type BytesChan chan []byte
4146 type BytesChanRecv <-chan []byte
4147 type BytesChanSend chan<- []byte
4149 var convertTests = []struct {
4155 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4161 var numbers = []string{
4162 "int8", "uint8", "int16", "uint16",
4163 "int32", "uint32", "int64", "uint64",
4164 "int", "uint", "uintptr",
4165 "float32", "float64",
4169 // all pairs but in an unusual order,
4170 // to emit all the int8, uint8 cases
4171 // before n grows too big.
4173 for i, f := range numbers {
4174 for _, g := range numbers[i:] {
4175 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4178 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4185 {V(int8(1)), V(int8(1))},
4186 {V(int8(2)), V(uint8(2))},
4187 {V(uint8(3)), V(int8(3))},
4188 {V(int8(4)), V(int16(4))},
4189 {V(int16(5)), V(int8(5))},
4190 {V(int8(6)), V(uint16(6))},
4191 {V(uint16(7)), V(int8(7))},
4192 {V(int8(8)), V(int32(8))},
4193 {V(int32(9)), V(int8(9))},
4194 {V(int8(10)), V(uint32(10))},
4195 {V(uint32(11)), V(int8(11))},
4196 {V(int8(12)), V(int64(12))},
4197 {V(int64(13)), V(int8(13))},
4198 {V(int8(14)), V(uint64(14))},
4199 {V(uint64(15)), V(int8(15))},
4200 {V(int8(16)), V(int(16))},
4201 {V(int(17)), V(int8(17))},
4202 {V(int8(18)), V(uint(18))},
4203 {V(uint(19)), V(int8(19))},
4204 {V(int8(20)), V(uintptr(20))},
4205 {V(uintptr(21)), V(int8(21))},
4206 {V(int8(22)), V(float32(22))},
4207 {V(float32(23)), V(int8(23))},
4208 {V(int8(24)), V(float64(24))},
4209 {V(float64(25)), V(int8(25))},
4210 {V(uint8(26)), V(uint8(26))},
4211 {V(uint8(27)), V(int16(27))},
4212 {V(int16(28)), V(uint8(28))},
4213 {V(uint8(29)), V(uint16(29))},
4214 {V(uint16(30)), V(uint8(30))},
4215 {V(uint8(31)), V(int32(31))},
4216 {V(int32(32)), V(uint8(32))},
4217 {V(uint8(33)), V(uint32(33))},
4218 {V(uint32(34)), V(uint8(34))},
4219 {V(uint8(35)), V(int64(35))},
4220 {V(int64(36)), V(uint8(36))},
4221 {V(uint8(37)), V(uint64(37))},
4222 {V(uint64(38)), V(uint8(38))},
4223 {V(uint8(39)), V(int(39))},
4224 {V(int(40)), V(uint8(40))},
4225 {V(uint8(41)), V(uint(41))},
4226 {V(uint(42)), V(uint8(42))},
4227 {V(uint8(43)), V(uintptr(43))},
4228 {V(uintptr(44)), V(uint8(44))},
4229 {V(uint8(45)), V(float32(45))},
4230 {V(float32(46)), V(uint8(46))},
4231 {V(uint8(47)), V(float64(47))},
4232 {V(float64(48)), V(uint8(48))},
4233 {V(int16(49)), V(int16(49))},
4234 {V(int16(50)), V(uint16(50))},
4235 {V(uint16(51)), V(int16(51))},
4236 {V(int16(52)), V(int32(52))},
4237 {V(int32(53)), V(int16(53))},
4238 {V(int16(54)), V(uint32(54))},
4239 {V(uint32(55)), V(int16(55))},
4240 {V(int16(56)), V(int64(56))},
4241 {V(int64(57)), V(int16(57))},
4242 {V(int16(58)), V(uint64(58))},
4243 {V(uint64(59)), V(int16(59))},
4244 {V(int16(60)), V(int(60))},
4245 {V(int(61)), V(int16(61))},
4246 {V(int16(62)), V(uint(62))},
4247 {V(uint(63)), V(int16(63))},
4248 {V(int16(64)), V(uintptr(64))},
4249 {V(uintptr(65)), V(int16(65))},
4250 {V(int16(66)), V(float32(66))},
4251 {V(float32(67)), V(int16(67))},
4252 {V(int16(68)), V(float64(68))},
4253 {V(float64(69)), V(int16(69))},
4254 {V(uint16(70)), V(uint16(70))},
4255 {V(uint16(71)), V(int32(71))},
4256 {V(int32(72)), V(uint16(72))},
4257 {V(uint16(73)), V(uint32(73))},
4258 {V(uint32(74)), V(uint16(74))},
4259 {V(uint16(75)), V(int64(75))},
4260 {V(int64(76)), V(uint16(76))},
4261 {V(uint16(77)), V(uint64(77))},
4262 {V(uint64(78)), V(uint16(78))},
4263 {V(uint16(79)), V(int(79))},
4264 {V(int(80)), V(uint16(80))},
4265 {V(uint16(81)), V(uint(81))},
4266 {V(uint(82)), V(uint16(82))},
4267 {V(uint16(83)), V(uintptr(83))},
4268 {V(uintptr(84)), V(uint16(84))},
4269 {V(uint16(85)), V(float32(85))},
4270 {V(float32(86)), V(uint16(86))},
4271 {V(uint16(87)), V(float64(87))},
4272 {V(float64(88)), V(uint16(88))},
4273 {V(int32(89)), V(int32(89))},
4274 {V(int32(90)), V(uint32(90))},
4275 {V(uint32(91)), V(int32(91))},
4276 {V(int32(92)), V(int64(92))},
4277 {V(int64(93)), V(int32(93))},
4278 {V(int32(94)), V(uint64(94))},
4279 {V(uint64(95)), V(int32(95))},
4280 {V(int32(96)), V(int(96))},
4281 {V(int(97)), V(int32(97))},
4282 {V(int32(98)), V(uint(98))},
4283 {V(uint(99)), V(int32(99))},
4284 {V(int32(100)), V(uintptr(100))},
4285 {V(uintptr(101)), V(int32(101))},
4286 {V(int32(102)), V(float32(102))},
4287 {V(float32(103)), V(int32(103))},
4288 {V(int32(104)), V(float64(104))},
4289 {V(float64(105)), V(int32(105))},
4290 {V(uint32(106)), V(uint32(106))},
4291 {V(uint32(107)), V(int64(107))},
4292 {V(int64(108)), V(uint32(108))},
4293 {V(uint32(109)), V(uint64(109))},
4294 {V(uint64(110)), V(uint32(110))},
4295 {V(uint32(111)), V(int(111))},
4296 {V(int(112)), V(uint32(112))},
4297 {V(uint32(113)), V(uint(113))},
4298 {V(uint(114)), V(uint32(114))},
4299 {V(uint32(115)), V(uintptr(115))},
4300 {V(uintptr(116)), V(uint32(116))},
4301 {V(uint32(117)), V(float32(117))},
4302 {V(float32(118)), V(uint32(118))},
4303 {V(uint32(119)), V(float64(119))},
4304 {V(float64(120)), V(uint32(120))},
4305 {V(int64(121)), V(int64(121))},
4306 {V(int64(122)), V(uint64(122))},
4307 {V(uint64(123)), V(int64(123))},
4308 {V(int64(124)), V(int(124))},
4309 {V(int(125)), V(int64(125))},
4310 {V(int64(126)), V(uint(126))},
4311 {V(uint(127)), V(int64(127))},
4312 {V(int64(128)), V(uintptr(128))},
4313 {V(uintptr(129)), V(int64(129))},
4314 {V(int64(130)), V(float32(130))},
4315 {V(float32(131)), V(int64(131))},
4316 {V(int64(132)), V(float64(132))},
4317 {V(float64(133)), V(int64(133))},
4318 {V(uint64(134)), V(uint64(134))},
4319 {V(uint64(135)), V(int(135))},
4320 {V(int(136)), V(uint64(136))},
4321 {V(uint64(137)), V(uint(137))},
4322 {V(uint(138)), V(uint64(138))},
4323 {V(uint64(139)), V(uintptr(139))},
4324 {V(uintptr(140)), V(uint64(140))},
4325 {V(uint64(141)), V(float32(141))},
4326 {V(float32(142)), V(uint64(142))},
4327 {V(uint64(143)), V(float64(143))},
4328 {V(float64(144)), V(uint64(144))},
4329 {V(int(145)), V(int(145))},
4330 {V(int(146)), V(uint(146))},
4331 {V(uint(147)), V(int(147))},
4332 {V(int(148)), V(uintptr(148))},
4333 {V(uintptr(149)), V(int(149))},
4334 {V(int(150)), V(float32(150))},
4335 {V(float32(151)), V(int(151))},
4336 {V(int(152)), V(float64(152))},
4337 {V(float64(153)), V(int(153))},
4338 {V(uint(154)), V(uint(154))},
4339 {V(uint(155)), V(uintptr(155))},
4340 {V(uintptr(156)), V(uint(156))},
4341 {V(uint(157)), V(float32(157))},
4342 {V(float32(158)), V(uint(158))},
4343 {V(uint(159)), V(float64(159))},
4344 {V(float64(160)), V(uint(160))},
4345 {V(uintptr(161)), V(uintptr(161))},
4346 {V(uintptr(162)), V(float32(162))},
4347 {V(float32(163)), V(uintptr(163))},
4348 {V(uintptr(164)), V(float64(164))},
4349 {V(float64(165)), V(uintptr(165))},
4350 {V(float32(166)), V(float32(166))},
4351 {V(float32(167)), V(float64(167))},
4352 {V(float64(168)), V(float32(168))},
4353 {V(float64(169)), V(float64(169))},
4356 {V(float64(1.5)), V(int(1))},
4359 {V(complex64(1i)), V(complex64(1i))},
4360 {V(complex64(2i)), V(complex128(2i))},
4361 {V(complex128(3i)), V(complex64(3i))},
4362 {V(complex128(4i)), V(complex128(4i))},
4365 {V(string("hello")), V(string("hello"))},
4366 {V(string("bytes1")), V([]byte("bytes1"))},
4367 {V([]byte("bytes2")), V(string("bytes2"))},
4368 {V([]byte("bytes3")), V([]byte("bytes3"))},
4369 {V(string("runes♝")), V([]rune("runes♝"))},
4370 {V([]rune("runes♕")), V(string("runes♕"))},
4371 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4372 {V(int('a')), V(string("a"))},
4373 {V(int8('a')), V(string("a"))},
4374 {V(int16('a')), V(string("a"))},
4375 {V(int32('a')), V(string("a"))},
4376 {V(int64('a')), V(string("a"))},
4377 {V(uint('a')), V(string("a"))},
4378 {V(uint8('a')), V(string("a"))},
4379 {V(uint16('a')), V(string("a"))},
4380 {V(uint32('a')), V(string("a"))},
4381 {V(uint64('a')), V(string("a"))},
4382 {V(uintptr('a')), V(string("a"))},
4383 {V(int(-1)), V(string("\uFFFD"))},
4384 {V(int8(-2)), V(string("\uFFFD"))},
4385 {V(int16(-3)), V(string("\uFFFD"))},
4386 {V(int32(-4)), V(string("\uFFFD"))},
4387 {V(int64(-5)), V(string("\uFFFD"))},
4388 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4389 {V(int64(1 << 32)), V(string("\uFFFD"))},
4390 {V(uint(0x110001)), V(string("\uFFFD"))},
4391 {V(uint32(0x110002)), V(string("\uFFFD"))},
4392 {V(uint64(0x110003)), V(string("\uFFFD"))},
4393 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4394 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4397 {V(MyString("hello")), V(string("hello"))},
4398 {V(string("hello")), V(MyString("hello"))},
4399 {V(string("hello")), V(string("hello"))},
4400 {V(MyString("hello")), V(MyString("hello"))},
4401 {V(MyString("bytes1")), V([]byte("bytes1"))},
4402 {V([]byte("bytes2")), V(MyString("bytes2"))},
4403 {V([]byte("bytes3")), V([]byte("bytes3"))},
4404 {V(MyString("runes♝")), V([]rune("runes♝"))},
4405 {V([]rune("runes♕")), V(MyString("runes♕"))},
4406 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4407 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4408 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4409 {V(int('a')), V(MyString("a"))},
4410 {V(int8('a')), V(MyString("a"))},
4411 {V(int16('a')), V(MyString("a"))},
4412 {V(int32('a')), V(MyString("a"))},
4413 {V(int64('a')), V(MyString("a"))},
4414 {V(uint('a')), V(MyString("a"))},
4415 {V(uint8('a')), V(MyString("a"))},
4416 {V(uint16('a')), V(MyString("a"))},
4417 {V(uint32('a')), V(MyString("a"))},
4418 {V(uint64('a')), V(MyString("a"))},
4419 {V(uintptr('a')), V(MyString("a"))},
4420 {V(int(-1)), V(MyString("\uFFFD"))},
4421 {V(int8(-2)), V(MyString("\uFFFD"))},
4422 {V(int16(-3)), V(MyString("\uFFFD"))},
4423 {V(int32(-4)), V(MyString("\uFFFD"))},
4424 {V(int64(-5)), V(MyString("\uFFFD"))},
4425 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4426 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4427 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4428 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4431 {V(string("bytes1")), V(MyBytes("bytes1"))},
4432 {V(MyBytes("bytes2")), V(string("bytes2"))},
4433 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4434 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4435 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4438 {V(string("runes♝")), V(MyRunes("runes♝"))},
4439 {V(MyRunes("runes♕")), V(string("runes♕"))},
4440 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4441 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4442 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4444 // slice to array pointer
4445 {V([]byte(nil)), V((*[0]byte)(nil))},
4446 {V([]byte{}), V(new([0]byte))},
4447 {V([]byte{7}), V(&[1]byte{7})},
4448 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4449 {V(MyBytes([]byte{})), V(new([0]byte))},
4450 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4451 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4452 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4453 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4454 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4455 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4457 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4458 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4459 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4460 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4461 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4462 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4463 {V(new([0]byte)), V(new(MyBytesArray0))},
4464 {V(new(MyBytesArray0)), V(new([0]byte))},
4465 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4466 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4468 // named types and equal underlying types
4469 {V(new(int)), V(new(integer))},
4470 {V(new(integer)), V(new(int))},
4471 {V(Empty{}), V(struct{}{})},
4472 {V(new(Empty)), V(new(struct{}))},
4473 {V(struct{}{}), V(Empty{})},
4474 {V(new(struct{})), V(new(Empty))},
4475 {V(Empty{}), V(Empty{})},
4476 {V(MyBytes{}), V([]byte{})},
4477 {V([]byte{}), V(MyBytes{})},
4478 {V((func())(nil)), V(MyFunc(nil))},
4479 {V((MyFunc)(nil)), V((func())(nil))},
4481 // structs with different tags
4494 {V(MyStruct{}), V(struct {
4500 }{}), V(MyStruct{})},
4502 {V(MyStruct{}), V(struct {
4508 }{}), V(MyStruct{})},
4510 {V(MyStruct1{}), V(MyStruct2{})},
4511 {V(MyStruct2{}), V(MyStruct1{})},
4513 // can convert *byte and *MyByte
4514 {V((*byte)(nil)), V((*MyByte)(nil))},
4515 {V((*MyByte)(nil)), V((*byte)(nil))},
4517 // cannot convert mismatched array sizes
4518 {V([2]byte{}), V([2]byte{})},
4519 {V([3]byte{}), V([3]byte{})},
4521 // cannot convert other instances
4522 {V((**byte)(nil)), V((**byte)(nil))},
4523 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4524 {V((chan byte)(nil)), V((chan byte)(nil))},
4525 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4526 {V(([]byte)(nil)), V(([]byte)(nil))},
4527 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4528 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4529 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4530 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4531 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4532 {V([2]byte{}), V([2]byte{})},
4533 {V([2]MyByte{}), V([2]MyByte{})},
4536 {V((***int)(nil)), V((***int)(nil))},
4537 {V((***byte)(nil)), V((***byte)(nil))},
4538 {V((***int32)(nil)), V((***int32)(nil))},
4539 {V((***int64)(nil)), V((***int64)(nil))},
4540 {V((chan byte)(nil)), V((chan byte)(nil))},
4541 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4542 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4543 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4544 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4545 {V([]uint(nil)), V([]uint(nil))},
4546 {V([]int(nil)), V([]int(nil))},
4547 {V(new(any)), V(new(any))},
4548 {V(new(io.Reader)), V(new(io.Reader))},
4549 {V(new(io.Writer)), V(new(io.Writer))},
4552 {V(IntChan(nil)), V((chan<- int)(nil))},
4553 {V(IntChan(nil)), V((<-chan int)(nil))},
4554 {V((chan int)(nil)), V(IntChanRecv(nil))},
4555 {V((chan int)(nil)), V(IntChanSend(nil))},
4556 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4557 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4558 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4559 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4560 {V(IntChan(nil)), V((chan int)(nil))},
4561 {V((chan int)(nil)), V(IntChan(nil))},
4562 {V((chan int)(nil)), V((<-chan int)(nil))},
4563 {V((chan int)(nil)), V((chan<- int)(nil))},
4564 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4565 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4566 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4567 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4568 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4569 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4570 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4571 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4572 {V(BytesChan(nil)), V((chan []byte)(nil))},
4573 {V((chan []byte)(nil)), V(BytesChan(nil))},
4574 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4575 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4577 // cannot convert other instances (channels)
4578 {V(IntChan(nil)), V(IntChan(nil))},
4579 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4580 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4581 {V(BytesChan(nil)), V(BytesChan(nil))},
4582 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4583 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4586 {V(int(1)), EmptyInterfaceV(int(1))},
4587 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4588 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4589 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4590 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4593 func TestConvert(t *testing.T) {
4594 canConvert := map[[2]Type]bool{}
4595 all := map[Type]bool{}
4597 for _, tt := range convertTests {
4599 if !t1.ConvertibleTo(t1) {
4600 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4605 if !t1.ConvertibleTo(t2) {
4606 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4612 canConvert[[2]Type{t1, t2}] = true
4614 // vout1 represents the in value converted to the in type.
4616 if !v1.CanConvert(t1) {
4617 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4619 vout1 := v1.Convert(t1)
4620 out1 := vout1.Interface()
4621 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4622 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4625 // vout2 represents the in value converted to the out type.
4626 if !v1.CanConvert(t2) {
4627 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4629 vout2 := v1.Convert(t2)
4630 out2 := vout2.Interface()
4631 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4632 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4634 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4635 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4638 // vout3 represents a new value of the out type, set to vout2. This makes
4639 // sure the converted value vout2 is really usable as a regular value.
4640 vout3 := New(t2).Elem()
4642 out3 := vout3.Interface()
4643 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4644 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4648 t.Errorf("table entry %v is RO, should not be", v1)
4651 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4654 t.Errorf("conversion output %v is RO, should not be", vout2)
4657 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4659 if !IsRO(MakeRO(v1).Convert(t1)) {
4660 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4662 if !IsRO(MakeRO(v1).Convert(t2)) {
4663 t.Errorf("RO conversion output %v is not RO, should be", v1)
4667 // Assume that of all the types we saw during the tests,
4668 // if there wasn't an explicit entry for a conversion between
4669 // a pair of types, then it's not to be allowed. This checks for
4670 // things like 'int64' converting to '*int'.
4671 for t1 := range all {
4672 for t2 := range all {
4673 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4674 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4675 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4681 func TestConvertPanic(t *testing.T) {
4682 s := make([]byte, 4)
4686 if !v.Type().ConvertibleTo(pt) {
4687 t.Errorf("[]byte should be convertible to *[8]byte")
4689 if v.CanConvert(pt) {
4690 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4692 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4697 var gFloat32 float32
4699 const snan uint32 = 0x7f800001
4701 func TestConvertNaNs(t *testing.T) {
4702 // Test to see if a store followed by a load of a signaling NaN
4703 // maintains the signaling bit. (This used to fail on the 387 port.)
4704 gFloat32 = math.Float32frombits(snan)
4705 runtime.Gosched() // make sure we don't optimize the store/load away
4706 if got := math.Float32bits(gFloat32); got != snan {
4707 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4709 // Test reflect's conversion between float32s. See issue 36400.
4710 type myFloat32 float32
4711 x := V(myFloat32(math.Float32frombits(snan)))
4712 y := x.Convert(TypeOf(float32(0)))
4713 z := y.Interface().(float32)
4714 if got := math.Float32bits(z); got != snan {
4715 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4719 type ComparableStruct struct {
4723 type NonComparableStruct struct {
4728 var comparableTests = []struct {
4733 {TypeOf("hello"), true},
4734 {TypeOf(new(byte)), true},
4735 {TypeOf((func())(nil)), false},
4736 {TypeOf([]byte{}), false},
4737 {TypeOf(map[string]int{}), false},
4738 {TypeOf(make(chan int)), true},
4739 {TypeOf(1.5), true},
4740 {TypeOf(false), true},
4742 {TypeOf(ComparableStruct{}), true},
4743 {TypeOf(NonComparableStruct{}), false},
4744 {TypeOf([10]map[string]int{}), false},
4745 {TypeOf([10]string{}), true},
4746 {TypeOf(new(any)).Elem(), true},
4749 func TestComparable(t *testing.T) {
4750 for _, tt := range comparableTests {
4751 if ok := tt.typ.Comparable(); ok != tt.ok {
4752 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4757 func TestOverflow(t *testing.T) {
4758 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4759 t.Errorf("%v wrongly overflows float64", 1e300)
4762 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4763 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4764 t.Errorf("%v wrongly overflows float32", maxFloat32)
4766 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4767 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4768 t.Errorf("%v should overflow float32", ovfFloat32)
4770 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4771 t.Errorf("%v should overflow float32", -ovfFloat32)
4774 maxInt32 := int64(0x7fffffff)
4775 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4776 t.Errorf("%v wrongly overflows int32", maxInt32)
4778 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4779 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4781 ovfInt32 := int64(1 << 31)
4782 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4783 t.Errorf("%v should overflow int32", ovfInt32)
4786 maxUint32 := uint64(0xffffffff)
4787 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4788 t.Errorf("%v wrongly overflows uint32", maxUint32)
4790 ovfUint32 := uint64(1 << 32)
4791 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4792 t.Errorf("%v should overflow uint32", ovfUint32)
4796 func checkSameType(t *testing.T, x Type, y any) {
4797 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4798 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4802 func TestArrayOf(t *testing.T) {
4803 // check construction and use of type not in binary
4806 value func(i int) any
4812 value: func(i int) any { type Tint int; return Tint(i) },
4818 value: func(i int) any { type Tint int; return Tint(i) },
4820 want: "[0 1 2 3 4 5 6 7 8 9]",
4824 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4826 want: "[0 1 2 3 4 5 6 7 8 9]",
4830 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4832 want: "[0 1 2 3 4 5 6 7 8 9]",
4836 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4838 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4842 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4844 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4848 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4850 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4854 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4856 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4860 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4862 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4866 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4868 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4872 value: func(i int) any {
4873 type TstructUV struct {
4877 return TstructUV{i, float64(i)}
4880 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4884 for _, table := range tests {
4885 at := ArrayOf(table.n, TypeOf(table.value(0)))
4887 vok := New(at).Elem()
4888 vnot := New(at).Elem()
4889 for i := 0; i < v.Len(); i++ {
4890 v.Index(i).Set(ValueOf(table.value(i)))
4891 vok.Index(i).Set(ValueOf(table.value(i)))
4896 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4898 s := fmt.Sprint(v.Interface())
4899 if s != table.want {
4900 t.Errorf("constructed array = %s, want %s", s, table.want)
4903 if table.comparable != at.Comparable() {
4904 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4906 if table.comparable {
4908 if DeepEqual(vnot.Interface(), v.Interface()) {
4910 "arrays (%#v) compare ok (but should not)",
4915 if !DeepEqual(vok.Interface(), v.Interface()) {
4917 "arrays (%#v) compare NOT-ok (but should)",
4924 // check that type already in binary is found
4926 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4929 func TestArrayOfGC(t *testing.T) {
4931 tt := TypeOf(T(nil))
4934 for i := 0; i < n; i++ {
4935 v := New(ArrayOf(n, tt)).Elem()
4936 for j := 0; j < v.Len(); j++ {
4938 *p = uintptr(i*n + j)
4939 v.Index(j).Set(ValueOf(p).Convert(tt))
4941 x = append(x, v.Interface())
4945 for i, xi := range x {
4947 for j := 0; j < v.Len(); j++ {
4948 k := v.Index(j).Elem().Interface()
4949 if k != uintptr(i*n+j) {
4950 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4956 func TestArrayOfAlg(t *testing.T) {
4957 at := ArrayOf(6, TypeOf(byte(0)))
4958 v1 := New(at).Elem()
4959 v2 := New(at).Elem()
4960 if v1.Interface() != v1.Interface() {
4961 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4963 v1.Index(5).Set(ValueOf(byte(1)))
4964 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4965 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4968 at = ArrayOf(6, TypeOf([]int(nil)))
4970 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4973 func TestArrayOfGenericAlg(t *testing.T) {
4974 at1 := ArrayOf(5, TypeOf(string("")))
4975 at := ArrayOf(6, at1)
4976 v1 := New(at).Elem()
4977 v2 := New(at).Elem()
4978 if v1.Interface() != v1.Interface() {
4979 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4982 v1.Index(0).Index(0).Set(ValueOf("abc"))
4983 v2.Index(0).Index(0).Set(ValueOf("efg"))
4984 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4985 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4988 v1.Index(0).Index(0).Set(ValueOf("abc"))
4989 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4990 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4991 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4995 m := MakeMap(MapOf(at, TypeOf(int(0))))
4996 m.SetMapIndex(v1, ValueOf(1))
4997 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4998 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
5002 func TestArrayOfDirectIface(t *testing.T) {
5005 i1 := Zero(TypeOf(T{})).Interface()
5006 v1 := ValueOf(&i1).Elem()
5007 p1 := v1.InterfaceData()[1]
5009 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
5010 v2 := ValueOf(&i2).Elem()
5011 p2 := v2.InterfaceData()[1]
5014 t.Errorf("got p1=%v. want=%v", p1, nil)
5018 t.Errorf("got p2=%v. want=%v", p2, nil)
5023 i1 := Zero(TypeOf(T{})).Interface()
5024 v1 := ValueOf(&i1).Elem()
5025 p1 := v1.InterfaceData()[1]
5027 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
5028 v2 := ValueOf(&i2).Elem()
5029 p2 := v2.InterfaceData()[1]
5032 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5036 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5041 // Ensure passing in negative lengths panics.
5042 // See https://golang.org/issue/43603
5043 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
5044 shouldPanic("reflect: negative length passed to ArrayOf", func() {
5045 ArrayOf(-1, TypeOf(byte(0)))
5049 func TestSliceOf(t *testing.T) {
5050 // check construction and use of type not in binary
5052 st := SliceOf(TypeOf(T(1)))
5053 if got, want := st.String(), "[]reflect_test.T"; got != want {
5054 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
5056 v := MakeSlice(st, 10, 10)
5058 for i := 0; i < v.Len(); i++ {
5059 v.Index(i).Set(ValueOf(T(i)))
5062 s := fmt.Sprint(v.Interface())
5063 want := "[0 1 2 3 4 5 6 7 8 9]"
5065 t.Errorf("constructed slice = %s, want %s", s, want)
5068 // check that type already in binary is found
5070 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
5073 func TestSliceOverflow(t *testing.T) {
5074 // check that MakeSlice panics when size of slice overflows uint
5077 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5079 t.Fatal("slice size does not overflow")
5082 st := SliceOf(TypeOf(x))
5086 t.Fatal("slice overflow does not panic")
5089 MakeSlice(st, int(l), int(l))
5092 func TestSliceOfGC(t *testing.T) {
5094 tt := TypeOf(T(nil))
5098 for i := 0; i < n; i++ {
5099 v := MakeSlice(st, n, n)
5100 for j := 0; j < v.Len(); j++ {
5102 *p = uintptr(i*n + j)
5103 v.Index(j).Set(ValueOf(p).Convert(tt))
5105 x = append(x, v.Interface())
5109 for i, xi := range x {
5111 for j := 0; j < v.Len(); j++ {
5112 k := v.Index(j).Elem().Interface()
5113 if k != uintptr(i*n+j) {
5114 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5120 func TestStructOfFieldName(t *testing.T) {
5121 // invalid field name "1nvalid"
5122 shouldPanic("has invalid name", func() {
5123 StructOf([]StructField{
5124 {Name: "Valid", Type: TypeOf("")},
5125 {Name: "1nvalid", Type: TypeOf("")},
5129 // invalid field name "+"
5130 shouldPanic("has invalid name", func() {
5131 StructOf([]StructField{
5132 {Name: "Val1d", Type: TypeOf("")},
5133 {Name: "+", Type: TypeOf("")},
5138 shouldPanic("has no name", func() {
5139 StructOf([]StructField{
5140 {Name: "", Type: TypeOf("")},
5144 // verify creation of a struct with valid struct fields
5145 validFields := []StructField{
5160 validStruct := StructOf(validFields)
5162 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5163 if got, want := validStruct.String(), structStr; got != want {
5164 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5168 func TestStructOf(t *testing.T) {
5169 // check construction and use of type not in binary
5170 fields := []StructField{
5179 Type: TypeOf(byte(0)),
5183 Type: TypeOf(uint64(0)),
5187 Type: TypeOf([3]uint16{}),
5191 st := StructOf(fields)
5194 v.FieldByName("X").Set(ValueOf(byte(2)))
5195 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5198 s := fmt.Sprint(v.Interface())
5199 want := `{ 1 0 [0 0 0]}`
5201 t.Errorf("constructed struct = %s, want %s", s, want)
5203 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5204 if got, want := st.String(), stStr; got != want {
5205 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5208 // check the size, alignment and field offsets
5209 stt := TypeOf(struct {
5215 if st.Size() != stt.Size() {
5216 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5218 if st.Align() != stt.Align() {
5219 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5221 if st.FieldAlign() != stt.FieldAlign() {
5222 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5224 for i := 0; i < st.NumField(); i++ {
5225 o1 := st.Field(i).Offset
5226 o2 := stt.Field(i).Offset
5228 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5232 // Check size and alignment with a trailing zero-sized field.
5233 st = StructOf([]StructField{
5236 Type: TypeOf(byte(0)),
5240 Type: TypeOf([0]*byte{}),
5243 stt = TypeOf(struct {
5247 if st.Size() != stt.Size() {
5248 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5250 if st.Align() != stt.Align() {
5251 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5253 if st.FieldAlign() != stt.FieldAlign() {
5254 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5256 for i := 0; i < st.NumField(); i++ {
5257 o1 := st.Field(i).Offset
5258 o2 := stt.Field(i).Offset
5260 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5264 // check duplicate names
5265 shouldPanic("duplicate field", func() {
5266 StructOf([]StructField{
5267 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5268 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5271 shouldPanic("has no name", func() {
5272 StructOf([]StructField{
5274 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5277 shouldPanic("has no name", func() {
5278 StructOf([]StructField{
5283 // check that type already in binary is found
5284 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5286 // gccgo used to fail this test.
5287 type structFieldType any
5289 StructOf([]StructField{
5292 Type: TypeOf((*structFieldType)(nil)).Elem(),
5295 struct{ F structFieldType }{})
5298 func TestStructOfExportRules(t *testing.T) {
5304 testPanic := func(i int, mustPanic bool, f func()) {
5307 if err == nil && mustPanic {
5308 t.Errorf("test-%d did not panic", i)
5310 if err != nil && !mustPanic {
5311 t.Errorf("test-%d panicked: %v\n", i, err)
5323 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5327 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5331 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5335 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5339 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5343 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5347 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5351 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5355 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5359 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5363 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5366 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5369 field: StructField{Name: "S", Type: TypeOf(S1{})},
5373 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5377 field: StructField{Name: "S", Type: TypeOf(s2{})},
5381 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5385 field: StructField{Name: "s", Type: TypeOf(S1{})},
5389 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5393 field: StructField{Name: "s", Type: TypeOf(s2{})},
5397 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5401 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5404 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5407 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5410 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5413 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5417 field: StructField{Name: "", Type: TypeOf(φType{})},
5421 field: StructField{Name: "Φ", Type: TypeOf(0)},
5425 field: StructField{Name: "φ", Type: TypeOf(0)},
5430 for i, test := range tests {
5431 testPanic(i, test.mustPanic, func() {
5432 typ := StructOf([]StructField{test.field})
5434 t.Errorf("test-%d: error creating struct type", i)
5437 field := typ.Field(0)
5440 panic("field.Name must not be empty")
5442 exported := token.IsExported(n)
5443 if exported != test.exported {
5444 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5446 if field.PkgPath != test.field.PkgPath {
5447 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5453 func TestStructOfGC(t *testing.T) {
5455 tt := TypeOf(T(nil))
5456 fields := []StructField{
5457 {Name: "X", Type: tt},
5458 {Name: "Y", Type: tt},
5460 st := StructOf(fields)
5464 for i := 0; i < n; i++ {
5466 for j := 0; j < v.NumField(); j++ {
5468 *p = uintptr(i*n + j)
5469 v.Field(j).Set(ValueOf(p).Convert(tt))
5471 x = append(x, v.Interface())
5475 for i, xi := range x {
5477 for j := 0; j < v.NumField(); j++ {
5478 k := v.Field(j).Elem().Interface()
5479 if k != uintptr(i*n+j) {
5480 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5486 func TestStructOfAlg(t *testing.T) {
5487 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5488 v1 := New(st).Elem()
5489 v2 := New(st).Elem()
5490 if !DeepEqual(v1.Interface(), v1.Interface()) {
5491 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5493 v1.FieldByName("X").Set(ValueOf(int(1)))
5494 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5495 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5498 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5500 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5503 func TestStructOfGenericAlg(t *testing.T) {
5504 st1 := StructOf([]StructField{
5505 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5506 {Name: "Y", Type: TypeOf(string(""))},
5508 st := StructOf([]StructField{
5509 {Name: "S0", Type: st1},
5510 {Name: "S1", Type: st1},
5528 {Name: "XX", Type: TypeOf([0]int{})},
5529 {Name: "YY", Type: TypeOf("")},
5537 {Name: "XX", Type: TypeOf([0]int{})},
5538 {Name: "YY", Type: TypeOf("")},
5539 {Name: "ZZ", Type: TypeOf([2]int{})},
5547 {Name: "XX", Type: TypeOf([1]int{})},
5548 {Name: "YY", Type: TypeOf("")},
5556 {Name: "XX", Type: TypeOf([1]int{})},
5557 {Name: "YY", Type: TypeOf("")},
5558 {Name: "ZZ", Type: TypeOf([1]int{})},
5566 {Name: "XX", Type: TypeOf([2]int{})},
5567 {Name: "YY", Type: TypeOf("")},
5568 {Name: "ZZ", Type: TypeOf([2]int{})},
5576 {Name: "XX", Type: TypeOf(int64(0))},
5577 {Name: "YY", Type: TypeOf(byte(0))},
5578 {Name: "ZZ", Type: TypeOf("")},
5586 {Name: "XX", Type: TypeOf(int64(0))},
5587 {Name: "YY", Type: TypeOf(int64(0))},
5588 {Name: "ZZ", Type: TypeOf("")},
5589 {Name: "AA", Type: TypeOf([1]int64{})},
5596 for _, table := range tests {
5597 v1 := New(table.rt).Elem()
5598 v2 := New(table.rt).Elem()
5600 if !DeepEqual(v1.Interface(), v1.Interface()) {
5601 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5604 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5605 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5606 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5607 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5611 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5612 val := "+" + abc + "-"
5613 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5614 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5615 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5619 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5620 m.SetMapIndex(v1, ValueOf(1))
5621 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5622 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5625 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5626 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5627 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5630 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5631 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5636 func TestStructOfDirectIface(t *testing.T) {
5638 type T struct{ X [1]*byte }
5639 i1 := Zero(TypeOf(T{})).Interface()
5640 v1 := ValueOf(&i1).Elem()
5641 p1 := v1.InterfaceData()[1]
5643 i2 := Zero(StructOf([]StructField{
5646 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5649 v2 := ValueOf(&i2).Elem()
5650 p2 := v2.InterfaceData()[1]
5653 t.Errorf("got p1=%v. want=%v", p1, nil)
5657 t.Errorf("got p2=%v. want=%v", p2, nil)
5661 type T struct{ X [0]*byte }
5662 i1 := Zero(TypeOf(T{})).Interface()
5663 v1 := ValueOf(&i1).Elem()
5664 p1 := v1.InterfaceData()[1]
5666 i2 := Zero(StructOf([]StructField{
5669 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5672 v2 := ValueOf(&i2).Elem()
5673 p2 := v2.InterfaceData()[1]
5676 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5680 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5687 func (i StructI) Get() int { return int(i) }
5691 func (i *StructIPtr) Get() int { return int(*i) }
5692 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5694 type SettableStruct struct {
5698 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5700 type SettablePointer struct {
5704 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5706 func TestStructOfWithInterface(t *testing.T) {
5708 type Iface interface {
5711 type IfaceSet interface {
5722 typ: TypeOf(StructI(want)),
5723 val: ValueOf(StructI(want)),
5728 typ: PointerTo(TypeOf(StructI(want))),
5729 val: ValueOf(func() any {
5737 typ: PointerTo(TypeOf(StructIPtr(want))),
5738 val: ValueOf(func() any {
5739 v := StructIPtr(want)
5746 typ: TypeOf(StructIPtr(want)),
5747 val: ValueOf(StructIPtr(want)),
5751 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5752 // val: ValueOf(StructI(want)),
5757 for i, table := range tests {
5758 for j := 0; j < 2; j++ {
5759 var fields []StructField
5761 fields = append(fields, StructField{
5764 Type: TypeOf(int(0)),
5767 fields = append(fields, StructField{
5774 // We currently do not correctly implement methods
5775 // for embedded fields other than the first.
5776 // Therefore, for now, we expect those methods
5777 // to not exist. See issues 15924 and 20824.
5778 // When those issues are fixed, this test of panic
5779 // should be removed.
5780 if j == 1 && table.impl {
5783 if err := recover(); err == nil {
5784 t.Errorf("test-%d-%d did not panic", i, j)
5787 _ = StructOf(fields)
5792 rt := StructOf(fields)
5793 rv := New(rt).Elem()
5794 rv.Field(j).Set(table.val)
5796 if _, ok := rv.Interface().(Iface); ok != table.impl {
5798 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5800 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5809 v := rv.Interface().(Iface).Get()
5811 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5814 fct := rv.MethodByName("Get")
5815 out := fct.Call(nil)
5816 if !DeepEqual(out[0].Interface(), want) {
5817 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5822 // Test an embedded nil pointer with pointer methods.
5823 fields := []StructField{{
5826 Type: PointerTo(TypeOf(StructIPtr(want))),
5828 rt := StructOf(fields)
5829 rv := New(rt).Elem()
5830 // This should panic since the pointer is nil.
5831 shouldPanic("", func() {
5832 rv.Interface().(IfaceSet).Set(want)
5835 // Test an embedded nil pointer to a struct with pointer methods.
5837 fields = []StructField{{
5838 Name: "SettableStruct",
5840 Type: PointerTo(TypeOf(SettableStruct{})),
5842 rt = StructOf(fields)
5844 // This should panic since the pointer is nil.
5845 shouldPanic("", func() {
5846 rv.Interface().(IfaceSet).Set(want)
5849 // The behavior is different if there is a second field,
5850 // since now an interface value holds a pointer to the struct
5851 // rather than just holding a copy of the struct.
5852 fields = []StructField{
5854 Name: "SettableStruct",
5856 Type: PointerTo(TypeOf(SettableStruct{})),
5859 Name: "EmptyStruct",
5861 Type: StructOf(nil),
5864 // With the current implementation this is expected to panic.
5865 // Ideally it should work and we should be able to see a panic
5866 // if we call the Set method.
5867 shouldPanic("", func() {
5871 // Embed a field that can be stored directly in an interface,
5872 // with a second field.
5873 fields = []StructField{
5875 Name: "SettablePointer",
5877 Type: TypeOf(SettablePointer{}),
5880 Name: "EmptyStruct",
5882 Type: StructOf(nil),
5885 // With the current implementation this is expected to panic.
5886 // Ideally it should work and we should be able to call the
5887 // Set and Get methods.
5888 shouldPanic("", func() {
5893 func TestStructOfTooManyFields(t *testing.T) {
5894 // Bug Fix: #25402 - this should not panic
5895 tt := StructOf([]StructField{
5896 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5899 if _, present := tt.MethodByName("After"); !present {
5900 t.Errorf("Expected method `After` to be found")
5904 func TestStructOfDifferentPkgPath(t *testing.T) {
5905 fields := []StructField{
5909 Type: TypeOf(int(0)),
5914 Type: TypeOf(int(0)),
5917 shouldPanic("different PkgPath", func() {
5922 func TestStructOfTooLarge(t *testing.T) {
5923 t1 := TypeOf(byte(0))
5924 t2 := TypeOf(int16(0))
5925 t4 := TypeOf(int32(0))
5926 t0 := ArrayOf(0, t1)
5928 // 2^64-3 sized type (or 2^32-3 on 32-bit archs)
5929 bigType := StructOf([]StructField{
5930 {Name: "F1", Type: ArrayOf(int(^uintptr(0)>>1), t1)},
5931 {Name: "F2", Type: ArrayOf(int(^uintptr(0)>>1-1), t1)},
5936 fields []StructField
5941 shouldPanic: false, // 2^64-1, ok
5942 fields: []StructField{
5943 {Name: "F1", Type: bigType},
5944 {Name: "F2", Type: ArrayOf(2, t1)},
5948 shouldPanic: true, // overflow in total size
5949 fields: []StructField{
5950 {Name: "F1", Type: bigType},
5951 {Name: "F2", Type: ArrayOf(3, t1)},
5955 shouldPanic: true, // overflow while aligning F2
5956 fields: []StructField{
5957 {Name: "F1", Type: bigType},
5958 {Name: "F2", Type: t4},
5962 shouldPanic: true, // overflow while adding trailing byte for zero-sized fields
5963 fields: []StructField{
5964 {Name: "F1", Type: bigType},
5965 {Name: "F2", Type: ArrayOf(2, t1)},
5966 {Name: "F3", Type: t0},
5970 shouldPanic: true, // overflow while aligning total size
5971 fields: []StructField{
5972 {Name: "F1", Type: t2},
5973 {Name: "F2", Type: bigType},
5978 for i, tt := range tests {
5982 if !tt.shouldPanic {
5984 t.Errorf("test %d should not panic, got %s", i, err)
5989 t.Errorf("test %d expected to panic", i)
5992 s := fmt.Sprintf("%s", err)
5993 if s != "reflect.StructOf: struct size would exceed virtual address space" {
5994 t.Errorf("test %d wrong panic message: %s", i, s)
5998 _ = StructOf(tt.fields)
6003 func TestChanOf(t *testing.T) {
6004 // check construction and use of type not in binary
6006 ct := ChanOf(BothDir, TypeOf(T("")))
6007 v := MakeChan(ct, 2)
6009 v.Send(ValueOf(T("hello")))
6011 v.Send(ValueOf(T("world")))
6018 if s1 != "hello" || s2 != "world" {
6019 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
6022 // check that type already in binary is found
6024 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
6026 // Check arrow token association in undefined chan types.
6027 var left chan<- chan T
6028 var right chan (<-chan T)
6029 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
6030 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
6031 if tLeft != TypeOf(left) {
6032 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
6034 if tRight != TypeOf(right) {
6035 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
6039 func TestChanOfDir(t *testing.T) {
6040 // check construction and use of type not in binary
6042 crt := ChanOf(RecvDir, TypeOf(T("")))
6043 cst := ChanOf(SendDir, TypeOf(T("")))
6045 // check that type already in binary is found
6047 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
6048 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
6050 // check String form of ChanDir
6051 if crt.ChanDir().String() != "<-chan" {
6052 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
6054 if cst.ChanDir().String() != "chan<-" {
6055 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
6059 func TestChanOfGC(t *testing.T) {
6060 done := make(chan bool, 1)
6064 case <-time.After(5 * time.Second):
6065 panic("deadlock in TestChanOfGC")
6074 tt := TypeOf(T(nil))
6075 ct := ChanOf(BothDir, tt)
6077 // NOTE: The garbage collector handles allocated channels specially,
6078 // so we have to save pointers to channels in x; the pointer code will
6079 // use the gc info in the newly constructed chan type.
6082 for i := 0; i < n; i++ {
6083 v := MakeChan(ct, n)
6084 for j := 0; j < n; j++ {
6086 *p = uintptr(i*n + j)
6087 v.Send(ValueOf(p).Convert(tt))
6091 x = append(x, pv.Interface())
6095 for i, xi := range x {
6096 v := ValueOf(xi).Elem()
6097 for j := 0; j < n; j++ {
6099 k := pv.Elem().Interface()
6100 if k != uintptr(i*n+j) {
6101 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6107 func TestMapOf(t *testing.T) {
6108 // check construction and use of type not in binary
6112 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
6114 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
6117 s := fmt.Sprint(v.Interface())
6120 t.Errorf("constructed map = %s, want %s", s, want)
6123 // check that type already in binary is found
6124 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
6126 // check that invalid key type panics
6127 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
6130 func TestMapOfGCKeys(t *testing.T) {
6132 tt := TypeOf(T(nil))
6133 mt := MapOf(tt, TypeOf(false))
6135 // NOTE: The garbage collector handles allocated maps specially,
6136 // so we have to save pointers to maps in x; the pointer code will
6137 // use the gc info in the newly constructed map type.
6140 for i := 0; i < n; i++ {
6142 for j := 0; j < n; j++ {
6144 *p = uintptr(i*n + j)
6145 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
6149 x = append(x, pv.Interface())
6153 for i, xi := range x {
6154 v := ValueOf(xi).Elem()
6156 for _, kv := range v.MapKeys() {
6157 out = append(out, int(kv.Elem().Interface().(uintptr)))
6160 for j, k := range out {
6162 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6168 func TestMapOfGCValues(t *testing.T) {
6170 tt := TypeOf(T(nil))
6171 mt := MapOf(TypeOf(1), tt)
6173 // NOTE: The garbage collector handles allocated maps specially,
6174 // so we have to save pointers to maps in x; the pointer code will
6175 // use the gc info in the newly constructed map type.
6178 for i := 0; i < n; i++ {
6180 for j := 0; j < n; j++ {
6182 *p = uintptr(i*n + j)
6183 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6187 x = append(x, pv.Interface())
6191 for i, xi := range x {
6192 v := ValueOf(xi).Elem()
6193 for j := 0; j < n; j++ {
6194 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6195 if k != uintptr(i*n+j) {
6196 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6202 func TestTypelinksSorted(t *testing.T) {
6204 for i, n := range TypeLinks() {
6206 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6212 func TestFuncOf(t *testing.T) {
6213 // check construction and use of type not in binary
6217 fn := func(args []Value) []Value {
6219 t.Errorf("args == %v, want exactly one arg", args)
6220 } else if args[0].Type() != TypeOf(K("")) {
6221 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6222 } else if args[0].String() != "gopher" {
6223 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6225 return []Value{ValueOf(V(3.14))}
6227 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6229 outs := v.Call([]Value{ValueOf(K("gopher"))})
6231 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6232 } else if outs[0].Type() != TypeOf(V(0)) {
6233 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6235 f := outs[0].Float()
6237 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6240 // check that types already in binary are found
6242 testCases := []struct {
6247 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6248 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6249 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6250 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6251 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6253 for _, tt := range testCases {
6254 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6257 // check that variadic requires last element be a slice.
6258 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6259 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6260 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6269 func BenchmarkFieldByName1(b *testing.B) {
6271 b.RunParallel(func(pb *testing.PB) {
6278 func BenchmarkFieldByName2(b *testing.B) {
6280 b.RunParallel(func(pb *testing.PB) {
6357 func TestEmbed(t *testing.T) {
6359 f, ok := typ.FieldByName("X")
6361 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6365 func BenchmarkFieldByName3(b *testing.B) {
6367 b.RunParallel(func(pb *testing.PB) {
6379 func BenchmarkInterfaceBig(b *testing.B) {
6381 b.RunParallel(func(pb *testing.PB) {
6389 func TestAllocsInterfaceBig(t *testing.T) {
6390 if testing.Short() {
6391 t.Skip("skipping malloc count in short mode")
6394 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6395 t.Error("allocs:", allocs)
6399 func BenchmarkInterfaceSmall(b *testing.B) {
6400 v := ValueOf(int64(0))
6401 b.RunParallel(func(pb *testing.PB) {
6408 func TestAllocsInterfaceSmall(t *testing.T) {
6409 if testing.Short() {
6410 t.Skip("skipping malloc count in short mode")
6412 v := ValueOf(int64(0))
6413 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6414 t.Error("allocs:", allocs)
6418 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6419 // The basic usage is:
6422 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6425 // Each iteration of the loop returns a different set of results, until all
6426 // possible result sets have been explored. It is okay for different code paths
6427 // to make different method call sequences on x, but there must be no
6428 // other source of non-determinism in the call sequences.
6430 // When faced with a new decision, x chooses randomly. Future explorations
6431 // of that path will choose successive values for the result. Thus, stopping
6432 // the loop after a fixed number of iterations gives somewhat stochastic
6438 // v := make([]bool, x.Choose(4))
6439 // for i := range v {
6445 // prints (in some order):
6454 // [false false false]
6457 // [false false false false]
6459 // [true true true true]
6460 type exhaustive struct {
6466 type choice struct {
6472 func (x *exhaustive) Next() bool {
6474 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6481 for i := len(x.last) - 1; i >= 0; i-- {
6485 x.last = x.last[:i+1]
6492 func (x *exhaustive) Choose(max int) int {
6493 if x.pos >= len(x.last) {
6494 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6499 panic("inconsistent use of exhaustive tester")
6501 return (c.n + c.off) % max
6504 func (x *exhaustive) Maybe() bool {
6505 return x.Choose(2) == 1
6508 func GCFunc(args []Value) []Value {
6513 func TestReflectFuncTraceback(t *testing.T) {
6514 f := MakeFunc(TypeOf(func() {}), GCFunc)
6518 func TestReflectMethodTraceback(t *testing.T) {
6520 m := ValueOf(p).MethodByName("GCMethod")
6521 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6523 t.Errorf("Call returned %d; want 8", i)
6527 func TestSmallZero(t *testing.T) {
6530 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6531 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6535 func TestBigZero(t *testing.T) {
6536 const size = 1 << 10
6538 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6539 for i := 0; i < size; i++ {
6541 t.Fatalf("Zero object not all zero, index %d", i)
6546 func TestZeroSet(t *testing.T) {
6554 a: 0xaaaaaaaaaaaaaaaa,
6555 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6556 b: 0xbbbbbbbbbbbbbbbb,
6558 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6560 a: 0xaaaaaaaaaaaaaaaa,
6561 b: 0xbbbbbbbbbbbbbbbb,
6563 t.Fatalf("Setting a field to a Zero value didn't work")
6567 func TestFieldByIndexNil(t *testing.T) {
6576 v.FieldByName("P") // should be fine
6579 if err := recover(); err == nil {
6580 t.Fatalf("no error")
6581 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6582 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6585 v.FieldByName("F") // should panic
6587 t.Fatalf("did not panic")
6591 // type Outer struct {
6595 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6596 // The implementation is logically:
6597 // func (p *Outer) M() {
6600 // but since the only change here is the replacement of one pointer receiver with another,
6601 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6602 // then jumps to the M method expecting the *Inner receiver.
6604 // During reflect.Value.Call, we create an argument frame and the associated data structures
6605 // to describe it to the garbage collector, populate the frame, call reflect.call to
6606 // run a function call using that frame, and then copy the results back out of the frame.
6607 // The reflect.call function does a memmove of the frame structure onto the
6608 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6609 // the frame structure (to preserve the outputs).
6611 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6612 // were for the full stack frame. However, in the case where the called function was
6613 // one of these wrappers, the rewritten receiver is almost certainly a different type
6614 // than the original receiver. This is not a problem on the stack, where we use the
6615 // program counter to determine the type information and understand that
6616 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6617 // memory word is now an *Inner. But in the statically typed argument frame created
6618 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6619 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6620 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6621 // memory as if it were an *Outer. If the two have different memory layouts, the
6622 // collection will interpret the memory incorrectly.
6624 // One such possible incorrect interpretation is to treat two arbitrary memory words
6625 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6626 // an interface requires dereferencing the itab word, the misinterpretation will try to
6627 // deference Inner.P1, causing a crash during garbage collection.
6629 // This came up in a real program in issue 7725.
6642 func (pi *Inner) M() {
6643 // Clear references to pi so that the only way the
6644 // garbage collection will find the pointer is in the
6645 // argument frame, typed as a *Outer.
6648 // Set up an interface value that will cause a crash.
6649 // P1 = 1 is a non-zero, so the interface looks non-nil.
6650 // P2 = pi ensures that the data word points into the
6651 // allocated heap; if not the collection skips the interface
6652 // value as irrelevant, without dereferencing P1.
6654 pi.P2 = uintptr(unsafe.Pointer(pi))
6657 func TestCallMethodJump(t *testing.T) {
6658 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6659 // returns but before the args frame has been discarded.
6660 // This is a little clumsy but makes the failure repeatable.
6663 p := &Outer{Inner: new(Inner)}
6665 ValueOf(p).Method(0).Call(nil)
6667 // Stop garbage collecting during reflect.call.
6671 func TestCallArgLive(t *testing.T) {
6672 type T struct{ X, Y *string } // pointerful aggregate
6674 F := func(t T) { *t.X = "ok" }
6676 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6677 // between marshaling argument and the actual call.
6681 runtime.SetFinalizer(x, func(p *string) {
6683 t.Errorf("x dead prematurely")
6688 ValueOf(F).Call([]Value{ValueOf(v)})
6690 // Stop garbage collecting during reflect.call.
6694 func TestMakeFuncStackCopy(t *testing.T) {
6695 target := func(in []Value) []Value {
6698 return []Value{ValueOf(9)}
6701 var concrete func(*int, int) int
6702 fn := MakeFunc(ValueOf(concrete).Type(), target)
6703 ValueOf(&concrete).Elem().Set(fn)
6704 x := concrete(nil, 7)
6706 t.Errorf("have %#q want 9", x)
6710 // use about n KB of stack
6711 func useStack(n int) {
6715 var b [1024]byte // makes frame about 1KB
6716 useStack(n - 1 + int(b[99]))
6723 func TestValueString(t *testing.T) {
6724 rv := ValueOf(Impl{})
6725 if rv.String() != "<reflect_test.Impl Value>" {
6726 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6729 method := rv.Method(0)
6730 if method.String() != "<func() Value>" {
6731 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6735 func TestInvalid(t *testing.T) {
6736 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6737 type T struct{ v any }
6739 v := ValueOf(T{}).Field(0)
6740 if v.IsValid() != true || v.Kind() != Interface {
6741 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6744 if v.IsValid() != false || v.Kind() != Invalid {
6745 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6750 func TestLargeGCProg(t *testing.T) {
6751 fv := ValueOf(func([256]*byte) {})
6752 fv.Call([]Value{ValueOf([256]*byte{})})
6755 func fieldIndexRecover(t Type, i int) (recovered any) {
6757 recovered = recover()
6765 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6766 typ := TypeOf(struct{ X int }{10})
6767 testIndices := [...]struct {
6776 for i, tt := range testIndices {
6777 recoveredErr := fieldIndexRecover(typ, tt.i)
6779 if recoveredErr == nil {
6780 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6783 if recoveredErr != nil {
6784 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6791 func TestCallGC(t *testing.T) {
6792 f := func(a, b, c, d, e string) {
6794 g := func(in []Value) []Value {
6798 typ := ValueOf(f).Type()
6799 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6800 f2("four", "five5", "six666", "seven77", "eight888")
6803 // Issue 18635 (function version).
6804 func TestKeepFuncLive(t *testing.T) {
6805 // Test that we keep makeFuncImpl live as long as it is
6806 // referenced on the stack.
6807 typ := TypeOf(func(i int) {})
6808 var f, g func(in []Value) []Value
6809 f = func(in []Value) []Value {
6811 i := int(in[0].Int())
6813 // We can't use Value.Call here because
6814 // runtime.call* will keep the makeFuncImpl
6815 // alive. However, by converting it to an
6816 // interface value and calling that,
6817 // reflect.callReflect is the only thing that
6818 // can keep the makeFuncImpl live.
6820 // Alternate between f and g so that if we do
6821 // reuse the memory prematurely it's more
6822 // likely to get obviously corrupted.
6823 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6827 g = func(in []Value) []Value {
6829 i := int(in[0].Int())
6830 MakeFunc(typ, f).Interface().(func(i int))(i)
6833 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6836 type UnExportedFirst int
6838 func (i UnExportedFirst) ΦExported() {}
6839 func (i UnExportedFirst) unexported() {}
6842 func TestMethodByNameUnExportedFirst(t *testing.T) {
6844 if recover() != nil {
6845 t.Errorf("should not panic")
6848 typ := TypeOf(UnExportedFirst(0))
6849 m, _ := typ.MethodByName("ΦExported")
6850 if m.Name != "ΦExported" {
6851 t.Errorf("got %s, expected ΦExported", m.Name)
6855 // Issue 18635 (method version).
6856 type KeepMethodLive struct{}
6858 func (k KeepMethodLive) Method1(i int) {
6861 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6865 func (k KeepMethodLive) Method2(i int) {
6867 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6870 func TestKeepMethodLive(t *testing.T) {
6871 // Test that we keep methodValue live as long as it is
6872 // referenced on the stack.
6873 KeepMethodLive{}.Method1(10)
6876 // clobber tries to clobber unreachable memory.
6879 for i := 1; i < 32; i++ {
6880 for j := 0; j < 10; j++ {
6881 obj := make([]*byte, i)
6888 func TestFuncLayout(t *testing.T) {
6889 align := func(x uintptr) uintptr {
6890 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6893 if goarch.PtrSize == 4 {
6894 r = []byte{0, 0, 0, 1}
6906 size, argsize, retOffset uintptr
6907 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6908 intRegs, floatRegs int
6909 floatRegSize uintptr
6913 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6914 size: 6 * goarch.PtrSize,
6915 argsize: 4 * goarch.PtrSize,
6916 retOffset: 4 * goarch.PtrSize,
6917 stack: []byte{1, 0, 1, 0, 1},
6918 gc: []byte{1, 0, 1, 0, 1},
6921 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6922 size: align(align(3*4) + goarch.PtrSize + 2),
6923 argsize: align(3*4) + goarch.PtrSize + 2,
6924 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6929 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6930 size: 4 * goarch.PtrSize,
6931 argsize: 4 * goarch.PtrSize,
6932 retOffset: 4 * goarch.PtrSize,
6933 stack: []byte{1, 0, 1, 1},
6934 gc: []byte{1, 0, 1, 1},
6937 typ: ValueOf(func(a S) {}).Type(),
6938 size: 4 * goarch.PtrSize,
6939 argsize: 4 * goarch.PtrSize,
6940 retOffset: 4 * goarch.PtrSize,
6941 stack: []byte{0, 0, 1, 1},
6942 gc: []byte{0, 0, 1, 1},
6945 rcvr: ValueOf((*byte)(nil)).Type(),
6946 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6947 size: 3 * goarch.PtrSize,
6948 argsize: 3 * goarch.PtrSize,
6949 retOffset: 3 * goarch.PtrSize,
6950 stack: []byte{1, 0, 1},
6951 gc: []byte{1, 0, 1},
6954 typ: ValueOf(func(a uintptr) {}).Type(),
6955 size: goarch.PtrSize,
6956 argsize: goarch.PtrSize,
6957 retOffset: goarch.PtrSize,
6962 typ: ValueOf(func() uintptr { return 0 }).Type(),
6963 size: goarch.PtrSize,
6970 rcvr: ValueOf(uintptr(0)).Type(),
6971 typ: ValueOf(func(a uintptr) {}).Type(),
6972 size: 2 * goarch.PtrSize,
6973 argsize: 2 * goarch.PtrSize,
6974 retOffset: 2 * goarch.PtrSize,
6977 // Note: this one is tricky, as the receiver is not a pointer. But we
6978 // pass the receiver by reference to the autogenerated pointer-receiver
6979 // version of the function.
6981 // TODO(mknyszek): Add tests for non-zero register count.
6983 for _, lt := range tests {
6984 name := lt.typ.String()
6986 name = lt.rcvr.String() + "." + name
6988 t.Run(name, func(t *testing.T) {
6989 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6991 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6992 if typ.Size() != lt.size {
6993 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6995 if argsize != lt.argsize {
6996 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6998 if retOffset != lt.retOffset {
6999 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
7001 if !bytes.Equal(stack, lt.stack) {
7002 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
7004 if !bytes.Equal(gc, lt.gc) {
7005 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
7007 if !bytes.Equal(inRegs, lt.inRegs) {
7008 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
7010 if !bytes.Equal(outRegs, lt.outRegs) {
7011 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
7013 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
7014 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
7020 // trimBitmap removes trailing 0 elements from b and returns the result.
7021 func trimBitmap(b []byte) []byte {
7022 for len(b) > 0 && b[len(b)-1] == 0 {
7028 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
7029 heapBits := GCBits(New(typ).Interface())
7031 // Trim scalars at the end, as bits might end in zero,
7032 // e.g. with rep(2, lit(1, 0)).
7033 bits = trimBitmap(bits)
7035 if !bytes.Equal(heapBits, bits) {
7036 _, _, line, _ := runtime.Caller(1)
7037 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
7041 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
7042 // Creating a slice causes the runtime to repeat a bitmap,
7043 // which exercises a different path from making the compiler
7044 // repeat a bitmap for a small array or executing a repeat in
7046 val := MakeSlice(typ, 0, cap)
7047 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
7048 heapBits := GCBits(data.Interface())
7049 // Repeat the bitmap for the slice size, trimming scalars in
7050 // the last element.
7051 bits = trimBitmap(rep(cap, bits))
7052 if !bytes.Equal(heapBits, bits) {
7053 _, _, line, _ := runtime.Caller(1)
7054 t.Errorf("line %d: heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", line, typ, cap, heapBits, bits)
7058 func TestGCBits(t *testing.T) {
7059 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
7061 // Building blocks for types seen by the compiler (like [2]Xscalar).
7062 // The compiler will create the type structures for the derived types,
7063 // including their GC metadata.
7064 type Xscalar struct{ x uintptr }
7065 type Xptr struct{ x *byte }
7066 type Xptrscalar struct {
7070 type Xscalarptr struct {
7074 type Xbigptrscalar struct {
7079 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
7081 // Building blocks for types constructed by reflect.
7082 // This code is in a separate block so that code below
7083 // cannot accidentally refer to these.
7084 // The compiler must NOT see types derived from these
7085 // (for example, [2]Scalar must NOT appear in the program),
7086 // or else reflect will use it instead of having to construct one.
7087 // The goal is to test the construction.
7088 type Scalar struct{ x uintptr }
7089 type Ptr struct{ x *byte }
7090 type Ptrscalar struct {
7094 type Scalarptr struct {
7098 type Bigptrscalar struct {
7103 Tscalar = TypeOf(Scalar{})
7104 Tint64 = TypeOf(Int64(0))
7105 Tptr = TypeOf(Ptr{})
7106 Tscalarptr = TypeOf(Scalarptr{})
7107 Tptrscalar = TypeOf(Ptrscalar{})
7108 Tbigptrscalar = TypeOf(Bigptrscalar{})
7113 verifyGCBits(t, TypeOf(Xscalar{}), empty)
7114 verifyGCBits(t, Tscalar, empty)
7115 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
7116 verifyGCBits(t, Tptr, lit(1))
7117 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
7118 verifyGCBits(t, Tscalarptr, lit(0, 1))
7119 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
7120 verifyGCBits(t, Tptrscalar, lit(1))
7122 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
7123 verifyGCBits(t, ArrayOf(0, Tptr), empty)
7124 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
7125 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
7126 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
7127 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
7128 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
7129 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
7130 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
7131 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
7132 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
7133 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
7134 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
7135 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
7136 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
7137 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
7138 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
7139 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
7140 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7141 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
7142 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7143 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
7144 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
7145 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
7146 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7147 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7149 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
7150 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
7151 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
7152 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
7153 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
7154 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
7155 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
7156 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
7157 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
7158 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
7159 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
7160 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
7161 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
7162 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
7163 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
7164 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
7165 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
7166 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
7167 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
7168 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7169 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7170 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7171 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7172 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7173 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7174 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7176 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7177 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7179 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7180 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7182 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7183 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7185 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7186 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7188 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7189 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7191 hdr := make([]byte, 8/goarch.PtrSize)
7193 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7194 verifyGCBits(t, MapBucketOf(k, e), want)
7195 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7199 map[Xscalar]Xptr(nil),
7200 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7203 map[Xscalarptr]Xptr(nil),
7204 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7205 verifyMapBucket(t, Tint64, Tptr,
7206 map[int64]Xptr(nil),
7207 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7210 map[Xscalar]Xscalar(nil),
7213 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7214 map[[2]Xscalarptr][3]Xptrscalar(nil),
7215 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7217 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7218 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7219 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7221 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7222 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7223 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7225 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7226 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7227 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7229 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7230 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7231 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7234 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7235 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7236 func lit(x ...byte) []byte { return x }
7238 func TestTypeOfTypeOf(t *testing.T) {
7239 // Check that all the type constructors return concrete *rtype implementations.
7240 // It's difficult to test directly because the reflect package is only at arm's length.
7241 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7242 check := func(name string, typ Type) {
7243 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7244 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7248 type T struct{ int }
7249 check("TypeOf", TypeOf(T{}))
7251 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7252 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7253 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7254 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7255 check("PtrTo", PointerTo(TypeOf(T{})))
7256 check("SliceOf", SliceOf(TypeOf(T{})))
7259 type XM struct{ _ bool }
7261 func (*XM) String() string { return "" }
7263 func TestPtrToMethods(t *testing.T) {
7265 yp := New(TypeOf(y)).Interface()
7266 _, ok := yp.(fmt.Stringer)
7268 t.Fatal("does not implement Stringer, but should")
7272 func TestMapAlloc(t *testing.T) {
7273 m := ValueOf(make(map[int]int, 10))
7276 allocs := testing.AllocsPerRun(100, func() {
7280 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7285 val := ValueOf(&tmp).Elem()
7286 allocs = testing.AllocsPerRun(100, func() {
7287 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7288 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7289 for i := 0; i < size/2; i++ {
7290 val.SetInt(int64(i))
7291 mv.SetMapIndex(val, val)
7295 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7297 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7298 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7299 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7302 func TestChanAlloc(t *testing.T) {
7303 // Note: for a chan int, the return Value must be allocated, so we
7304 // use a chan *int instead.
7305 c := ValueOf(make(chan *int, 1))
7306 v := ValueOf(new(int))
7307 allocs := testing.AllocsPerRun(100, func() {
7311 if allocs < 0.5 || allocs > 1.5 {
7312 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7314 // Note: there is one allocation in reflect.recv which seems to be
7315 // a limitation of escape analysis. If that is ever fixed the
7316 // allocs < 0.5 condition will trigger and this test should be fixed.
7319 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7321 type nameTest struct {
7326 var nameTests = []nameTest{
7327 {(*int32)(nil), "int32"},
7330 {(*chan D1)(nil), ""},
7331 {(*func() D1)(nil), ""},
7332 {(*<-chan D1)(nil), ""},
7333 {(*chan<- D1)(nil), ""},
7338 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7341 func TestNames(t *testing.T) {
7342 for _, test := range nameTests {
7343 typ := TypeOf(test.v).Elem()
7344 if got := typ.Name(); got != test.want {
7345 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7350 func TestExported(t *testing.T) {
7351 type ΦExported struct{}
7352 type φUnexported struct{}
7359 type exportTest struct {
7363 exportTests := []exportTest{
7367 {(*big)(nil), false},
7368 {(BigP)(nil), true},
7369 {(*BigP)(nil), true},
7370 {ΦExported{}, true},
7371 {φUnexported{}, false},
7378 for i, test := range exportTests {
7379 typ := TypeOf(test.v)
7380 if got := IsExported(typ); got != test.want {
7381 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7386 func TestTypeStrings(t *testing.T) {
7387 type stringTest struct {
7391 stringTests := []stringTest{
7392 {TypeOf(func(int) {}), "func(int)"},
7393 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7394 {TypeOf(XM{}), "reflect_test.XM"},
7395 {TypeOf(new(XM)), "*reflect_test.XM"},
7396 {TypeOf(new(XM).String), "func() string"},
7397 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7398 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7399 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7400 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7401 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7404 for i, test := range stringTests {
7405 if got, want := test.typ.String(), test.want; got != want {
7406 t.Errorf("type %d String()=%q, want %q", i, got, want)
7411 func TestOffsetLock(t *testing.T) {
7412 var wg sync.WaitGroup
7413 for i := 0; i < 4; i++ {
7417 for j := 0; j < 50; j++ {
7418 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7426 func BenchmarkNew(b *testing.B) {
7428 b.RunParallel(func(pb *testing.PB) {
7435 func BenchmarkMap(b *testing.B) {
7438 value := ValueOf((V)(nil))
7439 stringKeys := []string{}
7440 mapOfStrings := map[string]V{}
7441 uint64Keys := []uint64{}
7442 mapOfUint64s := map[uint64]V{}
7443 userStringKeys := []S{}
7444 mapOfUserStrings := map[S]V{}
7445 for i := 0; i < 100; i++ {
7446 stringKey := fmt.Sprintf("key%d", i)
7447 stringKeys = append(stringKeys, stringKey)
7448 mapOfStrings[stringKey] = nil
7450 uint64Key := uint64(i)
7451 uint64Keys = append(uint64Keys, uint64Key)
7452 mapOfUint64s[uint64Key] = nil
7454 userStringKey := S(fmt.Sprintf("key%d", i))
7455 userStringKeys = append(userStringKeys, userStringKey)
7456 mapOfUserStrings[userStringKey] = nil
7461 m, keys, value Value
7463 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7464 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7465 {"UserStringKeys", ValueOf(mapOfUserStrings), ValueOf(userStringKeys), value},
7468 for _, tt := range tests {
7469 b.Run(tt.label, func(b *testing.B) {
7470 b.Run("MapIndex", func(b *testing.B) {
7472 for i := 0; i < b.N; i++ {
7473 for j := tt.keys.Len() - 1; j >= 0; j-- {
7474 tt.m.MapIndex(tt.keys.Index(j))
7478 b.Run("SetMapIndex", func(b *testing.B) {
7480 for i := 0; i < b.N; i++ {
7481 for j := tt.keys.Len() - 1; j >= 0; j-- {
7482 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7490 func TestSwapper(t *testing.T) {
7496 type pairPtr struct {
7508 in: []int{1, 20, 300},
7511 want: []int{300, 20, 1},
7514 in: []uintptr{1, 20, 300},
7517 want: []uintptr{300, 20, 1},
7520 in: []int16{1, 20, 300},
7523 want: []int16{300, 20, 1},
7526 in: []int8{1, 20, 100},
7529 want: []int8{100, 20, 1},
7532 in: []*I{&a, &b, &c},
7535 want: []*I{&c, &b, &a},
7538 in: []string{"eric", "sergey", "larry"},
7541 want: []string{"larry", "sergey", "eric"},
7544 in: []S{"eric", "sergey", "larry"},
7547 want: []S{"larry", "sergey", "eric"},
7550 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7553 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7556 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7559 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7563 for i, tt := range tests {
7564 inStr := fmt.Sprint(tt.in)
7565 Swapper(tt.in)(tt.i, tt.j)
7566 if !DeepEqual(tt.in, tt.want) {
7567 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7572 // TestUnaddressableField tests that the reflect package will not allow
7573 // a type from another package to be used as a named type with an
7574 // unexported field.
7576 // This ensures that unexported fields cannot be modified by other packages.
7577 func TestUnaddressableField(t *testing.T) {
7578 var b Buffer // type defined in reflect, a different package
7579 var localBuffer struct {
7582 lv := ValueOf(&localBuffer).Elem()
7584 shouldPanic("Set", func() {
7593 type Talias1 struct {
7601 type Talias2 struct {
7606 func TestAliasNames(t *testing.T) {
7607 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7608 out := fmt.Sprintf("%#v", t1)
7609 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7611 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7614 t2 := Talias2{Tint: 1, Tint2: 2}
7615 out = fmt.Sprintf("%#v", t2)
7616 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7618 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7622 func TestIssue22031(t *testing.T) {
7623 type s []struct{ C int }
7626 type t2 struct{ f s }
7629 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7630 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7633 for i, test := range tests {
7635 t.Errorf("%d: CanSet: got true, want false", i)
7640 type NonExportedFirst int
7642 func (i NonExportedFirst) ΦExported() {}
7643 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7645 func TestIssue22073(t *testing.T) {
7646 m := ValueOf(NonExportedFirst(0)).Method(0)
7648 if got := m.Type().NumOut(); got != 0 {
7649 t.Errorf("NumOut: got %v, want 0", got)
7656 func TestMapIterNonEmptyMap(t *testing.T) {
7657 m := map[string]int{"one": 1, "two": 2, "three": 3}
7658 iter := ValueOf(m).MapRange()
7659 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7660 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7664 func TestMapIterNilMap(t *testing.T) {
7665 var m map[string]int
7666 iter := ValueOf(m).MapRange()
7667 if got, want := iterateToString(iter), `[]`; got != want {
7668 t.Errorf("non-empty result iteratoring nil map: %s", got)
7672 func TestMapIterReset(t *testing.T) {
7673 iter := new(MapIter)
7675 // Use of zero iterator should panic.
7677 defer func() { recover() }()
7679 t.Error("Next did not panic")
7682 // Reset to new Map should work.
7683 m := map[string]int{"one": 1, "two": 2, "three": 3}
7684 iter.Reset(ValueOf(m))
7685 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7686 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7689 // Reset to Zero value should work, but iterating over it should panic.
7692 defer func() { recover() }()
7694 t.Error("Next did not panic")
7697 // Reset to a different Map with different types should work.
7698 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7699 iter.Reset(ValueOf(m2))
7700 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7701 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7704 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7705 m3 := map[uint64]uint64{
7710 kv := New(TypeOf(uint64(0))).Elem()
7711 for i := 0; i < 5; i++ {
7712 var seenk, seenv uint64
7713 iter.Reset(ValueOf(m3))
7717 kv.SetIterValue(iter)
7721 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7723 if seenv != 0b1110 {
7724 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7728 // Reset should not allocate.
7729 n := int(testing.AllocsPerRun(10, func() {
7730 iter.Reset(ValueOf(m2))
7734 t.Errorf("MapIter.Reset allocated %d times", n)
7738 func TestMapIterSafety(t *testing.T) {
7739 // Using a zero MapIter causes a panic, but not a crash.
7741 defer func() { recover() }()
7743 t.Fatal("Key did not panic")
7746 defer func() { recover() }()
7747 new(MapIter).Value()
7748 t.Fatal("Value did not panic")
7751 defer func() { recover() }()
7753 t.Fatal("Next did not panic")
7756 // Calling Key/Value on a MapIter before Next
7757 // causes a panic, but not a crash.
7758 var m map[string]int
7759 iter := ValueOf(m).MapRange()
7762 defer func() { recover() }()
7764 t.Fatal("Key did not panic")
7767 defer func() { recover() }()
7769 t.Fatal("Value did not panic")
7772 // Calling Next, Key, or Value on an exhausted iterator
7773 // causes a panic, but not a crash.
7774 iter.Next() // -> false
7776 defer func() { recover() }()
7778 t.Fatal("Key did not panic")
7781 defer func() { recover() }()
7783 t.Fatal("Value did not panic")
7786 defer func() { recover() }()
7788 t.Fatal("Next did not panic")
7792 func TestMapIterNext(t *testing.T) {
7793 // The first call to Next should reflect any
7794 // insertions to the map since the iterator was created.
7795 m := map[string]int{}
7796 iter := ValueOf(m).MapRange()
7798 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7799 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7803 func BenchmarkMapIterNext(b *testing.B) {
7804 m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3})
7806 for i := 0; i < b.N; i++ {
7813 func TestMapIterDelete0(t *testing.T) {
7814 // Delete all elements before first iteration.
7815 m := map[string]int{"one": 1, "two": 2, "three": 3}
7816 iter := ValueOf(m).MapRange()
7820 if got, want := iterateToString(iter), `[]`; got != want {
7821 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7825 func TestMapIterDelete1(t *testing.T) {
7826 // Delete all elements after first iteration.
7827 m := map[string]int{"one": 1, "two": 2, "three": 3}
7828 iter := ValueOf(m).MapRange()
7831 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7837 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7841 // iterateToString returns the set of elements
7842 // returned by an iterator in readable form.
7843 func iterateToString(it *MapIter) string {
7846 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7847 got = append(got, line)
7850 return "[" + strings.Join(got, ", ") + "]"
7853 func TestConvertibleTo(t *testing.T) {
7854 t1 := ValueOf(example1.MyStruct{}).Type()
7855 t2 := ValueOf(example2.MyStruct{}).Type()
7857 // Shouldn't raise stack overflow
7858 if t1.ConvertibleTo(t2) {
7859 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7862 t3 := ValueOf([]example1.MyStruct{}).Type()
7863 t4 := ValueOf([]example2.MyStruct{}).Type()
7865 if t3.ConvertibleTo(t4) {
7866 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7870 func TestSetIter(t *testing.T) {
7871 data := map[string]int{
7879 k := New(TypeOf("")).Elem()
7880 v := New(TypeOf(0)).Elem()
7881 shouldPanic("Value.SetIterKey called before Next", func() {
7884 shouldPanic("Value.SetIterValue called before Next", func() {
7887 data2 := map[string]int{}
7891 data2[k.Interface().(string)] = v.Interface().(int)
7893 if !DeepEqual(data, data2) {
7894 t.Errorf("maps not equal, got %v want %v", data2, data)
7896 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7899 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7905 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7906 ValueOf("").SetIterKey(i)
7908 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7909 ValueOf(0).SetIterValue(i)
7911 shouldPanic("value of type string is not assignable to type int", func() {
7912 New(TypeOf(0)).Elem().SetIterKey(i)
7914 shouldPanic("value of type int is not assignable to type string", func() {
7915 New(TypeOf("")).Elem().SetIterValue(i)
7918 // Make sure assignment conversion works.
7920 y := ValueOf(&x).Elem()
7922 if _, ok := data[x.(string)]; !ok {
7923 t.Errorf("got key %s which is not in map", x)
7926 if x.(int) < 1 || x.(int) > 3 {
7927 t.Errorf("got value %d which is not in map", x)
7930 // Try some key/value types which are direct interfaces.
7933 pp := map[*int]*int{
7936 i = ValueOf(pp).MapRange()
7939 if got := *y.Interface().(*int); got != a {
7940 t.Errorf("pointer incorrect: got %d want %d", got, a)
7943 if got := *y.Interface().(*int); got != b {
7944 t.Errorf("pointer incorrect: got %d want %d", got, b)
7949 type nih struct{ x int }
7951 var global_nih = nih{x: 7}
7953 func TestNotInHeapDeref(t *testing.T) {
7955 v := ValueOf((*nih)(nil))
7957 shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
7959 v = ValueOf(&global_nih)
7960 if got := v.Elem().Field(0).Int(); got != 7 {
7961 t.Fatalf("got %d, want 7", got)
7964 v = ValueOf((*nih)(unsafe.Pointer(new(int))))
7965 shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
7966 shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() })
7967 shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() })
7970 func TestMethodCallValueCodePtr(t *testing.T) {
7971 m := ValueOf(Point{}).Method(1)
7972 want := MethodValueCallCodePtr()
7973 if got := uintptr(m.UnsafePointer()); got != want {
7974 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7976 if got := m.Pointer(); got != want {
7977 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7982 type B[T any] struct{}
7984 func TestIssue50208(t *testing.T) {
7985 want1 := "B[reflect_test.A]"
7986 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7987 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7989 want2 := "B[reflect_test.B[reflect_test.A]]"
7990 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7991 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7995 func TestNegativeKindString(t *testing.T) {
7997 s := Kind(x).String()
8000 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
8009 var sourceAll = struct {
8018 Bool: ValueOf(new(bool)).Elem(),
8019 String: ValueOf(new(string)).Elem(),
8020 Bytes: ValueOf(new([]byte)).Elem(),
8021 NamedBytes: ValueOf(new(namedBytes)).Elem(),
8022 BytesArray: ValueOf(new([32]byte)).Elem(),
8023 SliceAny: ValueOf(new([]any)).Elem(),
8024 MapStringAny: ValueOf(new(map[string]any)).Elem(),
8027 var sinkAll struct {
8034 func BenchmarkBool(b *testing.B) {
8035 for i := 0; i < b.N; i++ {
8036 sinkAll.RawBool = sourceAll.Bool.Bool()
8040 func BenchmarkString(b *testing.B) {
8041 for i := 0; i < b.N; i++ {
8042 sinkAll.RawString = sourceAll.String.String()
8046 func BenchmarkBytes(b *testing.B) {
8047 for i := 0; i < b.N; i++ {
8048 sinkAll.RawBytes = sourceAll.Bytes.Bytes()
8052 func BenchmarkNamedBytes(b *testing.B) {
8053 for i := 0; i < b.N; i++ {
8054 sinkAll.RawBytes = sourceAll.NamedBytes.Bytes()
8058 func BenchmarkBytesArray(b *testing.B) {
8059 for i := 0; i < b.N; i++ {
8060 sinkAll.RawBytes = sourceAll.BytesArray.Bytes()
8064 func BenchmarkSliceLen(b *testing.B) {
8065 for i := 0; i < b.N; i++ {
8066 sinkAll.RawInt = sourceAll.SliceAny.Len()
8070 func BenchmarkMapLen(b *testing.B) {
8071 for i := 0; i < b.N; i++ {
8072 sinkAll.RawInt = sourceAll.MapStringAny.Len()
8076 func BenchmarkStringLen(b *testing.B) {
8077 for i := 0; i < b.N; i++ {
8078 sinkAll.RawInt = sourceAll.String.Len()
8082 func BenchmarkArrayLen(b *testing.B) {
8083 for i := 0; i < b.N; i++ {
8084 sinkAll.RawInt = sourceAll.BytesArray.Len()
8088 func BenchmarkSliceCap(b *testing.B) {
8089 for i := 0; i < b.N; i++ {
8090 sinkAll.RawInt = sourceAll.SliceAny.Cap()
8094 func TestValue_Cap(t *testing.T) {
8095 a := &[3]int{1, 2, 3}
8097 if v.Cap() != cap(a) {
8098 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
8103 if v.Cap() != cap(a) {
8104 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
8107 getError := func(f func()) (errorStr string) {
8110 if str, ok := e.(string); ok {
8117 e := getError(func() {
8121 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
8123 t.Errorf("error is %q, want %q", e, wantStr)
8127 func TestValue_Len(t *testing.T) {
8128 a := &[3]int{1, 2, 3}
8130 if v.Len() != len(a) {
8131 t.Errorf("Len = %d want %d", v.Len(), len(a))
8136 if v.Len() != len(a) {
8137 t.Errorf("Len = %d want %d", v.Len(), len(a))
8140 getError := func(f func()) (errorStr string) {
8143 if str, ok := e.(string); ok {
8150 e := getError(func() {
8154 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
8156 t.Errorf("error is %q, want %q", e, wantStr)