1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
20 "reflect/internal/example1"
21 "reflect/internal/example2"
35 func TestBool(t *testing.T) {
38 t.Fatal("ValueOf(true).Bool() = false")
50 var _ = T{} == T{} // tests depend on T being comparable
57 func assert(t *testing.T, s, want string) {
59 t.Errorf("have %#q want %#q", s, want)
63 var typeTests = []pair{
64 {struct{ x int }{}, "int"},
65 {struct{ x int8 }{}, "int8"},
66 {struct{ x int16 }{}, "int16"},
67 {struct{ x int32 }{}, "int32"},
68 {struct{ x int64 }{}, "int64"},
69 {struct{ x uint }{}, "uint"},
70 {struct{ x uint8 }{}, "uint8"},
71 {struct{ x uint16 }{}, "uint16"},
72 {struct{ x uint32 }{}, "uint32"},
73 {struct{ x uint64 }{}, "uint64"},
74 {struct{ x float32 }{}, "float32"},
75 {struct{ x float64 }{}, "float64"},
76 {struct{ x int8 }{}, "int8"},
77 {struct{ x (**int8) }{}, "**int8"},
78 {struct{ x (**integer) }{}, "**reflect_test.integer"},
79 {struct{ x ([32]int32) }{}, "[32]int32"},
80 {struct{ x ([]int8) }{}, "[]int8"},
81 {struct{ x (map[string]int32) }{}, "map[string]int32"},
82 {struct{ x (chan<- string) }{}, "chan<- string"},
83 {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
84 {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
85 {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
86 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
93 "struct { c chan *int32; d float32 }",
95 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
98 c func(chan *integer, *int8)
101 "struct { c func(chan *reflect_test.integer, *int8) }",
109 "struct { a int8; b int32 }",
118 "struct { a int8; b int8; c int32 }",
128 "struct { a int8; b int8; c int8; d int32 }",
139 "struct { a int8; b int8; c int8; d int8; e int32 }",
151 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
155 a int8 `reflect:"hi there"`
158 `struct { a int8 "reflect:\"hi there\"" }`,
162 a int8 `reflect:"hi \x00there\t\n\"\\"`
165 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
172 "struct { f func(...int) }",
176 a(func(func(int) int) func(func(int)) int)
180 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
188 "struct { int32; int64 }",
192 var valueTests = []pair{
203 {new(float32), "256.25"},
204 {new(float64), "512.125"},
205 {new(complex64), "532.125+10i"},
206 {new(complex128), "564.25+1i"},
207 {new(string), "stringy cheese"},
209 {new(*int8), "*int8(0)"},
210 {new(**int8), "**int8(0)"},
211 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
212 {new(**integer), "**reflect_test.integer(0)"},
213 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
214 {new(chan<- string), "chan<- string"},
215 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
220 "struct { c chan *int32; d float32 }{chan *int32, 0}",
222 {new(struct{ c func(chan *integer, *int8) }),
223 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
229 "struct { a int8; b int32 }{0, 0}",
236 "struct { a int8; b int8; c int32 }{0, 0, 0}",
240 func testType(t *testing.T, i int, typ Type, want string) {
243 t.Errorf("#%d: have %#q, want %#q", i, s, want)
247 func TestTypes(t *testing.T) {
248 for i, tt := range typeTests {
249 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
253 func TestSet(t *testing.T) {
254 for i, tt := range valueTests {
283 v.SetComplex(532.125 + 10i)
285 v.SetComplex(564.25 + 1i)
287 v.SetString("stringy cheese")
291 s := valueToString(v)
293 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
298 func TestSetValue(t *testing.T) {
299 for i, tt := range valueTests {
300 v := ValueOf(tt.i).Elem()
303 v.Set(ValueOf(int(132)))
305 v.Set(ValueOf(int8(8)))
307 v.Set(ValueOf(int16(16)))
309 v.Set(ValueOf(int32(32)))
311 v.Set(ValueOf(int64(64)))
313 v.Set(ValueOf(uint(132)))
315 v.Set(ValueOf(uint8(8)))
317 v.Set(ValueOf(uint16(16)))
319 v.Set(ValueOf(uint32(32)))
321 v.Set(ValueOf(uint64(64)))
323 v.Set(ValueOf(float32(256.25)))
325 v.Set(ValueOf(512.125))
327 v.Set(ValueOf(complex64(532.125 + 10i)))
329 v.Set(ValueOf(complex128(564.25 + 1i)))
331 v.Set(ValueOf("stringy cheese"))
335 s := valueToString(v)
337 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
342 func TestMapIterSet(t *testing.T) {
343 m := make(map[string]any, len(valueTests))
344 for _, tt := range valueTests {
349 k := New(v.Type().Key()).Elem()
350 e := New(v.Type().Elem()).Elem()
356 want := m[k.String()]
359 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
361 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
362 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
364 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
365 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
369 if testenv.OptimizationOff() {
370 return // no inlining with the noopt builder
373 got := int(testing.AllocsPerRun(10, func() {
380 // Calling MapRange should not allocate even though it returns a *MapIter.
381 // The function is inlineable, so if the local usage does not escape
382 // the *MapIter, it can remain stack allocated.
385 t.Errorf("wanted %d alloc, got %d", want, got)
389 func TestCanIntUintFloatComplex(t *testing.T) {
393 type complex complex128
395 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
397 var testCases = []struct {
402 {132, [...]bool{true, false, false, false}},
403 {int8(8), [...]bool{true, false, false, false}},
404 {int16(16), [...]bool{true, false, false, false}},
405 {int32(32), [...]bool{true, false, false, false}},
406 {int64(64), [...]bool{true, false, false, false}},
408 {uint(132), [...]bool{false, true, false, false}},
409 {uint8(8), [...]bool{false, true, false, false}},
410 {uint16(16), [...]bool{false, true, false, false}},
411 {uint32(32), [...]bool{false, true, false, false}},
412 {uint64(64), [...]bool{false, true, false, false}},
413 {uintptr(0xABCD), [...]bool{false, true, false, false}},
415 {float32(256.25), [...]bool{false, false, true, false}},
416 {float64(512.125), [...]bool{false, false, true, false}},
418 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
419 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
421 {integer(-132), [...]bool{true, false, false, false}},
422 {uinteger(132), [...]bool{false, true, false, false}},
423 {float(256.25), [...]bool{false, false, true, false}},
424 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
426 {"hello world", [...]bool{false, false, false, false}},
427 {new(int), [...]bool{false, false, false, false}},
428 {new(uint), [...]bool{false, false, false, false}},
429 {new(float64), [...]bool{false, false, false, false}},
430 {new(complex64), [...]bool{false, false, false, false}},
431 {new([5]int), [...]bool{false, false, false, false}},
432 {new(integer), [...]bool{false, false, false, false}},
433 {new(map[int]int), [...]bool{false, false, false, false}},
434 {new(chan<- int), [...]bool{false, false, false, false}},
435 {new(func(a int8)), [...]bool{false, false, false, false}},
436 {new(struct{ i int }), [...]bool{false, false, false, false}},
439 for i, tc := range testCases {
441 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
443 for j := range tc.want {
444 if got[j] != tc.want[j] {
446 "#%d: v.%s() returned %t for type %T, want %t",
458 func TestCanSetField(t *testing.T) {
459 type embed struct{ x, X int }
460 type Embed struct{ x, X int }
478 type testCase struct {
479 // -1 means Addr().Elem() of current value
490 {[]int{0, -1}, false},
491 {[]int{0, 0}, false},
492 {[]int{0, 0, -1}, false},
493 {[]int{0, -1, 0}, false},
494 {[]int{0, -1, 0, -1}, false},
496 {[]int{0, 1, -1}, true},
497 {[]int{0, -1, 1}, true},
498 {[]int{0, -1, 1, -1}, true},
500 {[]int{1, -1}, false},
502 {[]int{2, -1}, true},
505 val: ValueOf(&S2{embed: &embed{}}),
508 {[]int{0, -1}, false},
509 {[]int{0, 0}, false},
510 {[]int{0, 0, -1}, false},
511 {[]int{0, -1, 0}, false},
512 {[]int{0, -1, 0, -1}, false},
514 {[]int{0, 1, -1}, true},
515 {[]int{0, -1, 1}, true},
516 {[]int{0, -1, 1, -1}, true},
524 {[]int{0, -1}, true},
525 {[]int{0, 0}, false},
526 {[]int{0, 0, -1}, false},
527 {[]int{0, -1, 0}, false},
528 {[]int{0, -1, 0, -1}, false},
530 {[]int{0, 1, -1}, true},
531 {[]int{0, -1, 1}, true},
532 {[]int{0, -1, 1, -1}, true},
537 val: ValueOf(&S4{Embed: &Embed{}}),
540 {[]int{0, -1}, true},
541 {[]int{0, 0}, false},
542 {[]int{0, 0, -1}, false},
543 {[]int{0, -1, 0}, false},
544 {[]int{0, -1, 0, -1}, false},
546 {[]int{0, 1, -1}, true},
547 {[]int{0, -1, 1}, true},
548 {[]int{0, -1, 1, -1}, true},
554 for _, tt := range tests {
555 t.Run(tt.val.Type().Name(), func(t *testing.T) {
556 for _, tc := range tt.cases {
558 for _, i := range tc.index {
559 if f.Kind() == Pointer {
568 if got := f.CanSet(); got != tc.canSet {
569 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
578 var valueToStringTests = []pair{
583 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
584 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
585 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
586 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
587 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
588 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
591 func TestValueToString(t *testing.T) {
592 for i, test := range valueToStringTests {
593 s := valueToString(ValueOf(test.i))
595 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
600 func TestArrayElemSet(t *testing.T) {
601 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
602 v.Index(4).SetInt(123)
603 s := valueToString(v)
604 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
606 t.Errorf("[10]int: have %#q want %#q", s, want)
609 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
610 v.Index(4).SetInt(123)
612 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
614 t.Errorf("[]int: have %#q want %#q", s, want1)
618 func TestPtrPointTo(t *testing.T) {
622 vi := ValueOf(&i).Elem()
623 vip.Elem().Set(vi.Addr())
625 t.Errorf("got %d, want 1234", *ip)
629 vp := ValueOf(&ip).Elem()
630 vp.Set(Zero(vp.Type()))
632 t.Errorf("got non-nil (%p), want nil", ip)
636 func TestPtrSetNil(t *testing.T) {
640 vip.Elem().Set(Zero(vip.Elem().Type()))
642 t.Errorf("got non-nil (%d), want nil", *ip)
646 func TestMapSetNil(t *testing.T) {
647 m := make(map[string]int)
649 vm.Elem().Set(Zero(vm.Elem().Type()))
651 t.Errorf("got non-nil (%p), want nil", m)
655 func TestAll(t *testing.T) {
656 testType(t, 1, TypeOf((int8)(0)), "int8")
657 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
659 typ := TypeOf((*struct {
663 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
665 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
668 testType(t, 5, f.Type, "chan *int32")
670 f, present := styp.FieldByName("d")
672 t.Errorf("FieldByName says present field is absent")
674 testType(t, 6, f.Type, "float32")
676 f, present = styp.FieldByName("absent")
678 t.Errorf("FieldByName says absent field is present")
681 typ = TypeOf([32]int32{})
682 testType(t, 7, typ, "[32]int32")
683 testType(t, 8, typ.Elem(), "int32")
685 typ = TypeOf((map[string]*int32)(nil))
686 testType(t, 9, typ, "map[string]*int32")
688 testType(t, 10, mtyp.Key(), "string")
689 testType(t, 11, mtyp.Elem(), "*int32")
691 typ = TypeOf((chan<- string)(nil))
692 testType(t, 12, typ, "chan<- string")
693 testType(t, 13, typ.Elem(), "string")
695 // make sure tag strings are not part of element type
696 typ = TypeOf(struct {
697 d []uint32 `reflect:"TAG"`
699 testType(t, 14, typ, "[]uint32")
702 func TestInterfaceGet(t *testing.T) {
707 v1 := ValueOf(&inter)
708 v2 := v1.Elem().Field(0)
709 assert(t, v2.Type().String(), "interface {}")
712 assert(t, v3.Type().String(), "float64")
715 func TestInterfaceValue(t *testing.T) {
720 v1 := ValueOf(&inter)
721 v2 := v1.Elem().Field(0)
722 assert(t, v2.Type().String(), "interface {}")
724 assert(t, v3.Type().String(), "float64")
727 if _, ok := i3.(float64); !ok {
728 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
732 func TestFunctionValue(t *testing.T) {
733 var x any = func() {}
735 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
736 t.Fatalf("TestFunction returned wrong pointer")
738 assert(t, v.Type().String(), "func()")
741 var appendTests = []struct {
744 {make([]int, 2, 4), []int{22}},
745 {make([]int, 2, 4), []int{22, 33, 44}},
748 func sameInts(x, y []int) bool {
749 if len(x) != len(y) {
752 for i, xx := range x {
760 func TestAppend(t *testing.T) {
761 for i, test := range appendTests {
762 origLen, extraLen := len(test.orig), len(test.extra)
763 want := append(test.orig, test.extra...)
764 // Convert extra from []int to []Value.
765 e0 := make([]Value, len(test.extra))
766 for j, e := range test.extra {
769 // Convert extra from []int to *SliceValue.
770 e1 := ValueOf(test.extra)
772 a0 := ValueOf(test.orig)
773 have0 := Append(a0, e0...).Interface().([]int)
774 if !sameInts(have0, want) {
775 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
777 // Check that the orig and extra slices were not modified.
778 if len(test.orig) != origLen {
779 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
781 if len(test.extra) != extraLen {
782 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
785 a1 := ValueOf(test.orig)
786 have1 := AppendSlice(a1, e1).Interface().([]int)
787 if !sameInts(have1, want) {
788 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
790 // Check that the orig and extra slices were not modified.
791 if len(test.orig) != origLen {
792 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
794 if len(test.extra) != extraLen {
795 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
800 func TestCopy(t *testing.T) {
801 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
802 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
803 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
804 for i := 0; i < len(b); i++ {
806 t.Fatalf("b != c before test")
811 aa := ValueOf(&a1).Elem()
812 ab := ValueOf(&b1).Elem()
813 for tocopy := 1; tocopy <= 7; tocopy++ {
817 for i := 0; i < tocopy; i++ {
819 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
820 tocopy, i, a[i], i, b[i])
823 for i := tocopy; i < len(b); i++ {
826 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
827 tocopy, i, a[i], i, b[i], i, c[i])
829 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
830 tocopy, i, b[i], i, c[i])
833 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
839 func TestCopyString(t *testing.T) {
840 t.Run("Slice", func(t *testing.T) {
841 s := bytes.Repeat([]byte{'_'}, 8)
844 n := Copy(val, ValueOf(""))
845 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
846 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
849 n = Copy(val, ValueOf("hello"))
850 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
851 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
854 n = Copy(val, ValueOf("helloworld"))
855 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
856 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
859 t.Run("Array", func(t *testing.T) {
860 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
861 val := ValueOf(&s).Elem()
863 n := Copy(val, ValueOf(""))
864 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
865 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
868 n = Copy(val, ValueOf("hello"))
869 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
870 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
873 n = Copy(val, ValueOf("helloworld"))
874 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
875 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
880 func TestCopyArray(t *testing.T) {
881 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
882 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
884 aa := ValueOf(&a).Elem()
885 ab := ValueOf(&b).Elem()
887 for i := 0; i < len(a); i++ {
889 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
892 for i := len(a); i < len(b); i++ {
894 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
896 t.Logf("elem %d is okay\n", i)
901 func TestBigUnnamedStruct(t *testing.T) {
902 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
904 b1 := v.Interface().(struct {
907 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
908 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
916 func TestBigStruct(t *testing.T) {
917 b := big{1, 2, 3, 4, 5}
919 b1 := v.Interface().(big)
920 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
921 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
932 type DeepEqualTest struct {
937 // Simple functions for DeepEqual tests.
941 fn3 = func() { fn1() } // Not nil.
949 var loop1, loop2 Loop
950 var loopy1, loopy2 Loopy
951 var cycleMap1, cycleMap2, cycleMap3 map[string]any
953 type structWithSelfPtr struct {
965 cycleMap1 = map[string]any{}
966 cycleMap1["cycle"] = cycleMap1
967 cycleMap2 = map[string]any{}
968 cycleMap2["cycle"] = cycleMap2
969 cycleMap3 = map[string]any{}
970 cycleMap3["different"] = cycleMap3
973 var deepEqualTests = []DeepEqualTest{
977 {int32(1), int32(1), true},
979 {float32(0.5), float32(0.5), true},
980 {"hello", "hello", true},
981 {make([]int, 10), make([]int, 10), true},
982 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
983 {Basic{1, 0.5}, Basic{1, 0.5}, true},
984 {error(nil), error(nil), true},
985 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
987 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
988 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
989 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
993 {int32(1), int32(2), false},
995 {float32(0.5), float32(0.6), false},
996 {"hello", "hey", false},
997 {make([]int, 10), make([]int, 11), false},
998 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
999 {Basic{1, 0.5}, Basic{1, 0.6}, false},
1000 {Basic{1, 0}, Basic{2, 0}, false},
1001 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
1002 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
1003 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
1004 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
1009 {[][]int{{1}}, [][]int{{2}}, false},
1010 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1012 // Fun with floating point.
1013 {math.NaN(), math.NaN(), false},
1014 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1015 {&[1]float64{math.NaN()}, self{}, true},
1016 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1017 {[]float64{math.NaN()}, self{}, true},
1018 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1019 {map[float64]float64{math.NaN(): 1}, self{}, true},
1021 // Nil vs empty: not the same.
1022 {[]int{}, []int(nil), false},
1023 {[]int{}, []int{}, true},
1024 {[]int(nil), []int(nil), true},
1025 {map[int]int{}, map[int]int(nil), false},
1026 {map[int]int{}, map[int]int{}, true},
1027 {map[int]int(nil), map[int]int(nil), true},
1031 {int32(1), int64(1), false},
1032 {0.5, "hello", false},
1033 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1034 {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
1035 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1036 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1037 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1038 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1039 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1042 {&loop1, &loop1, true},
1043 {&loop1, &loop2, true},
1044 {&loopy1, &loopy1, true},
1045 {&loopy1, &loopy2, true},
1046 {&cycleMap1, &cycleMap2, true},
1047 {&cycleMap1, &cycleMap3, false},
1050 func TestDeepEqual(t *testing.T) {
1051 for _, test := range deepEqualTests {
1052 if test.b == (self{}) {
1055 if r := DeepEqual(test.a, test.b); r != test.eq {
1056 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1061 func TestTypeOf(t *testing.T) {
1062 // Special case for nil
1063 if typ := TypeOf(nil); typ != nil {
1064 t.Errorf("expected nil type for nil value; got %v", typ)
1066 for _, test := range deepEqualTests {
1067 v := ValueOf(test.a)
1071 typ := TypeOf(test.a)
1072 if typ != v.Type() {
1073 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1078 type Recursive struct {
1083 func TestDeepEqualRecursiveStruct(t *testing.T) {
1084 a, b := new(Recursive), new(Recursive)
1085 *a = Recursive{12, a}
1086 *b = Recursive{12, b}
1087 if !DeepEqual(a, b) {
1088 t.Error("DeepEqual(recursive same) = false, want true")
1092 type _Complex struct {
1096 d map[float64]float64
1099 func TestDeepEqualComplexStruct(t *testing.T) {
1100 m := make(map[float64]float64)
1101 stra, strb := "hello", "hello"
1102 a, b := new(_Complex), new(_Complex)
1103 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1104 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1105 if !DeepEqual(a, b) {
1106 t.Error("DeepEqual(complex same) = false, want true")
1110 func TestDeepEqualComplexStructInequality(t *testing.T) {
1111 m := make(map[float64]float64)
1112 stra, strb := "hello", "helloo" // Difference is here
1113 a, b := new(_Complex), new(_Complex)
1114 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1115 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1116 if DeepEqual(a, b) {
1117 t.Error("DeepEqual(complex different) = true, want false")
1121 type UnexpT struct {
1125 func TestDeepEqualUnexportedMap(t *testing.T) {
1126 // Check that DeepEqual can look at unexported fields.
1127 x1 := UnexpT{map[int]int{1: 2}}
1128 x2 := UnexpT{map[int]int{1: 2}}
1129 if !DeepEqual(&x1, &x2) {
1130 t.Error("DeepEqual(x1, x2) = false, want true")
1133 y1 := UnexpT{map[int]int{2: 3}}
1134 if DeepEqual(&x1, &y1) {
1135 t.Error("DeepEqual(x1, y1) = true, want false")
1139 var deepEqualPerfTests = []struct {
1142 {x: int8(99), y: int8(99)},
1143 {x: []int8{99}, y: []int8{99}},
1144 {x: int16(99), y: int16(99)},
1145 {x: []int16{99}, y: []int16{99}},
1146 {x: int32(99), y: int32(99)},
1147 {x: []int32{99}, y: []int32{99}},
1148 {x: int64(99), y: int64(99)},
1149 {x: []int64{99}, y: []int64{99}},
1150 {x: int(999999), y: int(999999)},
1151 {x: []int{999999}, y: []int{999999}},
1153 {x: uint8(99), y: uint8(99)},
1154 {x: []uint8{99}, y: []uint8{99}},
1155 {x: uint16(99), y: uint16(99)},
1156 {x: []uint16{99}, y: []uint16{99}},
1157 {x: uint32(99), y: uint32(99)},
1158 {x: []uint32{99}, y: []uint32{99}},
1159 {x: uint64(99), y: uint64(99)},
1160 {x: []uint64{99}, y: []uint64{99}},
1161 {x: uint(999999), y: uint(999999)},
1162 {x: []uint{999999}, y: []uint{999999}},
1163 {x: uintptr(999999), y: uintptr(999999)},
1164 {x: []uintptr{999999}, y: []uintptr{999999}},
1166 {x: float32(1.414), y: float32(1.414)},
1167 {x: []float32{1.414}, y: []float32{1.414}},
1168 {x: float64(1.414), y: float64(1.414)},
1169 {x: []float64{1.414}, y: []float64{1.414}},
1171 {x: complex64(1.414), y: complex64(1.414)},
1172 {x: []complex64{1.414}, y: []complex64{1.414}},
1173 {x: complex128(1.414), y: complex128(1.414)},
1174 {x: []complex128{1.414}, y: []complex128{1.414}},
1177 {x: []bool{true}, y: []bool{true}},
1179 {x: "abcdef", y: "abcdef"},
1180 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1182 {x: []byte("abcdef"), y: []byte("abcdef")},
1183 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1185 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1186 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1189 func TestDeepEqualAllocs(t *testing.T) {
1190 for _, tt := range deepEqualPerfTests {
1191 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1192 got := testing.AllocsPerRun(100, func() {
1193 if !DeepEqual(tt.x, tt.y) {
1194 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1198 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1204 func BenchmarkDeepEqual(b *testing.B) {
1205 for _, bb := range deepEqualPerfTests {
1206 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1208 for i := 0; i < b.N; i++ {
1209 sink = DeepEqual(bb.x, bb.y)
1215 func check2ndField(x any, offs uintptr, t *testing.T) {
1217 f := s.Type().Field(1)
1218 if f.Offset != offs {
1219 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1223 // Check that structure alignment & offsets viewed through reflect agree with those
1224 // from the compiler itself.
1225 func TestAlignment(t *testing.T) {
1226 type T1inner struct {
1233 type T2inner struct {
1241 x := T1{T1inner{2}, 17}
1242 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1244 x1 := T2{T2inner{2, 3}, 17}
1245 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1248 func Nil(a any, t *testing.T) {
1249 n := ValueOf(a).Field(0)
1251 t.Errorf("%v should be nil", a)
1255 func NotNil(a any, t *testing.T) {
1256 n := ValueOf(a).Field(0)
1258 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1262 func TestIsNil(t *testing.T) {
1263 // These implement IsNil.
1264 // Wrap in extra struct to hide interface type.
1268 struct{ x map[string]int }{},
1269 struct{ x func() bool }{},
1270 struct{ x chan int }{},
1271 struct{ x []string }{},
1272 struct{ x unsafe.Pointer }{},
1274 for _, ts := range doNil {
1275 ty := TypeOf(ts).Field(0).Type
1277 v.IsNil() // panics if not okay to call
1280 // Check the implementations
1292 si.x = make([]int, 10)
1299 ci.x = make(chan int)
1306 mi.x = make(map[int]int)
1317 x func(t *testing.T)
1324 func TestIsZero(t *testing.T) {
1325 for i, tt := range []struct {
1354 {float32(1.2), false},
1356 {float64(1.2), false},
1357 {math.Copysign(0, -1), false},
1358 {complex64(0), true},
1359 {complex64(1.2), false},
1360 {complex128(0), true},
1361 {complex128(1.2), false},
1362 {complex(math.Copysign(0, -1), 0), false},
1363 {complex(0, math.Copysign(0, -1)), false},
1364 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1366 {uintptr(128), false},
1368 {Zero(TypeOf([5]string{})).Interface(), true},
1369 {[5]string{}, true}, // comparable array
1370 {[5]string{"", "", "", "a", ""}, false}, // comparable array
1371 {[1]*int{}, true}, // direct pointer array
1372 {[1]*int{new(int)}, false}, // direct pointer array
1373 {[3][]int{}, true}, // incomparable array
1374 {[3][]int{{1}}, false}, // incomparable array
1375 {[1 << 12]byte{}, true},
1376 {[1 << 12]byte{1}, false},
1378 {[3]Value{{}, ValueOf(0), {}}, false},
1380 {(chan string)(nil), true},
1381 {make(chan string), false},
1382 {time.After(1), false},
1384 {(func())(nil), true},
1387 {New(TypeOf(new(error)).Elem()).Elem(), true},
1388 {(io.Reader)(strings.NewReader("")), false},
1390 {(map[string]string)(nil), true},
1391 {map[string]string{}, false},
1392 {make(map[string]string), false},
1394 {(*func())(nil), true},
1395 {(*int)(nil), true},
1398 {[]string{}, false},
1399 {([]string)(nil), true},
1400 {make([]string, 0), false},
1403 {"not-zero", false},
1405 {T{}, true}, // comparable struct
1406 {T{123, 456.75, "hello", &_i}, false}, // comparable struct
1407 {struct{ p *int }{}, true}, // direct pointer struct
1408 {struct{ p *int }{new(int)}, false}, // direct pointer struct
1409 {struct{ s []int }{}, true}, // incomparable struct
1410 {struct{ s []int }{[]int{1}}, false}, // incomparable struct
1411 {struct{ Value }{}, true},
1412 {struct{ Value }{ValueOf(0)}, false},
1414 {(unsafe.Pointer)(nil), true},
1415 {(unsafe.Pointer)(new(int)), false},
1418 if v, ok := tt.x.(Value); ok {
1426 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1429 if !Zero(TypeOf(tt.x)).IsZero() {
1430 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1433 p := New(x.Type()).Elem()
1437 t.Errorf("%d: IsZero((%s)(%+v)) is true after SetZero", i, p.Kind(), tt.x)
1443 if r := recover(); r == nil {
1444 t.Error("should panic for invalid value")
1451 func BenchmarkIsZero(b *testing.B) {
1452 source := ValueOf(struct {
1453 ArrayComparable [4]T
1454 ArrayIncomparable [4]_Complex
1456 StructIncomparable _Complex
1459 for i := 0; i < source.NumField(); i++ {
1460 name := source.Type().Field(i).Name
1461 value := source.Field(i)
1462 b.Run(name, func(b *testing.B) {
1463 for i := 0; i < b.N; i++ {
1464 sink = value.IsZero()
1470 func BenchmarkSetZero(b *testing.B) {
1471 source := ValueOf(new(struct {
1480 Interface interface{ String() string }
1481 Map map[string]Value
1488 for i := 0; i < source.NumField(); i++ {
1489 name := source.Type().Field(i).Name
1490 value := source.Field(i)
1491 zero := Zero(value.Type())
1492 b.Run(name+"/Direct", func(b *testing.B) {
1493 for i := 0; i < b.N; i++ {
1497 b.Run(name+"/CachedZero", func(b *testing.B) {
1498 for i := 0; i < b.N; i++ {
1502 b.Run(name+"/NewZero", func(b *testing.B) {
1503 for i := 0; i < b.N; i++ {
1504 value.Set(Zero(value.Type()))
1510 func TestInterfaceExtraction(t *testing.T) {
1516 v := Indirect(ValueOf(&s)).Field(0).Interface()
1518 t.Error("Interface() on interface: ", v, s.W)
1522 func TestNilPtrValueSub(t *testing.T) {
1524 if pv := ValueOf(pi); pv.Elem().IsValid() {
1525 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1529 func TestMap(t *testing.T) {
1530 m := map[string]int{"a": 1, "b": 2}
1532 if n := mv.Len(); n != len(m) {
1533 t.Errorf("Len = %d, want %d", n, len(m))
1535 keys := mv.MapKeys()
1536 newmap := MakeMap(mv.Type())
1537 for k, v := range m {
1538 // Check that returned Keys match keys in range.
1539 // These aren't required to be in the same order.
1541 for _, kv := range keys {
1542 if kv.String() == k {
1548 t.Errorf("Missing key %q", k)
1551 // Check that value lookup is correct.
1552 vv := mv.MapIndex(ValueOf(k))
1553 if vi := vv.Int(); vi != int64(v) {
1554 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1557 // Copy into new map.
1558 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1560 vv := mv.MapIndex(ValueOf("not-present"))
1562 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1565 newm := newmap.Interface().(map[string]int)
1566 if len(newm) != len(m) {
1567 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1570 for k, v := range newm {
1573 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1577 newmap.SetMapIndex(ValueOf("a"), Value{})
1580 t.Errorf("newm[\"a\"] = %d after delete", v)
1583 mv = ValueOf(&m).Elem()
1584 mv.Set(Zero(mv.Type()))
1586 t.Errorf("mv.Set(nil) failed")
1590 shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
1591 shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
1594 func TestNilMap(t *testing.T) {
1595 var m map[string]int
1597 keys := mv.MapKeys()
1599 t.Errorf(">0 keys for nil map: %v", keys)
1602 // Check that value for missing key is zero.
1603 x := mv.MapIndex(ValueOf("hello"))
1604 if x.Kind() != Invalid {
1605 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1608 // Check big value too.
1609 var mbig map[string][10 << 20]byte
1610 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1611 if x.Kind() != Invalid {
1612 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1615 // Test that deletes from a nil map succeed.
1616 mv.SetMapIndex(ValueOf("hi"), Value{})
1619 func TestChan(t *testing.T) {
1620 for loop := 0; loop < 2; loop++ {
1624 // check both ways to allocate channels
1627 c = make(chan int, 1)
1630 cv = MakeChan(TypeOf(c), 1)
1631 c = cv.Interface().(chan int)
1636 if i := <-c; i != 2 {
1637 t.Errorf("reflect Send 2, native recv %d", i)
1642 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1643 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1647 val, ok := cv.TryRecv()
1648 if val.IsValid() || ok {
1649 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1654 val, ok = cv.TryRecv()
1656 t.Errorf("TryRecv on ready chan got nil")
1657 } else if i := val.Int(); i != 4 || !ok {
1658 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1663 ok = cv.TrySend(ValueOf(5))
1666 t.Errorf("TrySend on full chan succeeded: value %d", i)
1670 ok = cv.TrySend(ValueOf(6))
1672 t.Errorf("TrySend on empty chan failed")
1675 t.Errorf("TrySend failed but it did send %d", x)
1679 if i = <-c; i != 6 {
1680 t.Errorf("TrySend 6, recv %d", i)
1687 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1688 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1690 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1691 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1695 // check creation of unbuffered channel
1697 cv := MakeChan(TypeOf(c), 0)
1698 c = cv.Interface().(chan int)
1699 if cv.TrySend(ValueOf(7)) {
1700 t.Errorf("TrySend on sync chan succeeded")
1702 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1703 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1707 cv = MakeChan(TypeOf(c), 10)
1708 c = cv.Interface().(chan int)
1709 for i := 0; i < 3; i++ {
1712 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1713 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1717 // caseInfo describes a single case in a select test.
1718 type caseInfo struct {
1727 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1729 func TestSelect(t *testing.T) {
1730 selectWatch.once.Do(func() { go selectWatcher() })
1734 newop := func(n int, cap int) (ch, val Value) {
1737 c := make(chan int, cap)
1741 c := make(chan string, cap)
1743 val = ValueOf(fmt.Sprint(n))
1748 for n := 0; x.Next(); n++ {
1749 if testing.Short() && n >= 1000 {
1752 if n >= 100000 && !*allselect {
1755 if n%100000 == 0 && testing.Verbose() {
1756 println("TestSelect", n)
1758 var cases []SelectCase
1763 ch, val := newop(len(cases), 1)
1764 cases = append(cases, SelectCase{
1769 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1774 ch, val := newop(len(cases), 1)
1776 cases = append(cases, SelectCase{
1780 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1785 ch, val := newop(len(cases), 0)
1786 cases = append(cases, SelectCase{
1793 f := func() { ch.Recv() }
1794 info = append(info, caseInfo{desc: "blocking send", helper: f})
1796 info = append(info, caseInfo{desc: "blocking send"})
1802 ch, val := newop(len(cases), 0)
1803 cases = append(cases, SelectCase{
1809 f := func() { ch.Send(val) }
1810 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1812 info = append(info, caseInfo{desc: "blocking recv"})
1818 // Maybe include value to send.
1823 cases = append(cases, SelectCase{
1827 info = append(info, caseInfo{desc: "zero Chan send"})
1830 // Zero Chan receive.
1832 cases = append(cases, SelectCase{
1835 info = append(info, caseInfo{desc: "zero Chan recv"})
1840 cases = append(cases, SelectCase{
1842 Chan: ValueOf((chan int)(nil)),
1845 info = append(info, caseInfo{desc: "nil Chan send"})
1850 cases = append(cases, SelectCase{
1852 Chan: ValueOf((chan int)(nil)),
1854 info = append(info, caseInfo{desc: "nil Chan recv"})
1857 // closed Chan send.
1859 ch := make(chan int)
1861 cases = append(cases, SelectCase{
1866 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1869 // closed Chan recv.
1871 ch, val := newop(len(cases), 0)
1873 val = Zero(val.Type())
1874 cases = append(cases, SelectCase{
1878 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1881 var helper func() // goroutine to help the select complete
1883 // Add default? Must be last case here, but will permute.
1884 // Add the default if the select would otherwise
1885 // block forever, and maybe add it anyway.
1891 for i, c := range info {
1899 } else if c.helper != nil {
1901 helpers = append(helpers, i)
1904 if !canProceed || x.Maybe() {
1905 cases = append(cases, SelectCase{
1908 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1910 } else if canBlock {
1911 // Select needs to communicate with another goroutine.
1912 cas := &info[helpers[x.Choose(len(helpers))]]
1914 cas.canSelect = true
1918 // Permute cases and case info.
1919 // Doing too much here makes the exhaustive loop
1920 // too exhausting, so just do two swaps.
1921 for loop := 0; loop < 2; loop++ {
1922 i := x.Choose(len(cases))
1923 j := x.Choose(len(cases))
1924 cases[i], cases[j] = cases[j], cases[i]
1925 info[i], info[j] = info[j], info[i]
1929 // We wait before kicking off a goroutine to satisfy a blocked select.
1930 // The pause needs to be big enough to let the select block before
1931 // we run the helper, but if we lose that race once in a while it's okay: the
1932 // select will just proceed immediately. Not a big deal.
1933 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1934 pause := 10 * time.Microsecond
1935 if testing.Short() {
1936 pause = 100 * time.Microsecond
1938 time.AfterFunc(pause, helper)
1942 i, recv, recvOK, panicErr := runSelect(cases, info)
1943 if panicErr != nil && !canPanic {
1944 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1946 if panicErr == nil && canPanic && numCanSelect == 1 {
1947 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1949 if panicErr != nil {
1957 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1959 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1962 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1965 if cases[i].Dir == SelectRecv {
1966 if !recv.IsValid() {
1967 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1969 if !cas.recv.IsValid() {
1970 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1972 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1973 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1974 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1976 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1979 if recv.IsValid() || recvOK {
1980 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1986 func TestSelectMaxCases(t *testing.T) {
1987 var sCases []SelectCase
1988 channel := make(chan int)
1990 for i := 0; i < 65536; i++ {
1991 sCases = append(sCases, SelectCase{
1993 Chan: ValueOf(channel),
1997 _, _, _ = Select(sCases)
1998 sCases = append(sCases, SelectCase{
2000 Chan: ValueOf(channel),
2003 if err := recover(); err != nil {
2004 if err.(string) != "reflect.Select: too many cases (max 65536)" {
2005 t.Fatalf("unexpected error from select call with greater than max supported cases")
2008 t.Fatalf("expected select call to panic with greater than max supported cases")
2012 _, _, _ = Select(sCases)
2015 func TestSelectNop(t *testing.T) {
2016 // "select { default: }" should always return the default case.
2017 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
2019 t.Fatalf("expected Select to return 0, but got %#v", chosen)
2023 func BenchmarkSelect(b *testing.B) {
2024 channel := make(chan int)
2026 var cases []SelectCase
2027 for i := 0; i < 8; i++ {
2028 cases = append(cases, SelectCase{
2030 Chan: ValueOf(channel),
2033 for _, numCases := range []int{1, 4, 8} {
2034 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
2036 for i := 0; i < b.N; i++ {
2037 _, _, _ = Select(cases[:numCases])
2043 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
2044 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
2045 // an error describing the select and panics the entire test binary.
2046 var selectWatch struct {
2053 func selectWatcher() {
2055 time.Sleep(1 * time.Second)
2057 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
2058 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
2059 panic("select stuck")
2061 selectWatch.Unlock()
2065 // runSelect runs a single select test.
2066 // It returns the values returned by Select but also returns
2067 // a panic value if the Select panics.
2068 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
2070 panicErr = recover()
2073 selectWatch.info = nil
2074 selectWatch.Unlock()
2078 selectWatch.now = time.Now()
2079 selectWatch.info = info
2080 selectWatch.Unlock()
2082 chosen, recv, recvOK = Select(cases)
2086 // fmtSelect formats the information about a single select test.
2087 func fmtSelect(info []caseInfo) string {
2088 var buf bytes.Buffer
2089 fmt.Fprintf(&buf, "\nselect {\n")
2090 for i, cas := range info {
2091 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2092 if cas.recv.IsValid() {
2093 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2096 fmt.Fprintf(&buf, " canselect")
2099 fmt.Fprintf(&buf, " panic")
2101 fmt.Fprintf(&buf, "\n")
2103 fmt.Fprintf(&buf, "}")
2109 // Difficult test for function call because of
2110 // implicit padding between arguments.
2111 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) {
2112 return b, c, d, e, f, g, h
2115 func TestFunc(t *testing.T) {
2116 ret := ValueOf(dummy).Call([]Value{
2120 ValueOf(two{40, 50}),
2122 ValueOf(float32(70)),
2126 t.Fatalf("Call returned %d values, want 7", len(ret))
2129 i := byte(ret[0].Uint())
2130 j := int(ret[1].Int())
2131 k := byte(ret[2].Uint())
2132 l := ret[3].Interface().(two)
2133 m := byte(ret[4].Uint())
2134 n := float32(ret[5].Float())
2135 o := byte(ret[6].Uint())
2137 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2138 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)
2141 for i, v := range ret {
2143 t.Errorf("result %d is addressable", i)
2148 func TestCallConvert(t *testing.T) {
2149 v := ValueOf(new(io.ReadWriter)).Elem()
2150 f := ValueOf(func(r io.Reader) io.Reader { return r })
2151 out := f.Call([]Value{v})
2152 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2153 t.Errorf("expected [nil], got %v", out)
2157 type emptyStruct struct{}
2159 type nonEmptyStruct struct {
2163 func returnEmpty() emptyStruct {
2164 return emptyStruct{}
2167 func takesEmpty(e emptyStruct) {
2170 func returnNonEmpty(i int) nonEmptyStruct {
2171 return nonEmptyStruct{member: i}
2174 func takesNonEmpty(n nonEmptyStruct) int {
2178 func TestCallWithStruct(t *testing.T) {
2179 r := ValueOf(returnEmpty).Call(nil)
2180 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2181 t.Errorf("returning empty struct returned %#v instead", r)
2183 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2185 t.Errorf("takesEmpty returned values: %#v", r)
2187 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2188 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2189 t.Errorf("returnNonEmpty returned %#v", r)
2191 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2192 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2193 t.Errorf("takesNonEmpty returned %#v", r)
2197 func TestCallReturnsEmpty(t *testing.T) {
2198 // Issue 21717: past-the-end pointer write in Call with
2199 // nonzero-sized frame and zero-sized return value.
2201 var finalized uint32
2202 f := func() (emptyStruct, *[2]int64) {
2203 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2204 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2205 return emptyStruct{}, i
2207 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2208 timeout := time.After(5 * time.Second)
2209 for atomic.LoadUint32(&finalized) == 0 {
2212 t.Fatal("finalizer did not run")
2218 runtime.KeepAlive(v)
2221 func BenchmarkCall(b *testing.B) {
2222 fv := ValueOf(func(a, b string) {})
2224 b.RunParallel(func(pb *testing.PB) {
2225 args := []Value{ValueOf("a"), ValueOf("b")}
2234 func (i *myint) inc() {
2238 func BenchmarkCallMethod(b *testing.B) {
2243 for i := 0; i < b.N; i++ {
2248 func BenchmarkCallArgCopy(b *testing.B) {
2249 byteArray := func(n int) Value {
2250 return Zero(ArrayOf(n, TypeOf(byte(0))))
2252 sizes := [...]struct {
2256 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2257 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2258 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2259 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2260 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2262 for _, size := range sizes {
2263 bench := func(b *testing.B) {
2264 args := []Value{size.arg}
2265 b.SetBytes(int64(size.arg.Len()))
2267 b.RunParallel(func(pb *testing.PB) {
2273 name := fmt.Sprintf("size=%v", size.arg.Len())
2278 func TestMakeFunc(t *testing.T) {
2280 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2281 ValueOf(&f).Elem().Set(fv)
2283 // Call g with small arguments so that there is
2284 // something predictable (and different from the
2285 // correct results) in those positions on the stack.
2287 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2289 // Call constructed function f.
2290 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2291 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2292 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)
2296 func TestMakeFuncInterface(t *testing.T) {
2297 fn := func(i int) int { return i }
2298 incr := func(in []Value) []Value {
2299 return []Value{ValueOf(int(in[0].Int() + 1))}
2301 fv := MakeFunc(TypeOf(fn), incr)
2302 ValueOf(&fn).Elem().Set(fv)
2303 if r := fn(2); r != 3 {
2304 t.Errorf("Call returned %d, want 3", r)
2306 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2307 t.Errorf("Call returned %d, want 15", r)
2309 if r := fv.Interface().(func(int) int)(26); r != 27 {
2310 t.Errorf("Call returned %d, want 27", r)
2314 func TestMakeFuncVariadic(t *testing.T) {
2315 // Test that variadic arguments are packed into a slice and passed as last arg
2316 fn := func(_ int, is ...int) []int { return nil }
2317 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2318 ValueOf(&fn).Elem().Set(fv)
2321 if r[0] != 2 || r[1] != 3 {
2322 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2325 r = fn(1, []int{2, 3}...)
2326 if r[0] != 2 || r[1] != 3 {
2327 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2330 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2331 if r[0] != 2 || r[1] != 3 {
2332 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2335 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2336 if r[0] != 2 || r[1] != 3 {
2337 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2340 f := fv.Interface().(func(int, ...int) []int)
2343 if r[0] != 2 || r[1] != 3 {
2344 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2346 r = f(1, []int{2, 3}...)
2347 if r[0] != 2 || r[1] != 3 {
2348 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2352 // Dummy type that implements io.WriteCloser
2356 func (w *WC) Write(p []byte) (n int, err error) {
2359 func (w *WC) Close() error {
2363 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2364 // reflect.Values returned from the wrapped function should be assignment-converted
2365 // to the types returned by the result of MakeFunc.
2367 // Concrete types should be promotable to interfaces they implement.
2369 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2370 return []Value{ValueOf(io.EOF)}
2371 }).Interface().(func() error)
2374 // Super-interfaces should be promotable to simpler interfaces.
2375 var g func() io.Writer
2376 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2377 var w io.WriteCloser = &WC{}
2378 return []Value{ValueOf(&w).Elem()}
2379 }).Interface().(func() io.Writer)
2382 // Channels should be promotable to directional channels.
2383 var h func() <-chan int
2384 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2385 return []Value{ValueOf(make(chan int))}
2386 }).Interface().(func() <-chan int)
2389 // Unnamed types should be promotable to named types.
2390 type T struct{ a, b, c int }
2392 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2393 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2394 }).Interface().(func() T)
2398 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2399 // Type doesn't implement the required interface.
2400 shouldPanic("", func() {
2402 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2403 return []Value{ValueOf(int(7))}
2404 }).Interface().(func() error)
2407 // Assigning to an interface with additional methods.
2408 shouldPanic("", func() {
2409 var f func() io.ReadWriteCloser
2410 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2411 var w io.WriteCloser = &WC{}
2412 return []Value{ValueOf(&w).Elem()}
2413 }).Interface().(func() io.ReadWriteCloser)
2416 // Directional channels can't be assigned to bidirectional ones.
2417 shouldPanic("", func() {
2418 var f func() chan int
2419 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2420 var c <-chan int = make(chan int)
2421 return []Value{ValueOf(c)}
2422 }).Interface().(func() chan int)
2425 // Two named types which are otherwise identical.
2426 shouldPanic("", func() {
2427 type T struct{ a, b, c int }
2428 type U struct{ a, b, c int }
2430 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2431 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2432 }).Interface().(func() T)
2441 // This will be index 0.
2442 func (p Point) AnotherMethod(scale int) int {
2446 // This will be index 1.
2447 func (p Point) Dist(scale int) int {
2448 //println("Point.Dist", p.x, p.y, scale)
2449 return p.x*p.x*scale + p.y*p.y*scale
2452 // This will be index 2.
2453 func (p Point) GCMethod(k int) int {
2458 // This will be index 3.
2459 func (p Point) NoArgs() {
2460 // Exercise no-argument/no-result paths.
2463 // This will be index 4.
2464 func (p Point) TotalDist(points ...Point) int {
2466 for _, q := range points {
2469 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2475 // This will be index 5.
2476 func (p *Point) Int64Method(x int64) int64 {
2480 // This will be index 6.
2481 func (p *Point) Int32Method(x int32) int32 {
2485 func TestMethod(t *testing.T) {
2486 // Non-curried method of type.
2488 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2490 t.Errorf("Type Method returned %d; want 250", i)
2493 m, ok := TypeOf(p).MethodByName("Dist")
2495 t.Fatalf("method by name failed")
2497 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2499 t.Errorf("Type MethodByName returned %d; want 275", i)
2502 m, ok = TypeOf(p).MethodByName("NoArgs")
2504 t.Fatalf("method by name failed")
2506 n := len(m.Func.Call([]Value{ValueOf(p)}))
2508 t.Errorf("NoArgs returned %d values; want 0", n)
2511 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2513 t.Errorf("Pointer Type Method returned %d; want 300", i)
2516 m, ok = TypeOf(&p).MethodByName("Dist")
2518 t.Fatalf("ptr method by name failed")
2520 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2522 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2525 m, ok = TypeOf(&p).MethodByName("NoArgs")
2527 t.Fatalf("method by name failed")
2529 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2531 t.Errorf("NoArgs returned %d values; want 0", n)
2534 // Curried method of value.
2535 tfunc := TypeOf((func(int) int)(nil))
2536 v := ValueOf(p).Method(1)
2537 if tt := v.Type(); tt != tfunc {
2538 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2540 i = v.Call([]Value{ValueOf(14)})[0].Int()
2542 t.Errorf("Value Method returned %d; want 350", i)
2544 v = ValueOf(p).MethodByName("Dist")
2545 if tt := v.Type(); tt != tfunc {
2546 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2548 i = v.Call([]Value{ValueOf(15)})[0].Int()
2550 t.Errorf("Value MethodByName returned %d; want 375", i)
2552 v = ValueOf(p).MethodByName("NoArgs")
2555 // Curried method of pointer.
2556 v = ValueOf(&p).Method(1)
2557 if tt := v.Type(); tt != tfunc {
2558 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2560 i = v.Call([]Value{ValueOf(16)})[0].Int()
2562 t.Errorf("Pointer Value Method returned %d; want 400", i)
2564 v = ValueOf(&p).MethodByName("Dist")
2565 if tt := v.Type(); tt != tfunc {
2566 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2568 i = v.Call([]Value{ValueOf(17)})[0].Int()
2570 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2572 v = ValueOf(&p).MethodByName("NoArgs")
2575 // Curried method of interface value.
2576 // Have to wrap interface value in a struct to get at it.
2577 // Passing it to ValueOf directly would
2578 // access the underlying Point, not the interface.
2582 pv := ValueOf(&x).Elem()
2584 if tt := v.Type(); tt != tfunc {
2585 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2587 i = v.Call([]Value{ValueOf(18)})[0].Int()
2589 t.Errorf("Interface Method returned %d; want 450", i)
2591 v = pv.MethodByName("Dist")
2592 if tt := v.Type(); tt != tfunc {
2593 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2595 i = v.Call([]Value{ValueOf(19)})[0].Int()
2597 t.Errorf("Interface MethodByName returned %d; want 475", i)
2601 func TestMethodValue(t *testing.T) {
2605 // Check that method value have the same underlying code pointers.
2606 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2607 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2610 // Curried method of value.
2611 tfunc := TypeOf((func(int) int)(nil))
2612 v := ValueOf(p).Method(1)
2613 if tt := v.Type(); tt != tfunc {
2614 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2616 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2618 t.Errorf("Value Method returned %d; want 250", i)
2620 v = ValueOf(p).MethodByName("Dist")
2621 if tt := v.Type(); tt != tfunc {
2622 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2624 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2626 t.Errorf("Value MethodByName returned %d; want 275", i)
2628 v = ValueOf(p).MethodByName("NoArgs")
2629 ValueOf(v.Interface()).Call(nil)
2630 v.Interface().(func())()
2632 // Curried method of pointer.
2633 v = ValueOf(&p).Method(1)
2634 if tt := v.Type(); tt != tfunc {
2635 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2637 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2639 t.Errorf("Pointer Value Method returned %d; want 300", i)
2641 v = ValueOf(&p).MethodByName("Dist")
2642 if tt := v.Type(); tt != tfunc {
2643 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2645 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2647 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2649 v = ValueOf(&p).MethodByName("NoArgs")
2650 ValueOf(v.Interface()).Call(nil)
2651 v.Interface().(func())()
2653 // Curried method of pointer to pointer.
2655 v = ValueOf(&pp).Elem().Method(1)
2656 if tt := v.Type(); tt != tfunc {
2657 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2659 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2661 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2663 v = ValueOf(&pp).Elem().MethodByName("Dist")
2664 if tt := v.Type(); tt != tfunc {
2665 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2667 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2669 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2672 // Curried method of interface value.
2673 // Have to wrap interface value in a struct to get at it.
2674 // Passing it to ValueOf directly would
2675 // access the underlying Point, not the interface.
2681 pv := ValueOf(s).Field(0)
2683 if tt := v.Type(); tt != tfunc {
2684 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2686 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2688 t.Errorf("Interface Method returned %d; want 400", i)
2690 v = pv.MethodByName("Dist")
2691 if tt := v.Type(); tt != tfunc {
2692 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2694 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2696 t.Errorf("Interface MethodByName returned %d; want 425", i)
2699 // For issue #33628: method args are not stored at the right offset
2701 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2702 if x := m64(123); x != 123 {
2703 t.Errorf("Int64Method returned %d; want 123", x)
2705 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2706 if x := m32(456); x != 456 {
2707 t.Errorf("Int32Method returned %d; want 456", x)
2711 func TestVariadicMethodValue(t *testing.T) {
2713 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2714 want := int64(p.TotalDist(points[0], points[1], points[2]))
2716 // Variadic method of type.
2717 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2718 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2719 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2722 // Curried method of value.
2723 tfunc = TypeOf((func(...Point) int)(nil))
2724 v := ValueOf(p).Method(4)
2725 if tt := v.Type(); tt != tfunc {
2726 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2728 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2730 t.Errorf("Variadic Method returned %d; want %d", i, want)
2732 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2734 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2737 f := v.Interface().(func(...Point) int)
2738 i = int64(f(points[0], points[1], points[2]))
2740 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2742 i = int64(f(points...))
2744 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2748 type DirectIfaceT struct {
2752 func (d DirectIfaceT) M() int { return *d.p }
2754 func TestDirectIfaceMethod(t *testing.T) {
2756 v := DirectIfaceT{&x}
2758 m, ok := typ.MethodByName("M")
2760 t.Fatalf("cannot find method M")
2762 in := []Value{ValueOf(v)}
2763 out := m.Func.Call(in)
2764 if got := out[0].Int(); got != 42 {
2765 t.Errorf("Call with value receiver got %d, want 42", got)
2770 m, ok = typ.MethodByName("M")
2772 t.Fatalf("cannot find method M")
2774 in = []Value{ValueOf(pv)}
2775 out = m.Func.Call(in)
2776 if got := out[0].Int(); got != 42 {
2777 t.Errorf("Call with pointer receiver got %d, want 42", got)
2781 // Reflect version of $GOROOT/test/method5.go
2783 // Concrete types implementing M method.
2784 // Smaller than a word, word-sized, larger than a word.
2785 // Value and pointer receivers.
2787 type Tinter interface {
2788 M(int, byte) (byte, int)
2793 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2797 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2801 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2805 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2807 type Tbigv [2]uintptr
2809 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2811 type Tbigp [2]uintptr
2813 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2815 type tinter interface {
2816 m(int, byte) (byte, int)
2819 // Embedding via pointer.
2836 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2838 func TestMethod5(t *testing.T) {
2839 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2841 if b != 99 || x != 1000+inc {
2842 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2846 CheckV := func(name string, i Value, inc int) {
2847 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2848 b := bx[0].Interface()
2849 x := bx[1].Interface()
2850 if b != byte(99) || x != 1000+inc {
2851 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2854 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2857 var TinterType = TypeOf(new(Tinter)).Elem()
2859 CheckI := func(name string, i any, inc int) {
2861 CheckV(name, v, inc)
2862 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2867 CheckI("&sv", &sv, 1)
2870 CheckI("&sp", &sp, 2)
2874 CheckI("&wv", &wv, 3)
2877 CheckI("&wp", &wp, 4)
2879 bv := Tbigv([2]uintptr{5, 6})
2880 CheckI("bv", bv, 11)
2881 CheckI("&bv", &bv, 11)
2883 bp := Tbigp([2]uintptr{7, 8})
2884 CheckI("&bp", &bp, 15)
2890 CheckI("t4", t4, 40)
2891 CheckI("&t4", &t4, 40)
2892 CheckI("t3", t3, 40)
2893 CheckI("&t3", &t3, 40)
2894 CheckI("t2", t2, 40)
2895 CheckI("&t2", &t2, 40)
2896 CheckI("t1", t1, 40)
2897 CheckI("&t1", &t1, 40)
2900 vnil := ValueOf(&tnil).Elem()
2901 shouldPanic("Method", func() { vnil.Method(0) })
2904 func TestInterfaceSet(t *testing.T) {
2913 sv := ValueOf(&s).Elem()
2914 sv.Field(0).Set(ValueOf(p))
2915 if q := s.I.(*Point); q != p {
2916 t.Errorf("i: have %p want %p", q, p)
2921 if q := s.P.(*Point); q != p {
2922 t.Errorf("i: have %p want %p", q, p)
2925 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2927 t.Errorf("Interface Method returned %d; want 250", i)
2936 func TestAnonymousFields(t *testing.T) {
2937 var field StructField
2941 if field, ok = type1.FieldByName("int"); !ok {
2942 t.Fatal("no field 'int'")
2944 if field.Index[0] != 1 {
2945 t.Error("field index should be 1; is", field.Index)
2999 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
3021 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
3040 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
3054 var fieldTests = []FTest{
3055 {struct{}{}, "", nil, 0},
3056 {struct{}{}, "Foo", nil, 0},
3057 {S0{A: 'a'}, "A", []int{0}, 'a'},
3058 {S0{}, "D", nil, 0},
3059 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
3060 {S1{B: 'b'}, "B", []int{0}, 'b'},
3061 {S1{}, "S0", []int{1}, 0},
3062 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
3063 {S2{A: 'a'}, "A", []int{0}, 'a'},
3064 {S2{}, "S1", []int{1}, 0},
3065 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
3066 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
3067 {S2{}, "D", nil, 0},
3068 {S3{}, "S1", nil, 0},
3069 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
3070 {S3{}, "B", nil, 0},
3071 {S3{D: 'd'}, "D", []int{2}, 0},
3072 {S3{E: 'e'}, "E", []int{3}, 'e'},
3073 {S4{A: 'a'}, "A", []int{1}, 'a'},
3074 {S4{}, "B", nil, 0},
3075 {S5{}, "X", nil, 0},
3076 {S5{}, "Y", []int{2, 0, 1}, 0},
3077 {S10{}, "X", nil, 0},
3078 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
3079 {S14{}, "X", nil, 0},
3082 func TestFieldByIndex(t *testing.T) {
3083 for _, test := range fieldTests {
3085 f := s.FieldByIndex(test.index)
3087 if test.index != nil {
3088 if f.Name != test.name {
3089 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3092 t.Errorf("%s.%s found", s.Name(), f.Name)
3094 } else if len(test.index) > 0 {
3095 t.Errorf("%s.%s not found", s.Name(), test.name)
3098 if test.value != 0 {
3099 v := ValueOf(test.s).FieldByIndex(test.index)
3101 if x, ok := v.Interface().(int); ok {
3102 if x != test.value {
3103 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3106 t.Errorf("%s%v value not an int", s.Name(), test.index)
3109 t.Errorf("%s%v value not found", s.Name(), test.index)
3115 func TestFieldByName(t *testing.T) {
3116 for _, test := range fieldTests {
3118 f, found := s.FieldByName(test.name)
3120 if test.index != nil {
3121 // Verify field depth and index.
3122 if len(f.Index) != len(test.index) {
3123 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)
3125 for i, x := range f.Index {
3126 if x != test.index[i] {
3127 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3132 t.Errorf("%s.%s found", s.Name(), f.Name)
3134 } else if len(test.index) > 0 {
3135 t.Errorf("%s.%s not found", s.Name(), test.name)
3138 if test.value != 0 {
3139 v := ValueOf(test.s).FieldByName(test.name)
3141 if x, ok := v.Interface().(int); ok {
3142 if x != test.value {
3143 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3146 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3149 t.Errorf("%s.%s value not found", s.Name(), test.name)
3155 func TestImportPath(t *testing.T) {
3160 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3161 {TypeOf(int(0)), ""},
3162 {TypeOf(int8(0)), ""},
3163 {TypeOf(int16(0)), ""},
3164 {TypeOf(int32(0)), ""},
3165 {TypeOf(int64(0)), ""},
3166 {TypeOf(uint(0)), ""},
3167 {TypeOf(uint8(0)), ""},
3168 {TypeOf(uint16(0)), ""},
3169 {TypeOf(uint32(0)), ""},
3170 {TypeOf(uint64(0)), ""},
3171 {TypeOf(uintptr(0)), ""},
3172 {TypeOf(float32(0)), ""},
3173 {TypeOf(float64(0)), ""},
3174 {TypeOf(complex64(0)), ""},
3175 {TypeOf(complex128(0)), ""},
3176 {TypeOf(byte(0)), ""},
3177 {TypeOf(rune(0)), ""},
3178 {TypeOf([]byte(nil)), ""},
3179 {TypeOf([]rune(nil)), ""},
3180 {TypeOf(string("")), ""},
3181 {TypeOf((*any)(nil)).Elem(), ""},
3182 {TypeOf((*byte)(nil)), ""},
3183 {TypeOf((*rune)(nil)), ""},
3184 {TypeOf((*int64)(nil)), ""},
3185 {TypeOf(map[string]int{}), ""},
3186 {TypeOf((*error)(nil)).Elem(), ""},
3187 {TypeOf((*Point)(nil)), ""},
3188 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3190 for _, test := range tests {
3191 if path := test.t.PkgPath(); path != test.path {
3192 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3197 func TestFieldPkgPath(t *testing.T) {
3199 typ := TypeOf(struct {
3207 type pkgpathTest struct {
3214 checkPkgPath := func(name string, s []pkgpathTest) {
3215 for _, test := range s {
3216 f := typ.FieldByIndex(test.index)
3217 if got, want := f.PkgPath, test.pkgPath; got != want {
3218 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3220 if got, want := f.Anonymous, test.embedded; got != want {
3221 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3223 if got, want := f.IsExported(), test.exported; got != want {
3224 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3229 checkPkgPath("testStruct", []pkgpathTest{
3230 {[]int{0}, "", false, true}, // Exported
3231 {[]int{1}, "reflect_test", false, false}, // unexported
3232 {[]int{2}, "", true, true}, // OtherPkgFields
3233 {[]int{2, 0}, "", false, true}, // OtherExported
3234 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3235 {[]int{3}, "reflect_test", true, false}, // int
3236 {[]int{4}, "reflect_test", true, false}, // *x
3239 type localOtherPkgFields OtherPkgFields
3240 typ = TypeOf(localOtherPkgFields{})
3241 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3242 {[]int{0}, "", false, true}, // OtherExported
3243 {[]int{1}, "reflect", false, false}, // otherUnexported
3247 func TestMethodPkgPath(t *testing.T) {
3252 typ := TypeOf((*interface {
3265 {"x", "reflect_test", false},
3266 {"y", "reflect_test", false},
3269 for _, test := range tests {
3270 m, _ := typ.MethodByName(test.name)
3271 if got, want := m.PkgPath, test.pkgPath; got != want {
3272 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3274 if got, want := m.IsExported(), test.exported; got != want {
3275 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3280 func TestVariadicType(t *testing.T) {
3281 // Test example from Type documentation.
3282 var f func(x int, y ...float64)
3284 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3286 if sl.Kind() == Slice {
3287 if sl.Elem() == TypeOf(0.0) {
3295 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3296 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3297 for i := 0; i < typ.NumIn(); i++ {
3298 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3312 func (*inner) M() {}
3313 func (*outer) M() {}
3315 func TestNestedMethods(t *testing.T) {
3316 typ := TypeOf((*outer)(nil))
3317 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3318 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3319 for i := 0; i < typ.NumMethod(); i++ {
3321 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3328 func (*unexp) f() (int32, int8) { return 7, 7 }
3329 func (*unexp) g() (int64, int8) { return 8, 8 }
3331 type unexpI interface {
3335 var unexpi unexpI = new(unexp)
3337 func TestUnexportedMethods(t *testing.T) {
3338 typ := TypeOf(unexpi)
3340 if got := typ.NumMethod(); got != 0 {
3341 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3345 type InnerInt struct {
3349 type OuterInt struct {
3354 func (i *InnerInt) M() int {
3358 func TestEmbeddedMethods(t *testing.T) {
3359 typ := TypeOf((*OuterInt)(nil))
3360 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3361 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3362 for i := 0; i < typ.NumMethod(); i++ {
3364 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3369 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3370 t.Errorf("i.M() = %d, want 3", v)
3373 o := &OuterInt{1, InnerInt{2}}
3374 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3375 t.Errorf("i.M() = %d, want 2", v)
3379 if v := f(o); v != 2 {
3380 t.Errorf("f(o) = %d, want 2", v)
3384 type FuncDDD func(...any) error
3386 func (f FuncDDD) M() {}
3388 func TestNumMethodOnDDD(t *testing.T) {
3389 rv := ValueOf((FuncDDD)(nil))
3390 if n := rv.NumMethod(); n != 1 {
3391 t.Fatalf("NumMethod()=%d, want 1", n)
3395 func TestPtrTo(t *testing.T) {
3396 // This block of code means that the ptrToThis field of the
3397 // reflect data for *unsafe.Pointer is non zero, see
3398 // https://golang.org/issue/19003
3399 var x unsafe.Pointer
3406 for i = 0; i < 100; i++ {
3407 typ = PointerTo(typ)
3409 for i = 0; i < 100; i++ {
3412 if typ != TypeOf(z) {
3413 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3417 func TestPtrToGC(t *testing.T) {
3419 tt := TypeOf(T(nil))
3423 for i := 0; i < n; i++ {
3428 v.Elem().Set(ValueOf(p).Convert(pt))
3429 x = append(x, v.Interface())
3433 for i, xi := range x {
3434 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3435 if k != uintptr(i) {
3436 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3441 func BenchmarkPtrTo(b *testing.B) {
3442 // Construct a type with a zero ptrToThis.
3443 type T struct{ int }
3444 t := SliceOf(TypeOf(T{}))
3445 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3446 if !ptrToThis.IsValid() {
3447 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3449 if ptrToThis.Int() != 0 {
3450 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3454 // Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on
3456 b.RunParallel(func(pb *testing.PB) {
3463 func TestAddr(t *testing.T) {
3475 t.Errorf("Addr.Elem.Set failed to set value")
3478 // Again but take address of the ValueOf value.
3479 // Exercises generation of PtrTypes not present in the binary.
3481 v = ValueOf(&q).Elem()
3490 t.Errorf("Addr.Elem.Set failed to set value")
3493 // Starting without pointer we should get changed value
3496 v = ValueOf(&qq).Elem()
3502 if p.X != 3 { // should be unchanged from last time
3503 t.Errorf("somehow value Set changed original p")
3505 p = v0.Interface().(struct {
3509 t.Errorf("Addr.Elem.Set valued to set value in top value")
3512 // Verify that taking the address of a type gives us a pointer
3513 // which we can convert back using the usual interface
3518 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3519 *(ps.(**bool)) = new(bool)
3521 t.Errorf("Addr.Interface direct assignment failed")
3525 func noAlloc(t *testing.T, n int, f func(int)) {
3526 if testing.Short() {
3527 t.Skip("skipping malloc count in short mode")
3529 if runtime.GOMAXPROCS(0) > 1 {
3530 t.Skip("skipping; GOMAXPROCS>1")
3533 allocs := testing.AllocsPerRun(n, func() {
3538 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3542 func TestAllocations(t *testing.T) {
3543 noAlloc(t, 100, func(j int) {
3547 // We can uncomment this when compiler escape analysis
3548 // is good enough to see that the integer assigned to i
3549 // does not escape and therefore need not be allocated.
3553 // if int(v.Int()) != 42+j {
3554 // panic("wrong int")
3557 i = func(j int) int { return j }
3559 if v.Interface().(func(int) int)(j) != j {
3560 panic("wrong result")
3565 func TestSmallNegativeInt(t *testing.T) {
3569 t.Errorf("int16(-1).Int() returned %v", v.Int())
3573 func TestIndex(t *testing.T) {
3574 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3575 v := ValueOf(xs).Index(3).Interface().(byte)
3577 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3579 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3580 v = ValueOf(xa).Index(2).Interface().(byte)
3582 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3585 v = ValueOf(s).Index(3).Interface().(byte)
3587 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3591 func TestSlice(t *testing.T) {
3592 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3593 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3595 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3598 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3600 if !DeepEqual(v[0:5], xs[3:]) {
3601 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3603 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3604 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3606 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3609 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3611 if !DeepEqual(v[0:6], xa[2:]) {
3612 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3615 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3617 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3620 rv := ValueOf(&xs).Elem()
3622 ptr2 := rv.UnsafePointer()
3624 ptr3 := rv.UnsafePointer()
3626 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3630 func TestSlice3(t *testing.T) {
3631 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3632 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3634 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3637 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3639 if !DeepEqual(v[0:4], xs[3:7:7]) {
3640 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3642 rv := ValueOf(&xs).Elem()
3643 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3644 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3645 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3647 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3648 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3650 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3653 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3655 if !DeepEqual(v[0:4], xa[2:6:6]) {
3656 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3658 rv = ValueOf(&xa).Elem()
3659 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3660 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3661 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3664 rv = ValueOf(&s).Elem()
3665 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3667 rv = ValueOf(&xs).Elem()
3668 rv = rv.Slice3(3, 5, 7)
3669 ptr2 := rv.UnsafePointer()
3670 rv = rv.Slice3(4, 4, 4)
3671 ptr3 := rv.UnsafePointer()
3673 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3677 func TestSetLenCap(t *testing.T) {
3678 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3679 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3681 vs := ValueOf(&xs).Elem()
3682 shouldPanic("SetLen", func() { vs.SetLen(10) })
3683 shouldPanic("SetCap", func() { vs.SetCap(10) })
3684 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3685 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3686 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3688 if len(xs) != 5 || cap(xs) != 8 {
3689 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3692 if len(xs) != 5 || cap(xs) != 6 {
3693 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3696 if len(xs) != 5 || cap(xs) != 5 {
3697 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3699 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3700 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3702 va := ValueOf(&xa).Elem()
3703 shouldPanic("SetLen", func() { va.SetLen(8) })
3704 shouldPanic("SetCap", func() { va.SetCap(8) })
3707 func TestVariadic(t *testing.T) {
3712 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3713 if b.String() != "hello, 42 world" {
3714 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3718 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3719 if b.String() != "hello, 42 world" {
3720 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3724 func TestFuncArg(t *testing.T) {
3725 f1 := func(i int, f func(int) int) int { return f(i) }
3726 f2 := func(i int) int { return i + 1 }
3727 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3728 if r[0].Int() != 101 {
3729 t.Errorf("function returned %d, want 101", r[0].Int())
3733 func TestStructArg(t *testing.T) {
3734 type padded struct {
3741 wantA = padded{"3", 4}
3744 f := func(a padded, b uint32) {
3747 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3748 if gotA != wantA || gotB != wantB {
3749 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3753 var tagGetTests = []struct {
3758 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3759 {`protobuf:"PB(1,2)"`, `foo`, ``},
3760 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3761 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3762 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3763 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3764 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3767 func TestTagGet(t *testing.T) {
3768 for _, tt := range tagGetTests {
3769 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3770 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3775 func TestBytes(t *testing.T) {
3776 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3777 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3781 y := ValueOf(x).Bytes()
3782 if !bytes.Equal(x, y) {
3783 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3786 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3791 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3792 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3793 b := ValueOf(&a).Elem().Bytes()
3794 if !bytes.Equal(a[:], y) {
3795 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3798 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3801 // Per issue #24746, it was decided that Bytes can be called on byte slices
3802 // that normally cannot be converted from per Go language semantics.
3806 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3807 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3808 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3809 ValueOf(new(AB)).Elem().Bytes() // should not panic
3812 func TestSetBytes(t *testing.T) {
3815 y := []byte{1, 2, 3, 4}
3816 ValueOf(&x).Elem().SetBytes(y)
3817 if !bytes.Equal(x, y) {
3818 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3821 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3825 type Private struct {
3831 func (p *Private) m() {
3834 type private struct {
3842 func (p *private) P() {
3845 type Public struct {
3851 func (p *Public) M() {
3854 func TestUnexported(t *testing.T) {
3859 isValid(v.Elem().Field(0))
3860 isValid(v.Elem().Field(1))
3861 isValid(v.Elem().Field(2))
3862 isValid(v.Elem().FieldByName("X"))
3863 isValid(v.Elem().FieldByName("Y"))
3864 isValid(v.Elem().FieldByName("Z"))
3865 isValid(v.Type().Method(0).Func)
3866 m, _ := v.Type().MethodByName("M")
3868 m, _ = v.Type().MethodByName("P")
3870 isNonNil(v.Elem().Field(0).Interface())
3871 isNonNil(v.Elem().Field(1).Interface())
3872 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3873 isNonNil(v.Elem().FieldByName("X").Interface())
3874 isNonNil(v.Elem().FieldByName("Y").Interface())
3875 isNonNil(v.Elem().FieldByName("Z").Interface())
3876 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3877 isNonNil(v.Type().Method(0).Func.Interface())
3878 m, _ = v.Type().MethodByName("P")
3879 isNonNil(m.Func.Interface())
3883 isValid(v.Elem().Field(0))
3884 isValid(v.Elem().Field(1))
3885 isValid(v.Elem().FieldByName("x"))
3886 isValid(v.Elem().FieldByName("y"))
3887 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3888 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3889 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3890 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3891 shouldPanic("Method", func() { v.Type().Method(0) })
3894 func TestSetPanic(t *testing.T) {
3895 ok := func(f func()) { f() }
3896 bad := func(f func()) { shouldPanic("Set", f) }
3897 clear := func(v Value) { v.Set(Zero(v.Type())) }
3925 bad(func() { clear(v.Field(0)) }) // .X
3926 bad(func() { clear(v.Field(1)) }) // .t1
3927 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3928 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3929 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3930 bad(func() { clear(v.Field(2)) }) // .T2
3931 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3932 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3933 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3934 bad(func() { clear(v.Field(3)) }) // .NamedT1
3935 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3936 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3937 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3938 bad(func() { clear(v.Field(4)) }) // .NamedT2
3939 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3940 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3941 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3942 bad(func() { clear(v.Field(5)) }) // .namedT1
3943 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3944 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3945 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3946 bad(func() { clear(v.Field(6)) }) // .namedT2
3947 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3948 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3949 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3952 v = ValueOf(&T{}).Elem()
3953 ok(func() { clear(v.Field(0)) }) // .X
3954 bad(func() { clear(v.Field(1)) }) // .t1
3955 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3956 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3957 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3958 ok(func() { clear(v.Field(2)) }) // .T2
3959 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3960 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3961 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3962 ok(func() { clear(v.Field(3)) }) // .NamedT1
3963 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3964 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3965 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3966 ok(func() { clear(v.Field(4)) }) // .NamedT2
3967 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3968 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3969 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3970 bad(func() { clear(v.Field(5)) }) // .namedT1
3971 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3972 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3973 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3974 bad(func() { clear(v.Field(6)) }) // .namedT2
3975 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3976 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3977 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3982 func (t timp) W() {}
3983 func (t timp) Y() {}
3984 func (t timp) w() {}
3985 func (t timp) y() {}
3987 func TestCallPanic(t *testing.T) {
4012 ok := func(f func()) { f() }
4013 badCall := func(f func()) { shouldPanic("Call", f) }
4014 badMethod := func(f func()) { shouldPanic("Method", f) }
4015 call := func(v Value) { v.Call(nil) }
4018 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
4019 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
4020 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
4021 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
4022 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
4023 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
4024 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
4025 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
4026 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
4028 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
4029 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
4030 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
4031 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
4033 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
4034 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
4035 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
4036 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
4038 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
4039 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
4040 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
4041 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
4043 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
4044 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
4045 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
4046 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
4048 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
4049 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
4050 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
4051 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
4053 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
4054 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
4055 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
4056 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
4059 func TestValuePanic(t *testing.T) {
4061 shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
4062 shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
4063 shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
4064 shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
4065 shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
4066 shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
4067 shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
4068 shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
4069 shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
4070 shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
4071 shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
4072 shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
4073 shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
4074 shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
4075 shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
4076 shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
4077 shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
4078 shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
4079 shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
4080 shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
4081 shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
4082 shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
4083 shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
4084 shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
4085 shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
4086 shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
4087 shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
4088 shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
4089 shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
4090 shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
4091 shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
4092 shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
4093 shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
4094 shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
4095 shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
4096 shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
4097 shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
4098 shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
4099 shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
4100 shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
4101 shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
4104 func shouldPanic(expect string, f func()) {
4108 panic("did not panic")
4112 switch r := r.(type) {
4118 panic(fmt.Sprintf("panicked with unexpected type %T", r))
4120 if !strings.HasPrefix(s, "reflect") {
4121 panic(`panic string does not start with "reflect": ` + s)
4123 if !strings.Contains(s, expect) {
4124 panic(`panic string does not contain "` + expect + `": ` + s)
4131 func isNonNil(x any) {
4133 panic("nil interface")
4137 func isValid(v Value) {
4143 func TestAlias(t *testing.T) {
4144 x := string("hello")
4145 v := ValueOf(&x).Elem()
4146 oldvalue := v.Interface()
4147 v.SetString("world")
4148 newvalue := v.Interface()
4150 if oldvalue != "hello" || newvalue != "world" {
4151 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
4157 func EmptyInterfaceV(x any) Value {
4158 return ValueOf(&x).Elem()
4161 func ReaderV(x io.Reader) Value {
4162 return ValueOf(&x).Elem()
4165 func ReadWriterV(x io.ReadWriter) Value {
4166 return ValueOf(&x).Elem()
4170 type MyStruct struct {
4173 type MyStruct1 struct {
4178 type MyStruct2 struct {
4183 type MyString string
4185 type MyBytesArrayPtr0 *[0]byte
4186 type MyBytesArrayPtr *[4]byte
4187 type MyBytesArray0 [0]byte
4188 type MyBytesArray [4]byte
4189 type MyRunes []int32
4193 type IntChan chan int
4194 type IntChanRecv <-chan int
4195 type IntChanSend chan<- int
4196 type BytesChan chan []byte
4197 type BytesChanRecv <-chan []byte
4198 type BytesChanSend chan<- []byte
4200 var convertTests = []struct {
4206 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4212 var numbers = []string{
4213 "int8", "uint8", "int16", "uint16",
4214 "int32", "uint32", "int64", "uint64",
4215 "int", "uint", "uintptr",
4216 "float32", "float64",
4220 // all pairs but in an unusual order,
4221 // to emit all the int8, uint8 cases
4222 // before n grows too big.
4224 for i, f := range numbers {
4225 for _, g := range numbers[i:] {
4226 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4229 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4236 {V(int8(1)), V(int8(1))},
4237 {V(int8(2)), V(uint8(2))},
4238 {V(uint8(3)), V(int8(3))},
4239 {V(int8(4)), V(int16(4))},
4240 {V(int16(5)), V(int8(5))},
4241 {V(int8(6)), V(uint16(6))},
4242 {V(uint16(7)), V(int8(7))},
4243 {V(int8(8)), V(int32(8))},
4244 {V(int32(9)), V(int8(9))},
4245 {V(int8(10)), V(uint32(10))},
4246 {V(uint32(11)), V(int8(11))},
4247 {V(int8(12)), V(int64(12))},
4248 {V(int64(13)), V(int8(13))},
4249 {V(int8(14)), V(uint64(14))},
4250 {V(uint64(15)), V(int8(15))},
4251 {V(int8(16)), V(int(16))},
4252 {V(int(17)), V(int8(17))},
4253 {V(int8(18)), V(uint(18))},
4254 {V(uint(19)), V(int8(19))},
4255 {V(int8(20)), V(uintptr(20))},
4256 {V(uintptr(21)), V(int8(21))},
4257 {V(int8(22)), V(float32(22))},
4258 {V(float32(23)), V(int8(23))},
4259 {V(int8(24)), V(float64(24))},
4260 {V(float64(25)), V(int8(25))},
4261 {V(uint8(26)), V(uint8(26))},
4262 {V(uint8(27)), V(int16(27))},
4263 {V(int16(28)), V(uint8(28))},
4264 {V(uint8(29)), V(uint16(29))},
4265 {V(uint16(30)), V(uint8(30))},
4266 {V(uint8(31)), V(int32(31))},
4267 {V(int32(32)), V(uint8(32))},
4268 {V(uint8(33)), V(uint32(33))},
4269 {V(uint32(34)), V(uint8(34))},
4270 {V(uint8(35)), V(int64(35))},
4271 {V(int64(36)), V(uint8(36))},
4272 {V(uint8(37)), V(uint64(37))},
4273 {V(uint64(38)), V(uint8(38))},
4274 {V(uint8(39)), V(int(39))},
4275 {V(int(40)), V(uint8(40))},
4276 {V(uint8(41)), V(uint(41))},
4277 {V(uint(42)), V(uint8(42))},
4278 {V(uint8(43)), V(uintptr(43))},
4279 {V(uintptr(44)), V(uint8(44))},
4280 {V(uint8(45)), V(float32(45))},
4281 {V(float32(46)), V(uint8(46))},
4282 {V(uint8(47)), V(float64(47))},
4283 {V(float64(48)), V(uint8(48))},
4284 {V(int16(49)), V(int16(49))},
4285 {V(int16(50)), V(uint16(50))},
4286 {V(uint16(51)), V(int16(51))},
4287 {V(int16(52)), V(int32(52))},
4288 {V(int32(53)), V(int16(53))},
4289 {V(int16(54)), V(uint32(54))},
4290 {V(uint32(55)), V(int16(55))},
4291 {V(int16(56)), V(int64(56))},
4292 {V(int64(57)), V(int16(57))},
4293 {V(int16(58)), V(uint64(58))},
4294 {V(uint64(59)), V(int16(59))},
4295 {V(int16(60)), V(int(60))},
4296 {V(int(61)), V(int16(61))},
4297 {V(int16(62)), V(uint(62))},
4298 {V(uint(63)), V(int16(63))},
4299 {V(int16(64)), V(uintptr(64))},
4300 {V(uintptr(65)), V(int16(65))},
4301 {V(int16(66)), V(float32(66))},
4302 {V(float32(67)), V(int16(67))},
4303 {V(int16(68)), V(float64(68))},
4304 {V(float64(69)), V(int16(69))},
4305 {V(uint16(70)), V(uint16(70))},
4306 {V(uint16(71)), V(int32(71))},
4307 {V(int32(72)), V(uint16(72))},
4308 {V(uint16(73)), V(uint32(73))},
4309 {V(uint32(74)), V(uint16(74))},
4310 {V(uint16(75)), V(int64(75))},
4311 {V(int64(76)), V(uint16(76))},
4312 {V(uint16(77)), V(uint64(77))},
4313 {V(uint64(78)), V(uint16(78))},
4314 {V(uint16(79)), V(int(79))},
4315 {V(int(80)), V(uint16(80))},
4316 {V(uint16(81)), V(uint(81))},
4317 {V(uint(82)), V(uint16(82))},
4318 {V(uint16(83)), V(uintptr(83))},
4319 {V(uintptr(84)), V(uint16(84))},
4320 {V(uint16(85)), V(float32(85))},
4321 {V(float32(86)), V(uint16(86))},
4322 {V(uint16(87)), V(float64(87))},
4323 {V(float64(88)), V(uint16(88))},
4324 {V(int32(89)), V(int32(89))},
4325 {V(int32(90)), V(uint32(90))},
4326 {V(uint32(91)), V(int32(91))},
4327 {V(int32(92)), V(int64(92))},
4328 {V(int64(93)), V(int32(93))},
4329 {V(int32(94)), V(uint64(94))},
4330 {V(uint64(95)), V(int32(95))},
4331 {V(int32(96)), V(int(96))},
4332 {V(int(97)), V(int32(97))},
4333 {V(int32(98)), V(uint(98))},
4334 {V(uint(99)), V(int32(99))},
4335 {V(int32(100)), V(uintptr(100))},
4336 {V(uintptr(101)), V(int32(101))},
4337 {V(int32(102)), V(float32(102))},
4338 {V(float32(103)), V(int32(103))},
4339 {V(int32(104)), V(float64(104))},
4340 {V(float64(105)), V(int32(105))},
4341 {V(uint32(106)), V(uint32(106))},
4342 {V(uint32(107)), V(int64(107))},
4343 {V(int64(108)), V(uint32(108))},
4344 {V(uint32(109)), V(uint64(109))},
4345 {V(uint64(110)), V(uint32(110))},
4346 {V(uint32(111)), V(int(111))},
4347 {V(int(112)), V(uint32(112))},
4348 {V(uint32(113)), V(uint(113))},
4349 {V(uint(114)), V(uint32(114))},
4350 {V(uint32(115)), V(uintptr(115))},
4351 {V(uintptr(116)), V(uint32(116))},
4352 {V(uint32(117)), V(float32(117))},
4353 {V(float32(118)), V(uint32(118))},
4354 {V(uint32(119)), V(float64(119))},
4355 {V(float64(120)), V(uint32(120))},
4356 {V(int64(121)), V(int64(121))},
4357 {V(int64(122)), V(uint64(122))},
4358 {V(uint64(123)), V(int64(123))},
4359 {V(int64(124)), V(int(124))},
4360 {V(int(125)), V(int64(125))},
4361 {V(int64(126)), V(uint(126))},
4362 {V(uint(127)), V(int64(127))},
4363 {V(int64(128)), V(uintptr(128))},
4364 {V(uintptr(129)), V(int64(129))},
4365 {V(int64(130)), V(float32(130))},
4366 {V(float32(131)), V(int64(131))},
4367 {V(int64(132)), V(float64(132))},
4368 {V(float64(133)), V(int64(133))},
4369 {V(uint64(134)), V(uint64(134))},
4370 {V(uint64(135)), V(int(135))},
4371 {V(int(136)), V(uint64(136))},
4372 {V(uint64(137)), V(uint(137))},
4373 {V(uint(138)), V(uint64(138))},
4374 {V(uint64(139)), V(uintptr(139))},
4375 {V(uintptr(140)), V(uint64(140))},
4376 {V(uint64(141)), V(float32(141))},
4377 {V(float32(142)), V(uint64(142))},
4378 {V(uint64(143)), V(float64(143))},
4379 {V(float64(144)), V(uint64(144))},
4380 {V(int(145)), V(int(145))},
4381 {V(int(146)), V(uint(146))},
4382 {V(uint(147)), V(int(147))},
4383 {V(int(148)), V(uintptr(148))},
4384 {V(uintptr(149)), V(int(149))},
4385 {V(int(150)), V(float32(150))},
4386 {V(float32(151)), V(int(151))},
4387 {V(int(152)), V(float64(152))},
4388 {V(float64(153)), V(int(153))},
4389 {V(uint(154)), V(uint(154))},
4390 {V(uint(155)), V(uintptr(155))},
4391 {V(uintptr(156)), V(uint(156))},
4392 {V(uint(157)), V(float32(157))},
4393 {V(float32(158)), V(uint(158))},
4394 {V(uint(159)), V(float64(159))},
4395 {V(float64(160)), V(uint(160))},
4396 {V(uintptr(161)), V(uintptr(161))},
4397 {V(uintptr(162)), V(float32(162))},
4398 {V(float32(163)), V(uintptr(163))},
4399 {V(uintptr(164)), V(float64(164))},
4400 {V(float64(165)), V(uintptr(165))},
4401 {V(float32(166)), V(float32(166))},
4402 {V(float32(167)), V(float64(167))},
4403 {V(float64(168)), V(float32(168))},
4404 {V(float64(169)), V(float64(169))},
4407 {V(float64(1.5)), V(int(1))},
4410 {V(complex64(1i)), V(complex64(1i))},
4411 {V(complex64(2i)), V(complex128(2i))},
4412 {V(complex128(3i)), V(complex64(3i))},
4413 {V(complex128(4i)), V(complex128(4i))},
4416 {V(string("hello")), V(string("hello"))},
4417 {V(string("bytes1")), V([]byte("bytes1"))},
4418 {V([]byte("bytes2")), V(string("bytes2"))},
4419 {V([]byte("bytes3")), V([]byte("bytes3"))},
4420 {V(string("runes♝")), V([]rune("runes♝"))},
4421 {V([]rune("runes♕")), V(string("runes♕"))},
4422 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4423 {V(int('a')), V(string("a"))},
4424 {V(int8('a')), V(string("a"))},
4425 {V(int16('a')), V(string("a"))},
4426 {V(int32('a')), V(string("a"))},
4427 {V(int64('a')), V(string("a"))},
4428 {V(uint('a')), V(string("a"))},
4429 {V(uint8('a')), V(string("a"))},
4430 {V(uint16('a')), V(string("a"))},
4431 {V(uint32('a')), V(string("a"))},
4432 {V(uint64('a')), V(string("a"))},
4433 {V(uintptr('a')), V(string("a"))},
4434 {V(int(-1)), V(string("\uFFFD"))},
4435 {V(int8(-2)), V(string("\uFFFD"))},
4436 {V(int16(-3)), V(string("\uFFFD"))},
4437 {V(int32(-4)), V(string("\uFFFD"))},
4438 {V(int64(-5)), V(string("\uFFFD"))},
4439 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4440 {V(int64(1 << 32)), V(string("\uFFFD"))},
4441 {V(uint(0x110001)), V(string("\uFFFD"))},
4442 {V(uint32(0x110002)), V(string("\uFFFD"))},
4443 {V(uint64(0x110003)), V(string("\uFFFD"))},
4444 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4445 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4448 {V(MyString("hello")), V(string("hello"))},
4449 {V(string("hello")), V(MyString("hello"))},
4450 {V(string("hello")), V(string("hello"))},
4451 {V(MyString("hello")), V(MyString("hello"))},
4452 {V(MyString("bytes1")), V([]byte("bytes1"))},
4453 {V([]byte("bytes2")), V(MyString("bytes2"))},
4454 {V([]byte("bytes3")), V([]byte("bytes3"))},
4455 {V(MyString("runes♝")), V([]rune("runes♝"))},
4456 {V([]rune("runes♕")), V(MyString("runes♕"))},
4457 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4458 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4459 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4460 {V(int('a')), V(MyString("a"))},
4461 {V(int8('a')), V(MyString("a"))},
4462 {V(int16('a')), V(MyString("a"))},
4463 {V(int32('a')), V(MyString("a"))},
4464 {V(int64('a')), V(MyString("a"))},
4465 {V(uint('a')), V(MyString("a"))},
4466 {V(uint8('a')), V(MyString("a"))},
4467 {V(uint16('a')), V(MyString("a"))},
4468 {V(uint32('a')), V(MyString("a"))},
4469 {V(uint64('a')), V(MyString("a"))},
4470 {V(uintptr('a')), V(MyString("a"))},
4471 {V(int(-1)), V(MyString("\uFFFD"))},
4472 {V(int8(-2)), V(MyString("\uFFFD"))},
4473 {V(int16(-3)), V(MyString("\uFFFD"))},
4474 {V(int32(-4)), V(MyString("\uFFFD"))},
4475 {V(int64(-5)), V(MyString("\uFFFD"))},
4476 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4477 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4478 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4479 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4482 {V(string("bytes1")), V(MyBytes("bytes1"))},
4483 {V(MyBytes("bytes2")), V(string("bytes2"))},
4484 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4485 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4486 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4489 {V(string("runes♝")), V(MyRunes("runes♝"))},
4490 {V(MyRunes("runes♕")), V(string("runes♕"))},
4491 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4492 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4493 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4495 // slice to array pointer
4496 {V([]byte(nil)), V((*[0]byte)(nil))},
4497 {V([]byte{}), V(new([0]byte))},
4498 {V([]byte{7}), V(&[1]byte{7})},
4499 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4500 {V(MyBytes([]byte{})), V(new([0]byte))},
4501 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4502 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4503 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4504 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4505 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4506 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4508 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4509 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4510 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4511 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4512 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4513 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4514 {V(new([0]byte)), V(new(MyBytesArray0))},
4515 {V(new(MyBytesArray0)), V(new([0]byte))},
4516 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4517 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4519 // named types and equal underlying types
4520 {V(new(int)), V(new(integer))},
4521 {V(new(integer)), V(new(int))},
4522 {V(Empty{}), V(struct{}{})},
4523 {V(new(Empty)), V(new(struct{}))},
4524 {V(struct{}{}), V(Empty{})},
4525 {V(new(struct{})), V(new(Empty))},
4526 {V(Empty{}), V(Empty{})},
4527 {V(MyBytes{}), V([]byte{})},
4528 {V([]byte{}), V(MyBytes{})},
4529 {V((func())(nil)), V(MyFunc(nil))},
4530 {V((MyFunc)(nil)), V((func())(nil))},
4532 // structs with different tags
4545 {V(MyStruct{}), V(struct {
4551 }{}), V(MyStruct{})},
4553 {V(MyStruct{}), V(struct {
4559 }{}), V(MyStruct{})},
4561 {V(MyStruct1{}), V(MyStruct2{})},
4562 {V(MyStruct2{}), V(MyStruct1{})},
4564 // can convert *byte and *MyByte
4565 {V((*byte)(nil)), V((*MyByte)(nil))},
4566 {V((*MyByte)(nil)), V((*byte)(nil))},
4568 // cannot convert mismatched array sizes
4569 {V([2]byte{}), V([2]byte{})},
4570 {V([3]byte{}), V([3]byte{})},
4572 // cannot convert other instances
4573 {V((**byte)(nil)), V((**byte)(nil))},
4574 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4575 {V((chan byte)(nil)), V((chan byte)(nil))},
4576 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4577 {V(([]byte)(nil)), V(([]byte)(nil))},
4578 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4579 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4580 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4581 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4582 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4583 {V([2]byte{}), V([2]byte{})},
4584 {V([2]MyByte{}), V([2]MyByte{})},
4587 {V((***int)(nil)), V((***int)(nil))},
4588 {V((***byte)(nil)), V((***byte)(nil))},
4589 {V((***int32)(nil)), V((***int32)(nil))},
4590 {V((***int64)(nil)), V((***int64)(nil))},
4591 {V((chan byte)(nil)), V((chan byte)(nil))},
4592 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4593 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4594 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4595 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4596 {V([]uint(nil)), V([]uint(nil))},
4597 {V([]int(nil)), V([]int(nil))},
4598 {V(new(any)), V(new(any))},
4599 {V(new(io.Reader)), V(new(io.Reader))},
4600 {V(new(io.Writer)), V(new(io.Writer))},
4603 {V(IntChan(nil)), V((chan<- int)(nil))},
4604 {V(IntChan(nil)), V((<-chan int)(nil))},
4605 {V((chan int)(nil)), V(IntChanRecv(nil))},
4606 {V((chan int)(nil)), V(IntChanSend(nil))},
4607 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4608 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4609 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4610 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4611 {V(IntChan(nil)), V((chan int)(nil))},
4612 {V((chan int)(nil)), V(IntChan(nil))},
4613 {V((chan int)(nil)), V((<-chan int)(nil))},
4614 {V((chan int)(nil)), V((chan<- int)(nil))},
4615 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4616 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4617 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4618 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4619 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4620 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4621 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4622 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4623 {V(BytesChan(nil)), V((chan []byte)(nil))},
4624 {V((chan []byte)(nil)), V(BytesChan(nil))},
4625 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4626 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4628 // cannot convert other instances (channels)
4629 {V(IntChan(nil)), V(IntChan(nil))},
4630 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4631 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4632 {V(BytesChan(nil)), V(BytesChan(nil))},
4633 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4634 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4637 {V(int(1)), EmptyInterfaceV(int(1))},
4638 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4639 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4640 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4641 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4644 func TestConvert(t *testing.T) {
4645 canConvert := map[[2]Type]bool{}
4646 all := map[Type]bool{}
4648 for _, tt := range convertTests {
4650 if !t1.ConvertibleTo(t1) {
4651 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4656 if !t1.ConvertibleTo(t2) {
4657 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4663 canConvert[[2]Type{t1, t2}] = true
4665 // vout1 represents the in value converted to the in type.
4667 if !v1.CanConvert(t1) {
4668 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4670 vout1 := v1.Convert(t1)
4671 out1 := vout1.Interface()
4672 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4673 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4676 // vout2 represents the in value converted to the out type.
4677 if !v1.CanConvert(t2) {
4678 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4680 vout2 := v1.Convert(t2)
4681 out2 := vout2.Interface()
4682 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4683 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4685 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4686 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4689 // vout3 represents a new value of the out type, set to vout2. This makes
4690 // sure the converted value vout2 is really usable as a regular value.
4691 vout3 := New(t2).Elem()
4693 out3 := vout3.Interface()
4694 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4695 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4699 t.Errorf("table entry %v is RO, should not be", v1)
4702 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4705 t.Errorf("conversion output %v is RO, should not be", vout2)
4708 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4710 if !IsRO(MakeRO(v1).Convert(t1)) {
4711 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4713 if !IsRO(MakeRO(v1).Convert(t2)) {
4714 t.Errorf("RO conversion output %v is not RO, should be", v1)
4718 // Assume that of all the types we saw during the tests,
4719 // if there wasn't an explicit entry for a conversion between
4720 // a pair of types, then it's not to be allowed. This checks for
4721 // things like 'int64' converting to '*int'.
4722 for t1 := range all {
4723 for t2 := range all {
4724 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4725 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4726 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4732 func TestConvertPanic(t *testing.T) {
4733 s := make([]byte, 4)
4737 if !v.Type().ConvertibleTo(pt) {
4738 t.Errorf("[]byte should be convertible to *[8]byte")
4740 if v.CanConvert(pt) {
4741 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4743 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4748 var gFloat32 float32
4750 const snan uint32 = 0x7f800001
4752 func TestConvertNaNs(t *testing.T) {
4753 // Test to see if a store followed by a load of a signaling NaN
4754 // maintains the signaling bit. (This used to fail on the 387 port.)
4755 gFloat32 = math.Float32frombits(snan)
4756 runtime.Gosched() // make sure we don't optimize the store/load away
4757 if got := math.Float32bits(gFloat32); got != snan {
4758 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4760 // Test reflect's conversion between float32s. See issue 36400.
4761 type myFloat32 float32
4762 x := V(myFloat32(math.Float32frombits(snan)))
4763 y := x.Convert(TypeOf(float32(0)))
4764 z := y.Interface().(float32)
4765 if got := math.Float32bits(z); got != snan {
4766 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4770 type ComparableStruct struct {
4774 type NonComparableStruct struct {
4779 var comparableTests = []struct {
4784 {TypeOf("hello"), true},
4785 {TypeOf(new(byte)), true},
4786 {TypeOf((func())(nil)), false},
4787 {TypeOf([]byte{}), false},
4788 {TypeOf(map[string]int{}), false},
4789 {TypeOf(make(chan int)), true},
4790 {TypeOf(1.5), true},
4791 {TypeOf(false), true},
4793 {TypeOf(ComparableStruct{}), true},
4794 {TypeOf(NonComparableStruct{}), false},
4795 {TypeOf([10]map[string]int{}), false},
4796 {TypeOf([10]string{}), true},
4797 {TypeOf(new(any)).Elem(), true},
4800 func TestComparable(t *testing.T) {
4801 for _, tt := range comparableTests {
4802 if ok := tt.typ.Comparable(); ok != tt.ok {
4803 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4808 func TestOverflow(t *testing.T) {
4809 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4810 t.Errorf("%v wrongly overflows float64", 1e300)
4813 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4814 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4815 t.Errorf("%v wrongly overflows float32", maxFloat32)
4817 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4818 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4819 t.Errorf("%v should overflow float32", ovfFloat32)
4821 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4822 t.Errorf("%v should overflow float32", -ovfFloat32)
4825 maxInt32 := int64(0x7fffffff)
4826 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4827 t.Errorf("%v wrongly overflows int32", maxInt32)
4829 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4830 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4832 ovfInt32 := int64(1 << 31)
4833 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4834 t.Errorf("%v should overflow int32", ovfInt32)
4837 maxUint32 := uint64(0xffffffff)
4838 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4839 t.Errorf("%v wrongly overflows uint32", maxUint32)
4841 ovfUint32 := uint64(1 << 32)
4842 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4843 t.Errorf("%v should overflow uint32", ovfUint32)
4847 func checkSameType(t *testing.T, x Type, y any) {
4848 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4849 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4853 func TestArrayOf(t *testing.T) {
4854 // check construction and use of type not in binary
4857 value func(i int) any
4863 value: func(i int) any { type Tint int; return Tint(i) },
4869 value: func(i int) any { type Tint int; return Tint(i) },
4871 want: "[0 1 2 3 4 5 6 7 8 9]",
4875 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4877 want: "[0 1 2 3 4 5 6 7 8 9]",
4881 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4883 want: "[0 1 2 3 4 5 6 7 8 9]",
4887 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4889 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4893 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4895 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4899 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4901 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4905 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4907 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4911 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4913 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4917 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4919 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4923 value: func(i int) any {
4924 type TstructUV struct {
4928 return TstructUV{i, float64(i)}
4931 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4935 for _, table := range tests {
4936 at := ArrayOf(table.n, TypeOf(table.value(0)))
4938 vok := New(at).Elem()
4939 vnot := New(at).Elem()
4940 for i := 0; i < v.Len(); i++ {
4941 v.Index(i).Set(ValueOf(table.value(i)))
4942 vok.Index(i).Set(ValueOf(table.value(i)))
4947 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4949 s := fmt.Sprint(v.Interface())
4950 if s != table.want {
4951 t.Errorf("constructed array = %s, want %s", s, table.want)
4954 if table.comparable != at.Comparable() {
4955 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4957 if table.comparable {
4959 if DeepEqual(vnot.Interface(), v.Interface()) {
4961 "arrays (%#v) compare ok (but should not)",
4966 if !DeepEqual(vok.Interface(), v.Interface()) {
4968 "arrays (%#v) compare NOT-ok (but should)",
4975 // check that type already in binary is found
4977 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4980 func TestArrayOfGC(t *testing.T) {
4982 tt := TypeOf(T(nil))
4985 for i := 0; i < n; i++ {
4986 v := New(ArrayOf(n, tt)).Elem()
4987 for j := 0; j < v.Len(); j++ {
4989 *p = uintptr(i*n + j)
4990 v.Index(j).Set(ValueOf(p).Convert(tt))
4992 x = append(x, v.Interface())
4996 for i, xi := range x {
4998 for j := 0; j < v.Len(); j++ {
4999 k := v.Index(j).Elem().Interface()
5000 if k != uintptr(i*n+j) {
5001 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5007 func TestArrayOfAlg(t *testing.T) {
5008 at := ArrayOf(6, TypeOf(byte(0)))
5009 v1 := New(at).Elem()
5010 v2 := New(at).Elem()
5011 if v1.Interface() != v1.Interface() {
5012 t.Errorf("constructed array %v not equal to itself", v1.Interface())
5014 v1.Index(5).Set(ValueOf(byte(1)))
5015 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
5016 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
5019 at = ArrayOf(6, TypeOf([]int(nil)))
5021 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5024 func TestArrayOfGenericAlg(t *testing.T) {
5025 at1 := ArrayOf(5, TypeOf(string("")))
5026 at := ArrayOf(6, at1)
5027 v1 := New(at).Elem()
5028 v2 := New(at).Elem()
5029 if v1.Interface() != v1.Interface() {
5030 t.Errorf("constructed array %v not equal to itself", v1.Interface())
5033 v1.Index(0).Index(0).Set(ValueOf("abc"))
5034 v2.Index(0).Index(0).Set(ValueOf("efg"))
5035 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
5036 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
5039 v1.Index(0).Index(0).Set(ValueOf("abc"))
5040 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
5041 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
5042 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
5046 m := MakeMap(MapOf(at, TypeOf(int(0))))
5047 m.SetMapIndex(v1, ValueOf(1))
5048 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5049 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
5053 func TestArrayOfDirectIface(t *testing.T) {
5056 i1 := Zero(TypeOf(T{})).Interface()
5057 v1 := ValueOf(&i1).Elem()
5058 p1 := v1.InterfaceData()[1]
5060 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
5061 v2 := ValueOf(&i2).Elem()
5062 p2 := v2.InterfaceData()[1]
5065 t.Errorf("got p1=%v. want=%v", p1, nil)
5069 t.Errorf("got p2=%v. want=%v", p2, nil)
5074 i1 := Zero(TypeOf(T{})).Interface()
5075 v1 := ValueOf(&i1).Elem()
5076 p1 := v1.InterfaceData()[1]
5078 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
5079 v2 := ValueOf(&i2).Elem()
5080 p2 := v2.InterfaceData()[1]
5083 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5087 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5092 // Ensure passing in negative lengths panics.
5093 // See https://golang.org/issue/43603
5094 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
5095 shouldPanic("reflect: negative length passed to ArrayOf", func() {
5096 ArrayOf(-1, TypeOf(byte(0)))
5100 func TestSliceOf(t *testing.T) {
5101 // check construction and use of type not in binary
5103 st := SliceOf(TypeOf(T(1)))
5104 if got, want := st.String(), "[]reflect_test.T"; got != want {
5105 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
5107 v := MakeSlice(st, 10, 10)
5109 for i := 0; i < v.Len(); i++ {
5110 v.Index(i).Set(ValueOf(T(i)))
5113 s := fmt.Sprint(v.Interface())
5114 want := "[0 1 2 3 4 5 6 7 8 9]"
5116 t.Errorf("constructed slice = %s, want %s", s, want)
5119 // check that type already in binary is found
5121 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
5124 func TestSliceOverflow(t *testing.T) {
5125 // check that MakeSlice panics when size of slice overflows uint
5128 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5130 t.Fatal("slice size does not overflow")
5133 st := SliceOf(TypeOf(x))
5137 t.Fatal("slice overflow does not panic")
5140 MakeSlice(st, int(l), int(l))
5143 func TestSliceOfGC(t *testing.T) {
5145 tt := TypeOf(T(nil))
5149 for i := 0; i < n; i++ {
5150 v := MakeSlice(st, n, n)
5151 for j := 0; j < v.Len(); j++ {
5153 *p = uintptr(i*n + j)
5154 v.Index(j).Set(ValueOf(p).Convert(tt))
5156 x = append(x, v.Interface())
5160 for i, xi := range x {
5162 for j := 0; j < v.Len(); j++ {
5163 k := v.Index(j).Elem().Interface()
5164 if k != uintptr(i*n+j) {
5165 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5171 func TestStructOfFieldName(t *testing.T) {
5172 // invalid field name "1nvalid"
5173 shouldPanic("has invalid name", func() {
5174 StructOf([]StructField{
5175 {Name: "Valid", Type: TypeOf("")},
5176 {Name: "1nvalid", Type: TypeOf("")},
5180 // invalid field name "+"
5181 shouldPanic("has invalid name", func() {
5182 StructOf([]StructField{
5183 {Name: "Val1d", Type: TypeOf("")},
5184 {Name: "+", Type: TypeOf("")},
5189 shouldPanic("has no name", func() {
5190 StructOf([]StructField{
5191 {Name: "", Type: TypeOf("")},
5195 // verify creation of a struct with valid struct fields
5196 validFields := []StructField{
5211 validStruct := StructOf(validFields)
5213 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5214 if got, want := validStruct.String(), structStr; got != want {
5215 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5219 func TestStructOf(t *testing.T) {
5220 // check construction and use of type not in binary
5221 fields := []StructField{
5230 Type: TypeOf(byte(0)),
5234 Type: TypeOf(uint64(0)),
5238 Type: TypeOf([3]uint16{}),
5242 st := StructOf(fields)
5245 v.FieldByName("X").Set(ValueOf(byte(2)))
5246 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5249 s := fmt.Sprint(v.Interface())
5250 want := `{ 1 0 [0 0 0]}`
5252 t.Errorf("constructed struct = %s, want %s", s, want)
5254 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5255 if got, want := st.String(), stStr; got != want {
5256 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5259 // check the size, alignment and field offsets
5260 stt := TypeOf(struct {
5266 if st.Size() != stt.Size() {
5267 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5269 if st.Align() != stt.Align() {
5270 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5272 if st.FieldAlign() != stt.FieldAlign() {
5273 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5275 for i := 0; i < st.NumField(); i++ {
5276 o1 := st.Field(i).Offset
5277 o2 := stt.Field(i).Offset
5279 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5283 // Check size and alignment with a trailing zero-sized field.
5284 st = StructOf([]StructField{
5287 Type: TypeOf(byte(0)),
5291 Type: TypeOf([0]*byte{}),
5294 stt = TypeOf(struct {
5298 if st.Size() != stt.Size() {
5299 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5301 if st.Align() != stt.Align() {
5302 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5304 if st.FieldAlign() != stt.FieldAlign() {
5305 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5307 for i := 0; i < st.NumField(); i++ {
5308 o1 := st.Field(i).Offset
5309 o2 := stt.Field(i).Offset
5311 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5315 // check duplicate names
5316 shouldPanic("duplicate field", func() {
5317 StructOf([]StructField{
5318 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5319 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5322 shouldPanic("has no name", func() {
5323 StructOf([]StructField{
5325 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5328 shouldPanic("has no name", func() {
5329 StructOf([]StructField{
5334 // check that type already in binary is found
5335 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5337 // gccgo used to fail this test.
5338 type structFieldType any
5340 StructOf([]StructField{
5343 Type: TypeOf((*structFieldType)(nil)).Elem(),
5346 struct{ F structFieldType }{})
5349 func TestStructOfExportRules(t *testing.T) {
5355 testPanic := func(i int, mustPanic bool, f func()) {
5358 if err == nil && mustPanic {
5359 t.Errorf("test-%d did not panic", i)
5361 if err != nil && !mustPanic {
5362 t.Errorf("test-%d panicked: %v\n", i, err)
5374 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5378 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5382 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5386 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5390 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5394 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5398 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5402 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5406 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5410 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5414 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5417 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5420 field: StructField{Name: "S", Type: TypeOf(S1{})},
5424 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5428 field: StructField{Name: "S", Type: TypeOf(s2{})},
5432 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5436 field: StructField{Name: "s", Type: TypeOf(S1{})},
5440 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5444 field: StructField{Name: "s", Type: TypeOf(s2{})},
5448 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5452 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5455 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5458 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5461 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5464 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5468 field: StructField{Name: "", Type: TypeOf(φType{})},
5472 field: StructField{Name: "Φ", Type: TypeOf(0)},
5476 field: StructField{Name: "φ", Type: TypeOf(0)},
5481 for i, test := range tests {
5482 testPanic(i, test.mustPanic, func() {
5483 typ := StructOf([]StructField{test.field})
5485 t.Errorf("test-%d: error creating struct type", i)
5488 field := typ.Field(0)
5491 panic("field.Name must not be empty")
5493 exported := token.IsExported(n)
5494 if exported != test.exported {
5495 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5497 if field.PkgPath != test.field.PkgPath {
5498 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5504 func TestStructOfGC(t *testing.T) {
5506 tt := TypeOf(T(nil))
5507 fields := []StructField{
5508 {Name: "X", Type: tt},
5509 {Name: "Y", Type: tt},
5511 st := StructOf(fields)
5515 for i := 0; i < n; i++ {
5517 for j := 0; j < v.NumField(); j++ {
5519 *p = uintptr(i*n + j)
5520 v.Field(j).Set(ValueOf(p).Convert(tt))
5522 x = append(x, v.Interface())
5526 for i, xi := range x {
5528 for j := 0; j < v.NumField(); j++ {
5529 k := v.Field(j).Elem().Interface()
5530 if k != uintptr(i*n+j) {
5531 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5537 func TestStructOfAlg(t *testing.T) {
5538 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5539 v1 := New(st).Elem()
5540 v2 := New(st).Elem()
5541 if !DeepEqual(v1.Interface(), v1.Interface()) {
5542 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5544 v1.FieldByName("X").Set(ValueOf(int(1)))
5545 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5546 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5549 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5551 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5554 func TestStructOfGenericAlg(t *testing.T) {
5555 st1 := StructOf([]StructField{
5556 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5557 {Name: "Y", Type: TypeOf(string(""))},
5559 st := StructOf([]StructField{
5560 {Name: "S0", Type: st1},
5561 {Name: "S1", Type: st1},
5579 {Name: "XX", Type: TypeOf([0]int{})},
5580 {Name: "YY", Type: TypeOf("")},
5588 {Name: "XX", Type: TypeOf([0]int{})},
5589 {Name: "YY", Type: TypeOf("")},
5590 {Name: "ZZ", Type: TypeOf([2]int{})},
5598 {Name: "XX", Type: TypeOf([1]int{})},
5599 {Name: "YY", Type: TypeOf("")},
5607 {Name: "XX", Type: TypeOf([1]int{})},
5608 {Name: "YY", Type: TypeOf("")},
5609 {Name: "ZZ", Type: TypeOf([1]int{})},
5617 {Name: "XX", Type: TypeOf([2]int{})},
5618 {Name: "YY", Type: TypeOf("")},
5619 {Name: "ZZ", Type: TypeOf([2]int{})},
5627 {Name: "XX", Type: TypeOf(int64(0))},
5628 {Name: "YY", Type: TypeOf(byte(0))},
5629 {Name: "ZZ", Type: TypeOf("")},
5637 {Name: "XX", Type: TypeOf(int64(0))},
5638 {Name: "YY", Type: TypeOf(int64(0))},
5639 {Name: "ZZ", Type: TypeOf("")},
5640 {Name: "AA", Type: TypeOf([1]int64{})},
5647 for _, table := range tests {
5648 v1 := New(table.rt).Elem()
5649 v2 := New(table.rt).Elem()
5651 if !DeepEqual(v1.Interface(), v1.Interface()) {
5652 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5655 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5656 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5657 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5658 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5662 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5663 val := "+" + abc + "-"
5664 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5665 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5666 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5670 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5671 m.SetMapIndex(v1, ValueOf(1))
5672 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5673 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5676 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5677 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5678 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5681 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5682 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5687 func TestStructOfDirectIface(t *testing.T) {
5689 type T struct{ X [1]*byte }
5690 i1 := Zero(TypeOf(T{})).Interface()
5691 v1 := ValueOf(&i1).Elem()
5692 p1 := v1.InterfaceData()[1]
5694 i2 := Zero(StructOf([]StructField{
5697 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5700 v2 := ValueOf(&i2).Elem()
5701 p2 := v2.InterfaceData()[1]
5704 t.Errorf("got p1=%v. want=%v", p1, nil)
5708 t.Errorf("got p2=%v. want=%v", p2, nil)
5712 type T struct{ X [0]*byte }
5713 i1 := Zero(TypeOf(T{})).Interface()
5714 v1 := ValueOf(&i1).Elem()
5715 p1 := v1.InterfaceData()[1]
5717 i2 := Zero(StructOf([]StructField{
5720 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5723 v2 := ValueOf(&i2).Elem()
5724 p2 := v2.InterfaceData()[1]
5727 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5731 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5738 func (i StructI) Get() int { return int(i) }
5742 func (i *StructIPtr) Get() int { return int(*i) }
5743 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5745 type SettableStruct struct {
5749 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5751 type SettablePointer struct {
5755 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5757 func TestStructOfWithInterface(t *testing.T) {
5759 type Iface interface {
5762 type IfaceSet interface {
5773 typ: TypeOf(StructI(want)),
5774 val: ValueOf(StructI(want)),
5779 typ: PointerTo(TypeOf(StructI(want))),
5780 val: ValueOf(func() any {
5788 typ: PointerTo(TypeOf(StructIPtr(want))),
5789 val: ValueOf(func() any {
5790 v := StructIPtr(want)
5797 typ: TypeOf(StructIPtr(want)),
5798 val: ValueOf(StructIPtr(want)),
5802 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5803 // val: ValueOf(StructI(want)),
5808 for i, table := range tests {
5809 for j := 0; j < 2; j++ {
5810 var fields []StructField
5812 fields = append(fields, StructField{
5815 Type: TypeOf(int(0)),
5818 fields = append(fields, StructField{
5825 // We currently do not correctly implement methods
5826 // for embedded fields other than the first.
5827 // Therefore, for now, we expect those methods
5828 // to not exist. See issues 15924 and 20824.
5829 // When those issues are fixed, this test of panic
5830 // should be removed.
5831 if j == 1 && table.impl {
5834 if err := recover(); err == nil {
5835 t.Errorf("test-%d-%d did not panic", i, j)
5838 _ = StructOf(fields)
5843 rt := StructOf(fields)
5844 rv := New(rt).Elem()
5845 rv.Field(j).Set(table.val)
5847 if _, ok := rv.Interface().(Iface); ok != table.impl {
5849 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5851 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5860 v := rv.Interface().(Iface).Get()
5862 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5865 fct := rv.MethodByName("Get")
5866 out := fct.Call(nil)
5867 if !DeepEqual(out[0].Interface(), want) {
5868 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5873 // Test an embedded nil pointer with pointer methods.
5874 fields := []StructField{{
5877 Type: PointerTo(TypeOf(StructIPtr(want))),
5879 rt := StructOf(fields)
5880 rv := New(rt).Elem()
5881 // This should panic since the pointer is nil.
5882 shouldPanic("", func() {
5883 rv.Interface().(IfaceSet).Set(want)
5886 // Test an embedded nil pointer to a struct with pointer methods.
5888 fields = []StructField{{
5889 Name: "SettableStruct",
5891 Type: PointerTo(TypeOf(SettableStruct{})),
5893 rt = StructOf(fields)
5895 // This should panic since the pointer is nil.
5896 shouldPanic("", func() {
5897 rv.Interface().(IfaceSet).Set(want)
5900 // The behavior is different if there is a second field,
5901 // since now an interface value holds a pointer to the struct
5902 // rather than just holding a copy of the struct.
5903 fields = []StructField{
5905 Name: "SettableStruct",
5907 Type: PointerTo(TypeOf(SettableStruct{})),
5910 Name: "EmptyStruct",
5912 Type: StructOf(nil),
5915 // With the current implementation this is expected to panic.
5916 // Ideally it should work and we should be able to see a panic
5917 // if we call the Set method.
5918 shouldPanic("", func() {
5922 // Embed a field that can be stored directly in an interface,
5923 // with a second field.
5924 fields = []StructField{
5926 Name: "SettablePointer",
5928 Type: TypeOf(SettablePointer{}),
5931 Name: "EmptyStruct",
5933 Type: StructOf(nil),
5936 // With the current implementation this is expected to panic.
5937 // Ideally it should work and we should be able to call the
5938 // Set and Get methods.
5939 shouldPanic("", func() {
5944 func TestStructOfTooManyFields(t *testing.T) {
5945 // Bug Fix: #25402 - this should not panic
5946 tt := StructOf([]StructField{
5947 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5950 if _, present := tt.MethodByName("After"); !present {
5951 t.Errorf("Expected method `After` to be found")
5955 func TestStructOfDifferentPkgPath(t *testing.T) {
5956 fields := []StructField{
5960 Type: TypeOf(int(0)),
5965 Type: TypeOf(int(0)),
5968 shouldPanic("different PkgPath", func() {
5973 func TestStructOfTooLarge(t *testing.T) {
5974 t1 := TypeOf(byte(0))
5975 t2 := TypeOf(int16(0))
5976 t4 := TypeOf(int32(0))
5977 t0 := ArrayOf(0, t1)
5979 // 2^64-3 sized type (or 2^32-3 on 32-bit archs)
5980 bigType := StructOf([]StructField{
5981 {Name: "F1", Type: ArrayOf(int(^uintptr(0)>>1), t1)},
5982 {Name: "F2", Type: ArrayOf(int(^uintptr(0)>>1-1), t1)},
5987 fields []StructField
5992 shouldPanic: false, // 2^64-1, ok
5993 fields: []StructField{
5994 {Name: "F1", Type: bigType},
5995 {Name: "F2", Type: ArrayOf(2, t1)},
5999 shouldPanic: true, // overflow in total size
6000 fields: []StructField{
6001 {Name: "F1", Type: bigType},
6002 {Name: "F2", Type: ArrayOf(3, t1)},
6006 shouldPanic: true, // overflow while aligning F2
6007 fields: []StructField{
6008 {Name: "F1", Type: bigType},
6009 {Name: "F2", Type: t4},
6013 shouldPanic: true, // overflow while adding trailing byte for zero-sized fields
6014 fields: []StructField{
6015 {Name: "F1", Type: bigType},
6016 {Name: "F2", Type: ArrayOf(2, t1)},
6017 {Name: "F3", Type: t0},
6021 shouldPanic: true, // overflow while aligning total size
6022 fields: []StructField{
6023 {Name: "F1", Type: t2},
6024 {Name: "F2", Type: bigType},
6029 for i, tt := range tests {
6033 if !tt.shouldPanic {
6035 t.Errorf("test %d should not panic, got %s", i, err)
6040 t.Errorf("test %d expected to panic", i)
6043 s := fmt.Sprintf("%s", err)
6044 if s != "reflect.StructOf: struct size would exceed virtual address space" {
6045 t.Errorf("test %d wrong panic message: %s", i, s)
6049 _ = StructOf(tt.fields)
6054 func TestChanOf(t *testing.T) {
6055 // check construction and use of type not in binary
6057 ct := ChanOf(BothDir, TypeOf(T("")))
6058 v := MakeChan(ct, 2)
6060 v.Send(ValueOf(T("hello")))
6062 v.Send(ValueOf(T("world")))
6069 if s1 != "hello" || s2 != "world" {
6070 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
6073 // check that type already in binary is found
6075 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
6077 // Check arrow token association in undefined chan types.
6078 var left chan<- chan T
6079 var right chan (<-chan T)
6080 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
6081 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
6082 if tLeft != TypeOf(left) {
6083 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
6085 if tRight != TypeOf(right) {
6086 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
6090 func TestChanOfDir(t *testing.T) {
6091 // check construction and use of type not in binary
6093 crt := ChanOf(RecvDir, TypeOf(T("")))
6094 cst := ChanOf(SendDir, TypeOf(T("")))
6096 // check that type already in binary is found
6098 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
6099 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
6101 // check String form of ChanDir
6102 if crt.ChanDir().String() != "<-chan" {
6103 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
6105 if cst.ChanDir().String() != "chan<-" {
6106 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
6110 func TestChanOfGC(t *testing.T) {
6111 done := make(chan bool, 1)
6115 case <-time.After(5 * time.Second):
6116 panic("deadlock in TestChanOfGC")
6125 tt := TypeOf(T(nil))
6126 ct := ChanOf(BothDir, tt)
6128 // NOTE: The garbage collector handles allocated channels specially,
6129 // so we have to save pointers to channels in x; the pointer code will
6130 // use the gc info in the newly constructed chan type.
6133 for i := 0; i < n; i++ {
6134 v := MakeChan(ct, n)
6135 for j := 0; j < n; j++ {
6137 *p = uintptr(i*n + j)
6138 v.Send(ValueOf(p).Convert(tt))
6142 x = append(x, pv.Interface())
6146 for i, xi := range x {
6147 v := ValueOf(xi).Elem()
6148 for j := 0; j < n; j++ {
6150 k := pv.Elem().Interface()
6151 if k != uintptr(i*n+j) {
6152 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6158 func TestMapOf(t *testing.T) {
6159 // check construction and use of type not in binary
6163 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
6165 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
6168 s := fmt.Sprint(v.Interface())
6171 t.Errorf("constructed map = %s, want %s", s, want)
6174 // check that type already in binary is found
6175 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
6177 // check that invalid key type panics
6178 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
6181 func TestMapOfGCKeys(t *testing.T) {
6183 tt := TypeOf(T(nil))
6184 mt := MapOf(tt, TypeOf(false))
6186 // NOTE: The garbage collector handles allocated maps specially,
6187 // so we have to save pointers to maps in x; the pointer code will
6188 // use the gc info in the newly constructed map type.
6191 for i := 0; i < n; i++ {
6193 for j := 0; j < n; j++ {
6195 *p = uintptr(i*n + j)
6196 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
6200 x = append(x, pv.Interface())
6204 for i, xi := range x {
6205 v := ValueOf(xi).Elem()
6207 for _, kv := range v.MapKeys() {
6208 out = append(out, int(kv.Elem().Interface().(uintptr)))
6211 for j, k := range out {
6213 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6219 func TestMapOfGCValues(t *testing.T) {
6221 tt := TypeOf(T(nil))
6222 mt := MapOf(TypeOf(1), tt)
6224 // NOTE: The garbage collector handles allocated maps specially,
6225 // so we have to save pointers to maps in x; the pointer code will
6226 // use the gc info in the newly constructed map type.
6229 for i := 0; i < n; i++ {
6231 for j := 0; j < n; j++ {
6233 *p = uintptr(i*n + j)
6234 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6238 x = append(x, pv.Interface())
6242 for i, xi := range x {
6243 v := ValueOf(xi).Elem()
6244 for j := 0; j < n; j++ {
6245 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6246 if k != uintptr(i*n+j) {
6247 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6253 func TestTypelinksSorted(t *testing.T) {
6255 for i, n := range TypeLinks() {
6257 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6263 func TestFuncOf(t *testing.T) {
6264 // check construction and use of type not in binary
6268 fn := func(args []Value) []Value {
6270 t.Errorf("args == %v, want exactly one arg", args)
6271 } else if args[0].Type() != TypeOf(K("")) {
6272 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6273 } else if args[0].String() != "gopher" {
6274 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6276 return []Value{ValueOf(V(3.14))}
6278 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6280 outs := v.Call([]Value{ValueOf(K("gopher"))})
6282 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6283 } else if outs[0].Type() != TypeOf(V(0)) {
6284 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6286 f := outs[0].Float()
6288 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6291 // check that types already in binary are found
6293 testCases := []struct {
6298 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6299 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6300 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6301 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6302 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6304 for _, tt := range testCases {
6305 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6308 // check that variadic requires last element be a slice.
6309 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6310 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6311 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6313 //testcase for #54669
6315 for i := 0; i < 51; i++ {
6316 in = append(in, TypeOf(1))
6318 FuncOf(in, nil, false)
6327 func BenchmarkFieldByName1(b *testing.B) {
6329 b.RunParallel(func(pb *testing.PB) {
6336 func BenchmarkFieldByName2(b *testing.B) {
6338 b.RunParallel(func(pb *testing.PB) {
6415 func TestEmbed(t *testing.T) {
6417 f, ok := typ.FieldByName("X")
6419 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6423 func BenchmarkFieldByName3(b *testing.B) {
6425 b.RunParallel(func(pb *testing.PB) {
6437 func BenchmarkInterfaceBig(b *testing.B) {
6439 b.RunParallel(func(pb *testing.PB) {
6447 func TestAllocsInterfaceBig(t *testing.T) {
6448 if testing.Short() {
6449 t.Skip("skipping malloc count in short mode")
6452 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6453 t.Error("allocs:", allocs)
6457 func BenchmarkInterfaceSmall(b *testing.B) {
6458 v := ValueOf(int64(0))
6459 b.RunParallel(func(pb *testing.PB) {
6466 func TestAllocsInterfaceSmall(t *testing.T) {
6467 if testing.Short() {
6468 t.Skip("skipping malloc count in short mode")
6470 v := ValueOf(int64(0))
6471 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6472 t.Error("allocs:", allocs)
6476 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6477 // The basic usage is:
6480 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6483 // Each iteration of the loop returns a different set of results, until all
6484 // possible result sets have been explored. It is okay for different code paths
6485 // to make different method call sequences on x, but there must be no
6486 // other source of non-determinism in the call sequences.
6488 // When faced with a new decision, x chooses randomly. Future explorations
6489 // of that path will choose successive values for the result. Thus, stopping
6490 // the loop after a fixed number of iterations gives somewhat stochastic
6496 // v := make([]bool, x.Choose(4))
6497 // for i := range v {
6503 // prints (in some order):
6512 // [false false false]
6515 // [false false false false]
6517 // [true true true true]
6518 type exhaustive struct {
6524 type choice struct {
6530 func (x *exhaustive) Next() bool {
6532 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6539 for i := len(x.last) - 1; i >= 0; i-- {
6543 x.last = x.last[:i+1]
6550 func (x *exhaustive) Choose(max int) int {
6551 if x.pos >= len(x.last) {
6552 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6557 panic("inconsistent use of exhaustive tester")
6559 return (c.n + c.off) % max
6562 func (x *exhaustive) Maybe() bool {
6563 return x.Choose(2) == 1
6566 func GCFunc(args []Value) []Value {
6571 func TestReflectFuncTraceback(t *testing.T) {
6572 f := MakeFunc(TypeOf(func() {}), GCFunc)
6576 func TestReflectMethodTraceback(t *testing.T) {
6578 m := ValueOf(p).MethodByName("GCMethod")
6579 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6581 t.Errorf("Call returned %d; want 8", i)
6585 func TestSmallZero(t *testing.T) {
6588 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6589 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6593 func TestBigZero(t *testing.T) {
6594 const size = 1 << 10
6596 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6597 for i := 0; i < size; i++ {
6599 t.Fatalf("Zero object not all zero, index %d", i)
6604 func TestZeroSet(t *testing.T) {
6612 a: 0xaaaaaaaaaaaaaaaa,
6613 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6614 b: 0xbbbbbbbbbbbbbbbb,
6616 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6618 a: 0xaaaaaaaaaaaaaaaa,
6619 b: 0xbbbbbbbbbbbbbbbb,
6621 t.Fatalf("Setting a field to a Zero value didn't work")
6625 func TestFieldByIndexNil(t *testing.T) {
6634 v.FieldByName("P") // should be fine
6637 if err := recover(); err == nil {
6638 t.Fatalf("no error")
6639 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6640 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6643 v.FieldByName("F") // should panic
6645 t.Fatalf("did not panic")
6649 // type Outer struct {
6653 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6654 // The implementation is logically:
6655 // func (p *Outer) M() {
6658 // but since the only change here is the replacement of one pointer receiver with another,
6659 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6660 // then jumps to the M method expecting the *Inner receiver.
6662 // During reflect.Value.Call, we create an argument frame and the associated data structures
6663 // to describe it to the garbage collector, populate the frame, call reflect.call to
6664 // run a function call using that frame, and then copy the results back out of the frame.
6665 // The reflect.call function does a memmove of the frame structure onto the
6666 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6667 // the frame structure (to preserve the outputs).
6669 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6670 // were for the full stack frame. However, in the case where the called function was
6671 // one of these wrappers, the rewritten receiver is almost certainly a different type
6672 // than the original receiver. This is not a problem on the stack, where we use the
6673 // program counter to determine the type information and understand that
6674 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6675 // memory word is now an *Inner. But in the statically typed argument frame created
6676 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6677 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6678 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6679 // memory as if it were an *Outer. If the two have different memory layouts, the
6680 // collection will interpret the memory incorrectly.
6682 // One such possible incorrect interpretation is to treat two arbitrary memory words
6683 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6684 // an interface requires dereferencing the itab word, the misinterpretation will try to
6685 // deference Inner.P1, causing a crash during garbage collection.
6687 // This came up in a real program in issue 7725.
6700 func (pi *Inner) M() {
6701 // Clear references to pi so that the only way the
6702 // garbage collection will find the pointer is in the
6703 // argument frame, typed as a *Outer.
6706 // Set up an interface value that will cause a crash.
6707 // P1 = 1 is a non-zero, so the interface looks non-nil.
6708 // P2 = pi ensures that the data word points into the
6709 // allocated heap; if not the collection skips the interface
6710 // value as irrelevant, without dereferencing P1.
6712 pi.P2 = uintptr(unsafe.Pointer(pi))
6715 func TestCallMethodJump(t *testing.T) {
6716 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6717 // returns but before the args frame has been discarded.
6718 // This is a little clumsy but makes the failure repeatable.
6721 p := &Outer{Inner: new(Inner)}
6723 ValueOf(p).Method(0).Call(nil)
6725 // Stop garbage collecting during reflect.call.
6729 func TestCallArgLive(t *testing.T) {
6730 type T struct{ X, Y *string } // pointerful aggregate
6732 F := func(t T) { *t.X = "ok" }
6734 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6735 // between marshaling argument and the actual call.
6739 runtime.SetFinalizer(x, func(p *string) {
6741 t.Errorf("x dead prematurely")
6746 ValueOf(F).Call([]Value{ValueOf(v)})
6748 // Stop garbage collecting during reflect.call.
6752 func TestMakeFuncStackCopy(t *testing.T) {
6753 target := func(in []Value) []Value {
6756 return []Value{ValueOf(9)}
6759 var concrete func(*int, int) int
6760 fn := MakeFunc(ValueOf(concrete).Type(), target)
6761 ValueOf(&concrete).Elem().Set(fn)
6762 x := concrete(nil, 7)
6764 t.Errorf("have %#q want 9", x)
6768 // use about n KB of stack
6769 func useStack(n int) {
6773 var b [1024]byte // makes frame about 1KB
6774 useStack(n - 1 + int(b[99]))
6781 func TestValueString(t *testing.T) {
6782 rv := ValueOf(Impl{})
6783 if rv.String() != "<reflect_test.Impl Value>" {
6784 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6787 method := rv.Method(0)
6788 if method.String() != "<func() Value>" {
6789 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6793 func TestInvalid(t *testing.T) {
6794 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6795 type T struct{ v any }
6797 v := ValueOf(T{}).Field(0)
6798 if v.IsValid() != true || v.Kind() != Interface {
6799 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6802 if v.IsValid() != false || v.Kind() != Invalid {
6803 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6808 func TestLargeGCProg(t *testing.T) {
6809 fv := ValueOf(func([256]*byte) {})
6810 fv.Call([]Value{ValueOf([256]*byte{})})
6813 func fieldIndexRecover(t Type, i int) (recovered any) {
6815 recovered = recover()
6823 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6824 typ := TypeOf(struct{ X int }{10})
6825 testIndices := [...]struct {
6834 for i, tt := range testIndices {
6835 recoveredErr := fieldIndexRecover(typ, tt.i)
6837 if recoveredErr == nil {
6838 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6841 if recoveredErr != nil {
6842 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6849 func TestCallGC(t *testing.T) {
6850 f := func(a, b, c, d, e string) {
6852 g := func(in []Value) []Value {
6856 typ := ValueOf(f).Type()
6857 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6858 f2("four", "five5", "six666", "seven77", "eight888")
6861 // Issue 18635 (function version).
6862 func TestKeepFuncLive(t *testing.T) {
6863 // Test that we keep makeFuncImpl live as long as it is
6864 // referenced on the stack.
6865 typ := TypeOf(func(i int) {})
6866 var f, g func(in []Value) []Value
6867 f = func(in []Value) []Value {
6869 i := int(in[0].Int())
6871 // We can't use Value.Call here because
6872 // runtime.call* will keep the makeFuncImpl
6873 // alive. However, by converting it to an
6874 // interface value and calling that,
6875 // reflect.callReflect is the only thing that
6876 // can keep the makeFuncImpl live.
6878 // Alternate between f and g so that if we do
6879 // reuse the memory prematurely it's more
6880 // likely to get obviously corrupted.
6881 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6885 g = func(in []Value) []Value {
6887 i := int(in[0].Int())
6888 MakeFunc(typ, f).Interface().(func(i int))(i)
6891 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6894 type UnExportedFirst int
6896 func (i UnExportedFirst) ΦExported() {}
6897 func (i UnExportedFirst) unexported() {}
6900 func TestMethodByNameUnExportedFirst(t *testing.T) {
6902 if recover() != nil {
6903 t.Errorf("should not panic")
6906 typ := TypeOf(UnExportedFirst(0))
6907 m, _ := typ.MethodByName("ΦExported")
6908 if m.Name != "ΦExported" {
6909 t.Errorf("got %s, expected ΦExported", m.Name)
6913 // Issue 18635 (method version).
6914 type KeepMethodLive struct{}
6916 func (k KeepMethodLive) Method1(i int) {
6919 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6923 func (k KeepMethodLive) Method2(i int) {
6925 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6928 func TestKeepMethodLive(t *testing.T) {
6929 // Test that we keep methodValue live as long as it is
6930 // referenced on the stack.
6931 KeepMethodLive{}.Method1(10)
6934 // clobber tries to clobber unreachable memory.
6937 for i := 1; i < 32; i++ {
6938 for j := 0; j < 10; j++ {
6939 obj := make([]*byte, i)
6946 func TestFuncLayout(t *testing.T) {
6947 align := func(x uintptr) uintptr {
6948 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6951 if goarch.PtrSize == 4 {
6952 r = []byte{0, 0, 0, 1}
6964 size, argsize, retOffset uintptr
6965 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6966 intRegs, floatRegs int
6967 floatRegSize uintptr
6971 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6972 size: 6 * goarch.PtrSize,
6973 argsize: 4 * goarch.PtrSize,
6974 retOffset: 4 * goarch.PtrSize,
6975 stack: []byte{1, 0, 1, 0, 1},
6976 gc: []byte{1, 0, 1, 0, 1},
6979 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6980 size: align(align(3*4) + goarch.PtrSize + 2),
6981 argsize: align(3*4) + goarch.PtrSize + 2,
6982 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6987 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6988 size: 4 * goarch.PtrSize,
6989 argsize: 4 * goarch.PtrSize,
6990 retOffset: 4 * goarch.PtrSize,
6991 stack: []byte{1, 0, 1, 1},
6992 gc: []byte{1, 0, 1, 1},
6995 typ: ValueOf(func(a S) {}).Type(),
6996 size: 4 * goarch.PtrSize,
6997 argsize: 4 * goarch.PtrSize,
6998 retOffset: 4 * goarch.PtrSize,
6999 stack: []byte{0, 0, 1, 1},
7000 gc: []byte{0, 0, 1, 1},
7003 rcvr: ValueOf((*byte)(nil)).Type(),
7004 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
7005 size: 3 * goarch.PtrSize,
7006 argsize: 3 * goarch.PtrSize,
7007 retOffset: 3 * goarch.PtrSize,
7008 stack: []byte{1, 0, 1},
7009 gc: []byte{1, 0, 1},
7012 typ: ValueOf(func(a uintptr) {}).Type(),
7013 size: goarch.PtrSize,
7014 argsize: goarch.PtrSize,
7015 retOffset: goarch.PtrSize,
7020 typ: ValueOf(func() uintptr { return 0 }).Type(),
7021 size: goarch.PtrSize,
7028 rcvr: ValueOf(uintptr(0)).Type(),
7029 typ: ValueOf(func(a uintptr) {}).Type(),
7030 size: 2 * goarch.PtrSize,
7031 argsize: 2 * goarch.PtrSize,
7032 retOffset: 2 * goarch.PtrSize,
7035 // Note: this one is tricky, as the receiver is not a pointer. But we
7036 // pass the receiver by reference to the autogenerated pointer-receiver
7037 // version of the function.
7039 // TODO(mknyszek): Add tests for non-zero register count.
7041 for _, lt := range tests {
7042 name := lt.typ.String()
7044 name = lt.rcvr.String() + "." + name
7046 t.Run(name, func(t *testing.T) {
7047 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
7049 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
7050 if typ.Size() != lt.size {
7051 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
7053 if argsize != lt.argsize {
7054 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
7056 if retOffset != lt.retOffset {
7057 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
7059 if !bytes.Equal(stack, lt.stack) {
7060 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
7062 if !bytes.Equal(gc, lt.gc) {
7063 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
7065 if !bytes.Equal(inRegs, lt.inRegs) {
7066 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
7068 if !bytes.Equal(outRegs, lt.outRegs) {
7069 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
7071 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
7072 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
7078 // trimBitmap removes trailing 0 elements from b and returns the result.
7079 func trimBitmap(b []byte) []byte {
7080 for len(b) > 0 && b[len(b)-1] == 0 {
7086 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
7087 heapBits := GCBits(New(typ).Interface())
7089 // Trim scalars at the end, as bits might end in zero,
7090 // e.g. with rep(2, lit(1, 0)).
7091 bits = trimBitmap(bits)
7093 if !bytes.Equal(heapBits, bits) {
7094 _, _, line, _ := runtime.Caller(1)
7095 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
7099 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
7100 // Creating a slice causes the runtime to repeat a bitmap,
7101 // which exercises a different path from making the compiler
7102 // repeat a bitmap for a small array or executing a repeat in
7104 val := MakeSlice(typ, 0, cap)
7105 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
7106 heapBits := GCBits(data.Interface())
7107 // Repeat the bitmap for the slice size, trimming scalars in
7108 // the last element.
7109 bits = trimBitmap(rep(cap, bits))
7110 if !bytes.Equal(heapBits, bits) {
7111 _, _, line, _ := runtime.Caller(1)
7112 t.Errorf("line %d: heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", line, typ, cap, heapBits, bits)
7116 func TestGCBits(t *testing.T) {
7117 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
7119 // Building blocks for types seen by the compiler (like [2]Xscalar).
7120 // The compiler will create the type structures for the derived types,
7121 // including their GC metadata.
7122 type Xscalar struct{ x uintptr }
7123 type Xptr struct{ x *byte }
7124 type Xptrscalar struct {
7128 type Xscalarptr struct {
7132 type Xbigptrscalar struct {
7137 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
7139 // Building blocks for types constructed by reflect.
7140 // This code is in a separate block so that code below
7141 // cannot accidentally refer to these.
7142 // The compiler must NOT see types derived from these
7143 // (for example, [2]Scalar must NOT appear in the program),
7144 // or else reflect will use it instead of having to construct one.
7145 // The goal is to test the construction.
7146 type Scalar struct{ x uintptr }
7147 type Ptr struct{ x *byte }
7148 type Ptrscalar struct {
7152 type Scalarptr struct {
7156 type Bigptrscalar struct {
7161 Tscalar = TypeOf(Scalar{})
7162 Tint64 = TypeOf(Int64(0))
7163 Tptr = TypeOf(Ptr{})
7164 Tscalarptr = TypeOf(Scalarptr{})
7165 Tptrscalar = TypeOf(Ptrscalar{})
7166 Tbigptrscalar = TypeOf(Bigptrscalar{})
7171 verifyGCBits(t, TypeOf(Xscalar{}), empty)
7172 verifyGCBits(t, Tscalar, empty)
7173 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
7174 verifyGCBits(t, Tptr, lit(1))
7175 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
7176 verifyGCBits(t, Tscalarptr, lit(0, 1))
7177 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
7178 verifyGCBits(t, Tptrscalar, lit(1))
7180 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
7181 verifyGCBits(t, ArrayOf(0, Tptr), empty)
7182 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
7183 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
7184 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
7185 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
7186 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
7187 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
7188 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
7189 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
7190 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
7191 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
7192 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
7193 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
7194 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
7195 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
7196 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
7197 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
7198 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7199 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
7200 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7201 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
7202 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
7203 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
7204 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7205 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7207 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
7208 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
7209 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
7210 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
7211 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
7212 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
7213 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
7214 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
7215 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
7216 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
7217 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
7218 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
7219 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
7220 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
7221 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
7222 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
7223 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
7224 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
7225 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
7226 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7227 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7228 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7229 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7230 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7231 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7232 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7234 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7235 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7237 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7238 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7240 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7241 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7243 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7244 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7246 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7247 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7249 hdr := make([]byte, 8/goarch.PtrSize)
7251 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7252 verifyGCBits(t, MapBucketOf(k, e), want)
7253 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7257 map[Xscalar]Xptr(nil),
7258 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7261 map[Xscalarptr]Xptr(nil),
7262 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7263 verifyMapBucket(t, Tint64, Tptr,
7264 map[int64]Xptr(nil),
7265 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7268 map[Xscalar]Xscalar(nil),
7271 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7272 map[[2]Xscalarptr][3]Xptrscalar(nil),
7273 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7275 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7276 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7277 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7279 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7280 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7281 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7283 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7284 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7285 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7287 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7288 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7289 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7292 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7293 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7294 func lit(x ...byte) []byte { return x }
7296 func TestTypeOfTypeOf(t *testing.T) {
7297 // Check that all the type constructors return concrete *rtype implementations.
7298 // It's difficult to test directly because the reflect package is only at arm's length.
7299 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7300 check := func(name string, typ Type) {
7301 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7302 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7306 type T struct{ int }
7307 check("TypeOf", TypeOf(T{}))
7309 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7310 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7311 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7312 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7313 check("PtrTo", PointerTo(TypeOf(T{})))
7314 check("SliceOf", SliceOf(TypeOf(T{})))
7317 type XM struct{ _ bool }
7319 func (*XM) String() string { return "" }
7321 func TestPtrToMethods(t *testing.T) {
7323 yp := New(TypeOf(y)).Interface()
7324 _, ok := yp.(fmt.Stringer)
7326 t.Fatal("does not implement Stringer, but should")
7330 func TestMapAlloc(t *testing.T) {
7331 m := ValueOf(make(map[int]int, 10))
7334 allocs := testing.AllocsPerRun(100, func() {
7338 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7343 val := ValueOf(&tmp).Elem()
7344 allocs = testing.AllocsPerRun(100, func() {
7345 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7346 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7347 for i := 0; i < size/2; i++ {
7348 val.SetInt(int64(i))
7349 mv.SetMapIndex(val, val)
7353 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7355 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7356 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7357 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7360 func TestChanAlloc(t *testing.T) {
7361 // Note: for a chan int, the return Value must be allocated, so we
7362 // use a chan *int instead.
7363 c := ValueOf(make(chan *int, 1))
7364 v := ValueOf(new(int))
7365 allocs := testing.AllocsPerRun(100, func() {
7369 if allocs < 0.5 || allocs > 1.5 {
7370 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7372 // Note: there is one allocation in reflect.recv which seems to be
7373 // a limitation of escape analysis. If that is ever fixed the
7374 // allocs < 0.5 condition will trigger and this test should be fixed.
7377 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7379 type nameTest struct {
7384 var nameTests = []nameTest{
7385 {(*int32)(nil), "int32"},
7388 {(*chan D1)(nil), ""},
7389 {(*func() D1)(nil), ""},
7390 {(*<-chan D1)(nil), ""},
7391 {(*chan<- D1)(nil), ""},
7396 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7399 func TestNames(t *testing.T) {
7400 for _, test := range nameTests {
7401 typ := TypeOf(test.v).Elem()
7402 if got := typ.Name(); got != test.want {
7403 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7408 func TestExported(t *testing.T) {
7409 type ΦExported struct{}
7410 type φUnexported struct{}
7417 type exportTest struct {
7421 exportTests := []exportTest{
7425 {(*big)(nil), false},
7426 {(BigP)(nil), true},
7427 {(*BigP)(nil), true},
7428 {ΦExported{}, true},
7429 {φUnexported{}, false},
7436 for i, test := range exportTests {
7437 typ := TypeOf(test.v)
7438 if got := IsExported(typ); got != test.want {
7439 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7444 func TestTypeStrings(t *testing.T) {
7445 type stringTest struct {
7449 stringTests := []stringTest{
7450 {TypeOf(func(int) {}), "func(int)"},
7451 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7452 {TypeOf(XM{}), "reflect_test.XM"},
7453 {TypeOf(new(XM)), "*reflect_test.XM"},
7454 {TypeOf(new(XM).String), "func() string"},
7455 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7456 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7457 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7458 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7459 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7462 for i, test := range stringTests {
7463 if got, want := test.typ.String(), test.want; got != want {
7464 t.Errorf("type %d String()=%q, want %q", i, got, want)
7469 func TestOffsetLock(t *testing.T) {
7470 var wg sync.WaitGroup
7471 for i := 0; i < 4; i++ {
7475 for j := 0; j < 50; j++ {
7476 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7484 func BenchmarkNew(b *testing.B) {
7486 b.RunParallel(func(pb *testing.PB) {
7493 func BenchmarkMap(b *testing.B) {
7496 value := ValueOf((V)(nil))
7497 stringKeys := []string{}
7498 mapOfStrings := map[string]V{}
7499 uint64Keys := []uint64{}
7500 mapOfUint64s := map[uint64]V{}
7501 userStringKeys := []S{}
7502 mapOfUserStrings := map[S]V{}
7503 for i := 0; i < 100; i++ {
7504 stringKey := fmt.Sprintf("key%d", i)
7505 stringKeys = append(stringKeys, stringKey)
7506 mapOfStrings[stringKey] = nil
7508 uint64Key := uint64(i)
7509 uint64Keys = append(uint64Keys, uint64Key)
7510 mapOfUint64s[uint64Key] = nil
7512 userStringKey := S(fmt.Sprintf("key%d", i))
7513 userStringKeys = append(userStringKeys, userStringKey)
7514 mapOfUserStrings[userStringKey] = nil
7519 m, keys, value Value
7521 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7522 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7523 {"UserStringKeys", ValueOf(mapOfUserStrings), ValueOf(userStringKeys), value},
7526 for _, tt := range tests {
7527 b.Run(tt.label, func(b *testing.B) {
7528 b.Run("MapIndex", func(b *testing.B) {
7530 for i := 0; i < b.N; i++ {
7531 for j := tt.keys.Len() - 1; j >= 0; j-- {
7532 tt.m.MapIndex(tt.keys.Index(j))
7536 b.Run("SetMapIndex", func(b *testing.B) {
7538 for i := 0; i < b.N; i++ {
7539 for j := tt.keys.Len() - 1; j >= 0; j-- {
7540 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7548 func TestSwapper(t *testing.T) {
7554 type pairPtr struct {
7566 in: []int{1, 20, 300},
7569 want: []int{300, 20, 1},
7572 in: []uintptr{1, 20, 300},
7575 want: []uintptr{300, 20, 1},
7578 in: []int16{1, 20, 300},
7581 want: []int16{300, 20, 1},
7584 in: []int8{1, 20, 100},
7587 want: []int8{100, 20, 1},
7590 in: []*I{&a, &b, &c},
7593 want: []*I{&c, &b, &a},
7596 in: []string{"eric", "sergey", "larry"},
7599 want: []string{"larry", "sergey", "eric"},
7602 in: []S{"eric", "sergey", "larry"},
7605 want: []S{"larry", "sergey", "eric"},
7608 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7611 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7614 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7617 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7621 for i, tt := range tests {
7622 inStr := fmt.Sprint(tt.in)
7623 Swapper(tt.in)(tt.i, tt.j)
7624 if !DeepEqual(tt.in, tt.want) {
7625 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7630 // TestUnaddressableField tests that the reflect package will not allow
7631 // a type from another package to be used as a named type with an
7632 // unexported field.
7634 // This ensures that unexported fields cannot be modified by other packages.
7635 func TestUnaddressableField(t *testing.T) {
7636 var b Buffer // type defined in reflect, a different package
7637 var localBuffer struct {
7640 lv := ValueOf(&localBuffer).Elem()
7642 shouldPanic("Set", func() {
7651 type Talias1 struct {
7659 type Talias2 struct {
7664 func TestAliasNames(t *testing.T) {
7665 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7666 out := fmt.Sprintf("%#v", t1)
7667 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7669 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7672 t2 := Talias2{Tint: 1, Tint2: 2}
7673 out = fmt.Sprintf("%#v", t2)
7674 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7676 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7680 func TestIssue22031(t *testing.T) {
7681 type s []struct{ C int }
7684 type t2 struct{ f s }
7687 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7688 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7691 for i, test := range tests {
7693 t.Errorf("%d: CanSet: got true, want false", i)
7698 type NonExportedFirst int
7700 func (i NonExportedFirst) ΦExported() {}
7701 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7703 func TestIssue22073(t *testing.T) {
7704 m := ValueOf(NonExportedFirst(0)).Method(0)
7706 if got := m.Type().NumOut(); got != 0 {
7707 t.Errorf("NumOut: got %v, want 0", got)
7714 func TestMapIterNonEmptyMap(t *testing.T) {
7715 m := map[string]int{"one": 1, "two": 2, "three": 3}
7716 iter := ValueOf(m).MapRange()
7717 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7718 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7722 func TestMapIterNilMap(t *testing.T) {
7723 var m map[string]int
7724 iter := ValueOf(m).MapRange()
7725 if got, want := iterateToString(iter), `[]`; got != want {
7726 t.Errorf("non-empty result iteratoring nil map: %s", got)
7730 func TestMapIterReset(t *testing.T) {
7731 iter := new(MapIter)
7733 // Use of zero iterator should panic.
7735 defer func() { recover() }()
7737 t.Error("Next did not panic")
7740 // Reset to new Map should work.
7741 m := map[string]int{"one": 1, "two": 2, "three": 3}
7742 iter.Reset(ValueOf(m))
7743 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7744 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7747 // Reset to Zero value should work, but iterating over it should panic.
7750 defer func() { recover() }()
7752 t.Error("Next did not panic")
7755 // Reset to a different Map with different types should work.
7756 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7757 iter.Reset(ValueOf(m2))
7758 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7759 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7762 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7763 m3 := map[uint64]uint64{
7768 kv := New(TypeOf(uint64(0))).Elem()
7769 for i := 0; i < 5; i++ {
7770 var seenk, seenv uint64
7771 iter.Reset(ValueOf(m3))
7775 kv.SetIterValue(iter)
7779 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7781 if seenv != 0b1110 {
7782 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7786 // Reset should not allocate.
7787 n := int(testing.AllocsPerRun(10, func() {
7788 iter.Reset(ValueOf(m2))
7792 t.Errorf("MapIter.Reset allocated %d times", n)
7796 func TestMapIterSafety(t *testing.T) {
7797 // Using a zero MapIter causes a panic, but not a crash.
7799 defer func() { recover() }()
7801 t.Fatal("Key did not panic")
7804 defer func() { recover() }()
7805 new(MapIter).Value()
7806 t.Fatal("Value did not panic")
7809 defer func() { recover() }()
7811 t.Fatal("Next did not panic")
7814 // Calling Key/Value on a MapIter before Next
7815 // causes a panic, but not a crash.
7816 var m map[string]int
7817 iter := ValueOf(m).MapRange()
7820 defer func() { recover() }()
7822 t.Fatal("Key did not panic")
7825 defer func() { recover() }()
7827 t.Fatal("Value did not panic")
7830 // Calling Next, Key, or Value on an exhausted iterator
7831 // causes a panic, but not a crash.
7832 iter.Next() // -> false
7834 defer func() { recover() }()
7836 t.Fatal("Key did not panic")
7839 defer func() { recover() }()
7841 t.Fatal("Value did not panic")
7844 defer func() { recover() }()
7846 t.Fatal("Next did not panic")
7850 func TestMapIterNext(t *testing.T) {
7851 // The first call to Next should reflect any
7852 // insertions to the map since the iterator was created.
7853 m := map[string]int{}
7854 iter := ValueOf(m).MapRange()
7856 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7857 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7861 func BenchmarkMapIterNext(b *testing.B) {
7862 m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3})
7864 for i := 0; i < b.N; i++ {
7871 func TestMapIterDelete0(t *testing.T) {
7872 // Delete all elements before first iteration.
7873 m := map[string]int{"one": 1, "two": 2, "three": 3}
7874 iter := ValueOf(m).MapRange()
7878 if got, want := iterateToString(iter), `[]`; got != want {
7879 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7883 func TestMapIterDelete1(t *testing.T) {
7884 // Delete all elements after first iteration.
7885 m := map[string]int{"one": 1, "two": 2, "three": 3}
7886 iter := ValueOf(m).MapRange()
7889 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7895 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7899 // iterateToString returns the set of elements
7900 // returned by an iterator in readable form.
7901 func iterateToString(it *MapIter) string {
7904 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7905 got = append(got, line)
7908 return "[" + strings.Join(got, ", ") + "]"
7911 func TestConvertibleTo(t *testing.T) {
7912 t1 := ValueOf(example1.MyStruct{}).Type()
7913 t2 := ValueOf(example2.MyStruct{}).Type()
7915 // Shouldn't raise stack overflow
7916 if t1.ConvertibleTo(t2) {
7917 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7920 t3 := ValueOf([]example1.MyStruct{}).Type()
7921 t4 := ValueOf([]example2.MyStruct{}).Type()
7923 if t3.ConvertibleTo(t4) {
7924 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7928 func TestSetIter(t *testing.T) {
7929 data := map[string]int{
7937 k := New(TypeOf("")).Elem()
7938 v := New(TypeOf(0)).Elem()
7939 shouldPanic("Value.SetIterKey called before Next", func() {
7942 shouldPanic("Value.SetIterValue called before Next", func() {
7945 data2 := map[string]int{}
7949 data2[k.Interface().(string)] = v.Interface().(int)
7951 if !DeepEqual(data, data2) {
7952 t.Errorf("maps not equal, got %v want %v", data2, data)
7954 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7957 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7963 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7964 ValueOf("").SetIterKey(i)
7966 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7967 ValueOf(0).SetIterValue(i)
7969 shouldPanic("value of type string is not assignable to type int", func() {
7970 New(TypeOf(0)).Elem().SetIterKey(i)
7972 shouldPanic("value of type int is not assignable to type string", func() {
7973 New(TypeOf("")).Elem().SetIterValue(i)
7976 // Make sure assignment conversion works.
7978 y := ValueOf(&x).Elem()
7980 if _, ok := data[x.(string)]; !ok {
7981 t.Errorf("got key %s which is not in map", x)
7984 if x.(int) < 1 || x.(int) > 3 {
7985 t.Errorf("got value %d which is not in map", x)
7988 // Try some key/value types which are direct interfaces.
7991 pp := map[*int]*int{
7994 i = ValueOf(pp).MapRange()
7997 if got := *y.Interface().(*int); got != a {
7998 t.Errorf("pointer incorrect: got %d want %d", got, a)
8001 if got := *y.Interface().(*int); got != b {
8002 t.Errorf("pointer incorrect: got %d want %d", got, b)
8006 func TestMethodCallValueCodePtr(t *testing.T) {
8007 m := ValueOf(Point{}).Method(1)
8008 want := MethodValueCallCodePtr()
8009 if got := uintptr(m.UnsafePointer()); got != want {
8010 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
8012 if got := m.Pointer(); got != want {
8013 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
8018 type B[T any] struct{}
8020 func TestIssue50208(t *testing.T) {
8021 want1 := "B[reflect_test.A]"
8022 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
8023 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
8025 want2 := "B[reflect_test.B[reflect_test.A]]"
8026 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
8027 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
8031 func TestNegativeKindString(t *testing.T) {
8033 s := Kind(x).String()
8036 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
8045 var sourceAll = struct {
8054 Bool: ValueOf(new(bool)).Elem(),
8055 String: ValueOf(new(string)).Elem(),
8056 Bytes: ValueOf(new([]byte)).Elem(),
8057 NamedBytes: ValueOf(new(namedBytes)).Elem(),
8058 BytesArray: ValueOf(new([32]byte)).Elem(),
8059 SliceAny: ValueOf(new([]any)).Elem(),
8060 MapStringAny: ValueOf(new(map[string]any)).Elem(),
8063 var sinkAll struct {
8070 func BenchmarkBool(b *testing.B) {
8071 for i := 0; i < b.N; i++ {
8072 sinkAll.RawBool = sourceAll.Bool.Bool()
8076 func BenchmarkString(b *testing.B) {
8077 for i := 0; i < b.N; i++ {
8078 sinkAll.RawString = sourceAll.String.String()
8082 func BenchmarkBytes(b *testing.B) {
8083 for i := 0; i < b.N; i++ {
8084 sinkAll.RawBytes = sourceAll.Bytes.Bytes()
8088 func BenchmarkNamedBytes(b *testing.B) {
8089 for i := 0; i < b.N; i++ {
8090 sinkAll.RawBytes = sourceAll.NamedBytes.Bytes()
8094 func BenchmarkBytesArray(b *testing.B) {
8095 for i := 0; i < b.N; i++ {
8096 sinkAll.RawBytes = sourceAll.BytesArray.Bytes()
8100 func BenchmarkSliceLen(b *testing.B) {
8101 for i := 0; i < b.N; i++ {
8102 sinkAll.RawInt = sourceAll.SliceAny.Len()
8106 func BenchmarkMapLen(b *testing.B) {
8107 for i := 0; i < b.N; i++ {
8108 sinkAll.RawInt = sourceAll.MapStringAny.Len()
8112 func BenchmarkStringLen(b *testing.B) {
8113 for i := 0; i < b.N; i++ {
8114 sinkAll.RawInt = sourceAll.String.Len()
8118 func BenchmarkArrayLen(b *testing.B) {
8119 for i := 0; i < b.N; i++ {
8120 sinkAll.RawInt = sourceAll.BytesArray.Len()
8124 func BenchmarkSliceCap(b *testing.B) {
8125 for i := 0; i < b.N; i++ {
8126 sinkAll.RawInt = sourceAll.SliceAny.Cap()
8130 func TestValue_Cap(t *testing.T) {
8131 a := &[3]int{1, 2, 3}
8133 if v.Cap() != cap(a) {
8134 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
8139 if v.Cap() != cap(a) {
8140 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
8143 getError := func(f func()) (errorStr string) {
8146 if str, ok := e.(string); ok {
8153 e := getError(func() {
8157 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
8159 t.Errorf("error is %q, want %q", e, wantStr)
8163 func TestValue_Len(t *testing.T) {
8164 a := &[3]int{1, 2, 3}
8166 if v.Len() != len(a) {
8167 t.Errorf("Len = %d want %d", v.Len(), len(a))
8172 if v.Len() != len(a) {
8173 t.Errorf("Len = %d want %d", v.Len(), len(a))
8176 getError := func(f func()) (errorStr string) {
8179 if str, ok := e.(string); ok {
8186 e := getError(func() {
8190 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
8192 t.Errorf("error is %q, want %q", e, wantStr)
8196 func TestValue_Comparable(t *testing.T) {
8199 var i interface{} = a
8200 var iSlice interface{} = s
8201 var iArrayFalse interface{} = [2]interface{}{1, map[int]int{}}
8202 var iArrayTrue interface{} = [2]interface{}{1, struct{ I interface{} }{1}}
8203 var testcases = []struct {
8254 ValueOf(float32(1)),
8259 ValueOf(float64(1)),
8264 ValueOf(complex(float32(1), float32(1))),
8269 ValueOf(complex(float64(1), float64(1))),
8284 ValueOf(map[int]int{}),
8324 ValueOf([2]map[int]int{}),
8329 ValueOf([0]func(){}),
8334 ValueOf([2]struct{ I interface{} }{{1}, {1}}),
8339 ValueOf([2]struct{ I interface{} }{{[]int{}}, {1}}),
8344 ValueOf([2]interface{}{1, struct{ I int }{1}}),
8349 ValueOf([2]interface{}{[1]interface{}{map[int]int{}}, struct{ I int }{1}}),
8354 ValueOf(&iArrayFalse),
8359 ValueOf(&iArrayTrue),
8365 for _, cas := range testcases {
8370 got := v.Comparable()
8371 if got != cas.comparable {
8372 t.Errorf("%T.Comparable = %t, want %t", v, got, cas.comparable)
8377 type ValueEqualTest struct {
8383 var equalI interface{} = 1
8384 var equalSlice interface{} = []int{1}
8385 var nilInterface interface{}
8386 var mapInterface interface{} = map[int]int{}
8388 var valueEqualTests = []ValueEqualTest{
8435 uint16(1), uint16(1),
8440 uint32(1), uint32(1),
8445 uint64(1), uint64(1),
8450 float32(1), float32(1),
8455 float64(1), float64(1),
8460 complex(1, 1), complex(1, 1),
8465 complex128(1 + 1i), complex128(1 + 1i),
8480 &equalSlice, []int{1},
8485 map[int]int{}, map[int]int{},
8490 (chan int)(nil), nil,
8495 (chan int)(nil), (chan int)(nil),
8505 struct{ i int }{1}, struct{ i int }{1},
8510 struct{ i int }{1}, struct{ i int }{2},
8515 &nilInterface, &nilInterface,
8520 1, ValueOf(struct{ i int }{1}).Field(0),
8525 &mapInterface, &mapInterface,
8531 func TestValue_Equal(t *testing.T) {
8532 for _, test := range valueEqualTests {
8534 if vv, ok := test.v.(Value); ok {
8540 if uu, ok := test.u.(Value); ok {
8553 if r := v.Equal(u); r != test.eq {
8554 t.Errorf("%s == %s got %t, want %t", v.Type(), u.Type(), r, test.eq)