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.
21 "reflect/internal/example1"
22 "reflect/internal/example2"
36 func TestBool(t *testing.T) {
39 t.Fatal("ValueOf(true).Bool() = false")
51 var _ = T{} == T{} // tests depend on T being comparable
58 func assert(t *testing.T, s, want string) {
60 t.Errorf("have %#q want %#q", s, want)
64 var typeTests = []pair{
65 {struct{ x int }{}, "int"},
66 {struct{ x int8 }{}, "int8"},
67 {struct{ x int16 }{}, "int16"},
68 {struct{ x int32 }{}, "int32"},
69 {struct{ x int64 }{}, "int64"},
70 {struct{ x uint }{}, "uint"},
71 {struct{ x uint8 }{}, "uint8"},
72 {struct{ x uint16 }{}, "uint16"},
73 {struct{ x uint32 }{}, "uint32"},
74 {struct{ x uint64 }{}, "uint64"},
75 {struct{ x float32 }{}, "float32"},
76 {struct{ x float64 }{}, "float64"},
77 {struct{ x int8 }{}, "int8"},
78 {struct{ x (**int8) }{}, "**int8"},
79 {struct{ x (**integer) }{}, "**reflect_test.integer"},
80 {struct{ x ([32]int32) }{}, "[32]int32"},
81 {struct{ x ([]int8) }{}, "[]int8"},
82 {struct{ x (map[string]int32) }{}, "map[string]int32"},
83 {struct{ x (chan<- string) }{}, "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"},
87 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
94 "struct { c chan *int32; d float32 }",
96 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
99 c func(chan *integer, *int8)
102 "struct { c func(chan *reflect_test.integer, *int8) }",
110 "struct { a int8; b int32 }",
119 "struct { a int8; b int8; c int32 }",
129 "struct { a int8; b int8; c int8; d int32 }",
140 "struct { a int8; b int8; c int8; d int8; e int32 }",
152 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
156 a int8 `reflect:"hi there"`
159 `struct { a int8 "reflect:\"hi there\"" }`,
163 a int8 `reflect:"hi \x00there\t\n\"\\"`
166 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
173 "struct { f func(...int) }",
177 a(func(func(int) int) func(func(int)) int)
181 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
189 "struct { int32; int64 }",
193 var valueTests = []pair{
204 {new(float32), "256.25"},
205 {new(float64), "512.125"},
206 {new(complex64), "532.125+10i"},
207 {new(complex128), "564.25+1i"},
208 {new(string), "stringy cheese"},
210 {new(*int8), "*int8(0)"},
211 {new(**int8), "**int8(0)"},
212 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
213 {new(**integer), "**reflect_test.integer(0)"},
214 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
215 {new(chan<- string), "chan<- string"},
216 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
221 "struct { c chan *int32; d float32 }{chan *int32, 0}",
223 {new(struct{ c func(chan *integer, *int8) }),
224 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
230 "struct { a int8; b int32 }{0, 0}",
237 "struct { a int8; b int8; c int32 }{0, 0, 0}",
241 func testType(t *testing.T, i int, typ Type, want string) {
244 t.Errorf("#%d: have %#q, want %#q", i, s, want)
248 func TestTypes(t *testing.T) {
249 for i, tt := range typeTests {
250 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
254 func TestSet(t *testing.T) {
255 for i, tt := range valueTests {
284 v.SetComplex(532.125 + 10i)
286 v.SetComplex(564.25 + 1i)
288 v.SetString("stringy cheese")
292 s := valueToString(v)
294 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
299 func TestSetValue(t *testing.T) {
300 for i, tt := range valueTests {
301 v := ValueOf(tt.i).Elem()
304 v.Set(ValueOf(int(132)))
306 v.Set(ValueOf(int8(8)))
308 v.Set(ValueOf(int16(16)))
310 v.Set(ValueOf(int32(32)))
312 v.Set(ValueOf(int64(64)))
314 v.Set(ValueOf(uint(132)))
316 v.Set(ValueOf(uint8(8)))
318 v.Set(ValueOf(uint16(16)))
320 v.Set(ValueOf(uint32(32)))
322 v.Set(ValueOf(uint64(64)))
324 v.Set(ValueOf(float32(256.25)))
326 v.Set(ValueOf(512.125))
328 v.Set(ValueOf(complex64(532.125 + 10i)))
330 v.Set(ValueOf(complex128(564.25 + 1i)))
332 v.Set(ValueOf("stringy cheese"))
336 s := valueToString(v)
338 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
343 func TestMapIterSet(t *testing.T) {
344 m := make(map[string]any, len(valueTests))
345 for _, tt := range valueTests {
350 k := New(v.Type().Key()).Elem()
351 e := New(v.Type().Elem()).Elem()
357 want := m[k.String()]
360 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
362 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
363 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
365 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
366 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
370 if testenv.OptimizationOff() {
371 return // no inlining with the noopt builder
374 got := int(testing.AllocsPerRun(10, func() {
381 // Calling MapRange should not allocate even though it returns a *MapIter.
382 // The function is inlineable, so if the local usage does not escape
383 // the *MapIter, it can remain stack allocated.
386 t.Errorf("wanted %d alloc, got %d", want, got)
390 func TestCanIntUintFloatComplex(t *testing.T) {
394 type complex complex128
396 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
398 var testCases = []struct {
403 {132, [...]bool{true, false, false, false}},
404 {int8(8), [...]bool{true, false, false, false}},
405 {int16(16), [...]bool{true, false, false, false}},
406 {int32(32), [...]bool{true, false, false, false}},
407 {int64(64), [...]bool{true, false, false, false}},
409 {uint(132), [...]bool{false, true, false, false}},
410 {uint8(8), [...]bool{false, true, false, false}},
411 {uint16(16), [...]bool{false, true, false, false}},
412 {uint32(32), [...]bool{false, true, false, false}},
413 {uint64(64), [...]bool{false, true, false, false}},
414 {uintptr(0xABCD), [...]bool{false, true, false, false}},
416 {float32(256.25), [...]bool{false, false, true, false}},
417 {float64(512.125), [...]bool{false, false, true, false}},
419 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
420 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
422 {integer(-132), [...]bool{true, false, false, false}},
423 {uinteger(132), [...]bool{false, true, false, false}},
424 {float(256.25), [...]bool{false, false, true, false}},
425 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
427 {"hello world", [...]bool{false, false, false, false}},
428 {new(int), [...]bool{false, false, false, false}},
429 {new(uint), [...]bool{false, false, false, false}},
430 {new(float64), [...]bool{false, false, false, false}},
431 {new(complex64), [...]bool{false, false, false, false}},
432 {new([5]int), [...]bool{false, false, false, false}},
433 {new(integer), [...]bool{false, false, false, false}},
434 {new(map[int]int), [...]bool{false, false, false, false}},
435 {new(chan<- int), [...]bool{false, false, false, false}},
436 {new(func(a int8)), [...]bool{false, false, false, false}},
437 {new(struct{ i int }), [...]bool{false, false, false, false}},
440 for i, tc := range testCases {
442 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
444 for j := range tc.want {
445 if got[j] != tc.want[j] {
447 "#%d: v.%s() returned %t for type %T, want %t",
459 func TestCanSetField(t *testing.T) {
460 type embed struct{ x, X int }
461 type Embed struct{ x, X int }
479 type testCase struct {
480 // -1 means Addr().Elem() of current value
491 {[]int{0, -1}, false},
492 {[]int{0, 0}, false},
493 {[]int{0, 0, -1}, false},
494 {[]int{0, -1, 0}, false},
495 {[]int{0, -1, 0, -1}, false},
497 {[]int{0, 1, -1}, true},
498 {[]int{0, -1, 1}, true},
499 {[]int{0, -1, 1, -1}, true},
501 {[]int{1, -1}, false},
503 {[]int{2, -1}, true},
506 val: ValueOf(&S2{embed: &embed{}}),
509 {[]int{0, -1}, false},
510 {[]int{0, 0}, false},
511 {[]int{0, 0, -1}, false},
512 {[]int{0, -1, 0}, false},
513 {[]int{0, -1, 0, -1}, false},
515 {[]int{0, 1, -1}, true},
516 {[]int{0, -1, 1}, true},
517 {[]int{0, -1, 1, -1}, true},
525 {[]int{0, -1}, true},
526 {[]int{0, 0}, false},
527 {[]int{0, 0, -1}, false},
528 {[]int{0, -1, 0}, false},
529 {[]int{0, -1, 0, -1}, false},
531 {[]int{0, 1, -1}, true},
532 {[]int{0, -1, 1}, true},
533 {[]int{0, -1, 1, -1}, true},
538 val: ValueOf(&S4{Embed: &Embed{}}),
541 {[]int{0, -1}, true},
542 {[]int{0, 0}, false},
543 {[]int{0, 0, -1}, false},
544 {[]int{0, -1, 0}, false},
545 {[]int{0, -1, 0, -1}, false},
547 {[]int{0, 1, -1}, true},
548 {[]int{0, -1, 1}, true},
549 {[]int{0, -1, 1, -1}, true},
555 for _, tt := range tests {
556 t.Run(tt.val.Type().Name(), func(t *testing.T) {
557 for _, tc := range tt.cases {
559 for _, i := range tc.index {
560 if f.Kind() == Pointer {
569 if got := f.CanSet(); got != tc.canSet {
570 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
579 var valueToStringTests = []pair{
584 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
585 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
586 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
587 {&[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})"},
588 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
589 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
592 func TestValueToString(t *testing.T) {
593 for i, test := range valueToStringTests {
594 s := valueToString(ValueOf(test.i))
596 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
601 func TestArrayElemSet(t *testing.T) {
602 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
603 v.Index(4).SetInt(123)
604 s := valueToString(v)
605 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
607 t.Errorf("[10]int: have %#q want %#q", s, want)
610 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
611 v.Index(4).SetInt(123)
613 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
615 t.Errorf("[]int: have %#q want %#q", s, want1)
619 func TestPtrPointTo(t *testing.T) {
623 vi := ValueOf(&i).Elem()
624 vip.Elem().Set(vi.Addr())
626 t.Errorf("got %d, want 1234", *ip)
630 vp := ValueOf(&ip).Elem()
631 vp.Set(Zero(vp.Type()))
633 t.Errorf("got non-nil (%p), want nil", ip)
637 func TestPtrSetNil(t *testing.T) {
641 vip.Elem().Set(Zero(vip.Elem().Type()))
643 t.Errorf("got non-nil (%d), want nil", *ip)
647 func TestMapSetNil(t *testing.T) {
648 m := make(map[string]int)
650 vm.Elem().Set(Zero(vm.Elem().Type()))
652 t.Errorf("got non-nil (%p), want nil", m)
656 func TestAll(t *testing.T) {
657 testType(t, 1, TypeOf((int8)(0)), "int8")
658 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
660 typ := TypeOf((*struct {
664 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
666 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
669 testType(t, 5, f.Type, "chan *int32")
671 f, present := styp.FieldByName("d")
673 t.Errorf("FieldByName says present field is absent")
675 testType(t, 6, f.Type, "float32")
677 f, present = styp.FieldByName("absent")
679 t.Errorf("FieldByName says absent field is present")
682 typ = TypeOf([32]int32{})
683 testType(t, 7, typ, "[32]int32")
684 testType(t, 8, typ.Elem(), "int32")
686 typ = TypeOf((map[string]*int32)(nil))
687 testType(t, 9, typ, "map[string]*int32")
689 testType(t, 10, mtyp.Key(), "string")
690 testType(t, 11, mtyp.Elem(), "*int32")
692 typ = TypeOf((chan<- string)(nil))
693 testType(t, 12, typ, "chan<- string")
694 testType(t, 13, typ.Elem(), "string")
696 // make sure tag strings are not part of element type
697 typ = TypeOf(struct {
698 d []uint32 `reflect:"TAG"`
700 testType(t, 14, typ, "[]uint32")
703 func TestInterfaceGet(t *testing.T) {
708 v1 := ValueOf(&inter)
709 v2 := v1.Elem().Field(0)
710 assert(t, v2.Type().String(), "interface {}")
713 assert(t, v3.Type().String(), "float64")
716 func TestInterfaceValue(t *testing.T) {
721 v1 := ValueOf(&inter)
722 v2 := v1.Elem().Field(0)
723 assert(t, v2.Type().String(), "interface {}")
725 assert(t, v3.Type().String(), "float64")
728 if _, ok := i3.(float64); !ok {
729 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
733 func TestFunctionValue(t *testing.T) {
734 var x any = func() {}
736 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
737 t.Fatalf("TestFunction returned wrong pointer")
739 assert(t, v.Type().String(), "func()")
742 func TestGrow(t *testing.T) {
743 v := ValueOf([]int(nil))
744 shouldPanic("reflect.Value.Grow using unaddressable value", func() { v.Grow(0) })
745 v = ValueOf(new([]int)).Elem()
748 t.Errorf("v.Grow(0) should still be nil")
752 t.Errorf("v.Cap = %v, want non-zero", v.Cap())
754 want := v.UnsafePointer()
756 got := v.UnsafePointer()
758 t.Errorf("noop v.Grow should not change pointers")
761 t.Run("Append", func(t *testing.T) {
763 v := ValueOf(&got).Elem()
764 appendValue := func(vt T) {
766 v.SetLen(v.Len() + 1)
767 v.Index(v.Len() - 1).Set(ValueOf(vt))
769 for i := 0; i < 10; i++ {
770 vt := T{i, float64(i), strconv.Itoa(i), &i}
772 want = append(want, vt)
774 if !DeepEqual(got, want) {
775 t.Errorf("value mismatch:\ngot %v\nwant %v", got, want)
779 t.Run("Rate", func(t *testing.T) {
781 v := ValueOf(new([]byte)).Elem()
782 for i := 0; i < 10; i++ {
783 b = append(b[:cap(b)], make([]byte, 1)...)
786 if v.Cap() != cap(b) {
787 t.Errorf("v.Cap = %v, want %v", v.Cap(), cap(b))
792 t.Run("ZeroCapacity", func(t *testing.T) {
793 for i := 0; i < 10; i++ {
794 v := ValueOf(new([]byte)).Elem()
798 for i, c := range b {
800 t.Fatalf("Value.Bytes[%d] = 0x%02x, want 0x00", i, c)
809 var appendTests = []struct {
817 {[]int{}, []int{22}},
818 {make([]int, 2, 4), nil},
819 {make([]int, 2, 4), []int{}},
820 {make([]int, 2, 4), []int{22}},
821 {make([]int, 2, 4), []int{22, 33, 44}},
824 func TestAppend(t *testing.T) {
825 for i, test := range appendTests {
826 origLen, extraLen := len(test.orig), len(test.extra)
827 want := append(test.orig, test.extra...)
828 // Convert extra from []int to []Value.
829 e0 := make([]Value, len(test.extra))
830 for j, e := range test.extra {
833 // Convert extra from []int to *SliceValue.
834 e1 := ValueOf(test.extra)
837 a0 := ValueOf(&test.orig).Elem()
838 have0 := Append(a0, e0...)
840 t.Errorf("Append #%d: have slice should not be addressable", i)
842 if !DeepEqual(have0.Interface(), want) {
843 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0.Interface())
845 // Check that the orig and extra slices were not modified.
846 if a0.Len() != len(test.orig) {
847 t.Errorf("Append #%d: a0.Len: have %d, want %d", i, a0.Len(), origLen)
849 if len(test.orig) != origLen {
850 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
852 if len(test.extra) != extraLen {
853 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
857 a1 := ValueOf(&test.orig).Elem()
858 have1 := AppendSlice(a1, e1)
860 t.Errorf("AppendSlice #%d: have slice should not be addressable", i)
862 if !DeepEqual(have1.Interface(), want) {
863 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
865 // Check that the orig and extra slices were not modified.
866 if a1.Len() != len(test.orig) {
867 t.Errorf("AppendSlice #%d: a1.Len: have %d, want %d", i, a0.Len(), origLen)
869 if len(test.orig) != origLen {
870 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
872 if len(test.extra) != extraLen {
873 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
876 // Test Append and AppendSlice with unexported value.
877 ax := ValueOf(struct{ x []int }{test.orig}).Field(0)
878 shouldPanic("using unexported field", func() { Append(ax, e0...) })
879 shouldPanic("using unexported field", func() { AppendSlice(ax, e1) })
883 func TestCopy(t *testing.T) {
884 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
885 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
886 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
887 for i := 0; i < len(b); i++ {
889 t.Fatalf("b != c before test")
894 aa := ValueOf(&a1).Elem()
895 ab := ValueOf(&b1).Elem()
896 for tocopy := 1; tocopy <= 7; tocopy++ {
900 for i := 0; i < tocopy; i++ {
902 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
903 tocopy, i, a[i], i, b[i])
906 for i := tocopy; i < len(b); i++ {
909 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
910 tocopy, i, a[i], i, b[i], i, c[i])
912 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
913 tocopy, i, b[i], i, c[i])
916 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
922 func TestCopyString(t *testing.T) {
923 t.Run("Slice", func(t *testing.T) {
924 s := bytes.Repeat([]byte{'_'}, 8)
927 n := Copy(val, ValueOf(""))
928 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
929 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
932 n = Copy(val, ValueOf("hello"))
933 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
934 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
937 n = Copy(val, ValueOf("helloworld"))
938 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
939 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
942 t.Run("Array", func(t *testing.T) {
943 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
944 val := ValueOf(&s).Elem()
946 n := Copy(val, ValueOf(""))
947 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
948 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
951 n = Copy(val, ValueOf("hello"))
952 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
953 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
956 n = Copy(val, ValueOf("helloworld"))
957 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
958 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
963 func TestCopyArray(t *testing.T) {
964 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
965 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
967 aa := ValueOf(&a).Elem()
968 ab := ValueOf(&b).Elem()
970 for i := 0; i < len(a); i++ {
972 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
975 for i := len(a); i < len(b); i++ {
977 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
979 t.Logf("elem %d is okay\n", i)
984 func TestBigUnnamedStruct(t *testing.T) {
985 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
987 b1 := v.Interface().(struct {
990 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
991 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
999 func TestBigStruct(t *testing.T) {
1000 b := big{1, 2, 3, 4, 5}
1002 b1 := v.Interface().(big)
1003 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
1004 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
1015 type DeepEqualTest struct {
1020 // Simple functions for DeepEqual tests.
1024 fn3 = func() { fn1() } // Not nil.
1032 var loop1, loop2 Loop
1033 var loopy1, loopy2 Loopy
1034 var cycleMap1, cycleMap2, cycleMap3 map[string]any
1036 type structWithSelfPtr struct {
1037 p *structWithSelfPtr
1048 cycleMap1 = map[string]any{}
1049 cycleMap1["cycle"] = cycleMap1
1050 cycleMap2 = map[string]any{}
1051 cycleMap2["cycle"] = cycleMap2
1052 cycleMap3 = map[string]any{}
1053 cycleMap3["different"] = cycleMap3
1056 var deepEqualTests = []DeepEqualTest{
1060 {int32(1), int32(1), true},
1062 {float32(0.5), float32(0.5), true},
1063 {"hello", "hello", true},
1064 {make([]int, 10), make([]int, 10), true},
1065 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
1066 {Basic{1, 0.5}, Basic{1, 0.5}, true},
1067 {error(nil), error(nil), true},
1068 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
1070 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
1071 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
1072 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
1076 {int32(1), int32(2), false},
1078 {float32(0.5), float32(0.6), false},
1079 {"hello", "hey", false},
1080 {make([]int, 10), make([]int, 11), false},
1081 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
1082 {Basic{1, 0.5}, Basic{1, 0.6}, false},
1083 {Basic{1, 0}, Basic{2, 0}, false},
1084 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
1085 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
1086 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
1087 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
1092 {[][]int{{1}}, [][]int{{2}}, false},
1093 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1095 // Fun with floating point.
1096 {math.NaN(), math.NaN(), false},
1097 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1098 {&[1]float64{math.NaN()}, self{}, true},
1099 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1100 {[]float64{math.NaN()}, self{}, true},
1101 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1102 {map[float64]float64{math.NaN(): 1}, self{}, true},
1104 // Nil vs empty: not the same.
1105 {[]int{}, []int(nil), false},
1106 {[]int{}, []int{}, true},
1107 {[]int(nil), []int(nil), true},
1108 {map[int]int{}, map[int]int(nil), false},
1109 {map[int]int{}, map[int]int{}, true},
1110 {map[int]int(nil), map[int]int(nil), true},
1114 {int32(1), int64(1), false},
1115 {0.5, "hello", false},
1116 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1117 {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
1118 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1119 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1120 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1121 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1122 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1125 {&loop1, &loop1, true},
1126 {&loop1, &loop2, true},
1127 {&loopy1, &loopy1, true},
1128 {&loopy1, &loopy2, true},
1129 {&cycleMap1, &cycleMap2, true},
1130 {&cycleMap1, &cycleMap3, false},
1133 func TestDeepEqual(t *testing.T) {
1134 for _, test := range deepEqualTests {
1135 if test.b == (self{}) {
1138 if r := DeepEqual(test.a, test.b); r != test.eq {
1139 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1144 func TestTypeOf(t *testing.T) {
1145 // Special case for nil
1146 if typ := TypeOf(nil); typ != nil {
1147 t.Errorf("expected nil type for nil value; got %v", typ)
1149 for _, test := range deepEqualTests {
1150 v := ValueOf(test.a)
1154 typ := TypeOf(test.a)
1155 if typ != v.Type() {
1156 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1161 type Recursive struct {
1166 func TestDeepEqualRecursiveStruct(t *testing.T) {
1167 a, b := new(Recursive), new(Recursive)
1168 *a = Recursive{12, a}
1169 *b = Recursive{12, b}
1170 if !DeepEqual(a, b) {
1171 t.Error("DeepEqual(recursive same) = false, want true")
1175 type _Complex struct {
1179 d map[float64]float64
1182 func TestDeepEqualComplexStruct(t *testing.T) {
1183 m := make(map[float64]float64)
1184 stra, strb := "hello", "hello"
1185 a, b := new(_Complex), new(_Complex)
1186 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1187 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1188 if !DeepEqual(a, b) {
1189 t.Error("DeepEqual(complex same) = false, want true")
1193 func TestDeepEqualComplexStructInequality(t *testing.T) {
1194 m := make(map[float64]float64)
1195 stra, strb := "hello", "helloo" // Difference is here
1196 a, b := new(_Complex), new(_Complex)
1197 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1198 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1199 if DeepEqual(a, b) {
1200 t.Error("DeepEqual(complex different) = true, want false")
1204 type UnexpT struct {
1208 func TestDeepEqualUnexportedMap(t *testing.T) {
1209 // Check that DeepEqual can look at unexported fields.
1210 x1 := UnexpT{map[int]int{1: 2}}
1211 x2 := UnexpT{map[int]int{1: 2}}
1212 if !DeepEqual(&x1, &x2) {
1213 t.Error("DeepEqual(x1, x2) = false, want true")
1216 y1 := UnexpT{map[int]int{2: 3}}
1217 if DeepEqual(&x1, &y1) {
1218 t.Error("DeepEqual(x1, y1) = true, want false")
1222 var deepEqualPerfTests = []struct {
1225 {x: int8(99), y: int8(99)},
1226 {x: []int8{99}, y: []int8{99}},
1227 {x: int16(99), y: int16(99)},
1228 {x: []int16{99}, y: []int16{99}},
1229 {x: int32(99), y: int32(99)},
1230 {x: []int32{99}, y: []int32{99}},
1231 {x: int64(99), y: int64(99)},
1232 {x: []int64{99}, y: []int64{99}},
1233 {x: int(999999), y: int(999999)},
1234 {x: []int{999999}, y: []int{999999}},
1236 {x: uint8(99), y: uint8(99)},
1237 {x: []uint8{99}, y: []uint8{99}},
1238 {x: uint16(99), y: uint16(99)},
1239 {x: []uint16{99}, y: []uint16{99}},
1240 {x: uint32(99), y: uint32(99)},
1241 {x: []uint32{99}, y: []uint32{99}},
1242 {x: uint64(99), y: uint64(99)},
1243 {x: []uint64{99}, y: []uint64{99}},
1244 {x: uint(999999), y: uint(999999)},
1245 {x: []uint{999999}, y: []uint{999999}},
1246 {x: uintptr(999999), y: uintptr(999999)},
1247 {x: []uintptr{999999}, y: []uintptr{999999}},
1249 {x: float32(1.414), y: float32(1.414)},
1250 {x: []float32{1.414}, y: []float32{1.414}},
1251 {x: float64(1.414), y: float64(1.414)},
1252 {x: []float64{1.414}, y: []float64{1.414}},
1254 {x: complex64(1.414), y: complex64(1.414)},
1255 {x: []complex64{1.414}, y: []complex64{1.414}},
1256 {x: complex128(1.414), y: complex128(1.414)},
1257 {x: []complex128{1.414}, y: []complex128{1.414}},
1260 {x: []bool{true}, y: []bool{true}},
1262 {x: "abcdef", y: "abcdef"},
1263 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1265 {x: []byte("abcdef"), y: []byte("abcdef")},
1266 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1268 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1269 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1272 func TestDeepEqualAllocs(t *testing.T) {
1273 for _, tt := range deepEqualPerfTests {
1274 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1275 got := testing.AllocsPerRun(100, func() {
1276 if !DeepEqual(tt.x, tt.y) {
1277 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1281 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1287 func check2ndField(x any, offs uintptr, t *testing.T) {
1289 f := s.Type().Field(1)
1290 if f.Offset != offs {
1291 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1295 // Check that structure alignment & offsets viewed through reflect agree with those
1296 // from the compiler itself.
1297 func TestAlignment(t *testing.T) {
1298 type T1inner struct {
1305 type T2inner struct {
1313 x := T1{T1inner{2}, 17}
1314 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1316 x1 := T2{T2inner{2, 3}, 17}
1317 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1320 func Nil(a any, t *testing.T) {
1321 n := ValueOf(a).Field(0)
1323 t.Errorf("%v should be nil", a)
1327 func NotNil(a any, t *testing.T) {
1328 n := ValueOf(a).Field(0)
1330 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1334 func TestIsNil(t *testing.T) {
1335 // These implement IsNil.
1336 // Wrap in extra struct to hide interface type.
1340 struct{ x map[string]int }{},
1341 struct{ x func() bool }{},
1342 struct{ x chan int }{},
1343 struct{ x []string }{},
1344 struct{ x unsafe.Pointer }{},
1346 for _, ts := range doNil {
1347 ty := TypeOf(ts).Field(0).Type
1349 v.IsNil() // panics if not okay to call
1352 // Check the implementations
1364 si.x = make([]int, 10)
1371 ci.x = make(chan int)
1378 mi.x = make(map[int]int)
1389 x func(t *testing.T)
1396 func TestIsZero(t *testing.T) {
1397 for i, tt := range []struct {
1426 {float32(1.2), false},
1428 {float64(1.2), false},
1429 {math.Copysign(0, -1), false},
1430 {complex64(0), true},
1431 {complex64(1.2), false},
1432 {complex128(0), true},
1433 {complex128(1.2), false},
1434 {complex(math.Copysign(0, -1), 0), false},
1435 {complex(0, math.Copysign(0, -1)), false},
1436 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1438 {uintptr(128), false},
1440 {Zero(TypeOf([5]string{})).Interface(), true},
1441 {[5]string{}, true}, // comparable array
1442 {[5]string{"", "", "", "a", ""}, false}, // comparable array
1443 {[1]*int{}, true}, // direct pointer array
1444 {[1]*int{new(int)}, false}, // direct pointer array
1445 {[3][]int{}, true}, // incomparable array
1446 {[3][]int{{1}}, false}, // incomparable array
1447 {[1 << 12]byte{}, true},
1448 {[1 << 12]byte{1}, false},
1450 {[3]Value{{}, ValueOf(0), {}}, false},
1452 {(chan string)(nil), true},
1453 {make(chan string), false},
1454 {time.After(1), false},
1456 {(func())(nil), true},
1459 {New(TypeOf(new(error)).Elem()).Elem(), true},
1460 {(io.Reader)(strings.NewReader("")), false},
1462 {(map[string]string)(nil), true},
1463 {map[string]string{}, false},
1464 {make(map[string]string), false},
1466 {(*func())(nil), true},
1467 {(*int)(nil), true},
1470 {[]string{}, false},
1471 {([]string)(nil), true},
1472 {make([]string, 0), false},
1475 {"not-zero", false},
1477 {T{}, true}, // comparable struct
1478 {T{123, 456.75, "hello", &_i}, false}, // comparable struct
1479 {struct{ p *int }{}, true}, // direct pointer struct
1480 {struct{ p *int }{new(int)}, false}, // direct pointer struct
1481 {struct{ s []int }{}, true}, // incomparable struct
1482 {struct{ s []int }{[]int{1}}, false}, // incomparable struct
1483 {struct{ Value }{}, true},
1484 {struct{ Value }{ValueOf(0)}, false},
1486 {(unsafe.Pointer)(nil), true},
1487 {(unsafe.Pointer)(new(int)), false},
1490 if v, ok := tt.x.(Value); ok {
1498 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1501 if !Zero(TypeOf(tt.x)).IsZero() {
1502 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1505 p := New(x.Type()).Elem()
1509 t.Errorf("%d: IsZero((%s)(%+v)) is true after SetZero", i, p.Kind(), tt.x)
1515 if r := recover(); r == nil {
1516 t.Error("should panic for invalid value")
1523 func TestInterfaceExtraction(t *testing.T) {
1529 v := Indirect(ValueOf(&s)).Field(0).Interface()
1531 t.Error("Interface() on interface: ", v, s.W)
1535 func TestNilPtrValueSub(t *testing.T) {
1537 if pv := ValueOf(pi); pv.Elem().IsValid() {
1538 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1542 func TestMap(t *testing.T) {
1543 m := map[string]int{"a": 1, "b": 2}
1545 if n := mv.Len(); n != len(m) {
1546 t.Errorf("Len = %d, want %d", n, len(m))
1548 keys := mv.MapKeys()
1549 newmap := MakeMap(mv.Type())
1550 for k, v := range m {
1551 // Check that returned Keys match keys in range.
1552 // These aren't required to be in the same order.
1554 for _, kv := range keys {
1555 if kv.String() == k {
1561 t.Errorf("Missing key %q", k)
1564 // Check that value lookup is correct.
1565 vv := mv.MapIndex(ValueOf(k))
1566 if vi := vv.Int(); vi != int64(v) {
1567 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1570 // Copy into new map.
1571 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1573 vv := mv.MapIndex(ValueOf("not-present"))
1575 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1578 newm := newmap.Interface().(map[string]int)
1579 if len(newm) != len(m) {
1580 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1583 for k, v := range newm {
1586 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1590 newmap.SetMapIndex(ValueOf("a"), Value{})
1593 t.Errorf("newm[\"a\"] = %d after delete", v)
1596 mv = ValueOf(&m).Elem()
1597 mv.Set(Zero(mv.Type()))
1599 t.Errorf("mv.Set(nil) failed")
1603 shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
1604 shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
1607 func TestNilMap(t *testing.T) {
1608 var m map[string]int
1610 keys := mv.MapKeys()
1612 t.Errorf(">0 keys for nil map: %v", keys)
1615 // Check that value for missing key is zero.
1616 x := mv.MapIndex(ValueOf("hello"))
1617 if x.Kind() != Invalid {
1618 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1621 // Check big value too.
1622 var mbig map[string][10 << 20]byte
1623 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1624 if x.Kind() != Invalid {
1625 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1628 // Test that deletes from a nil map succeed.
1629 mv.SetMapIndex(ValueOf("hi"), Value{})
1632 func TestChan(t *testing.T) {
1633 for loop := 0; loop < 2; loop++ {
1637 // check both ways to allocate channels
1640 c = make(chan int, 1)
1643 cv = MakeChan(TypeOf(c), 1)
1644 c = cv.Interface().(chan int)
1649 if i := <-c; i != 2 {
1650 t.Errorf("reflect Send 2, native recv %d", i)
1655 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1656 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1660 val, ok := cv.TryRecv()
1661 if val.IsValid() || ok {
1662 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1667 val, ok = cv.TryRecv()
1669 t.Errorf("TryRecv on ready chan got nil")
1670 } else if i := val.Int(); i != 4 || !ok {
1671 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1676 ok = cv.TrySend(ValueOf(5))
1679 t.Errorf("TrySend on full chan succeeded: value %d", i)
1683 ok = cv.TrySend(ValueOf(6))
1685 t.Errorf("TrySend on empty chan failed")
1688 t.Errorf("TrySend failed but it did send %d", x)
1692 if i = <-c; i != 6 {
1693 t.Errorf("TrySend 6, recv %d", i)
1700 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1701 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1703 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1704 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1708 // check creation of unbuffered channel
1710 cv := MakeChan(TypeOf(c), 0)
1711 c = cv.Interface().(chan int)
1712 if cv.TrySend(ValueOf(7)) {
1713 t.Errorf("TrySend on sync chan succeeded")
1715 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1716 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1720 cv = MakeChan(TypeOf(c), 10)
1721 c = cv.Interface().(chan int)
1722 for i := 0; i < 3; i++ {
1725 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1726 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1730 // caseInfo describes a single case in a select test.
1731 type caseInfo struct {
1740 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1742 func TestSelect(t *testing.T) {
1743 selectWatch.once.Do(func() { go selectWatcher() })
1747 newop := func(n int, cap int) (ch, val Value) {
1750 c := make(chan int, cap)
1754 c := make(chan string, cap)
1756 val = ValueOf(fmt.Sprint(n))
1761 for n := 0; x.Next(); n++ {
1762 if testing.Short() && n >= 1000 {
1765 if n >= 100000 && !*allselect {
1768 if n%100000 == 0 && testing.Verbose() {
1769 println("TestSelect", n)
1771 var cases []SelectCase
1776 ch, val := newop(len(cases), 1)
1777 cases = append(cases, SelectCase{
1782 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1787 ch, val := newop(len(cases), 1)
1789 cases = append(cases, SelectCase{
1793 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1798 ch, val := newop(len(cases), 0)
1799 cases = append(cases, SelectCase{
1806 f := func() { ch.Recv() }
1807 info = append(info, caseInfo{desc: "blocking send", helper: f})
1809 info = append(info, caseInfo{desc: "blocking send"})
1815 ch, val := newop(len(cases), 0)
1816 cases = append(cases, SelectCase{
1822 f := func() { ch.Send(val) }
1823 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1825 info = append(info, caseInfo{desc: "blocking recv"})
1831 // Maybe include value to send.
1836 cases = append(cases, SelectCase{
1840 info = append(info, caseInfo{desc: "zero Chan send"})
1843 // Zero Chan receive.
1845 cases = append(cases, SelectCase{
1848 info = append(info, caseInfo{desc: "zero Chan recv"})
1853 cases = append(cases, SelectCase{
1855 Chan: ValueOf((chan int)(nil)),
1858 info = append(info, caseInfo{desc: "nil Chan send"})
1863 cases = append(cases, SelectCase{
1865 Chan: ValueOf((chan int)(nil)),
1867 info = append(info, caseInfo{desc: "nil Chan recv"})
1870 // closed Chan send.
1872 ch := make(chan int)
1874 cases = append(cases, SelectCase{
1879 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1882 // closed Chan recv.
1884 ch, val := newop(len(cases), 0)
1886 val = Zero(val.Type())
1887 cases = append(cases, SelectCase{
1891 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1894 var helper func() // goroutine to help the select complete
1896 // Add default? Must be last case here, but will permute.
1897 // Add the default if the select would otherwise
1898 // block forever, and maybe add it anyway.
1904 for i, c := range info {
1912 } else if c.helper != nil {
1914 helpers = append(helpers, i)
1917 if !canProceed || x.Maybe() {
1918 cases = append(cases, SelectCase{
1921 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1923 } else if canBlock {
1924 // Select needs to communicate with another goroutine.
1925 cas := &info[helpers[x.Choose(len(helpers))]]
1927 cas.canSelect = true
1931 // Permute cases and case info.
1932 // Doing too much here makes the exhaustive loop
1933 // too exhausting, so just do two swaps.
1934 for loop := 0; loop < 2; loop++ {
1935 i := x.Choose(len(cases))
1936 j := x.Choose(len(cases))
1937 cases[i], cases[j] = cases[j], cases[i]
1938 info[i], info[j] = info[j], info[i]
1942 // We wait before kicking off a goroutine to satisfy a blocked select.
1943 // The pause needs to be big enough to let the select block before
1944 // we run the helper, but if we lose that race once in a while it's okay: the
1945 // select will just proceed immediately. Not a big deal.
1946 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1947 pause := 10 * time.Microsecond
1948 if testing.Short() {
1949 pause = 100 * time.Microsecond
1951 time.AfterFunc(pause, helper)
1955 i, recv, recvOK, panicErr := runSelect(cases, info)
1956 if panicErr != nil && !canPanic {
1957 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1959 if panicErr == nil && canPanic && numCanSelect == 1 {
1960 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1962 if panicErr != nil {
1970 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1972 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1975 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1978 if cases[i].Dir == SelectRecv {
1979 if !recv.IsValid() {
1980 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1982 if !cas.recv.IsValid() {
1983 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1985 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1986 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1987 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1989 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1992 if recv.IsValid() || recvOK {
1993 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1999 func TestSelectMaxCases(t *testing.T) {
2000 var sCases []SelectCase
2001 channel := make(chan int)
2003 for i := 0; i < 65536; i++ {
2004 sCases = append(sCases, SelectCase{
2006 Chan: ValueOf(channel),
2010 _, _, _ = Select(sCases)
2011 sCases = append(sCases, SelectCase{
2013 Chan: ValueOf(channel),
2016 if err := recover(); err != nil {
2017 if err.(string) != "reflect.Select: too many cases (max 65536)" {
2018 t.Fatalf("unexpected error from select call with greater than max supported cases")
2021 t.Fatalf("expected select call to panic with greater than max supported cases")
2025 _, _, _ = Select(sCases)
2028 func TestSelectNop(t *testing.T) {
2029 // "select { default: }" should always return the default case.
2030 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
2032 t.Fatalf("expected Select to return 0, but got %#v", chosen)
2036 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
2037 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
2038 // an error describing the select and panics the entire test binary.
2039 var selectWatch struct {
2046 func selectWatcher() {
2048 time.Sleep(1 * time.Second)
2050 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
2051 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
2052 panic("select stuck")
2054 selectWatch.Unlock()
2058 // runSelect runs a single select test.
2059 // It returns the values returned by Select but also returns
2060 // a panic value if the Select panics.
2061 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
2063 panicErr = recover()
2066 selectWatch.info = nil
2067 selectWatch.Unlock()
2071 selectWatch.now = time.Now()
2072 selectWatch.info = info
2073 selectWatch.Unlock()
2075 chosen, recv, recvOK = Select(cases)
2079 // fmtSelect formats the information about a single select test.
2080 func fmtSelect(info []caseInfo) string {
2081 var buf strings.Builder
2082 fmt.Fprintf(&buf, "\nselect {\n")
2083 for i, cas := range info {
2084 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2085 if cas.recv.IsValid() {
2086 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2089 fmt.Fprintf(&buf, " canselect")
2092 fmt.Fprintf(&buf, " panic")
2094 fmt.Fprintf(&buf, "\n")
2096 fmt.Fprintf(&buf, "}")
2102 // Difficult test for function call because of
2103 // implicit padding between arguments.
2104 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) {
2105 return b, c, d, e, f, g, h
2108 func TestFunc(t *testing.T) {
2109 ret := ValueOf(dummy).Call([]Value{
2113 ValueOf(two{40, 50}),
2115 ValueOf(float32(70)),
2119 t.Fatalf("Call returned %d values, want 7", len(ret))
2122 i := byte(ret[0].Uint())
2123 j := int(ret[1].Int())
2124 k := byte(ret[2].Uint())
2125 l := ret[3].Interface().(two)
2126 m := byte(ret[4].Uint())
2127 n := float32(ret[5].Float())
2128 o := byte(ret[6].Uint())
2130 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2131 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)
2134 for i, v := range ret {
2136 t.Errorf("result %d is addressable", i)
2141 func TestCallConvert(t *testing.T) {
2142 v := ValueOf(new(io.ReadWriter)).Elem()
2143 f := ValueOf(func(r io.Reader) io.Reader { return r })
2144 out := f.Call([]Value{v})
2145 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2146 t.Errorf("expected [nil], got %v", out)
2150 type emptyStruct struct{}
2152 type nonEmptyStruct struct {
2156 func returnEmpty() emptyStruct {
2157 return emptyStruct{}
2160 func takesEmpty(e emptyStruct) {
2163 func returnNonEmpty(i int) nonEmptyStruct {
2164 return nonEmptyStruct{member: i}
2167 func takesNonEmpty(n nonEmptyStruct) int {
2171 func TestCallWithStruct(t *testing.T) {
2172 r := ValueOf(returnEmpty).Call(nil)
2173 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2174 t.Errorf("returning empty struct returned %#v instead", r)
2176 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2178 t.Errorf("takesEmpty returned values: %#v", r)
2180 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2181 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2182 t.Errorf("returnNonEmpty returned %#v", r)
2184 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2185 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2186 t.Errorf("takesNonEmpty returned %#v", r)
2190 func TestCallReturnsEmpty(t *testing.T) {
2191 // Issue 21717: past-the-end pointer write in Call with
2192 // nonzero-sized frame and zero-sized return value.
2194 var finalized uint32
2195 f := func() (emptyStruct, *[2]int64) {
2196 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2197 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2198 return emptyStruct{}, i
2200 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2201 timeout := time.After(5 * time.Second)
2202 for atomic.LoadUint32(&finalized) == 0 {
2205 t.Fatal("finalizer did not run")
2211 runtime.KeepAlive(v)
2214 func TestMakeFunc(t *testing.T) {
2216 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2217 ValueOf(&f).Elem().Set(fv)
2219 // Call g with small arguments so that there is
2220 // something predictable (and different from the
2221 // correct results) in those positions on the stack.
2223 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2225 // Call constructed function f.
2226 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2227 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2228 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)
2232 func TestMakeFuncInterface(t *testing.T) {
2233 fn := func(i int) int { return i }
2234 incr := func(in []Value) []Value {
2235 return []Value{ValueOf(int(in[0].Int() + 1))}
2237 fv := MakeFunc(TypeOf(fn), incr)
2238 ValueOf(&fn).Elem().Set(fv)
2239 if r := fn(2); r != 3 {
2240 t.Errorf("Call returned %d, want 3", r)
2242 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2243 t.Errorf("Call returned %d, want 15", r)
2245 if r := fv.Interface().(func(int) int)(26); r != 27 {
2246 t.Errorf("Call returned %d, want 27", r)
2250 func TestMakeFuncVariadic(t *testing.T) {
2251 // Test that variadic arguments are packed into a slice and passed as last arg
2252 fn := func(_ int, is ...int) []int { return nil }
2253 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2254 ValueOf(&fn).Elem().Set(fv)
2257 if r[0] != 2 || r[1] != 3 {
2258 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2261 r = fn(1, []int{2, 3}...)
2262 if r[0] != 2 || r[1] != 3 {
2263 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2266 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2267 if r[0] != 2 || r[1] != 3 {
2268 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2271 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2272 if r[0] != 2 || r[1] != 3 {
2273 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2276 f := fv.Interface().(func(int, ...int) []int)
2279 if r[0] != 2 || r[1] != 3 {
2280 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2282 r = f(1, []int{2, 3}...)
2283 if r[0] != 2 || r[1] != 3 {
2284 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2288 // Dummy type that implements io.WriteCloser
2292 func (w *WC) Write(p []byte) (n int, err error) {
2295 func (w *WC) Close() error {
2299 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2300 // reflect.Values returned from the wrapped function should be assignment-converted
2301 // to the types returned by the result of MakeFunc.
2303 // Concrete types should be promotable to interfaces they implement.
2305 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2306 return []Value{ValueOf(io.EOF)}
2307 }).Interface().(func() error)
2310 // Super-interfaces should be promotable to simpler interfaces.
2311 var g func() io.Writer
2312 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2313 var w io.WriteCloser = &WC{}
2314 return []Value{ValueOf(&w).Elem()}
2315 }).Interface().(func() io.Writer)
2318 // Channels should be promotable to directional channels.
2319 var h func() <-chan int
2320 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2321 return []Value{ValueOf(make(chan int))}
2322 }).Interface().(func() <-chan int)
2325 // Unnamed types should be promotable to named types.
2326 type T struct{ a, b, c int }
2328 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2329 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2330 }).Interface().(func() T)
2334 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2335 // Type doesn't implement the required interface.
2336 shouldPanic("", func() {
2338 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2339 return []Value{ValueOf(int(7))}
2340 }).Interface().(func() error)
2343 // Assigning to an interface with additional methods.
2344 shouldPanic("", func() {
2345 var f func() io.ReadWriteCloser
2346 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2347 var w io.WriteCloser = &WC{}
2348 return []Value{ValueOf(&w).Elem()}
2349 }).Interface().(func() io.ReadWriteCloser)
2352 // Directional channels can't be assigned to bidirectional ones.
2353 shouldPanic("", func() {
2354 var f func() chan int
2355 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2356 var c <-chan int = make(chan int)
2357 return []Value{ValueOf(c)}
2358 }).Interface().(func() chan int)
2361 // Two named types which are otherwise identical.
2362 shouldPanic("", func() {
2363 type T struct{ a, b, c int }
2364 type U struct{ a, b, c int }
2366 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2367 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2368 }).Interface().(func() T)
2377 // This will be index 0.
2378 func (p Point) AnotherMethod(scale int) int {
2382 // This will be index 1.
2383 func (p Point) Dist(scale int) int {
2384 //println("Point.Dist", p.x, p.y, scale)
2385 return p.x*p.x*scale + p.y*p.y*scale
2388 // This will be index 2.
2389 func (p Point) GCMethod(k int) int {
2394 // This will be index 3.
2395 func (p Point) NoArgs() {
2396 // Exercise no-argument/no-result paths.
2399 // This will be index 4.
2400 func (p Point) TotalDist(points ...Point) int {
2402 for _, q := range points {
2405 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2411 // This will be index 5.
2412 func (p *Point) Int64Method(x int64) int64 {
2416 // This will be index 6.
2417 func (p *Point) Int32Method(x int32) int32 {
2421 func TestMethod(t *testing.T) {
2422 // Non-curried method of type.
2424 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2426 t.Errorf("Type Method returned %d; want 250", i)
2429 m, ok := TypeOf(p).MethodByName("Dist")
2431 t.Fatalf("method by name failed")
2433 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2435 t.Errorf("Type MethodByName returned %d; want 275", i)
2438 m, ok = TypeOf(p).MethodByName("NoArgs")
2440 t.Fatalf("method by name failed")
2442 n := len(m.Func.Call([]Value{ValueOf(p)}))
2444 t.Errorf("NoArgs returned %d values; want 0", n)
2447 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2449 t.Errorf("Pointer Type Method returned %d; want 300", i)
2452 m, ok = TypeOf(&p).MethodByName("Dist")
2454 t.Fatalf("ptr method by name failed")
2456 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2458 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2461 m, ok = TypeOf(&p).MethodByName("NoArgs")
2463 t.Fatalf("method by name failed")
2465 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2467 t.Errorf("NoArgs returned %d values; want 0", n)
2470 _, ok = TypeOf(&p).MethodByName("AA")
2472 t.Errorf(`MethodByName("AA") should have failed`)
2475 _, ok = TypeOf(&p).MethodByName("ZZ")
2477 t.Errorf(`MethodByName("ZZ") should have failed`)
2480 // Curried method of value.
2481 tfunc := TypeOf((func(int) int)(nil))
2482 v := ValueOf(p).Method(1)
2483 if tt := v.Type(); tt != tfunc {
2484 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2486 i = v.Call([]Value{ValueOf(14)})[0].Int()
2488 t.Errorf("Value Method returned %d; want 350", i)
2490 v = ValueOf(p).MethodByName("Dist")
2491 if tt := v.Type(); tt != tfunc {
2492 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2494 i = v.Call([]Value{ValueOf(15)})[0].Int()
2496 t.Errorf("Value MethodByName returned %d; want 375", i)
2498 v = ValueOf(p).MethodByName("NoArgs")
2501 // Curried method of pointer.
2502 v = ValueOf(&p).Method(1)
2503 if tt := v.Type(); tt != tfunc {
2504 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2506 i = v.Call([]Value{ValueOf(16)})[0].Int()
2508 t.Errorf("Pointer Value Method returned %d; want 400", i)
2510 v = ValueOf(&p).MethodByName("Dist")
2511 if tt := v.Type(); tt != tfunc {
2512 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2514 i = v.Call([]Value{ValueOf(17)})[0].Int()
2516 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2518 v = ValueOf(&p).MethodByName("NoArgs")
2521 // Curried method of interface value.
2522 // Have to wrap interface value in a struct to get at it.
2523 // Passing it to ValueOf directly would
2524 // access the underlying Point, not the interface.
2528 pv := ValueOf(&x).Elem()
2530 if tt := v.Type(); tt != tfunc {
2531 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2533 i = v.Call([]Value{ValueOf(18)})[0].Int()
2535 t.Errorf("Interface Method returned %d; want 450", i)
2537 v = pv.MethodByName("Dist")
2538 if tt := v.Type(); tt != tfunc {
2539 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2541 i = v.Call([]Value{ValueOf(19)})[0].Int()
2543 t.Errorf("Interface MethodByName returned %d; want 475", i)
2547 func TestMethodValue(t *testing.T) {
2551 // Check that method value have the same underlying code pointers.
2552 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2553 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2556 // Curried method of value.
2557 tfunc := TypeOf((func(int) int)(nil))
2558 v := ValueOf(p).Method(1)
2559 if tt := v.Type(); tt != tfunc {
2560 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2562 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2564 t.Errorf("Value Method returned %d; want 250", i)
2566 v = ValueOf(p).MethodByName("Dist")
2567 if tt := v.Type(); tt != tfunc {
2568 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2570 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2572 t.Errorf("Value MethodByName returned %d; want 275", i)
2574 v = ValueOf(p).MethodByName("NoArgs")
2575 ValueOf(v.Interface()).Call(nil)
2576 v.Interface().(func())()
2578 // Curried method of pointer.
2579 v = ValueOf(&p).Method(1)
2580 if tt := v.Type(); tt != tfunc {
2581 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2583 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2585 t.Errorf("Pointer Value Method returned %d; want 300", i)
2587 v = ValueOf(&p).MethodByName("Dist")
2588 if tt := v.Type(); tt != tfunc {
2589 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2591 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2593 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2595 v = ValueOf(&p).MethodByName("NoArgs")
2596 ValueOf(v.Interface()).Call(nil)
2597 v.Interface().(func())()
2599 // Curried method of pointer to pointer.
2601 v = ValueOf(&pp).Elem().Method(1)
2602 if tt := v.Type(); tt != tfunc {
2603 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2605 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2607 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2609 v = ValueOf(&pp).Elem().MethodByName("Dist")
2610 if tt := v.Type(); tt != tfunc {
2611 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2613 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2615 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2618 // Curried method of interface value.
2619 // Have to wrap interface value in a struct to get at it.
2620 // Passing it to ValueOf directly would
2621 // access the underlying Point, not the interface.
2627 pv := ValueOf(s).Field(0)
2629 if tt := v.Type(); tt != tfunc {
2630 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2632 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2634 t.Errorf("Interface Method returned %d; want 400", i)
2636 v = pv.MethodByName("Dist")
2637 if tt := v.Type(); tt != tfunc {
2638 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2640 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2642 t.Errorf("Interface MethodByName returned %d; want 425", i)
2645 // For issue #33628: method args are not stored at the right offset
2647 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2648 if x := m64(123); x != 123 {
2649 t.Errorf("Int64Method returned %d; want 123", x)
2651 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2652 if x := m32(456); x != 456 {
2653 t.Errorf("Int32Method returned %d; want 456", x)
2657 func TestVariadicMethodValue(t *testing.T) {
2659 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2660 want := int64(p.TotalDist(points[0], points[1], points[2]))
2662 // Variadic method of type.
2663 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2664 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2665 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2668 // Curried method of value.
2669 tfunc = TypeOf((func(...Point) int)(nil))
2670 v := ValueOf(p).Method(4)
2671 if tt := v.Type(); tt != tfunc {
2672 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2674 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2676 t.Errorf("Variadic Method returned %d; want %d", i, want)
2678 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2680 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2683 f := v.Interface().(func(...Point) int)
2684 i = int64(f(points[0], points[1], points[2]))
2686 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2688 i = int64(f(points...))
2690 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2694 type DirectIfaceT struct {
2698 func (d DirectIfaceT) M() int { return *d.p }
2700 func TestDirectIfaceMethod(t *testing.T) {
2702 v := DirectIfaceT{&x}
2704 m, ok := typ.MethodByName("M")
2706 t.Fatalf("cannot find method M")
2708 in := []Value{ValueOf(v)}
2709 out := m.Func.Call(in)
2710 if got := out[0].Int(); got != 42 {
2711 t.Errorf("Call with value receiver got %d, want 42", got)
2716 m, ok = typ.MethodByName("M")
2718 t.Fatalf("cannot find method M")
2720 in = []Value{ValueOf(pv)}
2721 out = m.Func.Call(in)
2722 if got := out[0].Int(); got != 42 {
2723 t.Errorf("Call with pointer receiver got %d, want 42", got)
2727 // Reflect version of $GOROOT/test/method5.go
2729 // Concrete types implementing M method.
2730 // Smaller than a word, word-sized, larger than a word.
2731 // Value and pointer receivers.
2733 type Tinter interface {
2734 M(int, byte) (byte, int)
2739 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2743 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2747 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2751 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2753 type Tbigv [2]uintptr
2755 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2757 type Tbigp [2]uintptr
2759 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2761 type tinter interface {
2762 m(int, byte) (byte, int)
2765 // Embedding via pointer.
2782 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2784 func TestMethod5(t *testing.T) {
2785 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2787 if b != 99 || x != 1000+inc {
2788 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2792 CheckV := func(name string, i Value, inc int) {
2793 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2794 b := bx[0].Interface()
2795 x := bx[1].Interface()
2796 if b != byte(99) || x != 1000+inc {
2797 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2800 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2803 var TinterType = TypeOf(new(Tinter)).Elem()
2805 CheckI := func(name string, i any, inc int) {
2807 CheckV(name, v, inc)
2808 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2813 CheckI("&sv", &sv, 1)
2816 CheckI("&sp", &sp, 2)
2820 CheckI("&wv", &wv, 3)
2823 CheckI("&wp", &wp, 4)
2825 bv := Tbigv([2]uintptr{5, 6})
2826 CheckI("bv", bv, 11)
2827 CheckI("&bv", &bv, 11)
2829 bp := Tbigp([2]uintptr{7, 8})
2830 CheckI("&bp", &bp, 15)
2836 CheckI("t4", t4, 40)
2837 CheckI("&t4", &t4, 40)
2838 CheckI("t3", t3, 40)
2839 CheckI("&t3", &t3, 40)
2840 CheckI("t2", t2, 40)
2841 CheckI("&t2", &t2, 40)
2842 CheckI("t1", t1, 40)
2843 CheckI("&t1", &t1, 40)
2846 vnil := ValueOf(&tnil).Elem()
2847 shouldPanic("Method", func() { vnil.Method(0) })
2850 func TestInterfaceSet(t *testing.T) {
2859 sv := ValueOf(&s).Elem()
2860 sv.Field(0).Set(ValueOf(p))
2861 if q := s.I.(*Point); q != p {
2862 t.Errorf("i: have %p want %p", q, p)
2867 if q := s.P.(*Point); q != p {
2868 t.Errorf("i: have %p want %p", q, p)
2871 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2873 t.Errorf("Interface Method returned %d; want 250", i)
2882 func TestAnonymousFields(t *testing.T) {
2883 var field StructField
2887 if field, ok = type1.FieldByName("int"); !ok {
2888 t.Fatal("no field 'int'")
2890 if field.Index[0] != 1 {
2891 t.Error("field index should be 1; is", field.Index)
2945 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2967 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2986 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
3000 var fieldTests = []FTest{
3001 {struct{}{}, "", nil, 0},
3002 {struct{}{}, "Foo", nil, 0},
3003 {S0{A: 'a'}, "A", []int{0}, 'a'},
3004 {S0{}, "D", nil, 0},
3005 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
3006 {S1{B: 'b'}, "B", []int{0}, 'b'},
3007 {S1{}, "S0", []int{1}, 0},
3008 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
3009 {S2{A: 'a'}, "A", []int{0}, 'a'},
3010 {S2{}, "S1", []int{1}, 0},
3011 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
3012 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
3013 {S2{}, "D", nil, 0},
3014 {S3{}, "S1", nil, 0},
3015 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
3016 {S3{}, "B", nil, 0},
3017 {S3{D: 'd'}, "D", []int{2}, 0},
3018 {S3{E: 'e'}, "E", []int{3}, 'e'},
3019 {S4{A: 'a'}, "A", []int{1}, 'a'},
3020 {S4{}, "B", nil, 0},
3021 {S5{}, "X", nil, 0},
3022 {S5{}, "Y", []int{2, 0, 1}, 0},
3023 {S10{}, "X", nil, 0},
3024 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
3025 {S14{}, "X", nil, 0},
3028 func TestFieldByIndex(t *testing.T) {
3029 for _, test := range fieldTests {
3031 f := s.FieldByIndex(test.index)
3033 if test.index != nil {
3034 if f.Name != test.name {
3035 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3038 t.Errorf("%s.%s found", s.Name(), f.Name)
3040 } else if len(test.index) > 0 {
3041 t.Errorf("%s.%s not found", s.Name(), test.name)
3044 if test.value != 0 {
3045 v := ValueOf(test.s).FieldByIndex(test.index)
3047 if x, ok := v.Interface().(int); ok {
3048 if x != test.value {
3049 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3052 t.Errorf("%s%v value not an int", s.Name(), test.index)
3055 t.Errorf("%s%v value not found", s.Name(), test.index)
3061 func TestFieldByName(t *testing.T) {
3062 for _, test := range fieldTests {
3064 f, found := s.FieldByName(test.name)
3066 if test.index != nil {
3067 // Verify field depth and index.
3068 if len(f.Index) != len(test.index) {
3069 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)
3071 for i, x := range f.Index {
3072 if x != test.index[i] {
3073 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3078 t.Errorf("%s.%s found", s.Name(), f.Name)
3080 } else if len(test.index) > 0 {
3081 t.Errorf("%s.%s not found", s.Name(), test.name)
3084 if test.value != 0 {
3085 v := ValueOf(test.s).FieldByName(test.name)
3087 if x, ok := v.Interface().(int); ok {
3088 if x != test.value {
3089 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3092 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3095 t.Errorf("%s.%s value not found", s.Name(), test.name)
3101 func TestImportPath(t *testing.T) {
3106 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3107 {TypeOf(int(0)), ""},
3108 {TypeOf(int8(0)), ""},
3109 {TypeOf(int16(0)), ""},
3110 {TypeOf(int32(0)), ""},
3111 {TypeOf(int64(0)), ""},
3112 {TypeOf(uint(0)), ""},
3113 {TypeOf(uint8(0)), ""},
3114 {TypeOf(uint16(0)), ""},
3115 {TypeOf(uint32(0)), ""},
3116 {TypeOf(uint64(0)), ""},
3117 {TypeOf(uintptr(0)), ""},
3118 {TypeOf(float32(0)), ""},
3119 {TypeOf(float64(0)), ""},
3120 {TypeOf(complex64(0)), ""},
3121 {TypeOf(complex128(0)), ""},
3122 {TypeOf(byte(0)), ""},
3123 {TypeOf(rune(0)), ""},
3124 {TypeOf([]byte(nil)), ""},
3125 {TypeOf([]rune(nil)), ""},
3126 {TypeOf(string("")), ""},
3127 {TypeOf((*any)(nil)).Elem(), ""},
3128 {TypeOf((*byte)(nil)), ""},
3129 {TypeOf((*rune)(nil)), ""},
3130 {TypeOf((*int64)(nil)), ""},
3131 {TypeOf(map[string]int{}), ""},
3132 {TypeOf((*error)(nil)).Elem(), ""},
3133 {TypeOf((*Point)(nil)), ""},
3134 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3136 for _, test := range tests {
3137 if path := test.t.PkgPath(); path != test.path {
3138 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3143 func TestFieldPkgPath(t *testing.T) {
3145 typ := TypeOf(struct {
3153 type pkgpathTest struct {
3160 checkPkgPath := func(name string, s []pkgpathTest) {
3161 for _, test := range s {
3162 f := typ.FieldByIndex(test.index)
3163 if got, want := f.PkgPath, test.pkgPath; got != want {
3164 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3166 if got, want := f.Anonymous, test.embedded; got != want {
3167 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3169 if got, want := f.IsExported(), test.exported; got != want {
3170 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3175 checkPkgPath("testStruct", []pkgpathTest{
3176 {[]int{0}, "", false, true}, // Exported
3177 {[]int{1}, "reflect_test", false, false}, // unexported
3178 {[]int{2}, "", true, true}, // OtherPkgFields
3179 {[]int{2, 0}, "", false, true}, // OtherExported
3180 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3181 {[]int{3}, "reflect_test", true, false}, // int
3182 {[]int{4}, "reflect_test", true, false}, // *x
3185 type localOtherPkgFields OtherPkgFields
3186 typ = TypeOf(localOtherPkgFields{})
3187 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3188 {[]int{0}, "", false, true}, // OtherExported
3189 {[]int{1}, "reflect", false, false}, // otherUnexported
3193 func TestMethodPkgPath(t *testing.T) {
3198 typ := TypeOf((*interface {
3211 {"x", "reflect_test", false},
3212 {"y", "reflect_test", false},
3215 for _, test := range tests {
3216 m, _ := typ.MethodByName(test.name)
3217 if got, want := m.PkgPath, test.pkgPath; got != want {
3218 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3220 if got, want := m.IsExported(), test.exported; got != want {
3221 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3226 func TestVariadicType(t *testing.T) {
3227 // Test example from Type documentation.
3228 var f func(x int, y ...float64)
3230 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3232 if sl.Kind() == Slice {
3233 if sl.Elem() == TypeOf(0.0) {
3241 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3242 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3243 for i := 0; i < typ.NumIn(); i++ {
3244 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3258 func (*inner) M() {}
3259 func (*outer) M() {}
3261 func TestNestedMethods(t *testing.T) {
3262 typ := TypeOf((*outer)(nil))
3263 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3264 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3265 for i := 0; i < typ.NumMethod(); i++ {
3267 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3274 func (*unexp) f() (int32, int8) { return 7, 7 }
3275 func (*unexp) g() (int64, int8) { return 8, 8 }
3277 type unexpI interface {
3281 var unexpi unexpI = new(unexp)
3283 func TestUnexportedMethods(t *testing.T) {
3284 typ := TypeOf(unexpi)
3286 if got := typ.NumMethod(); got != 0 {
3287 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3291 type InnerInt struct {
3295 type OuterInt struct {
3300 func (i *InnerInt) M() int {
3304 func TestEmbeddedMethods(t *testing.T) {
3305 typ := TypeOf((*OuterInt)(nil))
3306 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3307 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3308 for i := 0; i < typ.NumMethod(); i++ {
3310 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3315 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3316 t.Errorf("i.M() = %d, want 3", v)
3319 o := &OuterInt{1, InnerInt{2}}
3320 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3321 t.Errorf("i.M() = %d, want 2", v)
3325 if v := f(o); v != 2 {
3326 t.Errorf("f(o) = %d, want 2", v)
3330 type FuncDDD func(...any) error
3332 func (f FuncDDD) M() {}
3334 func TestNumMethodOnDDD(t *testing.T) {
3335 rv := ValueOf((FuncDDD)(nil))
3336 if n := rv.NumMethod(); n != 1 {
3337 t.Fatalf("NumMethod()=%d, want 1", n)
3341 func TestPtrTo(t *testing.T) {
3342 // This block of code means that the ptrToThis field of the
3343 // reflect data for *unsafe.Pointer is non zero, see
3344 // https://golang.org/issue/19003
3345 var x unsafe.Pointer
3352 for i = 0; i < 100; i++ {
3353 typ = PointerTo(typ)
3355 for i = 0; i < 100; i++ {
3358 if typ != TypeOf(z) {
3359 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3363 func TestPtrToGC(t *testing.T) {
3365 tt := TypeOf(T(nil))
3369 for i := 0; i < n; i++ {
3374 v.Elem().Set(ValueOf(p).Convert(pt))
3375 x = append(x, v.Interface())
3379 for i, xi := range x {
3380 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3381 if k != uintptr(i) {
3382 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3387 func TestAddr(t *testing.T) {
3399 t.Errorf("Addr.Elem.Set failed to set value")
3402 // Again but take address of the ValueOf value.
3403 // Exercises generation of PtrTypes not present in the binary.
3405 v = ValueOf(&q).Elem()
3414 t.Errorf("Addr.Elem.Set failed to set value")
3417 // Starting without pointer we should get changed value
3420 v = ValueOf(&qq).Elem()
3426 if p.X != 3 { // should be unchanged from last time
3427 t.Errorf("somehow value Set changed original p")
3429 p = v0.Interface().(struct {
3433 t.Errorf("Addr.Elem.Set valued to set value in top value")
3436 // Verify that taking the address of a type gives us a pointer
3437 // which we can convert back using the usual interface
3442 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3443 *(ps.(**bool)) = new(bool)
3445 t.Errorf("Addr.Interface direct assignment failed")
3449 func noAlloc(t *testing.T, n int, f func(int)) {
3450 if testing.Short() {
3451 t.Skip("skipping malloc count in short mode")
3453 if runtime.GOMAXPROCS(0) > 1 {
3454 t.Skip("skipping; GOMAXPROCS>1")
3457 allocs := testing.AllocsPerRun(n, func() {
3462 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3466 func TestAllocations(t *testing.T) {
3467 noAlloc(t, 100, func(j int) {
3471 // We can uncomment this when compiler escape analysis
3472 // is good enough to see that the integer assigned to i
3473 // does not escape and therefore need not be allocated.
3477 // if int(v.Int()) != 42+j {
3478 // panic("wrong int")
3481 i = func(j int) int { return j }
3483 if v.Interface().(func(int) int)(j) != j {
3484 panic("wrong result")
3489 func TestSmallNegativeInt(t *testing.T) {
3493 t.Errorf("int16(-1).Int() returned %v", v.Int())
3497 func TestIndex(t *testing.T) {
3498 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3499 v := ValueOf(xs).Index(3).Interface().(byte)
3501 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3503 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3504 v = ValueOf(xa).Index(2).Interface().(byte)
3506 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3509 v = ValueOf(s).Index(3).Interface().(byte)
3511 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3515 func TestSlice(t *testing.T) {
3516 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3517 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3519 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3522 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3524 if !DeepEqual(v[0:5], xs[3:]) {
3525 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3527 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3528 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3530 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3533 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3535 if !DeepEqual(v[0:6], xa[2:]) {
3536 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3539 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3541 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3544 rv := ValueOf(&xs).Elem()
3546 ptr2 := rv.UnsafePointer()
3548 ptr3 := rv.UnsafePointer()
3550 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3554 func TestSlice3(t *testing.T) {
3555 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3556 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3558 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3561 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3563 if !DeepEqual(v[0:4], xs[3:7:7]) {
3564 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3566 rv := ValueOf(&xs).Elem()
3567 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3568 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3569 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3571 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3572 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3574 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3577 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3579 if !DeepEqual(v[0:4], xa[2:6:6]) {
3580 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3582 rv = ValueOf(&xa).Elem()
3583 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3584 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3585 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3588 rv = ValueOf(&s).Elem()
3589 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3591 rv = ValueOf(&xs).Elem()
3592 rv = rv.Slice3(3, 5, 7)
3593 ptr2 := rv.UnsafePointer()
3594 rv = rv.Slice3(4, 4, 4)
3595 ptr3 := rv.UnsafePointer()
3597 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3601 func TestSetLenCap(t *testing.T) {
3602 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3603 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3605 vs := ValueOf(&xs).Elem()
3606 shouldPanic("SetLen", func() { vs.SetLen(10) })
3607 shouldPanic("SetCap", func() { vs.SetCap(10) })
3608 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3609 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3610 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3612 if len(xs) != 5 || cap(xs) != 8 {
3613 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3616 if len(xs) != 5 || cap(xs) != 6 {
3617 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3620 if len(xs) != 5 || cap(xs) != 5 {
3621 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3623 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3624 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3626 va := ValueOf(&xa).Elem()
3627 shouldPanic("SetLen", func() { va.SetLen(8) })
3628 shouldPanic("SetCap", func() { va.SetCap(8) })
3631 func TestVariadic(t *testing.T) {
3632 var b strings.Builder
3636 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3637 if b.String() != "hello, 42 world" {
3638 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3642 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3643 if b.String() != "hello, 42 world" {
3644 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3648 func TestFuncArg(t *testing.T) {
3649 f1 := func(i int, f func(int) int) int { return f(i) }
3650 f2 := func(i int) int { return i + 1 }
3651 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3652 if r[0].Int() != 101 {
3653 t.Errorf("function returned %d, want 101", r[0].Int())
3657 func TestStructArg(t *testing.T) {
3658 type padded struct {
3665 wantA = padded{"3", 4}
3668 f := func(a padded, b uint32) {
3671 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3672 if gotA != wantA || gotB != wantB {
3673 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3677 var tagGetTests = []struct {
3682 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3683 {`protobuf:"PB(1,2)"`, `foo`, ``},
3684 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3685 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3686 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3687 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3688 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3691 func TestTagGet(t *testing.T) {
3692 for _, tt := range tagGetTests {
3693 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3694 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3699 func TestBytes(t *testing.T) {
3700 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3701 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3705 y := ValueOf(x).Bytes()
3706 if !bytes.Equal(x, y) {
3707 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3710 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3715 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3716 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3717 b := ValueOf(&a).Elem().Bytes()
3718 if !bytes.Equal(a[:], y) {
3719 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3722 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3725 // Per issue #24746, it was decided that Bytes can be called on byte slices
3726 // that normally cannot be converted from per Go language semantics.
3730 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3731 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3732 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3733 ValueOf(new(AB)).Elem().Bytes() // should not panic
3736 func TestSetBytes(t *testing.T) {
3739 y := []byte{1, 2, 3, 4}
3740 ValueOf(&x).Elem().SetBytes(y)
3741 if !bytes.Equal(x, y) {
3742 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3745 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3749 type Private struct {
3755 func (p *Private) m() {
3758 type private struct {
3766 func (p *private) P() {
3769 type Public struct {
3775 func (p *Public) M() {
3778 func TestUnexported(t *testing.T) {
3783 isValid(v.Elem().Field(0))
3784 isValid(v.Elem().Field(1))
3785 isValid(v.Elem().Field(2))
3786 isValid(v.Elem().FieldByName("X"))
3787 isValid(v.Elem().FieldByName("Y"))
3788 isValid(v.Elem().FieldByName("Z"))
3789 isValid(v.Type().Method(0).Func)
3790 m, _ := v.Type().MethodByName("M")
3792 m, _ = v.Type().MethodByName("P")
3794 isNonNil(v.Elem().Field(0).Interface())
3795 isNonNil(v.Elem().Field(1).Interface())
3796 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3797 isNonNil(v.Elem().FieldByName("X").Interface())
3798 isNonNil(v.Elem().FieldByName("Y").Interface())
3799 isNonNil(v.Elem().FieldByName("Z").Interface())
3800 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3801 isNonNil(v.Type().Method(0).Func.Interface())
3802 m, _ = v.Type().MethodByName("P")
3803 isNonNil(m.Func.Interface())
3807 isValid(v.Elem().Field(0))
3808 isValid(v.Elem().Field(1))
3809 isValid(v.Elem().FieldByName("x"))
3810 isValid(v.Elem().FieldByName("y"))
3811 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3812 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3813 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3814 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3815 shouldPanic("Method", func() { v.Type().Method(0) })
3818 func TestSetPanic(t *testing.T) {
3819 ok := func(f func()) { f() }
3820 bad := func(f func()) { shouldPanic("Set", f) }
3821 clear := func(v Value) { v.Set(Zero(v.Type())) }
3849 bad(func() { clear(v.Field(0)) }) // .X
3850 bad(func() { clear(v.Field(1)) }) // .t1
3851 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3852 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3853 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3854 bad(func() { clear(v.Field(2)) }) // .T2
3855 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3856 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3857 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3858 bad(func() { clear(v.Field(3)) }) // .NamedT1
3859 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3860 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3861 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3862 bad(func() { clear(v.Field(4)) }) // .NamedT2
3863 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3864 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3865 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3866 bad(func() { clear(v.Field(5)) }) // .namedT1
3867 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3868 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3869 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3870 bad(func() { clear(v.Field(6)) }) // .namedT2
3871 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3872 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3873 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3876 v = ValueOf(&T{}).Elem()
3877 ok(func() { clear(v.Field(0)) }) // .X
3878 bad(func() { clear(v.Field(1)) }) // .t1
3879 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3880 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3881 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3882 ok(func() { clear(v.Field(2)) }) // .T2
3883 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3884 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3885 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3886 ok(func() { clear(v.Field(3)) }) // .NamedT1
3887 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3888 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3889 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3890 ok(func() { clear(v.Field(4)) }) // .NamedT2
3891 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3892 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3893 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3894 bad(func() { clear(v.Field(5)) }) // .namedT1
3895 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3896 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3897 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3898 bad(func() { clear(v.Field(6)) }) // .namedT2
3899 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3900 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3901 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3906 func (t timp) W() {}
3907 func (t timp) Y() {}
3908 func (t timp) w() {}
3909 func (t timp) y() {}
3911 func TestCallPanic(t *testing.T) {
3936 ok := func(f func()) { f() }
3937 badCall := func(f func()) { shouldPanic("Call", f) }
3938 badMethod := func(f func()) { shouldPanic("Method", f) }
3939 call := func(v Value) { v.Call(nil) }
3942 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3943 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3944 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3945 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3946 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3947 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3948 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3949 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3950 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3952 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3953 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3954 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3955 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3957 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3958 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3959 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3960 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3962 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3963 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3964 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3965 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3967 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3968 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3969 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3970 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3972 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3973 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3974 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3975 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3977 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3978 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3979 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3980 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3983 func TestValuePanic(t *testing.T) {
3985 shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
3986 shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
3987 shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
3988 shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
3989 shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
3990 shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
3991 shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
3992 shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
3993 shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
3994 shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
3995 shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
3996 shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
3997 shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
3998 shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
3999 shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
4000 shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
4001 shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
4002 shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
4003 shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
4004 shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
4005 shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
4006 shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
4007 shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
4008 shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
4009 shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
4010 shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
4011 shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
4012 shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
4013 shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
4014 shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
4015 shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
4016 shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
4017 shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
4018 shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
4019 shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
4020 shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
4021 shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
4022 shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
4023 shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
4024 shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
4025 shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
4028 func shouldPanic(expect string, f func()) {
4032 panic("did not panic")
4036 switch r := r.(type) {
4042 panic(fmt.Sprintf("panicked with unexpected type %T", r))
4044 if !strings.HasPrefix(s, "reflect") {
4045 panic(`panic string does not start with "reflect": ` + s)
4047 if !strings.Contains(s, expect) {
4048 panic(`panic string does not contain "` + expect + `": ` + s)
4055 func isNonNil(x any) {
4057 panic("nil interface")
4061 func isValid(v Value) {
4067 func TestAlias(t *testing.T) {
4068 x := string("hello")
4069 v := ValueOf(&x).Elem()
4070 oldvalue := v.Interface()
4071 v.SetString("world")
4072 newvalue := v.Interface()
4074 if oldvalue != "hello" || newvalue != "world" {
4075 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
4081 func EmptyInterfaceV(x any) Value {
4082 return ValueOf(&x).Elem()
4085 func ReaderV(x io.Reader) Value {
4086 return ValueOf(&x).Elem()
4089 func ReadWriterV(x io.ReadWriter) Value {
4090 return ValueOf(&x).Elem()
4094 type MyStruct struct {
4097 type MyStruct1 struct {
4102 type MyStruct2 struct {
4107 type MyString string
4109 type MyBytesArrayPtr0 *[0]byte
4110 type MyBytesArrayPtr *[4]byte
4111 type MyBytesArray0 [0]byte
4112 type MyBytesArray [4]byte
4113 type MyRunes []int32
4117 type IntChan chan int
4118 type IntChanRecv <-chan int
4119 type IntChanSend chan<- int
4120 type BytesChan chan []byte
4121 type BytesChanRecv <-chan []byte
4122 type BytesChanSend chan<- []byte
4124 var convertTests = []struct {
4130 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4136 var numbers = []string{
4137 "int8", "uint8", "int16", "uint16",
4138 "int32", "uint32", "int64", "uint64",
4139 "int", "uint", "uintptr",
4140 "float32", "float64",
4144 // all pairs but in an unusual order,
4145 // to emit all the int8, uint8 cases
4146 // before n grows too big.
4148 for i, f := range numbers {
4149 for _, g := range numbers[i:] {
4150 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4153 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4160 {V(int8(1)), V(int8(1))},
4161 {V(int8(2)), V(uint8(2))},
4162 {V(uint8(3)), V(int8(3))},
4163 {V(int8(4)), V(int16(4))},
4164 {V(int16(5)), V(int8(5))},
4165 {V(int8(6)), V(uint16(6))},
4166 {V(uint16(7)), V(int8(7))},
4167 {V(int8(8)), V(int32(8))},
4168 {V(int32(9)), V(int8(9))},
4169 {V(int8(10)), V(uint32(10))},
4170 {V(uint32(11)), V(int8(11))},
4171 {V(int8(12)), V(int64(12))},
4172 {V(int64(13)), V(int8(13))},
4173 {V(int8(14)), V(uint64(14))},
4174 {V(uint64(15)), V(int8(15))},
4175 {V(int8(16)), V(int(16))},
4176 {V(int(17)), V(int8(17))},
4177 {V(int8(18)), V(uint(18))},
4178 {V(uint(19)), V(int8(19))},
4179 {V(int8(20)), V(uintptr(20))},
4180 {V(uintptr(21)), V(int8(21))},
4181 {V(int8(22)), V(float32(22))},
4182 {V(float32(23)), V(int8(23))},
4183 {V(int8(24)), V(float64(24))},
4184 {V(float64(25)), V(int8(25))},
4185 {V(uint8(26)), V(uint8(26))},
4186 {V(uint8(27)), V(int16(27))},
4187 {V(int16(28)), V(uint8(28))},
4188 {V(uint8(29)), V(uint16(29))},
4189 {V(uint16(30)), V(uint8(30))},
4190 {V(uint8(31)), V(int32(31))},
4191 {V(int32(32)), V(uint8(32))},
4192 {V(uint8(33)), V(uint32(33))},
4193 {V(uint32(34)), V(uint8(34))},
4194 {V(uint8(35)), V(int64(35))},
4195 {V(int64(36)), V(uint8(36))},
4196 {V(uint8(37)), V(uint64(37))},
4197 {V(uint64(38)), V(uint8(38))},
4198 {V(uint8(39)), V(int(39))},
4199 {V(int(40)), V(uint8(40))},
4200 {V(uint8(41)), V(uint(41))},
4201 {V(uint(42)), V(uint8(42))},
4202 {V(uint8(43)), V(uintptr(43))},
4203 {V(uintptr(44)), V(uint8(44))},
4204 {V(uint8(45)), V(float32(45))},
4205 {V(float32(46)), V(uint8(46))},
4206 {V(uint8(47)), V(float64(47))},
4207 {V(float64(48)), V(uint8(48))},
4208 {V(int16(49)), V(int16(49))},
4209 {V(int16(50)), V(uint16(50))},
4210 {V(uint16(51)), V(int16(51))},
4211 {V(int16(52)), V(int32(52))},
4212 {V(int32(53)), V(int16(53))},
4213 {V(int16(54)), V(uint32(54))},
4214 {V(uint32(55)), V(int16(55))},
4215 {V(int16(56)), V(int64(56))},
4216 {V(int64(57)), V(int16(57))},
4217 {V(int16(58)), V(uint64(58))},
4218 {V(uint64(59)), V(int16(59))},
4219 {V(int16(60)), V(int(60))},
4220 {V(int(61)), V(int16(61))},
4221 {V(int16(62)), V(uint(62))},
4222 {V(uint(63)), V(int16(63))},
4223 {V(int16(64)), V(uintptr(64))},
4224 {V(uintptr(65)), V(int16(65))},
4225 {V(int16(66)), V(float32(66))},
4226 {V(float32(67)), V(int16(67))},
4227 {V(int16(68)), V(float64(68))},
4228 {V(float64(69)), V(int16(69))},
4229 {V(uint16(70)), V(uint16(70))},
4230 {V(uint16(71)), V(int32(71))},
4231 {V(int32(72)), V(uint16(72))},
4232 {V(uint16(73)), V(uint32(73))},
4233 {V(uint32(74)), V(uint16(74))},
4234 {V(uint16(75)), V(int64(75))},
4235 {V(int64(76)), V(uint16(76))},
4236 {V(uint16(77)), V(uint64(77))},
4237 {V(uint64(78)), V(uint16(78))},
4238 {V(uint16(79)), V(int(79))},
4239 {V(int(80)), V(uint16(80))},
4240 {V(uint16(81)), V(uint(81))},
4241 {V(uint(82)), V(uint16(82))},
4242 {V(uint16(83)), V(uintptr(83))},
4243 {V(uintptr(84)), V(uint16(84))},
4244 {V(uint16(85)), V(float32(85))},
4245 {V(float32(86)), V(uint16(86))},
4246 {V(uint16(87)), V(float64(87))},
4247 {V(float64(88)), V(uint16(88))},
4248 {V(int32(89)), V(int32(89))},
4249 {V(int32(90)), V(uint32(90))},
4250 {V(uint32(91)), V(int32(91))},
4251 {V(int32(92)), V(int64(92))},
4252 {V(int64(93)), V(int32(93))},
4253 {V(int32(94)), V(uint64(94))},
4254 {V(uint64(95)), V(int32(95))},
4255 {V(int32(96)), V(int(96))},
4256 {V(int(97)), V(int32(97))},
4257 {V(int32(98)), V(uint(98))},
4258 {V(uint(99)), V(int32(99))},
4259 {V(int32(100)), V(uintptr(100))},
4260 {V(uintptr(101)), V(int32(101))},
4261 {V(int32(102)), V(float32(102))},
4262 {V(float32(103)), V(int32(103))},
4263 {V(int32(104)), V(float64(104))},
4264 {V(float64(105)), V(int32(105))},
4265 {V(uint32(106)), V(uint32(106))},
4266 {V(uint32(107)), V(int64(107))},
4267 {V(int64(108)), V(uint32(108))},
4268 {V(uint32(109)), V(uint64(109))},
4269 {V(uint64(110)), V(uint32(110))},
4270 {V(uint32(111)), V(int(111))},
4271 {V(int(112)), V(uint32(112))},
4272 {V(uint32(113)), V(uint(113))},
4273 {V(uint(114)), V(uint32(114))},
4274 {V(uint32(115)), V(uintptr(115))},
4275 {V(uintptr(116)), V(uint32(116))},
4276 {V(uint32(117)), V(float32(117))},
4277 {V(float32(118)), V(uint32(118))},
4278 {V(uint32(119)), V(float64(119))},
4279 {V(float64(120)), V(uint32(120))},
4280 {V(int64(121)), V(int64(121))},
4281 {V(int64(122)), V(uint64(122))},
4282 {V(uint64(123)), V(int64(123))},
4283 {V(int64(124)), V(int(124))},
4284 {V(int(125)), V(int64(125))},
4285 {V(int64(126)), V(uint(126))},
4286 {V(uint(127)), V(int64(127))},
4287 {V(int64(128)), V(uintptr(128))},
4288 {V(uintptr(129)), V(int64(129))},
4289 {V(int64(130)), V(float32(130))},
4290 {V(float32(131)), V(int64(131))},
4291 {V(int64(132)), V(float64(132))},
4292 {V(float64(133)), V(int64(133))},
4293 {V(uint64(134)), V(uint64(134))},
4294 {V(uint64(135)), V(int(135))},
4295 {V(int(136)), V(uint64(136))},
4296 {V(uint64(137)), V(uint(137))},
4297 {V(uint(138)), V(uint64(138))},
4298 {V(uint64(139)), V(uintptr(139))},
4299 {V(uintptr(140)), V(uint64(140))},
4300 {V(uint64(141)), V(float32(141))},
4301 {V(float32(142)), V(uint64(142))},
4302 {V(uint64(143)), V(float64(143))},
4303 {V(float64(144)), V(uint64(144))},
4304 {V(int(145)), V(int(145))},
4305 {V(int(146)), V(uint(146))},
4306 {V(uint(147)), V(int(147))},
4307 {V(int(148)), V(uintptr(148))},
4308 {V(uintptr(149)), V(int(149))},
4309 {V(int(150)), V(float32(150))},
4310 {V(float32(151)), V(int(151))},
4311 {V(int(152)), V(float64(152))},
4312 {V(float64(153)), V(int(153))},
4313 {V(uint(154)), V(uint(154))},
4314 {V(uint(155)), V(uintptr(155))},
4315 {V(uintptr(156)), V(uint(156))},
4316 {V(uint(157)), V(float32(157))},
4317 {V(float32(158)), V(uint(158))},
4318 {V(uint(159)), V(float64(159))},
4319 {V(float64(160)), V(uint(160))},
4320 {V(uintptr(161)), V(uintptr(161))},
4321 {V(uintptr(162)), V(float32(162))},
4322 {V(float32(163)), V(uintptr(163))},
4323 {V(uintptr(164)), V(float64(164))},
4324 {V(float64(165)), V(uintptr(165))},
4325 {V(float32(166)), V(float32(166))},
4326 {V(float32(167)), V(float64(167))},
4327 {V(float64(168)), V(float32(168))},
4328 {V(float64(169)), V(float64(169))},
4331 {V(float64(1.5)), V(int(1))},
4334 {V(complex64(1i)), V(complex64(1i))},
4335 {V(complex64(2i)), V(complex128(2i))},
4336 {V(complex128(3i)), V(complex64(3i))},
4337 {V(complex128(4i)), V(complex128(4i))},
4340 {V(string("hello")), V(string("hello"))},
4341 {V(string("bytes1")), V([]byte("bytes1"))},
4342 {V([]byte("bytes2")), V(string("bytes2"))},
4343 {V([]byte("bytes3")), V([]byte("bytes3"))},
4344 {V(string("runes♝")), V([]rune("runes♝"))},
4345 {V([]rune("runes♕")), V(string("runes♕"))},
4346 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4347 {V(int('a')), V(string("a"))},
4348 {V(int8('a')), V(string("a"))},
4349 {V(int16('a')), V(string("a"))},
4350 {V(int32('a')), V(string("a"))},
4351 {V(int64('a')), V(string("a"))},
4352 {V(uint('a')), V(string("a"))},
4353 {V(uint8('a')), V(string("a"))},
4354 {V(uint16('a')), V(string("a"))},
4355 {V(uint32('a')), V(string("a"))},
4356 {V(uint64('a')), V(string("a"))},
4357 {V(uintptr('a')), V(string("a"))},
4358 {V(int(-1)), V(string("\uFFFD"))},
4359 {V(int8(-2)), V(string("\uFFFD"))},
4360 {V(int16(-3)), V(string("\uFFFD"))},
4361 {V(int32(-4)), V(string("\uFFFD"))},
4362 {V(int64(-5)), V(string("\uFFFD"))},
4363 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4364 {V(int64(1 << 32)), V(string("\uFFFD"))},
4365 {V(uint(0x110001)), V(string("\uFFFD"))},
4366 {V(uint32(0x110002)), V(string("\uFFFD"))},
4367 {V(uint64(0x110003)), V(string("\uFFFD"))},
4368 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4369 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4372 {V(MyString("hello")), V(string("hello"))},
4373 {V(string("hello")), V(MyString("hello"))},
4374 {V(string("hello")), V(string("hello"))},
4375 {V(MyString("hello")), V(MyString("hello"))},
4376 {V(MyString("bytes1")), V([]byte("bytes1"))},
4377 {V([]byte("bytes2")), V(MyString("bytes2"))},
4378 {V([]byte("bytes3")), V([]byte("bytes3"))},
4379 {V(MyString("runes♝")), V([]rune("runes♝"))},
4380 {V([]rune("runes♕")), V(MyString("runes♕"))},
4381 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4382 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4383 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4384 {V(int('a')), V(MyString("a"))},
4385 {V(int8('a')), V(MyString("a"))},
4386 {V(int16('a')), V(MyString("a"))},
4387 {V(int32('a')), V(MyString("a"))},
4388 {V(int64('a')), V(MyString("a"))},
4389 {V(uint('a')), V(MyString("a"))},
4390 {V(uint8('a')), V(MyString("a"))},
4391 {V(uint16('a')), V(MyString("a"))},
4392 {V(uint32('a')), V(MyString("a"))},
4393 {V(uint64('a')), V(MyString("a"))},
4394 {V(uintptr('a')), V(MyString("a"))},
4395 {V(int(-1)), V(MyString("\uFFFD"))},
4396 {V(int8(-2)), V(MyString("\uFFFD"))},
4397 {V(int16(-3)), V(MyString("\uFFFD"))},
4398 {V(int32(-4)), V(MyString("\uFFFD"))},
4399 {V(int64(-5)), V(MyString("\uFFFD"))},
4400 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4401 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4402 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4403 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4406 {V(string("bytes1")), V(MyBytes("bytes1"))},
4407 {V(MyBytes("bytes2")), V(string("bytes2"))},
4408 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4409 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4410 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4413 {V(string("runes♝")), V(MyRunes("runes♝"))},
4414 {V(MyRunes("runes♕")), V(string("runes♕"))},
4415 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4416 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4417 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4420 {V([]byte(nil)), V([0]byte{})},
4421 {V([]byte{}), V([0]byte{})},
4422 {V([]byte{1}), V([1]byte{1})},
4423 {V([]byte{1, 2}), V([2]byte{1, 2})},
4424 {V([]byte{1, 2, 3}), V([3]byte{1, 2, 3})},
4425 {V(MyBytes([]byte(nil))), V([0]byte{})},
4426 {V(MyBytes{}), V([0]byte{})},
4427 {V(MyBytes{1}), V([1]byte{1})},
4428 {V(MyBytes{1, 2}), V([2]byte{1, 2})},
4429 {V(MyBytes{1, 2, 3}), V([3]byte{1, 2, 3})},
4430 {V([]byte(nil)), V(MyBytesArray0{})},
4431 {V([]byte{}), V(MyBytesArray0([0]byte{}))},
4432 {V([]byte{1, 2, 3, 4}), V(MyBytesArray([4]byte{1, 2, 3, 4}))},
4433 {V(MyBytes{}), V(MyBytesArray0([0]byte{}))},
4434 {V(MyBytes{5, 6, 7, 8}), V(MyBytesArray([4]byte{5, 6, 7, 8}))},
4435 {V([]MyByte{}), V([0]MyByte{})},
4436 {V([]MyByte{1, 2}), V([2]MyByte{1, 2})},
4438 // slice to array pointer
4439 {V([]byte(nil)), V((*[0]byte)(nil))},
4440 {V([]byte{}), V(new([0]byte))},
4441 {V([]byte{7}), V(&[1]byte{7})},
4442 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4443 {V(MyBytes([]byte{})), V(new([0]byte))},
4444 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4445 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4446 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4447 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4448 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4449 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4451 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4452 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4453 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4454 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4455 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4456 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4457 {V(new([0]byte)), V(new(MyBytesArray0))},
4458 {V(new(MyBytesArray0)), V(new([0]byte))},
4459 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4460 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4462 // named types and equal underlying types
4463 {V(new(int)), V(new(integer))},
4464 {V(new(integer)), V(new(int))},
4465 {V(Empty{}), V(struct{}{})},
4466 {V(new(Empty)), V(new(struct{}))},
4467 {V(struct{}{}), V(Empty{})},
4468 {V(new(struct{})), V(new(Empty))},
4469 {V(Empty{}), V(Empty{})},
4470 {V(MyBytes{}), V([]byte{})},
4471 {V([]byte{}), V(MyBytes{})},
4472 {V((func())(nil)), V(MyFunc(nil))},
4473 {V((MyFunc)(nil)), V((func())(nil))},
4475 // structs with different tags
4488 {V(MyStruct{}), V(struct {
4494 }{}), V(MyStruct{})},
4496 {V(MyStruct{}), V(struct {
4502 }{}), V(MyStruct{})},
4504 {V(MyStruct1{}), V(MyStruct2{})},
4505 {V(MyStruct2{}), V(MyStruct1{})},
4507 // can convert *byte and *MyByte
4508 {V((*byte)(nil)), V((*MyByte)(nil))},
4509 {V((*MyByte)(nil)), V((*byte)(nil))},
4511 // cannot convert mismatched array sizes
4512 {V([2]byte{}), V([2]byte{})},
4513 {V([3]byte{}), V([3]byte{})},
4514 {V(MyBytesArray0{}), V([0]byte{})},
4515 {V([0]byte{}), V(MyBytesArray0{})},
4517 // cannot convert other instances
4518 {V((**byte)(nil)), V((**byte)(nil))},
4519 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4520 {V((chan byte)(nil)), V((chan byte)(nil))},
4521 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4522 {V(([]byte)(nil)), V(([]byte)(nil))},
4523 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4524 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4525 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4526 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4527 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4528 {V([2]byte{}), V([2]byte{})},
4529 {V([2]MyByte{}), V([2]MyByte{})},
4532 {V((***int)(nil)), V((***int)(nil))},
4533 {V((***byte)(nil)), V((***byte)(nil))},
4534 {V((***int32)(nil)), V((***int32)(nil))},
4535 {V((***int64)(nil)), V((***int64)(nil))},
4536 {V((chan byte)(nil)), V((chan byte)(nil))},
4537 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4538 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4539 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4540 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4541 {V([]uint(nil)), V([]uint(nil))},
4542 {V([]int(nil)), V([]int(nil))},
4543 {V(new(any)), V(new(any))},
4544 {V(new(io.Reader)), V(new(io.Reader))},
4545 {V(new(io.Writer)), V(new(io.Writer))},
4548 {V(IntChan(nil)), V((chan<- int)(nil))},
4549 {V(IntChan(nil)), V((<-chan int)(nil))},
4550 {V((chan int)(nil)), V(IntChanRecv(nil))},
4551 {V((chan int)(nil)), V(IntChanSend(nil))},
4552 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4553 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4554 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4555 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4556 {V(IntChan(nil)), V((chan int)(nil))},
4557 {V((chan int)(nil)), V(IntChan(nil))},
4558 {V((chan int)(nil)), V((<-chan int)(nil))},
4559 {V((chan int)(nil)), V((chan<- int)(nil))},
4560 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4561 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4562 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4563 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4564 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4565 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4566 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4567 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4568 {V(BytesChan(nil)), V((chan []byte)(nil))},
4569 {V((chan []byte)(nil)), V(BytesChan(nil))},
4570 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4571 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4573 // cannot convert other instances (channels)
4574 {V(IntChan(nil)), V(IntChan(nil))},
4575 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4576 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4577 {V(BytesChan(nil)), V(BytesChan(nil))},
4578 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4579 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4582 {V(int(1)), EmptyInterfaceV(int(1))},
4583 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4584 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4585 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4586 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4589 func TestConvert(t *testing.T) {
4590 canConvert := map[[2]Type]bool{}
4591 all := map[Type]bool{}
4593 for _, tt := range convertTests {
4595 if !t1.ConvertibleTo(t1) {
4596 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4601 if !t1.ConvertibleTo(t2) {
4602 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4608 canConvert[[2]Type{t1, t2}] = true
4610 // vout1 represents the in value converted to the in type.
4612 if !v1.CanConvert(t1) {
4613 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4615 vout1 := v1.Convert(t1)
4616 out1 := vout1.Interface()
4617 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4618 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4621 // vout2 represents the in value converted to the out type.
4622 if !v1.CanConvert(t2) {
4623 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4625 vout2 := v1.Convert(t2)
4626 out2 := vout2.Interface()
4627 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4628 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4630 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4631 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4634 // vout3 represents a new value of the out type, set to vout2. This makes
4635 // sure the converted value vout2 is really usable as a regular value.
4636 vout3 := New(t2).Elem()
4638 out3 := vout3.Interface()
4639 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4640 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4644 t.Errorf("table entry %v is RO, should not be", v1)
4647 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4650 t.Errorf("conversion output %v is RO, should not be", vout2)
4653 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4655 if !IsRO(MakeRO(v1).Convert(t1)) {
4656 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4658 if !IsRO(MakeRO(v1).Convert(t2)) {
4659 t.Errorf("RO conversion output %v is not RO, should be", v1)
4663 // Assume that of all the types we saw during the tests,
4664 // if there wasn't an explicit entry for a conversion between
4665 // a pair of types, then it's not to be allowed. This checks for
4666 // things like 'int64' converting to '*int'.
4667 for t1 := range all {
4668 for t2 := range all {
4669 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4670 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4671 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4677 func TestConvertPanic(t *testing.T) {
4678 s := make([]byte, 4)
4682 if !v.Type().ConvertibleTo(pt) {
4683 t.Errorf("[]byte should be convertible to *[8]byte")
4685 if v.CanConvert(pt) {
4686 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4688 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4692 if v.CanConvert(pt.Elem()) {
4693 t.Errorf("slice with length 4 should not be convertible to [8]byte")
4695 shouldPanic("reflect: cannot convert slice with length 4 to array with length 8", func() {
4696 _ = v.Convert(pt.Elem())
4700 func TestConvertSlice2Array(t *testing.T) {
4706 // Converting a slice to non-empty array needs to return
4707 // a non-addressable copy of the original memory.
4709 t.Fatalf("convert slice to non-empty array returns a addressable copy array")
4712 ov.Index(i).Set(ValueOf(i + 1))
4715 if v.Index(i).Int() != 0 {
4716 t.Fatalf("slice (%v) mutation visible in converted result (%v)", ov, v)
4721 var gFloat32 float32
4723 const snan uint32 = 0x7f800001
4725 func TestConvertNaNs(t *testing.T) {
4726 // Test to see if a store followed by a load of a signaling NaN
4727 // maintains the signaling bit. (This used to fail on the 387 port.)
4728 gFloat32 = math.Float32frombits(snan)
4729 runtime.Gosched() // make sure we don't optimize the store/load away
4730 if got := math.Float32bits(gFloat32); got != snan {
4731 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4733 // Test reflect's conversion between float32s. See issue 36400.
4734 type myFloat32 float32
4735 x := V(myFloat32(math.Float32frombits(snan)))
4736 y := x.Convert(TypeOf(float32(0)))
4737 z := y.Interface().(float32)
4738 if got := math.Float32bits(z); got != snan {
4739 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4743 type ComparableStruct struct {
4747 type NonComparableStruct struct {
4752 var comparableTests = []struct {
4757 {TypeOf("hello"), true},
4758 {TypeOf(new(byte)), true},
4759 {TypeOf((func())(nil)), false},
4760 {TypeOf([]byte{}), false},
4761 {TypeOf(map[string]int{}), false},
4762 {TypeOf(make(chan int)), true},
4763 {TypeOf(1.5), true},
4764 {TypeOf(false), true},
4766 {TypeOf(ComparableStruct{}), true},
4767 {TypeOf(NonComparableStruct{}), false},
4768 {TypeOf([10]map[string]int{}), false},
4769 {TypeOf([10]string{}), true},
4770 {TypeOf(new(any)).Elem(), true},
4773 func TestComparable(t *testing.T) {
4774 for _, tt := range comparableTests {
4775 if ok := tt.typ.Comparable(); ok != tt.ok {
4776 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4781 func TestOverflow(t *testing.T) {
4782 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4783 t.Errorf("%v wrongly overflows float64", 1e300)
4786 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4787 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4788 t.Errorf("%v wrongly overflows float32", maxFloat32)
4790 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4791 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4792 t.Errorf("%v should overflow float32", ovfFloat32)
4794 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4795 t.Errorf("%v should overflow float32", -ovfFloat32)
4798 maxInt32 := int64(0x7fffffff)
4799 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4800 t.Errorf("%v wrongly overflows int32", maxInt32)
4802 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4803 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4805 ovfInt32 := int64(1 << 31)
4806 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4807 t.Errorf("%v should overflow int32", ovfInt32)
4810 maxUint32 := uint64(0xffffffff)
4811 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4812 t.Errorf("%v wrongly overflows uint32", maxUint32)
4814 ovfUint32 := uint64(1 << 32)
4815 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4816 t.Errorf("%v should overflow uint32", ovfUint32)
4820 func checkSameType(t *testing.T, x Type, y any) {
4821 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4822 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4826 func TestArrayOf(t *testing.T) {
4827 // check construction and use of type not in binary
4830 value func(i int) any
4836 value: func(i int) any { type Tint int; return Tint(i) },
4842 value: func(i int) any { type Tint int; return Tint(i) },
4844 want: "[0 1 2 3 4 5 6 7 8 9]",
4848 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4850 want: "[0 1 2 3 4 5 6 7 8 9]",
4854 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(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{i} },
4862 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4866 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4868 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4872 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4874 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4878 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4880 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4884 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4886 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4890 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4892 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4896 value: func(i int) any {
4897 type TstructUV struct {
4901 return TstructUV{i, float64(i)}
4904 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4908 for _, table := range tests {
4909 at := ArrayOf(table.n, TypeOf(table.value(0)))
4911 vok := New(at).Elem()
4912 vnot := New(at).Elem()
4913 for i := 0; i < v.Len(); i++ {
4914 v.Index(i).Set(ValueOf(table.value(i)))
4915 vok.Index(i).Set(ValueOf(table.value(i)))
4920 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4922 s := fmt.Sprint(v.Interface())
4923 if s != table.want {
4924 t.Errorf("constructed array = %s, want %s", s, table.want)
4927 if table.comparable != at.Comparable() {
4928 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4930 if table.comparable {
4932 if DeepEqual(vnot.Interface(), v.Interface()) {
4934 "arrays (%#v) compare ok (but should not)",
4939 if !DeepEqual(vok.Interface(), v.Interface()) {
4941 "arrays (%#v) compare NOT-ok (but should)",
4948 // check that type already in binary is found
4950 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4953 func TestArrayOfGC(t *testing.T) {
4955 tt := TypeOf(T(nil))
4958 for i := 0; i < n; i++ {
4959 v := New(ArrayOf(n, tt)).Elem()
4960 for j := 0; j < v.Len(); j++ {
4962 *p = uintptr(i*n + j)
4963 v.Index(j).Set(ValueOf(p).Convert(tt))
4965 x = append(x, v.Interface())
4969 for i, xi := range x {
4971 for j := 0; j < v.Len(); j++ {
4972 k := v.Index(j).Elem().Interface()
4973 if k != uintptr(i*n+j) {
4974 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4980 func TestArrayOfAlg(t *testing.T) {
4981 at := ArrayOf(6, TypeOf(byte(0)))
4982 v1 := New(at).Elem()
4983 v2 := New(at).Elem()
4984 if v1.Interface() != v1.Interface() {
4985 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4987 v1.Index(5).Set(ValueOf(byte(1)))
4988 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4989 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4992 at = ArrayOf(6, TypeOf([]int(nil)))
4994 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4997 func TestArrayOfGenericAlg(t *testing.T) {
4998 at1 := ArrayOf(5, TypeOf(string("")))
4999 at := ArrayOf(6, at1)
5000 v1 := New(at).Elem()
5001 v2 := New(at).Elem()
5002 if v1.Interface() != v1.Interface() {
5003 t.Errorf("constructed array %v not equal to itself", v1.Interface())
5006 v1.Index(0).Index(0).Set(ValueOf("abc"))
5007 v2.Index(0).Index(0).Set(ValueOf("efg"))
5008 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
5009 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
5012 v1.Index(0).Index(0).Set(ValueOf("abc"))
5013 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
5014 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
5015 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
5019 m := MakeMap(MapOf(at, TypeOf(int(0))))
5020 m.SetMapIndex(v1, ValueOf(1))
5021 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5022 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
5026 func TestArrayOfDirectIface(t *testing.T) {
5029 i1 := Zero(TypeOf(T{})).Interface()
5030 v1 := ValueOf(&i1).Elem()
5031 p1 := v1.InterfaceData()[1]
5033 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
5034 v2 := ValueOf(&i2).Elem()
5035 p2 := v2.InterfaceData()[1]
5038 t.Errorf("got p1=%v. want=%v", p1, nil)
5042 t.Errorf("got p2=%v. want=%v", p2, nil)
5047 i1 := Zero(TypeOf(T{})).Interface()
5048 v1 := ValueOf(&i1).Elem()
5049 p1 := v1.InterfaceData()[1]
5051 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
5052 v2 := ValueOf(&i2).Elem()
5053 p2 := v2.InterfaceData()[1]
5056 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5060 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5065 // Ensure passing in negative lengths panics.
5066 // See https://golang.org/issue/43603
5067 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
5068 shouldPanic("reflect: negative length passed to ArrayOf", func() {
5069 ArrayOf(-1, TypeOf(byte(0)))
5073 func TestSliceOf(t *testing.T) {
5074 // check construction and use of type not in binary
5076 st := SliceOf(TypeOf(T(1)))
5077 if got, want := st.String(), "[]reflect_test.T"; got != want {
5078 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
5080 v := MakeSlice(st, 10, 10)
5082 for i := 0; i < v.Len(); i++ {
5083 v.Index(i).Set(ValueOf(T(i)))
5086 s := fmt.Sprint(v.Interface())
5087 want := "[0 1 2 3 4 5 6 7 8 9]"
5089 t.Errorf("constructed slice = %s, want %s", s, want)
5092 // check that type already in binary is found
5094 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
5097 func TestSliceOverflow(t *testing.T) {
5098 // check that MakeSlice panics when size of slice overflows uint
5101 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5103 t.Fatal("slice size does not overflow")
5106 st := SliceOf(TypeOf(x))
5110 t.Fatal("slice overflow does not panic")
5113 MakeSlice(st, int(l), int(l))
5116 func TestSliceOfGC(t *testing.T) {
5118 tt := TypeOf(T(nil))
5122 for i := 0; i < n; i++ {
5123 v := MakeSlice(st, n, n)
5124 for j := 0; j < v.Len(); j++ {
5126 *p = uintptr(i*n + j)
5127 v.Index(j).Set(ValueOf(p).Convert(tt))
5129 x = append(x, v.Interface())
5133 for i, xi := range x {
5135 for j := 0; j < v.Len(); j++ {
5136 k := v.Index(j).Elem().Interface()
5137 if k != uintptr(i*n+j) {
5138 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5144 func TestStructOfFieldName(t *testing.T) {
5145 // invalid field name "1nvalid"
5146 shouldPanic("has invalid name", func() {
5147 StructOf([]StructField{
5148 {Name: "Valid", Type: TypeOf("")},
5149 {Name: "1nvalid", Type: TypeOf("")},
5153 // invalid field name "+"
5154 shouldPanic("has invalid name", func() {
5155 StructOf([]StructField{
5156 {Name: "Val1d", Type: TypeOf("")},
5157 {Name: "+", Type: TypeOf("")},
5162 shouldPanic("has no name", func() {
5163 StructOf([]StructField{
5164 {Name: "", Type: TypeOf("")},
5168 // verify creation of a struct with valid struct fields
5169 validFields := []StructField{
5184 validStruct := StructOf(validFields)
5186 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5187 if got, want := validStruct.String(), structStr; got != want {
5188 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5192 func TestStructOf(t *testing.T) {
5193 // check construction and use of type not in binary
5194 fields := []StructField{
5203 Type: TypeOf(byte(0)),
5207 Type: TypeOf(uint64(0)),
5211 Type: TypeOf([3]uint16{}),
5215 st := StructOf(fields)
5218 v.FieldByName("X").Set(ValueOf(byte(2)))
5219 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5222 s := fmt.Sprint(v.Interface())
5223 want := `{ 1 0 [0 0 0]}`
5225 t.Errorf("constructed struct = %s, want %s", s, want)
5227 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5228 if got, want := st.String(), stStr; got != want {
5229 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5232 // check the size, alignment and field offsets
5233 stt := TypeOf(struct {
5239 if st.Size() != stt.Size() {
5240 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5242 if st.Align() != stt.Align() {
5243 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5245 if st.FieldAlign() != stt.FieldAlign() {
5246 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5248 for i := 0; i < st.NumField(); i++ {
5249 o1 := st.Field(i).Offset
5250 o2 := stt.Field(i).Offset
5252 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5256 // Check size and alignment with a trailing zero-sized field.
5257 st = StructOf([]StructField{
5260 Type: TypeOf(byte(0)),
5264 Type: TypeOf([0]*byte{}),
5267 stt = TypeOf(struct {
5271 if st.Size() != stt.Size() {
5272 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5274 if st.Align() != stt.Align() {
5275 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5277 if st.FieldAlign() != stt.FieldAlign() {
5278 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5280 for i := 0; i < st.NumField(); i++ {
5281 o1 := st.Field(i).Offset
5282 o2 := stt.Field(i).Offset
5284 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5288 // check duplicate names
5289 shouldPanic("duplicate field", func() {
5290 StructOf([]StructField{
5291 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5292 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5295 shouldPanic("has no name", func() {
5296 StructOf([]StructField{
5298 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5301 shouldPanic("has no name", func() {
5302 StructOf([]StructField{
5307 // check that type already in binary is found
5308 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5310 // gccgo used to fail this test.
5311 type structFieldType any
5313 StructOf([]StructField{
5316 Type: TypeOf((*structFieldType)(nil)).Elem(),
5319 struct{ F structFieldType }{})
5322 func TestStructOfExportRules(t *testing.T) {
5328 testPanic := func(i int, mustPanic bool, f func()) {
5331 if err == nil && mustPanic {
5332 t.Errorf("test-%d did not panic", i)
5334 if err != nil && !mustPanic {
5335 t.Errorf("test-%d panicked: %v\n", i, err)
5347 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5351 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5355 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5359 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5363 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5367 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5371 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5375 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5379 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5383 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5387 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5390 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5393 field: StructField{Name: "S", Type: TypeOf(S1{})},
5397 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5401 field: StructField{Name: "S", Type: TypeOf(s2{})},
5405 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5409 field: StructField{Name: "s", Type: TypeOf(S1{})},
5413 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5417 field: StructField{Name: "s", Type: TypeOf(s2{})},
5421 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5425 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5428 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5431 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5434 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5437 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5441 field: StructField{Name: "", Type: TypeOf(φType{})},
5445 field: StructField{Name: "Φ", Type: TypeOf(0)},
5449 field: StructField{Name: "φ", Type: TypeOf(0)},
5454 for i, test := range tests {
5455 testPanic(i, test.mustPanic, func() {
5456 typ := StructOf([]StructField{test.field})
5458 t.Errorf("test-%d: error creating struct type", i)
5461 field := typ.Field(0)
5464 panic("field.Name must not be empty")
5466 exported := token.IsExported(n)
5467 if exported != test.exported {
5468 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5470 if field.PkgPath != test.field.PkgPath {
5471 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5477 func TestStructOfGC(t *testing.T) {
5479 tt := TypeOf(T(nil))
5480 fields := []StructField{
5481 {Name: "X", Type: tt},
5482 {Name: "Y", Type: tt},
5484 st := StructOf(fields)
5488 for i := 0; i < n; i++ {
5490 for j := 0; j < v.NumField(); j++ {
5492 *p = uintptr(i*n + j)
5493 v.Field(j).Set(ValueOf(p).Convert(tt))
5495 x = append(x, v.Interface())
5499 for i, xi := range x {
5501 for j := 0; j < v.NumField(); j++ {
5502 k := v.Field(j).Elem().Interface()
5503 if k != uintptr(i*n+j) {
5504 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5510 func TestStructOfAlg(t *testing.T) {
5511 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5512 v1 := New(st).Elem()
5513 v2 := New(st).Elem()
5514 if !DeepEqual(v1.Interface(), v1.Interface()) {
5515 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5517 v1.FieldByName("X").Set(ValueOf(int(1)))
5518 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5519 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5522 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5524 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5527 func TestStructOfGenericAlg(t *testing.T) {
5528 st1 := StructOf([]StructField{
5529 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5530 {Name: "Y", Type: TypeOf(string(""))},
5532 st := StructOf([]StructField{
5533 {Name: "S0", Type: st1},
5534 {Name: "S1", Type: st1},
5552 {Name: "XX", Type: TypeOf([0]int{})},
5553 {Name: "YY", Type: TypeOf("")},
5561 {Name: "XX", Type: TypeOf([0]int{})},
5562 {Name: "YY", Type: TypeOf("")},
5563 {Name: "ZZ", Type: TypeOf([2]int{})},
5571 {Name: "XX", Type: TypeOf([1]int{})},
5572 {Name: "YY", Type: TypeOf("")},
5580 {Name: "XX", Type: TypeOf([1]int{})},
5581 {Name: "YY", Type: TypeOf("")},
5582 {Name: "ZZ", Type: TypeOf([1]int{})},
5590 {Name: "XX", Type: TypeOf([2]int{})},
5591 {Name: "YY", Type: TypeOf("")},
5592 {Name: "ZZ", Type: TypeOf([2]int{})},
5600 {Name: "XX", Type: TypeOf(int64(0))},
5601 {Name: "YY", Type: TypeOf(byte(0))},
5602 {Name: "ZZ", Type: TypeOf("")},
5610 {Name: "XX", Type: TypeOf(int64(0))},
5611 {Name: "YY", Type: TypeOf(int64(0))},
5612 {Name: "ZZ", Type: TypeOf("")},
5613 {Name: "AA", Type: TypeOf([1]int64{})},
5620 for _, table := range tests {
5621 v1 := New(table.rt).Elem()
5622 v2 := New(table.rt).Elem()
5624 if !DeepEqual(v1.Interface(), v1.Interface()) {
5625 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5628 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5629 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5630 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5631 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5635 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5636 val := "+" + abc + "-"
5637 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5638 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5639 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5643 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5644 m.SetMapIndex(v1, ValueOf(1))
5645 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5646 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5649 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5650 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5651 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5654 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5655 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5660 func TestStructOfDirectIface(t *testing.T) {
5662 type T struct{ X [1]*byte }
5663 i1 := Zero(TypeOf(T{})).Interface()
5664 v1 := ValueOf(&i1).Elem()
5665 p1 := v1.InterfaceData()[1]
5667 i2 := Zero(StructOf([]StructField{
5670 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5673 v2 := ValueOf(&i2).Elem()
5674 p2 := v2.InterfaceData()[1]
5677 t.Errorf("got p1=%v. want=%v", p1, nil)
5681 t.Errorf("got p2=%v. want=%v", p2, nil)
5685 type T struct{ X [0]*byte }
5686 i1 := Zero(TypeOf(T{})).Interface()
5687 v1 := ValueOf(&i1).Elem()
5688 p1 := v1.InterfaceData()[1]
5690 i2 := Zero(StructOf([]StructField{
5693 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5696 v2 := ValueOf(&i2).Elem()
5697 p2 := v2.InterfaceData()[1]
5700 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5704 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5711 func (i StructI) Get() int { return int(i) }
5715 func (i *StructIPtr) Get() int { return int(*i) }
5716 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5718 type SettableStruct struct {
5722 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5724 type SettablePointer struct {
5728 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5730 func TestStructOfWithInterface(t *testing.T) {
5732 type Iface interface {
5735 type IfaceSet interface {
5746 typ: TypeOf(StructI(want)),
5747 val: ValueOf(StructI(want)),
5752 typ: PointerTo(TypeOf(StructI(want))),
5753 val: ValueOf(func() any {
5761 typ: PointerTo(TypeOf(StructIPtr(want))),
5762 val: ValueOf(func() any {
5763 v := StructIPtr(want)
5770 typ: TypeOf(StructIPtr(want)),
5771 val: ValueOf(StructIPtr(want)),
5775 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5776 // val: ValueOf(StructI(want)),
5781 for i, table := range tests {
5782 for j := 0; j < 2; j++ {
5783 var fields []StructField
5785 fields = append(fields, StructField{
5788 Type: TypeOf(int(0)),
5791 fields = append(fields, StructField{
5798 // We currently do not correctly implement methods
5799 // for embedded fields other than the first.
5800 // Therefore, for now, we expect those methods
5801 // to not exist. See issues 15924 and 20824.
5802 // When those issues are fixed, this test of panic
5803 // should be removed.
5804 if j == 1 && table.impl {
5807 if err := recover(); err == nil {
5808 t.Errorf("test-%d-%d did not panic", i, j)
5811 _ = StructOf(fields)
5816 rt := StructOf(fields)
5817 rv := New(rt).Elem()
5818 rv.Field(j).Set(table.val)
5820 if _, ok := rv.Interface().(Iface); ok != table.impl {
5822 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5824 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5833 v := rv.Interface().(Iface).Get()
5835 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5838 fct := rv.MethodByName("Get")
5839 out := fct.Call(nil)
5840 if !DeepEqual(out[0].Interface(), want) {
5841 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5846 // Test an embedded nil pointer with pointer methods.
5847 fields := []StructField{{
5850 Type: PointerTo(TypeOf(StructIPtr(want))),
5852 rt := StructOf(fields)
5853 rv := New(rt).Elem()
5854 // This should panic since the pointer is nil.
5855 shouldPanic("", func() {
5856 rv.Interface().(IfaceSet).Set(want)
5859 // Test an embedded nil pointer to a struct with pointer methods.
5861 fields = []StructField{{
5862 Name: "SettableStruct",
5864 Type: PointerTo(TypeOf(SettableStruct{})),
5866 rt = StructOf(fields)
5868 // This should panic since the pointer is nil.
5869 shouldPanic("", func() {
5870 rv.Interface().(IfaceSet).Set(want)
5873 // The behavior is different if there is a second field,
5874 // since now an interface value holds a pointer to the struct
5875 // rather than just holding a copy of the struct.
5876 fields = []StructField{
5878 Name: "SettableStruct",
5880 Type: PointerTo(TypeOf(SettableStruct{})),
5883 Name: "EmptyStruct",
5885 Type: StructOf(nil),
5888 // With the current implementation this is expected to panic.
5889 // Ideally it should work and we should be able to see a panic
5890 // if we call the Set method.
5891 shouldPanic("", func() {
5895 // Embed a field that can be stored directly in an interface,
5896 // with a second field.
5897 fields = []StructField{
5899 Name: "SettablePointer",
5901 Type: TypeOf(SettablePointer{}),
5904 Name: "EmptyStruct",
5906 Type: StructOf(nil),
5909 // With the current implementation this is expected to panic.
5910 // Ideally it should work and we should be able to call the
5911 // Set and Get methods.
5912 shouldPanic("", func() {
5917 func TestStructOfTooManyFields(t *testing.T) {
5918 // Bug Fix: #25402 - this should not panic
5919 tt := StructOf([]StructField{
5920 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5923 if _, present := tt.MethodByName("After"); !present {
5924 t.Errorf("Expected method `After` to be found")
5928 func TestStructOfDifferentPkgPath(t *testing.T) {
5929 fields := []StructField{
5933 Type: TypeOf(int(0)),
5938 Type: TypeOf(int(0)),
5941 shouldPanic("different PkgPath", func() {
5946 func TestStructOfTooLarge(t *testing.T) {
5947 t1 := TypeOf(byte(0))
5948 t2 := TypeOf(int16(0))
5949 t4 := TypeOf(int32(0))
5950 t0 := ArrayOf(0, t1)
5952 // 2^64-3 sized type (or 2^32-3 on 32-bit archs)
5953 bigType := StructOf([]StructField{
5954 {Name: "F1", Type: ArrayOf(int(^uintptr(0)>>1), t1)},
5955 {Name: "F2", Type: ArrayOf(int(^uintptr(0)>>1-1), t1)},
5960 fields []StructField
5965 shouldPanic: false, // 2^64-1, ok
5966 fields: []StructField{
5967 {Name: "F1", Type: bigType},
5968 {Name: "F2", Type: ArrayOf(2, t1)},
5972 shouldPanic: true, // overflow in total size
5973 fields: []StructField{
5974 {Name: "F1", Type: bigType},
5975 {Name: "F2", Type: ArrayOf(3, t1)},
5979 shouldPanic: true, // overflow while aligning F2
5980 fields: []StructField{
5981 {Name: "F1", Type: bigType},
5982 {Name: "F2", Type: t4},
5986 shouldPanic: true, // overflow while adding trailing byte for zero-sized fields
5987 fields: []StructField{
5988 {Name: "F1", Type: bigType},
5989 {Name: "F2", Type: ArrayOf(2, t1)},
5990 {Name: "F3", Type: t0},
5994 shouldPanic: true, // overflow while aligning total size
5995 fields: []StructField{
5996 {Name: "F1", Type: t2},
5997 {Name: "F2", Type: bigType},
6002 for i, tt := range tests {
6006 if !tt.shouldPanic {
6008 t.Errorf("test %d should not panic, got %s", i, err)
6013 t.Errorf("test %d expected to panic", i)
6016 s := fmt.Sprintf("%s", err)
6017 if s != "reflect.StructOf: struct size would exceed virtual address space" {
6018 t.Errorf("test %d wrong panic message: %s", i, s)
6022 _ = StructOf(tt.fields)
6027 func TestChanOf(t *testing.T) {
6028 // check construction and use of type not in binary
6030 ct := ChanOf(BothDir, TypeOf(T("")))
6031 v := MakeChan(ct, 2)
6033 v.Send(ValueOf(T("hello")))
6035 v.Send(ValueOf(T("world")))
6042 if s1 != "hello" || s2 != "world" {
6043 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
6046 // check that type already in binary is found
6048 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
6050 // Check arrow token association in undefined chan types.
6051 var left chan<- chan T
6052 var right chan (<-chan T)
6053 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
6054 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
6055 if tLeft != TypeOf(left) {
6056 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
6058 if tRight != TypeOf(right) {
6059 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
6063 func TestChanOfDir(t *testing.T) {
6064 // check construction and use of type not in binary
6066 crt := ChanOf(RecvDir, TypeOf(T("")))
6067 cst := ChanOf(SendDir, TypeOf(T("")))
6069 // check that type already in binary is found
6071 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
6072 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
6074 // check String form of ChanDir
6075 if crt.ChanDir().String() != "<-chan" {
6076 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
6078 if cst.ChanDir().String() != "chan<-" {
6079 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
6083 func TestChanOfGC(t *testing.T) {
6084 done := make(chan bool, 1)
6088 case <-time.After(5 * time.Second):
6089 panic("deadlock in TestChanOfGC")
6098 tt := TypeOf(T(nil))
6099 ct := ChanOf(BothDir, tt)
6101 // NOTE: The garbage collector handles allocated channels specially,
6102 // so we have to save pointers to channels in x; the pointer code will
6103 // use the gc info in the newly constructed chan type.
6106 for i := 0; i < n; i++ {
6107 v := MakeChan(ct, n)
6108 for j := 0; j < n; j++ {
6110 *p = uintptr(i*n + j)
6111 v.Send(ValueOf(p).Convert(tt))
6115 x = append(x, pv.Interface())
6119 for i, xi := range x {
6120 v := ValueOf(xi).Elem()
6121 for j := 0; j < n; j++ {
6123 k := pv.Elem().Interface()
6124 if k != uintptr(i*n+j) {
6125 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6131 func TestMapOf(t *testing.T) {
6132 // check construction and use of type not in binary
6136 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
6138 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
6141 s := fmt.Sprint(v.Interface())
6144 t.Errorf("constructed map = %s, want %s", s, want)
6147 // check that type already in binary is found
6148 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
6150 // check that invalid key type panics
6151 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
6154 func TestMapOfGCKeys(t *testing.T) {
6156 tt := TypeOf(T(nil))
6157 mt := MapOf(tt, TypeOf(false))
6159 // NOTE: The garbage collector handles allocated maps specially,
6160 // so we have to save pointers to maps in x; the pointer code will
6161 // use the gc info in the newly constructed map type.
6164 for i := 0; i < n; i++ {
6166 for j := 0; j < n; j++ {
6168 *p = uintptr(i*n + j)
6169 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
6173 x = append(x, pv.Interface())
6177 for i, xi := range x {
6178 v := ValueOf(xi).Elem()
6180 for _, kv := range v.MapKeys() {
6181 out = append(out, int(kv.Elem().Interface().(uintptr)))
6184 for j, k := range out {
6186 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6192 func TestMapOfGCValues(t *testing.T) {
6194 tt := TypeOf(T(nil))
6195 mt := MapOf(TypeOf(1), tt)
6197 // NOTE: The garbage collector handles allocated maps specially,
6198 // so we have to save pointers to maps in x; the pointer code will
6199 // use the gc info in the newly constructed map type.
6202 for i := 0; i < n; i++ {
6204 for j := 0; j < n; j++ {
6206 *p = uintptr(i*n + j)
6207 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6211 x = append(x, pv.Interface())
6215 for i, xi := range x {
6216 v := ValueOf(xi).Elem()
6217 for j := 0; j < n; j++ {
6218 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6219 if k != uintptr(i*n+j) {
6220 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6226 func TestTypelinksSorted(t *testing.T) {
6228 for i, n := range TypeLinks() {
6230 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6236 func TestFuncOf(t *testing.T) {
6237 // check construction and use of type not in binary
6241 fn := func(args []Value) []Value {
6243 t.Errorf("args == %v, want exactly one arg", args)
6244 } else if args[0].Type() != TypeOf(K("")) {
6245 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6246 } else if args[0].String() != "gopher" {
6247 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6249 return []Value{ValueOf(V(3.14))}
6251 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6253 outs := v.Call([]Value{ValueOf(K("gopher"))})
6255 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6256 } else if outs[0].Type() != TypeOf(V(0)) {
6257 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6259 f := outs[0].Float()
6261 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6264 // check that types already in binary are found
6266 testCases := []struct {
6271 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6272 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6273 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6274 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6275 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6277 for _, tt := range testCases {
6278 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6281 // check that variadic requires last element be a slice.
6282 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6283 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6284 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6286 //testcase for #54669
6288 for i := 0; i < 51; i++ {
6289 in = append(in, TypeOf(1))
6291 FuncOf(in, nil, false)
6364 func TestEmbed(t *testing.T) {
6366 f, ok := typ.FieldByName("X")
6368 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6372 func TestAllocsInterfaceBig(t *testing.T) {
6373 if testing.Short() {
6374 t.Skip("skipping malloc count in short mode")
6377 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6378 t.Error("allocs:", allocs)
6382 func TestAllocsInterfaceSmall(t *testing.T) {
6383 if testing.Short() {
6384 t.Skip("skipping malloc count in short mode")
6386 v := ValueOf(int64(0))
6387 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6388 t.Error("allocs:", allocs)
6392 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6393 // The basic usage is:
6396 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6399 // Each iteration of the loop returns a different set of results, until all
6400 // possible result sets have been explored. It is okay for different code paths
6401 // to make different method call sequences on x, but there must be no
6402 // other source of non-determinism in the call sequences.
6404 // When faced with a new decision, x chooses randomly. Future explorations
6405 // of that path will choose successive values for the result. Thus, stopping
6406 // the loop after a fixed number of iterations gives somewhat stochastic
6412 // v := make([]bool, x.Choose(4))
6413 // for i := range v {
6419 // prints (in some order):
6428 // [false false false]
6431 // [false false false false]
6433 // [true true true true]
6434 type exhaustive struct {
6440 type choice struct {
6446 func (x *exhaustive) Next() bool {
6448 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6455 for i := len(x.last) - 1; i >= 0; i-- {
6459 x.last = x.last[:i+1]
6466 func (x *exhaustive) Choose(max int) int {
6467 if x.pos >= len(x.last) {
6468 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6473 panic("inconsistent use of exhaustive tester")
6475 return (c.n + c.off) % max
6478 func (x *exhaustive) Maybe() bool {
6479 return x.Choose(2) == 1
6482 func GCFunc(args []Value) []Value {
6487 func TestReflectFuncTraceback(t *testing.T) {
6488 f := MakeFunc(TypeOf(func() {}), GCFunc)
6492 func TestReflectMethodTraceback(t *testing.T) {
6494 m := ValueOf(p).MethodByName("GCMethod")
6495 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6497 t.Errorf("Call returned %d; want 8", i)
6501 func TestSmallZero(t *testing.T) {
6504 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6505 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6509 func TestBigZero(t *testing.T) {
6510 const size = 1 << 10
6512 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6513 for i := 0; i < size; i++ {
6515 t.Fatalf("Zero object not all zero, index %d", i)
6520 func TestZeroSet(t *testing.T) {
6528 a: 0xaaaaaaaaaaaaaaaa,
6529 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6530 b: 0xbbbbbbbbbbbbbbbb,
6532 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6534 a: 0xaaaaaaaaaaaaaaaa,
6535 b: 0xbbbbbbbbbbbbbbbb,
6537 t.Fatalf("Setting a field to a Zero value didn't work")
6541 func TestFieldByIndexNil(t *testing.T) {
6550 v.FieldByName("P") // should be fine
6553 if err := recover(); err == nil {
6554 t.Fatalf("no error")
6555 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6556 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6559 v.FieldByName("F") // should panic
6561 t.Fatalf("did not panic")
6565 // type Outer struct {
6569 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6570 // The implementation is logically:
6571 // func (p *Outer) M() {
6574 // but since the only change here is the replacement of one pointer receiver with another,
6575 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6576 // then jumps to the M method expecting the *Inner receiver.
6578 // During reflect.Value.Call, we create an argument frame and the associated data structures
6579 // to describe it to the garbage collector, populate the frame, call reflect.call to
6580 // run a function call using that frame, and then copy the results back out of the frame.
6581 // The reflect.call function does a memmove of the frame structure onto the
6582 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6583 // the frame structure (to preserve the outputs).
6585 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6586 // were for the full stack frame. However, in the case where the called function was
6587 // one of these wrappers, the rewritten receiver is almost certainly a different type
6588 // than the original receiver. This is not a problem on the stack, where we use the
6589 // program counter to determine the type information and understand that
6590 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6591 // memory word is now an *Inner. But in the statically typed argument frame created
6592 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6593 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6594 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6595 // memory as if it were an *Outer. If the two have different memory layouts, the
6596 // collection will interpret the memory incorrectly.
6598 // One such possible incorrect interpretation is to treat two arbitrary memory words
6599 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6600 // an interface requires dereferencing the itab word, the misinterpretation will try to
6601 // deference Inner.P1, causing a crash during garbage collection.
6603 // This came up in a real program in issue 7725.
6616 func (pi *Inner) M() {
6617 // Clear references to pi so that the only way the
6618 // garbage collection will find the pointer is in the
6619 // argument frame, typed as a *Outer.
6622 // Set up an interface value that will cause a crash.
6623 // P1 = 1 is a non-zero, so the interface looks non-nil.
6624 // P2 = pi ensures that the data word points into the
6625 // allocated heap; if not the collection skips the interface
6626 // value as irrelevant, without dereferencing P1.
6628 pi.P2 = uintptr(unsafe.Pointer(pi))
6631 func TestCallMethodJump(t *testing.T) {
6632 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6633 // returns but before the args frame has been discarded.
6634 // This is a little clumsy but makes the failure repeatable.
6637 p := &Outer{Inner: new(Inner)}
6639 ValueOf(p).Method(0).Call(nil)
6641 // Stop garbage collecting during reflect.call.
6645 func TestCallArgLive(t *testing.T) {
6646 type T struct{ X, Y *string } // pointerful aggregate
6648 F := func(t T) { *t.X = "ok" }
6650 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6651 // between marshaling argument and the actual call.
6655 runtime.SetFinalizer(x, func(p *string) {
6657 t.Errorf("x dead prematurely")
6662 ValueOf(F).Call([]Value{ValueOf(v)})
6664 // Stop garbage collecting during reflect.call.
6668 func TestMakeFuncStackCopy(t *testing.T) {
6669 target := func(in []Value) []Value {
6672 return []Value{ValueOf(9)}
6675 var concrete func(*int, int) int
6676 fn := MakeFunc(ValueOf(concrete).Type(), target)
6677 ValueOf(&concrete).Elem().Set(fn)
6678 x := concrete(nil, 7)
6680 t.Errorf("have %#q want 9", x)
6684 // use about n KB of stack
6685 func useStack(n int) {
6689 var b [1024]byte // makes frame about 1KB
6690 useStack(n - 1 + int(b[99]))
6697 func TestValueString(t *testing.T) {
6698 rv := ValueOf(Impl{})
6699 if rv.String() != "<reflect_test.Impl Value>" {
6700 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6703 method := rv.Method(0)
6704 if method.String() != "<func() Value>" {
6705 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6709 func TestInvalid(t *testing.T) {
6710 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6711 type T struct{ v any }
6713 v := ValueOf(T{}).Field(0)
6714 if v.IsValid() != true || v.Kind() != Interface {
6715 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6718 if v.IsValid() != false || v.Kind() != Invalid {
6719 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6724 func TestLargeGCProg(t *testing.T) {
6725 fv := ValueOf(func([256]*byte) {})
6726 fv.Call([]Value{ValueOf([256]*byte{})})
6729 func fieldIndexRecover(t Type, i int) (recovered any) {
6731 recovered = recover()
6739 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6740 typ := TypeOf(struct{ X int }{10})
6741 testIndices := [...]struct {
6750 for i, tt := range testIndices {
6751 recoveredErr := fieldIndexRecover(typ, tt.i)
6753 if recoveredErr == nil {
6754 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6757 if recoveredErr != nil {
6758 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6765 func TestCallGC(t *testing.T) {
6766 f := func(a, b, c, d, e string) {
6768 g := func(in []Value) []Value {
6772 typ := ValueOf(f).Type()
6773 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6774 f2("four", "five5", "six666", "seven77", "eight888")
6777 // Issue 18635 (function version).
6778 func TestKeepFuncLive(t *testing.T) {
6779 // Test that we keep makeFuncImpl live as long as it is
6780 // referenced on the stack.
6781 typ := TypeOf(func(i int) {})
6782 var f, g func(in []Value) []Value
6783 f = func(in []Value) []Value {
6785 i := int(in[0].Int())
6787 // We can't use Value.Call here because
6788 // runtime.call* will keep the makeFuncImpl
6789 // alive. However, by converting it to an
6790 // interface value and calling that,
6791 // reflect.callReflect is the only thing that
6792 // can keep the makeFuncImpl live.
6794 // Alternate between f and g so that if we do
6795 // reuse the memory prematurely it's more
6796 // likely to get obviously corrupted.
6797 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6801 g = func(in []Value) []Value {
6803 i := int(in[0].Int())
6804 MakeFunc(typ, f).Interface().(func(i int))(i)
6807 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6810 type UnExportedFirst int
6812 func (i UnExportedFirst) ΦExported() {}
6813 func (i UnExportedFirst) unexported() {}
6816 func TestMethodByNameUnExportedFirst(t *testing.T) {
6818 if recover() != nil {
6819 t.Errorf("should not panic")
6822 typ := TypeOf(UnExportedFirst(0))
6823 m, _ := typ.MethodByName("ΦExported")
6824 if m.Name != "ΦExported" {
6825 t.Errorf("got %s, expected ΦExported", m.Name)
6829 // Issue 18635 (method version).
6830 type KeepMethodLive struct{}
6832 func (k KeepMethodLive) Method1(i int) {
6835 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6839 func (k KeepMethodLive) Method2(i int) {
6841 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6844 func TestKeepMethodLive(t *testing.T) {
6845 // Test that we keep methodValue live as long as it is
6846 // referenced on the stack.
6847 KeepMethodLive{}.Method1(10)
6850 // clobber tries to clobber unreachable memory.
6853 for i := 1; i < 32; i++ {
6854 for j := 0; j < 10; j++ {
6855 obj := make([]*byte, i)
6862 func TestFuncLayout(t *testing.T) {
6863 align := func(x uintptr) uintptr {
6864 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6867 if goarch.PtrSize == 4 {
6868 r = []byte{0, 0, 0, 1}
6880 size, argsize, retOffset uintptr
6881 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6882 intRegs, floatRegs int
6883 floatRegSize uintptr
6887 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6888 size: 6 * goarch.PtrSize,
6889 argsize: 4 * goarch.PtrSize,
6890 retOffset: 4 * goarch.PtrSize,
6891 stack: []byte{1, 0, 1, 0, 1},
6892 gc: []byte{1, 0, 1, 0, 1},
6895 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6896 size: align(align(3*4) + goarch.PtrSize + 2),
6897 argsize: align(3*4) + goarch.PtrSize + 2,
6898 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6903 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6904 size: 4 * goarch.PtrSize,
6905 argsize: 4 * goarch.PtrSize,
6906 retOffset: 4 * goarch.PtrSize,
6907 stack: []byte{1, 0, 1, 1},
6908 gc: []byte{1, 0, 1, 1},
6911 typ: ValueOf(func(a S) {}).Type(),
6912 size: 4 * goarch.PtrSize,
6913 argsize: 4 * goarch.PtrSize,
6914 retOffset: 4 * goarch.PtrSize,
6915 stack: []byte{0, 0, 1, 1},
6916 gc: []byte{0, 0, 1, 1},
6919 rcvr: ValueOf((*byte)(nil)).Type(),
6920 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6921 size: 3 * goarch.PtrSize,
6922 argsize: 3 * goarch.PtrSize,
6923 retOffset: 3 * goarch.PtrSize,
6924 stack: []byte{1, 0, 1},
6925 gc: []byte{1, 0, 1},
6928 typ: ValueOf(func(a uintptr) {}).Type(),
6929 size: goarch.PtrSize,
6930 argsize: goarch.PtrSize,
6931 retOffset: goarch.PtrSize,
6936 typ: ValueOf(func() uintptr { return 0 }).Type(),
6937 size: goarch.PtrSize,
6944 rcvr: ValueOf(uintptr(0)).Type(),
6945 typ: ValueOf(func(a uintptr) {}).Type(),
6946 size: 2 * goarch.PtrSize,
6947 argsize: 2 * goarch.PtrSize,
6948 retOffset: 2 * goarch.PtrSize,
6951 // Note: this one is tricky, as the receiver is not a pointer. But we
6952 // pass the receiver by reference to the autogenerated pointer-receiver
6953 // version of the function.
6955 // TODO(mknyszek): Add tests for non-zero register count.
6957 for _, lt := range tests {
6958 name := lt.typ.String()
6960 name = lt.rcvr.String() + "." + name
6962 t.Run(name, func(t *testing.T) {
6963 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6965 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6966 if typ.Size() != lt.size {
6967 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6969 if argsize != lt.argsize {
6970 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6972 if retOffset != lt.retOffset {
6973 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6975 if !bytes.Equal(stack, lt.stack) {
6976 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6978 if !bytes.Equal(gc, lt.gc) {
6979 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6981 if !bytes.Equal(inRegs, lt.inRegs) {
6982 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6984 if !bytes.Equal(outRegs, lt.outRegs) {
6985 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6987 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6988 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6994 // trimBitmap removes trailing 0 elements from b and returns the result.
6995 func trimBitmap(b []byte) []byte {
6996 for len(b) > 0 && b[len(b)-1] == 0 {
7002 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
7003 heapBits := GCBits(New(typ).Interface())
7005 // Trim scalars at the end, as bits might end in zero,
7006 // e.g. with rep(2, lit(1, 0)).
7007 bits = trimBitmap(bits)
7009 if !bytes.Equal(heapBits, bits) {
7010 _, _, line, _ := runtime.Caller(1)
7011 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
7015 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
7016 // Creating a slice causes the runtime to repeat a bitmap,
7017 // which exercises a different path from making the compiler
7018 // repeat a bitmap for a small array or executing a repeat in
7020 val := MakeSlice(typ, 0, cap)
7021 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
7022 heapBits := GCBits(data.Interface())
7023 // Repeat the bitmap for the slice size, trimming scalars in
7024 // the last element.
7025 bits = trimBitmap(rep(cap, bits))
7026 if !bytes.Equal(heapBits, bits) {
7027 _, _, line, _ := runtime.Caller(1)
7028 t.Errorf("line %d: heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", line, typ, cap, heapBits, bits)
7032 func TestGCBits(t *testing.T) {
7033 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
7035 // Building blocks for types seen by the compiler (like [2]Xscalar).
7036 // The compiler will create the type structures for the derived types,
7037 // including their GC metadata.
7038 type Xscalar struct{ x uintptr }
7039 type Xptr struct{ x *byte }
7040 type Xptrscalar struct {
7044 type Xscalarptr struct {
7048 type Xbigptrscalar struct {
7053 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
7055 // Building blocks for types constructed by reflect.
7056 // This code is in a separate block so that code below
7057 // cannot accidentally refer to these.
7058 // The compiler must NOT see types derived from these
7059 // (for example, [2]Scalar must NOT appear in the program),
7060 // or else reflect will use it instead of having to construct one.
7061 // The goal is to test the construction.
7062 type Scalar struct{ x uintptr }
7063 type Ptr struct{ x *byte }
7064 type Ptrscalar struct {
7068 type Scalarptr struct {
7072 type Bigptrscalar struct {
7077 Tscalar = TypeOf(Scalar{})
7078 Tint64 = TypeOf(Int64(0))
7079 Tptr = TypeOf(Ptr{})
7080 Tscalarptr = TypeOf(Scalarptr{})
7081 Tptrscalar = TypeOf(Ptrscalar{})
7082 Tbigptrscalar = TypeOf(Bigptrscalar{})
7087 verifyGCBits(t, TypeOf(Xscalar{}), empty)
7088 verifyGCBits(t, Tscalar, empty)
7089 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
7090 verifyGCBits(t, Tptr, lit(1))
7091 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
7092 verifyGCBits(t, Tscalarptr, lit(0, 1))
7093 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
7094 verifyGCBits(t, Tptrscalar, lit(1))
7096 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
7097 verifyGCBits(t, ArrayOf(0, Tptr), empty)
7098 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
7099 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
7100 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
7101 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
7102 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
7103 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
7104 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
7105 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
7106 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
7107 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
7108 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
7109 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
7110 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
7111 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
7112 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
7113 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
7114 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7115 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
7116 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7117 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
7118 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
7119 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
7120 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7121 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7123 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
7124 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
7125 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
7126 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
7127 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
7128 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
7129 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
7130 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
7131 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
7132 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
7133 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
7134 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
7135 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
7136 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
7137 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
7138 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
7139 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
7140 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
7141 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
7142 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7143 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7144 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7145 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7146 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7147 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7148 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7150 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7151 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7153 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7154 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7156 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7157 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7159 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7160 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7162 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7163 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7165 hdr := make([]byte, 8/goarch.PtrSize)
7167 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7168 verifyGCBits(t, MapBucketOf(k, e), want)
7169 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7173 map[Xscalar]Xptr(nil),
7174 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7177 map[Xscalarptr]Xptr(nil),
7178 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7179 verifyMapBucket(t, Tint64, Tptr,
7180 map[int64]Xptr(nil),
7181 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7184 map[Xscalar]Xscalar(nil),
7187 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7188 map[[2]Xscalarptr][3]Xptrscalar(nil),
7189 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7191 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7192 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7193 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7195 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7196 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7197 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7199 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7200 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7201 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7203 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7204 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7205 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7208 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7209 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7210 func lit(x ...byte) []byte { return x }
7212 func TestTypeOfTypeOf(t *testing.T) {
7213 // Check that all the type constructors return concrete *rtype implementations.
7214 // It's difficult to test directly because the reflect package is only at arm's length.
7215 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7216 check := func(name string, typ Type) {
7217 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7218 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7222 type T struct{ int }
7223 check("TypeOf", TypeOf(T{}))
7225 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7226 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7227 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7228 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7229 check("PtrTo", PointerTo(TypeOf(T{})))
7230 check("SliceOf", SliceOf(TypeOf(T{})))
7233 type XM struct{ _ bool }
7235 func (*XM) String() string { return "" }
7237 func TestPtrToMethods(t *testing.T) {
7239 yp := New(TypeOf(y)).Interface()
7240 _, ok := yp.(fmt.Stringer)
7242 t.Fatal("does not implement Stringer, but should")
7246 func TestMapAlloc(t *testing.T) {
7247 m := ValueOf(make(map[int]int, 10))
7250 allocs := testing.AllocsPerRun(100, func() {
7254 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7259 val := ValueOf(&tmp).Elem()
7260 allocs = testing.AllocsPerRun(100, func() {
7261 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7262 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7263 for i := 0; i < size/2; i++ {
7264 val.SetInt(int64(i))
7265 mv.SetMapIndex(val, val)
7269 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7271 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7272 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7273 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7276 func TestChanAlloc(t *testing.T) {
7277 // Note: for a chan int, the return Value must be allocated, so we
7278 // use a chan *int instead.
7279 c := ValueOf(make(chan *int, 1))
7280 v := ValueOf(new(int))
7281 allocs := testing.AllocsPerRun(100, func() {
7285 if allocs < 0.5 || allocs > 1.5 {
7286 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7288 // Note: there is one allocation in reflect.recv which seems to be
7289 // a limitation of escape analysis. If that is ever fixed the
7290 // allocs < 0.5 condition will trigger and this test should be fixed.
7293 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7295 type nameTest struct {
7300 var nameTests = []nameTest{
7301 {(*int32)(nil), "int32"},
7304 {(*chan D1)(nil), ""},
7305 {(*func() D1)(nil), ""},
7306 {(*<-chan D1)(nil), ""},
7307 {(*chan<- D1)(nil), ""},
7312 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7315 func TestNames(t *testing.T) {
7316 for _, test := range nameTests {
7317 typ := TypeOf(test.v).Elem()
7318 if got := typ.Name(); got != test.want {
7319 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7324 func TestExported(t *testing.T) {
7325 type ΦExported struct{}
7326 type φUnexported struct{}
7333 type exportTest struct {
7337 exportTests := []exportTest{
7341 {(*big)(nil), false},
7342 {(BigP)(nil), true},
7343 {(*BigP)(nil), true},
7344 {ΦExported{}, true},
7345 {φUnexported{}, false},
7352 for i, test := range exportTests {
7353 typ := TypeOf(test.v)
7354 if got := IsExported(typ); got != test.want {
7355 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7360 func TestTypeStrings(t *testing.T) {
7361 type stringTest struct {
7365 stringTests := []stringTest{
7366 {TypeOf(func(int) {}), "func(int)"},
7367 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7368 {TypeOf(XM{}), "reflect_test.XM"},
7369 {TypeOf(new(XM)), "*reflect_test.XM"},
7370 {TypeOf(new(XM).String), "func() string"},
7371 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7372 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7373 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7374 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7375 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7378 for i, test := range stringTests {
7379 if got, want := test.typ.String(), test.want; got != want {
7380 t.Errorf("type %d String()=%q, want %q", i, got, want)
7385 func TestOffsetLock(t *testing.T) {
7386 var wg sync.WaitGroup
7387 for i := 0; i < 4; i++ {
7391 for j := 0; j < 50; j++ {
7392 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7400 func TestSwapper(t *testing.T) {
7406 type pairPtr struct {
7418 in: []int{1, 20, 300},
7421 want: []int{300, 20, 1},
7424 in: []uintptr{1, 20, 300},
7427 want: []uintptr{300, 20, 1},
7430 in: []int16{1, 20, 300},
7433 want: []int16{300, 20, 1},
7436 in: []int8{1, 20, 100},
7439 want: []int8{100, 20, 1},
7442 in: []*I{&a, &b, &c},
7445 want: []*I{&c, &b, &a},
7448 in: []string{"eric", "sergey", "larry"},
7451 want: []string{"larry", "sergey", "eric"},
7454 in: []S{"eric", "sergey", "larry"},
7457 want: []S{"larry", "sergey", "eric"},
7460 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7463 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7466 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7469 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7473 for i, tt := range tests {
7474 inStr := fmt.Sprint(tt.in)
7475 Swapper(tt.in)(tt.i, tt.j)
7476 if !DeepEqual(tt.in, tt.want) {
7477 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7482 // TestUnaddressableField tests that the reflect package will not allow
7483 // a type from another package to be used as a named type with an
7484 // unexported field.
7486 // This ensures that unexported fields cannot be modified by other packages.
7487 func TestUnaddressableField(t *testing.T) {
7488 var b Buffer // type defined in reflect, a different package
7489 var localBuffer struct {
7492 lv := ValueOf(&localBuffer).Elem()
7494 shouldPanic("Set", func() {
7503 type Talias1 struct {
7511 type Talias2 struct {
7516 func TestAliasNames(t *testing.T) {
7517 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7518 out := fmt.Sprintf("%#v", t1)
7519 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7521 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7524 t2 := Talias2{Tint: 1, Tint2: 2}
7525 out = fmt.Sprintf("%#v", t2)
7526 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7528 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7532 func TestIssue22031(t *testing.T) {
7533 type s []struct{ C int }
7536 type t2 struct{ f s }
7539 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7540 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7543 for i, test := range tests {
7545 t.Errorf("%d: CanSet: got true, want false", i)
7550 type NonExportedFirst int
7552 func (i NonExportedFirst) ΦExported() {}
7553 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7555 func TestIssue22073(t *testing.T) {
7556 m := ValueOf(NonExportedFirst(0)).Method(0)
7558 if got := m.Type().NumOut(); got != 0 {
7559 t.Errorf("NumOut: got %v, want 0", got)
7566 func TestMapIterNonEmptyMap(t *testing.T) {
7567 m := map[string]int{"one": 1, "two": 2, "three": 3}
7568 iter := ValueOf(m).MapRange()
7569 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7570 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7574 func TestMapIterNilMap(t *testing.T) {
7575 var m map[string]int
7576 iter := ValueOf(m).MapRange()
7577 if got, want := iterateToString(iter), `[]`; got != want {
7578 t.Errorf("non-empty result iteratoring nil map: %s", got)
7582 func TestMapIterReset(t *testing.T) {
7583 iter := new(MapIter)
7585 // Use of zero iterator should panic.
7587 defer func() { recover() }()
7589 t.Error("Next did not panic")
7592 // Reset to new Map should work.
7593 m := map[string]int{"one": 1, "two": 2, "three": 3}
7594 iter.Reset(ValueOf(m))
7595 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7596 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7599 // Reset to Zero value should work, but iterating over it should panic.
7602 defer func() { recover() }()
7604 t.Error("Next did not panic")
7607 // Reset to a different Map with different types should work.
7608 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7609 iter.Reset(ValueOf(m2))
7610 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7611 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7614 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7615 m3 := map[uint64]uint64{
7620 kv := New(TypeOf(uint64(0))).Elem()
7621 for i := 0; i < 5; i++ {
7622 var seenk, seenv uint64
7623 iter.Reset(ValueOf(m3))
7627 kv.SetIterValue(iter)
7631 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7633 if seenv != 0b1110 {
7634 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7638 // Reset should not allocate.
7639 n := int(testing.AllocsPerRun(10, func() {
7640 iter.Reset(ValueOf(m2))
7644 t.Errorf("MapIter.Reset allocated %d times", n)
7648 func TestMapIterSafety(t *testing.T) {
7649 // Using a zero MapIter causes a panic, but not a crash.
7651 defer func() { recover() }()
7653 t.Fatal("Key did not panic")
7656 defer func() { recover() }()
7657 new(MapIter).Value()
7658 t.Fatal("Value did not panic")
7661 defer func() { recover() }()
7663 t.Fatal("Next did not panic")
7666 // Calling Key/Value on a MapIter before Next
7667 // causes a panic, but not a crash.
7668 var m map[string]int
7669 iter := ValueOf(m).MapRange()
7672 defer func() { recover() }()
7674 t.Fatal("Key did not panic")
7677 defer func() { recover() }()
7679 t.Fatal("Value did not panic")
7682 // Calling Next, Key, or Value on an exhausted iterator
7683 // causes a panic, but not a crash.
7684 iter.Next() // -> false
7686 defer func() { recover() }()
7688 t.Fatal("Key did not panic")
7691 defer func() { recover() }()
7693 t.Fatal("Value did not panic")
7696 defer func() { recover() }()
7698 t.Fatal("Next did not panic")
7702 func TestMapIterNext(t *testing.T) {
7703 // The first call to Next should reflect any
7704 // insertions to the map since the iterator was created.
7705 m := map[string]int{}
7706 iter := ValueOf(m).MapRange()
7708 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7709 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7713 func TestMapIterDelete0(t *testing.T) {
7714 // Delete all elements before first iteration.
7715 m := map[string]int{"one": 1, "two": 2, "three": 3}
7716 iter := ValueOf(m).MapRange()
7720 if got, want := iterateToString(iter), `[]`; got != want {
7721 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7725 func TestMapIterDelete1(t *testing.T) {
7726 // Delete all elements after first iteration.
7727 m := map[string]int{"one": 1, "two": 2, "three": 3}
7728 iter := ValueOf(m).MapRange()
7731 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7737 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7741 // iterateToString returns the set of elements
7742 // returned by an iterator in readable form.
7743 func iterateToString(it *MapIter) string {
7746 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7747 got = append(got, line)
7750 return "[" + strings.Join(got, ", ") + "]"
7753 func TestConvertibleTo(t *testing.T) {
7754 t1 := ValueOf(example1.MyStruct{}).Type()
7755 t2 := ValueOf(example2.MyStruct{}).Type()
7757 // Shouldn't raise stack overflow
7758 if t1.ConvertibleTo(t2) {
7759 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7762 t3 := ValueOf([]example1.MyStruct{}).Type()
7763 t4 := ValueOf([]example2.MyStruct{}).Type()
7765 if t3.ConvertibleTo(t4) {
7766 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7770 func TestSetIter(t *testing.T) {
7771 data := map[string]int{
7779 k := New(TypeOf("")).Elem()
7780 v := New(TypeOf(0)).Elem()
7781 shouldPanic("Value.SetIterKey called before Next", func() {
7784 shouldPanic("Value.SetIterValue called before Next", func() {
7787 data2 := map[string]int{}
7791 data2[k.Interface().(string)] = v.Interface().(int)
7793 if !DeepEqual(data, data2) {
7794 t.Errorf("maps not equal, got %v want %v", data2, data)
7796 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7799 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7805 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7806 ValueOf("").SetIterKey(i)
7808 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7809 ValueOf(0).SetIterValue(i)
7811 shouldPanic("value of type string is not assignable to type int", func() {
7812 New(TypeOf(0)).Elem().SetIterKey(i)
7814 shouldPanic("value of type int is not assignable to type string", func() {
7815 New(TypeOf("")).Elem().SetIterValue(i)
7818 // Make sure assignment conversion works.
7820 y := ValueOf(&x).Elem()
7822 if _, ok := data[x.(string)]; !ok {
7823 t.Errorf("got key %s which is not in map", x)
7826 if x.(int) < 1 || x.(int) > 3 {
7827 t.Errorf("got value %d which is not in map", x)
7830 // Try some key/value types which are direct interfaces.
7833 pp := map[*int]*int{
7836 i = ValueOf(pp).MapRange()
7839 if got := *y.Interface().(*int); got != a {
7840 t.Errorf("pointer incorrect: got %d want %d", got, a)
7843 if got := *y.Interface().(*int); got != b {
7844 t.Errorf("pointer incorrect: got %d want %d", got, b)
7847 // Make sure we panic assigning from an unexported field.
7848 m = ValueOf(struct{ m map[string]int }{data}).Field(0)
7849 for iter := m.MapRange(); iter.Next(); {
7850 shouldPanic("using value obtained using unexported field", func() {
7853 shouldPanic("using value obtained using unexported field", func() {
7854 v.SetIterValue(iter)
7859 func TestMethodCallValueCodePtr(t *testing.T) {
7860 m := ValueOf(Point{}).Method(1)
7861 want := MethodValueCallCodePtr()
7862 if got := uintptr(m.UnsafePointer()); got != want {
7863 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7865 if got := m.Pointer(); got != want {
7866 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7871 type B[T any] struct{}
7873 func TestIssue50208(t *testing.T) {
7874 want1 := "B[reflect_test.A]"
7875 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7876 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7878 want2 := "B[reflect_test.B[reflect_test.A]]"
7879 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7880 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7884 func TestNegativeKindString(t *testing.T) {
7886 s := Kind(x).String()
7889 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
7898 func TestValue_Cap(t *testing.T) {
7899 a := &[3]int{1, 2, 3}
7901 if v.Cap() != cap(a) {
7902 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7907 if v.Cap() != cap(a) {
7908 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7911 getError := func(f func()) (errorStr string) {
7914 if str, ok := e.(string); ok {
7921 e := getError(func() {
7925 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
7927 t.Errorf("error is %q, want %q", e, wantStr)
7931 func TestValue_Len(t *testing.T) {
7932 a := &[3]int{1, 2, 3}
7934 if v.Len() != len(a) {
7935 t.Errorf("Len = %d want %d", v.Len(), len(a))
7940 if v.Len() != len(a) {
7941 t.Errorf("Len = %d want %d", v.Len(), len(a))
7944 getError := func(f func()) (errorStr string) {
7947 if str, ok := e.(string); ok {
7954 e := getError(func() {
7958 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
7960 t.Errorf("error is %q, want %q", e, wantStr)
7964 func TestValue_Comparable(t *testing.T) {
7967 var i interface{} = a
7968 var iSlice interface{} = s
7969 var iArrayFalse interface{} = [2]interface{}{1, map[int]int{}}
7970 var iArrayTrue interface{} = [2]interface{}{1, struct{ I interface{} }{1}}
7971 var testcases = []struct {
8022 ValueOf(float32(1)),
8027 ValueOf(float64(1)),
8032 ValueOf(complex(float32(1), float32(1))),
8037 ValueOf(complex(float64(1), float64(1))),
8052 ValueOf(map[int]int{}),
8092 ValueOf([2]map[int]int{}),
8097 ValueOf([0]func(){}),
8102 ValueOf([2]struct{ I interface{} }{{1}, {1}}),
8107 ValueOf([2]struct{ I interface{} }{{[]int{}}, {1}}),
8112 ValueOf([2]interface{}{1, struct{ I int }{1}}),
8117 ValueOf([2]interface{}{[1]interface{}{map[int]int{}}, struct{ I int }{1}}),
8122 ValueOf(&iArrayFalse),
8127 ValueOf(&iArrayTrue),
8133 for _, cas := range testcases {
8138 got := v.Comparable()
8139 if got != cas.comparable {
8140 t.Errorf("%T.Comparable = %t, want %t", v, got, cas.comparable)
8145 type ValueEqualTest struct {
8151 var equalI interface{} = 1
8152 var equalSlice interface{} = []int{1}
8153 var nilInterface interface{}
8154 var mapInterface interface{} = map[int]int{}
8156 var valueEqualTests = []ValueEqualTest{
8203 uint16(1), uint16(1),
8208 uint32(1), uint32(1),
8213 uint64(1), uint64(1),
8218 float32(1), float32(1),
8223 float64(1), float64(1),
8228 complex(1, 1), complex(1, 1),
8233 complex128(1 + 1i), complex128(1 + 1i),
8248 (chan int)(nil), nil,
8253 (chan int)(nil), (chan int)(nil),
8263 struct{ i int }{1}, struct{ i int }{1},
8268 struct{ i int }{1}, struct{ i int }{2},
8273 &nilInterface, &nilInterface,
8278 1, ValueOf(struct{ i int }{1}).Field(0),
8284 func TestValue_Equal(t *testing.T) {
8285 for _, test := range valueEqualTests {
8287 if vv, ok := test.v.(Value); ok {
8293 if uu, ok := test.u.(Value); ok {
8306 if r := v.Equal(u); r != test.eq {
8307 t.Errorf("%s == %s got %t, want %t", v.Type(), u.Type(), r, test.eq)
8312 func TestValue_EqualNonComparable(t *testing.T) {
8313 var invalid = Value{} // ValueOf(nil)
8314 var values = []Value{
8315 // Value of slice is non-comparable.
8316 ValueOf([]int(nil)),
8319 // Value of map is non-comparable.
8320 ValueOf(map[int]int(nil)),
8321 ValueOf((map[int]int{})),
8323 // Value of func is non-comparable.
8324 ValueOf(((func())(nil))),
8327 // Value of struct is non-comparable because of non-comparable elements.
8328 ValueOf((NonComparableStruct{})),
8330 // Value of array is non-comparable because of non-comparable elements.
8331 ValueOf([0]map[int]int{}),
8332 ValueOf([0]func(){}),
8333 ValueOf(([1]struct{ I interface{} }{{[]int{}}})),
8334 ValueOf(([1]interface{}{[1]interface{}{map[int]int{}}})),
8336 for _, value := range values {
8337 // Panic when reflect.Value.Equal using two valid non-comparable values.
8338 shouldPanic("reflect.Value.Equal using two non-comparable values", func() { value.Equal(value) })
8340 // If one is non-comparable and the other is invalid, the expected result is always false.
8341 if r := value.Equal(invalid); r != false {
8342 t.Errorf("%s == invalid got %t, want false", value.Type(), r)
8347 func TestInitFuncTypes(t *testing.T) {
8349 var wg sync.WaitGroup
8352 for i := 0; i < n; i++ {
8355 ipT := TypeOf(net.IP{})
8356 for i := 0; i < ipT.NumMethod(); i++ {