1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
21 "reflect/internal/example1"
22 "reflect/internal/example2"
36 func TestBool(t *testing.T) {
39 t.Fatal("ValueOf(true).Bool() = false")
51 var _ = T{} == T{} // tests depend on T being comparable
58 func assert(t *testing.T, s, want string) {
60 t.Errorf("have %#q want %#q", s, want)
64 var typeTests = []pair{
65 {struct{ x int }{}, "int"},
66 {struct{ x int8 }{}, "int8"},
67 {struct{ x int16 }{}, "int16"},
68 {struct{ x int32 }{}, "int32"},
69 {struct{ x int64 }{}, "int64"},
70 {struct{ x uint }{}, "uint"},
71 {struct{ x uint8 }{}, "uint8"},
72 {struct{ x uint16 }{}, "uint16"},
73 {struct{ x uint32 }{}, "uint32"},
74 {struct{ x uint64 }{}, "uint64"},
75 {struct{ x float32 }{}, "float32"},
76 {struct{ x float64 }{}, "float64"},
77 {struct{ x int8 }{}, "int8"},
78 {struct{ x (**int8) }{}, "**int8"},
79 {struct{ x (**integer) }{}, "**reflect_test.integer"},
80 {struct{ x ([32]int32) }{}, "[32]int32"},
81 {struct{ x ([]int8) }{}, "[]int8"},
82 {struct{ x (map[string]int32) }{}, "map[string]int32"},
83 {struct{ x (chan<- string) }{}, "chan<- string"},
84 {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
85 {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
86 {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
87 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
94 "struct { c chan *int32; d float32 }",
96 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
99 c func(chan *integer, *int8)
102 "struct { c func(chan *reflect_test.integer, *int8) }",
110 "struct { a int8; b int32 }",
119 "struct { a int8; b int8; c int32 }",
129 "struct { a int8; b int8; c int8; d int32 }",
140 "struct { a int8; b int8; c int8; d int8; e int32 }",
152 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
156 a int8 `reflect:"hi there"`
159 `struct { a int8 "reflect:\"hi there\"" }`,
163 a int8 `reflect:"hi \x00there\t\n\"\\"`
166 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
173 "struct { f func(...int) }",
177 a(func(func(int) int) func(func(int)) int)
181 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
189 "struct { int32; int64 }",
193 var valueTests = []pair{
204 {new(float32), "256.25"},
205 {new(float64), "512.125"},
206 {new(complex64), "532.125+10i"},
207 {new(complex128), "564.25+1i"},
208 {new(string), "stringy cheese"},
210 {new(*int8), "*int8(0)"},
211 {new(**int8), "**int8(0)"},
212 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
213 {new(**integer), "**reflect_test.integer(0)"},
214 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
215 {new(chan<- string), "chan<- string"},
216 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
221 "struct { c chan *int32; d float32 }{chan *int32, 0}",
223 {new(struct{ c func(chan *integer, *int8) }),
224 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
230 "struct { a int8; b int32 }{0, 0}",
237 "struct { a int8; b int8; c int32 }{0, 0, 0}",
241 func testType(t *testing.T, i int, typ Type, want string) {
244 t.Errorf("#%d: have %#q, want %#q", i, s, want)
248 func TestTypes(t *testing.T) {
249 for i, tt := range typeTests {
250 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
254 func TestSet(t *testing.T) {
255 for i, tt := range valueTests {
284 v.SetComplex(532.125 + 10i)
286 v.SetComplex(564.25 + 1i)
288 v.SetString("stringy cheese")
292 s := valueToString(v)
294 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
299 func TestSetValue(t *testing.T) {
300 for i, tt := range valueTests {
301 v := ValueOf(tt.i).Elem()
304 v.Set(ValueOf(int(132)))
306 v.Set(ValueOf(int8(8)))
308 v.Set(ValueOf(int16(16)))
310 v.Set(ValueOf(int32(32)))
312 v.Set(ValueOf(int64(64)))
314 v.Set(ValueOf(uint(132)))
316 v.Set(ValueOf(uint8(8)))
318 v.Set(ValueOf(uint16(16)))
320 v.Set(ValueOf(uint32(32)))
322 v.Set(ValueOf(uint64(64)))
324 v.Set(ValueOf(float32(256.25)))
326 v.Set(ValueOf(512.125))
328 v.Set(ValueOf(complex64(532.125 + 10i)))
330 v.Set(ValueOf(complex128(564.25 + 1i)))
332 v.Set(ValueOf("stringy cheese"))
336 s := valueToString(v)
338 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
343 func TestMapIterSet(t *testing.T) {
344 m := make(map[string]any, len(valueTests))
345 for _, tt := range valueTests {
350 k := New(v.Type().Key()).Elem()
351 e := New(v.Type().Elem()).Elem()
357 want := m[k.String()]
360 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
362 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
363 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
365 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
366 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
370 if testenv.OptimizationOff() {
371 return // no inlining with the noopt builder
374 got := int(testing.AllocsPerRun(10, func() {
381 // Calling MapRange should not allocate even though it returns a *MapIter.
382 // The function is inlineable, so if the local usage does not escape
383 // the *MapIter, it can remain stack allocated.
386 t.Errorf("wanted %d alloc, got %d", want, got)
390 func TestCanIntUintFloatComplex(t *testing.T) {
394 type complex complex128
396 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
398 var testCases = []struct {
403 {132, [...]bool{true, false, false, false}},
404 {int8(8), [...]bool{true, false, false, false}},
405 {int16(16), [...]bool{true, false, false, false}},
406 {int32(32), [...]bool{true, false, false, false}},
407 {int64(64), [...]bool{true, false, false, false}},
409 {uint(132), [...]bool{false, true, false, false}},
410 {uint8(8), [...]bool{false, true, false, false}},
411 {uint16(16), [...]bool{false, true, false, false}},
412 {uint32(32), [...]bool{false, true, false, false}},
413 {uint64(64), [...]bool{false, true, false, false}},
414 {uintptr(0xABCD), [...]bool{false, true, false, false}},
416 {float32(256.25), [...]bool{false, false, true, false}},
417 {float64(512.125), [...]bool{false, false, true, false}},
419 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
420 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
422 {integer(-132), [...]bool{true, false, false, false}},
423 {uinteger(132), [...]bool{false, true, false, false}},
424 {float(256.25), [...]bool{false, false, true, false}},
425 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
427 {"hello world", [...]bool{false, false, false, false}},
428 {new(int), [...]bool{false, false, false, false}},
429 {new(uint), [...]bool{false, false, false, false}},
430 {new(float64), [...]bool{false, false, false, false}},
431 {new(complex64), [...]bool{false, false, false, false}},
432 {new([5]int), [...]bool{false, false, false, false}},
433 {new(integer), [...]bool{false, false, false, false}},
434 {new(map[int]int), [...]bool{false, false, false, false}},
435 {new(chan<- int), [...]bool{false, false, false, false}},
436 {new(func(a int8)), [...]bool{false, false, false, false}},
437 {new(struct{ i int }), [...]bool{false, false, false, false}},
440 for i, tc := range testCases {
442 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
444 for j := range tc.want {
445 if got[j] != tc.want[j] {
447 "#%d: v.%s() returned %t for type %T, want %t",
459 func TestCanSetField(t *testing.T) {
460 type embed struct{ x, X int }
461 type Embed struct{ x, X int }
479 type testCase struct {
480 // -1 means Addr().Elem() of current value
491 {[]int{0, -1}, false},
492 {[]int{0, 0}, false},
493 {[]int{0, 0, -1}, false},
494 {[]int{0, -1, 0}, false},
495 {[]int{0, -1, 0, -1}, false},
497 {[]int{0, 1, -1}, true},
498 {[]int{0, -1, 1}, true},
499 {[]int{0, -1, 1, -1}, true},
501 {[]int{1, -1}, false},
503 {[]int{2, -1}, true},
506 val: ValueOf(&S2{embed: &embed{}}),
509 {[]int{0, -1}, false},
510 {[]int{0, 0}, false},
511 {[]int{0, 0, -1}, false},
512 {[]int{0, -1, 0}, false},
513 {[]int{0, -1, 0, -1}, false},
515 {[]int{0, 1, -1}, true},
516 {[]int{0, -1, 1}, true},
517 {[]int{0, -1, 1, -1}, true},
525 {[]int{0, -1}, true},
526 {[]int{0, 0}, false},
527 {[]int{0, 0, -1}, false},
528 {[]int{0, -1, 0}, false},
529 {[]int{0, -1, 0, -1}, false},
531 {[]int{0, 1, -1}, true},
532 {[]int{0, -1, 1}, true},
533 {[]int{0, -1, 1, -1}, true},
538 val: ValueOf(&S4{Embed: &Embed{}}),
541 {[]int{0, -1}, true},
542 {[]int{0, 0}, false},
543 {[]int{0, 0, -1}, false},
544 {[]int{0, -1, 0}, false},
545 {[]int{0, -1, 0, -1}, false},
547 {[]int{0, 1, -1}, true},
548 {[]int{0, -1, 1}, true},
549 {[]int{0, -1, 1, -1}, true},
555 for _, tt := range tests {
556 t.Run(tt.val.Type().Name(), func(t *testing.T) {
557 for _, tc := range tt.cases {
559 for _, i := range tc.index {
560 if f.Kind() == Pointer {
569 if got := f.CanSet(); got != tc.canSet {
570 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
579 var valueToStringTests = []pair{
584 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
585 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
586 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
587 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
588 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
589 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
592 func TestValueToString(t *testing.T) {
593 for i, test := range valueToStringTests {
594 s := valueToString(ValueOf(test.i))
596 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
601 func TestArrayElemSet(t *testing.T) {
602 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
603 v.Index(4).SetInt(123)
604 s := valueToString(v)
605 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
607 t.Errorf("[10]int: have %#q want %#q", s, want)
610 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
611 v.Index(4).SetInt(123)
613 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
615 t.Errorf("[]int: have %#q want %#q", s, want1)
619 func TestPtrPointTo(t *testing.T) {
623 vi := ValueOf(&i).Elem()
624 vip.Elem().Set(vi.Addr())
626 t.Errorf("got %d, want 1234", *ip)
630 vp := ValueOf(&ip).Elem()
631 vp.Set(Zero(vp.Type()))
633 t.Errorf("got non-nil (%p), want nil", ip)
637 func TestPtrSetNil(t *testing.T) {
641 vip.Elem().Set(Zero(vip.Elem().Type()))
643 t.Errorf("got non-nil (%d), want nil", *ip)
647 func TestMapSetNil(t *testing.T) {
648 m := make(map[string]int)
650 vm.Elem().Set(Zero(vm.Elem().Type()))
652 t.Errorf("got non-nil (%p), want nil", m)
656 func TestAll(t *testing.T) {
657 testType(t, 1, TypeOf((int8)(0)), "int8")
658 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
660 typ := TypeOf((*struct {
664 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
666 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
669 testType(t, 5, f.Type, "chan *int32")
671 f, present := styp.FieldByName("d")
673 t.Errorf("FieldByName says present field is absent")
675 testType(t, 6, f.Type, "float32")
677 f, present = styp.FieldByName("absent")
679 t.Errorf("FieldByName says absent field is present")
682 typ = TypeOf([32]int32{})
683 testType(t, 7, typ, "[32]int32")
684 testType(t, 8, typ.Elem(), "int32")
686 typ = TypeOf((map[string]*int32)(nil))
687 testType(t, 9, typ, "map[string]*int32")
689 testType(t, 10, mtyp.Key(), "string")
690 testType(t, 11, mtyp.Elem(), "*int32")
692 typ = TypeOf((chan<- string)(nil))
693 testType(t, 12, typ, "chan<- string")
694 testType(t, 13, typ.Elem(), "string")
696 // make sure tag strings are not part of element type
697 typ = TypeOf(struct {
698 d []uint32 `reflect:"TAG"`
700 testType(t, 14, typ, "[]uint32")
703 func TestInterfaceGet(t *testing.T) {
708 v1 := ValueOf(&inter)
709 v2 := v1.Elem().Field(0)
710 assert(t, v2.Type().String(), "interface {}")
713 assert(t, v3.Type().String(), "float64")
716 func TestInterfaceValue(t *testing.T) {
721 v1 := ValueOf(&inter)
722 v2 := v1.Elem().Field(0)
723 assert(t, v2.Type().String(), "interface {}")
725 assert(t, v3.Type().String(), "float64")
728 if _, ok := i3.(float64); !ok {
729 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
733 func TestFunctionValue(t *testing.T) {
734 var x any = func() {}
736 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
737 t.Fatalf("TestFunction returned wrong pointer")
739 assert(t, v.Type().String(), "func()")
742 var appendTests = []struct {
745 {make([]int, 2, 4), []int{22}},
746 {make([]int, 2, 4), []int{22, 33, 44}},
749 func sameInts(x, y []int) bool {
750 if len(x) != len(y) {
753 for i, xx := range x {
761 func TestAppend(t *testing.T) {
762 for i, test := range appendTests {
763 origLen, extraLen := len(test.orig), len(test.extra)
764 want := append(test.orig, test.extra...)
765 // Convert extra from []int to []Value.
766 e0 := make([]Value, len(test.extra))
767 for j, e := range test.extra {
770 // Convert extra from []int to *SliceValue.
771 e1 := ValueOf(test.extra)
773 a0 := ValueOf(test.orig)
774 have0 := Append(a0, e0...).Interface().([]int)
775 if !sameInts(have0, want) {
776 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
778 // Check that the orig and extra slices were not modified.
779 if len(test.orig) != origLen {
780 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
782 if len(test.extra) != extraLen {
783 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
786 a1 := ValueOf(test.orig)
787 have1 := AppendSlice(a1, e1).Interface().([]int)
788 if !sameInts(have1, want) {
789 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
791 // Check that the orig and extra slices were not modified.
792 if len(test.orig) != origLen {
793 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
795 if len(test.extra) != extraLen {
796 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
801 func TestCopy(t *testing.T) {
802 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
803 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
804 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
805 for i := 0; i < len(b); i++ {
807 t.Fatalf("b != c before test")
812 aa := ValueOf(&a1).Elem()
813 ab := ValueOf(&b1).Elem()
814 for tocopy := 1; tocopy <= 7; tocopy++ {
818 for i := 0; i < tocopy; i++ {
820 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
821 tocopy, i, a[i], i, b[i])
824 for i := tocopy; i < len(b); i++ {
827 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
828 tocopy, i, a[i], i, b[i], i, c[i])
830 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
831 tocopy, i, b[i], i, c[i])
834 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
840 func TestCopyString(t *testing.T) {
841 t.Run("Slice", func(t *testing.T) {
842 s := bytes.Repeat([]byte{'_'}, 8)
845 n := Copy(val, ValueOf(""))
846 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
847 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
850 n = Copy(val, ValueOf("hello"))
851 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
852 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
855 n = Copy(val, ValueOf("helloworld"))
856 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
857 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
860 t.Run("Array", func(t *testing.T) {
861 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
862 val := ValueOf(&s).Elem()
864 n := Copy(val, ValueOf(""))
865 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
866 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
869 n = Copy(val, ValueOf("hello"))
870 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
871 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
874 n = Copy(val, ValueOf("helloworld"))
875 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
876 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
881 func TestCopyArray(t *testing.T) {
882 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
883 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
885 aa := ValueOf(&a).Elem()
886 ab := ValueOf(&b).Elem()
888 for i := 0; i < len(a); i++ {
890 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
893 for i := len(a); i < len(b); i++ {
895 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
897 t.Logf("elem %d is okay\n", i)
902 func TestBigUnnamedStruct(t *testing.T) {
903 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
905 b1 := v.Interface().(struct {
908 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
909 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
917 func TestBigStruct(t *testing.T) {
918 b := big{1, 2, 3, 4, 5}
920 b1 := v.Interface().(big)
921 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
922 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
933 type DeepEqualTest struct {
938 // Simple functions for DeepEqual tests.
942 fn3 = func() { fn1() } // Not nil.
950 var loop1, loop2 Loop
951 var loopy1, loopy2 Loopy
952 var cycleMap1, cycleMap2, cycleMap3 map[string]any
954 type structWithSelfPtr struct {
966 cycleMap1 = map[string]any{}
967 cycleMap1["cycle"] = cycleMap1
968 cycleMap2 = map[string]any{}
969 cycleMap2["cycle"] = cycleMap2
970 cycleMap3 = map[string]any{}
971 cycleMap3["different"] = cycleMap3
974 var deepEqualTests = []DeepEqualTest{
978 {int32(1), int32(1), true},
980 {float32(0.5), float32(0.5), true},
981 {"hello", "hello", true},
982 {make([]int, 10), make([]int, 10), true},
983 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
984 {Basic{1, 0.5}, Basic{1, 0.5}, true},
985 {error(nil), error(nil), true},
986 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
988 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
989 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
990 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
994 {int32(1), int32(2), false},
996 {float32(0.5), float32(0.6), false},
997 {"hello", "hey", false},
998 {make([]int, 10), make([]int, 11), false},
999 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
1000 {Basic{1, 0.5}, Basic{1, 0.6}, false},
1001 {Basic{1, 0}, Basic{2, 0}, false},
1002 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
1003 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
1004 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
1005 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
1010 {[][]int{{1}}, [][]int{{2}}, false},
1011 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1013 // Fun with floating point.
1014 {math.NaN(), math.NaN(), false},
1015 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1016 {&[1]float64{math.NaN()}, self{}, true},
1017 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1018 {[]float64{math.NaN()}, self{}, true},
1019 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1020 {map[float64]float64{math.NaN(): 1}, self{}, true},
1022 // Nil vs empty: not the same.
1023 {[]int{}, []int(nil), false},
1024 {[]int{}, []int{}, true},
1025 {[]int(nil), []int(nil), true},
1026 {map[int]int{}, map[int]int(nil), false},
1027 {map[int]int{}, map[int]int{}, true},
1028 {map[int]int(nil), map[int]int(nil), true},
1032 {int32(1), int64(1), false},
1033 {0.5, "hello", false},
1034 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1035 {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
1036 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1037 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1038 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1039 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1040 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1043 {&loop1, &loop1, true},
1044 {&loop1, &loop2, true},
1045 {&loopy1, &loopy1, true},
1046 {&loopy1, &loopy2, true},
1047 {&cycleMap1, &cycleMap2, true},
1048 {&cycleMap1, &cycleMap3, false},
1051 func TestDeepEqual(t *testing.T) {
1052 for _, test := range deepEqualTests {
1053 if test.b == (self{}) {
1056 if r := DeepEqual(test.a, test.b); r != test.eq {
1057 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1062 func TestTypeOf(t *testing.T) {
1063 // Special case for nil
1064 if typ := TypeOf(nil); typ != nil {
1065 t.Errorf("expected nil type for nil value; got %v", typ)
1067 for _, test := range deepEqualTests {
1068 v := ValueOf(test.a)
1072 typ := TypeOf(test.a)
1073 if typ != v.Type() {
1074 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1079 type Recursive struct {
1084 func TestDeepEqualRecursiveStruct(t *testing.T) {
1085 a, b := new(Recursive), new(Recursive)
1086 *a = Recursive{12, a}
1087 *b = Recursive{12, b}
1088 if !DeepEqual(a, b) {
1089 t.Error("DeepEqual(recursive same) = false, want true")
1093 type _Complex struct {
1097 d map[float64]float64
1100 func TestDeepEqualComplexStruct(t *testing.T) {
1101 m := make(map[float64]float64)
1102 stra, strb := "hello", "hello"
1103 a, b := new(_Complex), new(_Complex)
1104 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1105 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1106 if !DeepEqual(a, b) {
1107 t.Error("DeepEqual(complex same) = false, want true")
1111 func TestDeepEqualComplexStructInequality(t *testing.T) {
1112 m := make(map[float64]float64)
1113 stra, strb := "hello", "helloo" // Difference is here
1114 a, b := new(_Complex), new(_Complex)
1115 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1116 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1117 if DeepEqual(a, b) {
1118 t.Error("DeepEqual(complex different) = true, want false")
1122 type UnexpT struct {
1126 func TestDeepEqualUnexportedMap(t *testing.T) {
1127 // Check that DeepEqual can look at unexported fields.
1128 x1 := UnexpT{map[int]int{1: 2}}
1129 x2 := UnexpT{map[int]int{1: 2}}
1130 if !DeepEqual(&x1, &x2) {
1131 t.Error("DeepEqual(x1, x2) = false, want true")
1134 y1 := UnexpT{map[int]int{2: 3}}
1135 if DeepEqual(&x1, &y1) {
1136 t.Error("DeepEqual(x1, y1) = true, want false")
1140 var deepEqualPerfTests = []struct {
1143 {x: int8(99), y: int8(99)},
1144 {x: []int8{99}, y: []int8{99}},
1145 {x: int16(99), y: int16(99)},
1146 {x: []int16{99}, y: []int16{99}},
1147 {x: int32(99), y: int32(99)},
1148 {x: []int32{99}, y: []int32{99}},
1149 {x: int64(99), y: int64(99)},
1150 {x: []int64{99}, y: []int64{99}},
1151 {x: int(999999), y: int(999999)},
1152 {x: []int{999999}, y: []int{999999}},
1154 {x: uint8(99), y: uint8(99)},
1155 {x: []uint8{99}, y: []uint8{99}},
1156 {x: uint16(99), y: uint16(99)},
1157 {x: []uint16{99}, y: []uint16{99}},
1158 {x: uint32(99), y: uint32(99)},
1159 {x: []uint32{99}, y: []uint32{99}},
1160 {x: uint64(99), y: uint64(99)},
1161 {x: []uint64{99}, y: []uint64{99}},
1162 {x: uint(999999), y: uint(999999)},
1163 {x: []uint{999999}, y: []uint{999999}},
1164 {x: uintptr(999999), y: uintptr(999999)},
1165 {x: []uintptr{999999}, y: []uintptr{999999}},
1167 {x: float32(1.414), y: float32(1.414)},
1168 {x: []float32{1.414}, y: []float32{1.414}},
1169 {x: float64(1.414), y: float64(1.414)},
1170 {x: []float64{1.414}, y: []float64{1.414}},
1172 {x: complex64(1.414), y: complex64(1.414)},
1173 {x: []complex64{1.414}, y: []complex64{1.414}},
1174 {x: complex128(1.414), y: complex128(1.414)},
1175 {x: []complex128{1.414}, y: []complex128{1.414}},
1178 {x: []bool{true}, y: []bool{true}},
1180 {x: "abcdef", y: "abcdef"},
1181 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1183 {x: []byte("abcdef"), y: []byte("abcdef")},
1184 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1186 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1187 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1190 func TestDeepEqualAllocs(t *testing.T) {
1191 for _, tt := range deepEqualPerfTests {
1192 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1193 got := testing.AllocsPerRun(100, func() {
1194 if !DeepEqual(tt.x, tt.y) {
1195 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1199 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1205 func check2ndField(x any, offs uintptr, t *testing.T) {
1207 f := s.Type().Field(1)
1208 if f.Offset != offs {
1209 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1213 // Check that structure alignment & offsets viewed through reflect agree with those
1214 // from the compiler itself.
1215 func TestAlignment(t *testing.T) {
1216 type T1inner struct {
1223 type T2inner struct {
1231 x := T1{T1inner{2}, 17}
1232 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1234 x1 := T2{T2inner{2, 3}, 17}
1235 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1238 func Nil(a any, t *testing.T) {
1239 n := ValueOf(a).Field(0)
1241 t.Errorf("%v should be nil", a)
1245 func NotNil(a any, t *testing.T) {
1246 n := ValueOf(a).Field(0)
1248 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1252 func TestIsNil(t *testing.T) {
1253 // These implement IsNil.
1254 // Wrap in extra struct to hide interface type.
1258 struct{ x map[string]int }{},
1259 struct{ x func() bool }{},
1260 struct{ x chan int }{},
1261 struct{ x []string }{},
1262 struct{ x unsafe.Pointer }{},
1264 for _, ts := range doNil {
1265 ty := TypeOf(ts).Field(0).Type
1267 v.IsNil() // panics if not okay to call
1270 // Check the implementations
1282 si.x = make([]int, 10)
1289 ci.x = make(chan int)
1296 mi.x = make(map[int]int)
1307 x func(t *testing.T)
1314 func TestIsZero(t *testing.T) {
1315 for i, tt := range []struct {
1344 {float32(1.2), false},
1346 {float64(1.2), false},
1347 {math.Copysign(0, -1), false},
1348 {complex64(0), true},
1349 {complex64(1.2), false},
1350 {complex128(0), true},
1351 {complex128(1.2), false},
1352 {complex(math.Copysign(0, -1), 0), false},
1353 {complex(0, math.Copysign(0, -1)), false},
1354 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1356 {uintptr(128), false},
1358 {Zero(TypeOf([5]string{})).Interface(), true},
1359 {[5]string{}, true}, // comparable array
1360 {[5]string{"", "", "", "a", ""}, false}, // comparable array
1361 {[1]*int{}, true}, // direct pointer array
1362 {[1]*int{new(int)}, false}, // direct pointer array
1363 {[3][]int{}, true}, // incomparable array
1364 {[3][]int{{1}}, false}, // incomparable array
1365 {[1 << 12]byte{}, true},
1366 {[1 << 12]byte{1}, false},
1368 {[3]Value{{}, ValueOf(0), {}}, false},
1370 {(chan string)(nil), true},
1371 {make(chan string), false},
1372 {time.After(1), false},
1374 {(func())(nil), true},
1377 {New(TypeOf(new(error)).Elem()).Elem(), true},
1378 {(io.Reader)(strings.NewReader("")), false},
1380 {(map[string]string)(nil), true},
1381 {map[string]string{}, false},
1382 {make(map[string]string), false},
1384 {(*func())(nil), true},
1385 {(*int)(nil), true},
1388 {[]string{}, false},
1389 {([]string)(nil), true},
1390 {make([]string, 0), false},
1393 {"not-zero", false},
1395 {T{}, true}, // comparable struct
1396 {T{123, 456.75, "hello", &_i}, false}, // comparable struct
1397 {struct{ p *int }{}, true}, // direct pointer struct
1398 {struct{ p *int }{new(int)}, false}, // direct pointer struct
1399 {struct{ s []int }{}, true}, // incomparable struct
1400 {struct{ s []int }{[]int{1}}, false}, // incomparable struct
1401 {struct{ Value }{}, true},
1402 {struct{ Value }{ValueOf(0)}, false},
1404 {(unsafe.Pointer)(nil), true},
1405 {(unsafe.Pointer)(new(int)), false},
1408 if v, ok := tt.x.(Value); ok {
1416 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1419 if !Zero(TypeOf(tt.x)).IsZero() {
1420 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1423 p := New(x.Type()).Elem()
1427 t.Errorf("%d: IsZero((%s)(%+v)) is true after SetZero", i, p.Kind(), tt.x)
1433 if r := recover(); r == nil {
1434 t.Error("should panic for invalid value")
1441 func TestInterfaceExtraction(t *testing.T) {
1447 v := Indirect(ValueOf(&s)).Field(0).Interface()
1449 t.Error("Interface() on interface: ", v, s.W)
1453 func TestNilPtrValueSub(t *testing.T) {
1455 if pv := ValueOf(pi); pv.Elem().IsValid() {
1456 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1460 func TestMap(t *testing.T) {
1461 m := map[string]int{"a": 1, "b": 2}
1463 if n := mv.Len(); n != len(m) {
1464 t.Errorf("Len = %d, want %d", n, len(m))
1466 keys := mv.MapKeys()
1467 newmap := MakeMap(mv.Type())
1468 for k, v := range m {
1469 // Check that returned Keys match keys in range.
1470 // These aren't required to be in the same order.
1472 for _, kv := range keys {
1473 if kv.String() == k {
1479 t.Errorf("Missing key %q", k)
1482 // Check that value lookup is correct.
1483 vv := mv.MapIndex(ValueOf(k))
1484 if vi := vv.Int(); vi != int64(v) {
1485 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1488 // Copy into new map.
1489 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1491 vv := mv.MapIndex(ValueOf("not-present"))
1493 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1496 newm := newmap.Interface().(map[string]int)
1497 if len(newm) != len(m) {
1498 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1501 for k, v := range newm {
1504 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1508 newmap.SetMapIndex(ValueOf("a"), Value{})
1511 t.Errorf("newm[\"a\"] = %d after delete", v)
1514 mv = ValueOf(&m).Elem()
1515 mv.Set(Zero(mv.Type()))
1517 t.Errorf("mv.Set(nil) failed")
1521 shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
1522 shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
1525 func TestNilMap(t *testing.T) {
1526 var m map[string]int
1528 keys := mv.MapKeys()
1530 t.Errorf(">0 keys for nil map: %v", keys)
1533 // Check that value for missing key is zero.
1534 x := mv.MapIndex(ValueOf("hello"))
1535 if x.Kind() != Invalid {
1536 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1539 // Check big value too.
1540 var mbig map[string][10 << 20]byte
1541 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1542 if x.Kind() != Invalid {
1543 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1546 // Test that deletes from a nil map succeed.
1547 mv.SetMapIndex(ValueOf("hi"), Value{})
1550 func TestChan(t *testing.T) {
1551 for loop := 0; loop < 2; loop++ {
1555 // check both ways to allocate channels
1558 c = make(chan int, 1)
1561 cv = MakeChan(TypeOf(c), 1)
1562 c = cv.Interface().(chan int)
1567 if i := <-c; i != 2 {
1568 t.Errorf("reflect Send 2, native recv %d", i)
1573 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1574 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1578 val, ok := cv.TryRecv()
1579 if val.IsValid() || ok {
1580 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1585 val, ok = cv.TryRecv()
1587 t.Errorf("TryRecv on ready chan got nil")
1588 } else if i := val.Int(); i != 4 || !ok {
1589 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1594 ok = cv.TrySend(ValueOf(5))
1597 t.Errorf("TrySend on full chan succeeded: value %d", i)
1601 ok = cv.TrySend(ValueOf(6))
1603 t.Errorf("TrySend on empty chan failed")
1606 t.Errorf("TrySend failed but it did send %d", x)
1610 if i = <-c; i != 6 {
1611 t.Errorf("TrySend 6, recv %d", i)
1618 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1619 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1621 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1622 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1626 // check creation of unbuffered channel
1628 cv := MakeChan(TypeOf(c), 0)
1629 c = cv.Interface().(chan int)
1630 if cv.TrySend(ValueOf(7)) {
1631 t.Errorf("TrySend on sync chan succeeded")
1633 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1634 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1638 cv = MakeChan(TypeOf(c), 10)
1639 c = cv.Interface().(chan int)
1640 for i := 0; i < 3; i++ {
1643 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1644 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1648 // caseInfo describes a single case in a select test.
1649 type caseInfo struct {
1658 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1660 func TestSelect(t *testing.T) {
1661 selectWatch.once.Do(func() { go selectWatcher() })
1665 newop := func(n int, cap int) (ch, val Value) {
1668 c := make(chan int, cap)
1672 c := make(chan string, cap)
1674 val = ValueOf(fmt.Sprint(n))
1679 for n := 0; x.Next(); n++ {
1680 if testing.Short() && n >= 1000 {
1683 if n >= 100000 && !*allselect {
1686 if n%100000 == 0 && testing.Verbose() {
1687 println("TestSelect", n)
1689 var cases []SelectCase
1694 ch, val := newop(len(cases), 1)
1695 cases = append(cases, SelectCase{
1700 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1705 ch, val := newop(len(cases), 1)
1707 cases = append(cases, SelectCase{
1711 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1716 ch, val := newop(len(cases), 0)
1717 cases = append(cases, SelectCase{
1724 f := func() { ch.Recv() }
1725 info = append(info, caseInfo{desc: "blocking send", helper: f})
1727 info = append(info, caseInfo{desc: "blocking send"})
1733 ch, val := newop(len(cases), 0)
1734 cases = append(cases, SelectCase{
1740 f := func() { ch.Send(val) }
1741 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1743 info = append(info, caseInfo{desc: "blocking recv"})
1749 // Maybe include value to send.
1754 cases = append(cases, SelectCase{
1758 info = append(info, caseInfo{desc: "zero Chan send"})
1761 // Zero Chan receive.
1763 cases = append(cases, SelectCase{
1766 info = append(info, caseInfo{desc: "zero Chan recv"})
1771 cases = append(cases, SelectCase{
1773 Chan: ValueOf((chan int)(nil)),
1776 info = append(info, caseInfo{desc: "nil Chan send"})
1781 cases = append(cases, SelectCase{
1783 Chan: ValueOf((chan int)(nil)),
1785 info = append(info, caseInfo{desc: "nil Chan recv"})
1788 // closed Chan send.
1790 ch := make(chan int)
1792 cases = append(cases, SelectCase{
1797 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1800 // closed Chan recv.
1802 ch, val := newop(len(cases), 0)
1804 val = Zero(val.Type())
1805 cases = append(cases, SelectCase{
1809 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1812 var helper func() // goroutine to help the select complete
1814 // Add default? Must be last case here, but will permute.
1815 // Add the default if the select would otherwise
1816 // block forever, and maybe add it anyway.
1822 for i, c := range info {
1830 } else if c.helper != nil {
1832 helpers = append(helpers, i)
1835 if !canProceed || x.Maybe() {
1836 cases = append(cases, SelectCase{
1839 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1841 } else if canBlock {
1842 // Select needs to communicate with another goroutine.
1843 cas := &info[helpers[x.Choose(len(helpers))]]
1845 cas.canSelect = true
1849 // Permute cases and case info.
1850 // Doing too much here makes the exhaustive loop
1851 // too exhausting, so just do two swaps.
1852 for loop := 0; loop < 2; loop++ {
1853 i := x.Choose(len(cases))
1854 j := x.Choose(len(cases))
1855 cases[i], cases[j] = cases[j], cases[i]
1856 info[i], info[j] = info[j], info[i]
1860 // We wait before kicking off a goroutine to satisfy a blocked select.
1861 // The pause needs to be big enough to let the select block before
1862 // we run the helper, but if we lose that race once in a while it's okay: the
1863 // select will just proceed immediately. Not a big deal.
1864 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1865 pause := 10 * time.Microsecond
1866 if testing.Short() {
1867 pause = 100 * time.Microsecond
1869 time.AfterFunc(pause, helper)
1873 i, recv, recvOK, panicErr := runSelect(cases, info)
1874 if panicErr != nil && !canPanic {
1875 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1877 if panicErr == nil && canPanic && numCanSelect == 1 {
1878 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1880 if panicErr != nil {
1888 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1890 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1893 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1896 if cases[i].Dir == SelectRecv {
1897 if !recv.IsValid() {
1898 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1900 if !cas.recv.IsValid() {
1901 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1903 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1904 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1905 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1907 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1910 if recv.IsValid() || recvOK {
1911 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1917 func TestSelectMaxCases(t *testing.T) {
1918 var sCases []SelectCase
1919 channel := make(chan int)
1921 for i := 0; i < 65536; i++ {
1922 sCases = append(sCases, SelectCase{
1924 Chan: ValueOf(channel),
1928 _, _, _ = Select(sCases)
1929 sCases = append(sCases, SelectCase{
1931 Chan: ValueOf(channel),
1934 if err := recover(); err != nil {
1935 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1936 t.Fatalf("unexpected error from select call with greater than max supported cases")
1939 t.Fatalf("expected select call to panic with greater than max supported cases")
1943 _, _, _ = Select(sCases)
1946 func TestSelectNop(t *testing.T) {
1947 // "select { default: }" should always return the default case.
1948 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1950 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1954 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1955 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1956 // an error describing the select and panics the entire test binary.
1957 var selectWatch struct {
1964 func selectWatcher() {
1966 time.Sleep(1 * time.Second)
1968 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1969 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1970 panic("select stuck")
1972 selectWatch.Unlock()
1976 // runSelect runs a single select test.
1977 // It returns the values returned by Select but also returns
1978 // a panic value if the Select panics.
1979 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
1981 panicErr = recover()
1984 selectWatch.info = nil
1985 selectWatch.Unlock()
1989 selectWatch.now = time.Now()
1990 selectWatch.info = info
1991 selectWatch.Unlock()
1993 chosen, recv, recvOK = Select(cases)
1997 // fmtSelect formats the information about a single select test.
1998 func fmtSelect(info []caseInfo) string {
1999 var buf strings.Builder
2000 fmt.Fprintf(&buf, "\nselect {\n")
2001 for i, cas := range info {
2002 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2003 if cas.recv.IsValid() {
2004 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2007 fmt.Fprintf(&buf, " canselect")
2010 fmt.Fprintf(&buf, " panic")
2012 fmt.Fprintf(&buf, "\n")
2014 fmt.Fprintf(&buf, "}")
2020 // Difficult test for function call because of
2021 // implicit padding between arguments.
2022 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) {
2023 return b, c, d, e, f, g, h
2026 func TestFunc(t *testing.T) {
2027 ret := ValueOf(dummy).Call([]Value{
2031 ValueOf(two{40, 50}),
2033 ValueOf(float32(70)),
2037 t.Fatalf("Call returned %d values, want 7", len(ret))
2040 i := byte(ret[0].Uint())
2041 j := int(ret[1].Int())
2042 k := byte(ret[2].Uint())
2043 l := ret[3].Interface().(two)
2044 m := byte(ret[4].Uint())
2045 n := float32(ret[5].Float())
2046 o := byte(ret[6].Uint())
2048 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2049 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)
2052 for i, v := range ret {
2054 t.Errorf("result %d is addressable", i)
2059 func TestCallConvert(t *testing.T) {
2060 v := ValueOf(new(io.ReadWriter)).Elem()
2061 f := ValueOf(func(r io.Reader) io.Reader { return r })
2062 out := f.Call([]Value{v})
2063 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2064 t.Errorf("expected [nil], got %v", out)
2068 type emptyStruct struct{}
2070 type nonEmptyStruct struct {
2074 func returnEmpty() emptyStruct {
2075 return emptyStruct{}
2078 func takesEmpty(e emptyStruct) {
2081 func returnNonEmpty(i int) nonEmptyStruct {
2082 return nonEmptyStruct{member: i}
2085 func takesNonEmpty(n nonEmptyStruct) int {
2089 func TestCallWithStruct(t *testing.T) {
2090 r := ValueOf(returnEmpty).Call(nil)
2091 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2092 t.Errorf("returning empty struct returned %#v instead", r)
2094 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2096 t.Errorf("takesEmpty returned values: %#v", r)
2098 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2099 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2100 t.Errorf("returnNonEmpty returned %#v", r)
2102 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2103 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2104 t.Errorf("takesNonEmpty returned %#v", r)
2108 func TestCallReturnsEmpty(t *testing.T) {
2109 // Issue 21717: past-the-end pointer write in Call with
2110 // nonzero-sized frame and zero-sized return value.
2112 var finalized uint32
2113 f := func() (emptyStruct, *[2]int64) {
2114 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2115 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2116 return emptyStruct{}, i
2118 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2119 timeout := time.After(5 * time.Second)
2120 for atomic.LoadUint32(&finalized) == 0 {
2123 t.Fatal("finalizer did not run")
2129 runtime.KeepAlive(v)
2132 func TestMakeFunc(t *testing.T) {
2134 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2135 ValueOf(&f).Elem().Set(fv)
2137 // Call g with small arguments so that there is
2138 // something predictable (and different from the
2139 // correct results) in those positions on the stack.
2141 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2143 // Call constructed function f.
2144 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2145 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2146 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)
2150 func TestMakeFuncInterface(t *testing.T) {
2151 fn := func(i int) int { return i }
2152 incr := func(in []Value) []Value {
2153 return []Value{ValueOf(int(in[0].Int() + 1))}
2155 fv := MakeFunc(TypeOf(fn), incr)
2156 ValueOf(&fn).Elem().Set(fv)
2157 if r := fn(2); r != 3 {
2158 t.Errorf("Call returned %d, want 3", r)
2160 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2161 t.Errorf("Call returned %d, want 15", r)
2163 if r := fv.Interface().(func(int) int)(26); r != 27 {
2164 t.Errorf("Call returned %d, want 27", r)
2168 func TestMakeFuncVariadic(t *testing.T) {
2169 // Test that variadic arguments are packed into a slice and passed as last arg
2170 fn := func(_ int, is ...int) []int { return nil }
2171 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2172 ValueOf(&fn).Elem().Set(fv)
2175 if r[0] != 2 || r[1] != 3 {
2176 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2179 r = fn(1, []int{2, 3}...)
2180 if r[0] != 2 || r[1] != 3 {
2181 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2184 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2185 if r[0] != 2 || r[1] != 3 {
2186 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2189 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2190 if r[0] != 2 || r[1] != 3 {
2191 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2194 f := fv.Interface().(func(int, ...int) []int)
2197 if r[0] != 2 || r[1] != 3 {
2198 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2200 r = f(1, []int{2, 3}...)
2201 if r[0] != 2 || r[1] != 3 {
2202 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2206 // Dummy type that implements io.WriteCloser
2210 func (w *WC) Write(p []byte) (n int, err error) {
2213 func (w *WC) Close() error {
2217 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2218 // reflect.Values returned from the wrapped function should be assignment-converted
2219 // to the types returned by the result of MakeFunc.
2221 // Concrete types should be promotable to interfaces they implement.
2223 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2224 return []Value{ValueOf(io.EOF)}
2225 }).Interface().(func() error)
2228 // Super-interfaces should be promotable to simpler interfaces.
2229 var g func() io.Writer
2230 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2231 var w io.WriteCloser = &WC{}
2232 return []Value{ValueOf(&w).Elem()}
2233 }).Interface().(func() io.Writer)
2236 // Channels should be promotable to directional channels.
2237 var h func() <-chan int
2238 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2239 return []Value{ValueOf(make(chan int))}
2240 }).Interface().(func() <-chan int)
2243 // Unnamed types should be promotable to named types.
2244 type T struct{ a, b, c int }
2246 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2247 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2248 }).Interface().(func() T)
2252 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2253 // Type doesn't implement the required interface.
2254 shouldPanic("", func() {
2256 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2257 return []Value{ValueOf(int(7))}
2258 }).Interface().(func() error)
2261 // Assigning to an interface with additional methods.
2262 shouldPanic("", func() {
2263 var f func() io.ReadWriteCloser
2264 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2265 var w io.WriteCloser = &WC{}
2266 return []Value{ValueOf(&w).Elem()}
2267 }).Interface().(func() io.ReadWriteCloser)
2270 // Directional channels can't be assigned to bidirectional ones.
2271 shouldPanic("", func() {
2272 var f func() chan int
2273 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2274 var c <-chan int = make(chan int)
2275 return []Value{ValueOf(c)}
2276 }).Interface().(func() chan int)
2279 // Two named types which are otherwise identical.
2280 shouldPanic("", func() {
2281 type T struct{ a, b, c int }
2282 type U struct{ a, b, c int }
2284 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2285 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2286 }).Interface().(func() T)
2295 // This will be index 0.
2296 func (p Point) AnotherMethod(scale int) int {
2300 // This will be index 1.
2301 func (p Point) Dist(scale int) int {
2302 //println("Point.Dist", p.x, p.y, scale)
2303 return p.x*p.x*scale + p.y*p.y*scale
2306 // This will be index 2.
2307 func (p Point) GCMethod(k int) int {
2312 // This will be index 3.
2313 func (p Point) NoArgs() {
2314 // Exercise no-argument/no-result paths.
2317 // This will be index 4.
2318 func (p Point) TotalDist(points ...Point) int {
2320 for _, q := range points {
2323 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2329 // This will be index 5.
2330 func (p *Point) Int64Method(x int64) int64 {
2334 // This will be index 6.
2335 func (p *Point) Int32Method(x int32) int32 {
2339 func TestMethod(t *testing.T) {
2340 // Non-curried method of type.
2342 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2344 t.Errorf("Type Method returned %d; want 250", i)
2347 m, ok := TypeOf(p).MethodByName("Dist")
2349 t.Fatalf("method by name failed")
2351 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2353 t.Errorf("Type MethodByName returned %d; want 275", i)
2356 m, ok = TypeOf(p).MethodByName("NoArgs")
2358 t.Fatalf("method by name failed")
2360 n := len(m.Func.Call([]Value{ValueOf(p)}))
2362 t.Errorf("NoArgs returned %d values; want 0", n)
2365 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2367 t.Errorf("Pointer Type Method returned %d; want 300", i)
2370 m, ok = TypeOf(&p).MethodByName("Dist")
2372 t.Fatalf("ptr method by name failed")
2374 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2376 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2379 m, ok = TypeOf(&p).MethodByName("NoArgs")
2381 t.Fatalf("method by name failed")
2383 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2385 t.Errorf("NoArgs returned %d values; want 0", n)
2388 _, ok = TypeOf(&p).MethodByName("AA")
2390 t.Errorf(`MethodByName("AA") should have failed`)
2393 _, ok = TypeOf(&p).MethodByName("ZZ")
2395 t.Errorf(`MethodByName("ZZ") should have failed`)
2398 // Curried method of value.
2399 tfunc := TypeOf((func(int) int)(nil))
2400 v := ValueOf(p).Method(1)
2401 if tt := v.Type(); tt != tfunc {
2402 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2404 i = v.Call([]Value{ValueOf(14)})[0].Int()
2406 t.Errorf("Value Method returned %d; want 350", i)
2408 v = ValueOf(p).MethodByName("Dist")
2409 if tt := v.Type(); tt != tfunc {
2410 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2412 i = v.Call([]Value{ValueOf(15)})[0].Int()
2414 t.Errorf("Value MethodByName returned %d; want 375", i)
2416 v = ValueOf(p).MethodByName("NoArgs")
2419 // Curried method of pointer.
2420 v = ValueOf(&p).Method(1)
2421 if tt := v.Type(); tt != tfunc {
2422 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2424 i = v.Call([]Value{ValueOf(16)})[0].Int()
2426 t.Errorf("Pointer Value Method returned %d; want 400", i)
2428 v = ValueOf(&p).MethodByName("Dist")
2429 if tt := v.Type(); tt != tfunc {
2430 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2432 i = v.Call([]Value{ValueOf(17)})[0].Int()
2434 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2436 v = ValueOf(&p).MethodByName("NoArgs")
2439 // Curried method of interface value.
2440 // Have to wrap interface value in a struct to get at it.
2441 // Passing it to ValueOf directly would
2442 // access the underlying Point, not the interface.
2446 pv := ValueOf(&x).Elem()
2448 if tt := v.Type(); tt != tfunc {
2449 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2451 i = v.Call([]Value{ValueOf(18)})[0].Int()
2453 t.Errorf("Interface Method returned %d; want 450", i)
2455 v = pv.MethodByName("Dist")
2456 if tt := v.Type(); tt != tfunc {
2457 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2459 i = v.Call([]Value{ValueOf(19)})[0].Int()
2461 t.Errorf("Interface MethodByName returned %d; want 475", i)
2465 func TestMethodValue(t *testing.T) {
2469 // Check that method value have the same underlying code pointers.
2470 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2471 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2474 // Curried method of value.
2475 tfunc := TypeOf((func(int) int)(nil))
2476 v := ValueOf(p).Method(1)
2477 if tt := v.Type(); tt != tfunc {
2478 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2480 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2482 t.Errorf("Value Method returned %d; want 250", i)
2484 v = ValueOf(p).MethodByName("Dist")
2485 if tt := v.Type(); tt != tfunc {
2486 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2488 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2490 t.Errorf("Value MethodByName returned %d; want 275", i)
2492 v = ValueOf(p).MethodByName("NoArgs")
2493 ValueOf(v.Interface()).Call(nil)
2494 v.Interface().(func())()
2496 // Curried method of pointer.
2497 v = ValueOf(&p).Method(1)
2498 if tt := v.Type(); tt != tfunc {
2499 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2501 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2503 t.Errorf("Pointer Value Method returned %d; want 300", i)
2505 v = ValueOf(&p).MethodByName("Dist")
2506 if tt := v.Type(); tt != tfunc {
2507 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2509 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2511 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2513 v = ValueOf(&p).MethodByName("NoArgs")
2514 ValueOf(v.Interface()).Call(nil)
2515 v.Interface().(func())()
2517 // Curried method of pointer to pointer.
2519 v = ValueOf(&pp).Elem().Method(1)
2520 if tt := v.Type(); tt != tfunc {
2521 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2523 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2525 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2527 v = ValueOf(&pp).Elem().MethodByName("Dist")
2528 if tt := v.Type(); tt != tfunc {
2529 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2531 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2533 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2536 // Curried method of interface value.
2537 // Have to wrap interface value in a struct to get at it.
2538 // Passing it to ValueOf directly would
2539 // access the underlying Point, not the interface.
2545 pv := ValueOf(s).Field(0)
2547 if tt := v.Type(); tt != tfunc {
2548 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2550 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2552 t.Errorf("Interface Method returned %d; want 400", i)
2554 v = pv.MethodByName("Dist")
2555 if tt := v.Type(); tt != tfunc {
2556 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2558 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2560 t.Errorf("Interface MethodByName returned %d; want 425", i)
2563 // For issue #33628: method args are not stored at the right offset
2565 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2566 if x := m64(123); x != 123 {
2567 t.Errorf("Int64Method returned %d; want 123", x)
2569 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2570 if x := m32(456); x != 456 {
2571 t.Errorf("Int32Method returned %d; want 456", x)
2575 func TestVariadicMethodValue(t *testing.T) {
2577 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2578 want := int64(p.TotalDist(points[0], points[1], points[2]))
2580 // Variadic method of type.
2581 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2582 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2583 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2586 // Curried method of value.
2587 tfunc = TypeOf((func(...Point) int)(nil))
2588 v := ValueOf(p).Method(4)
2589 if tt := v.Type(); tt != tfunc {
2590 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2592 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2594 t.Errorf("Variadic Method returned %d; want %d", i, want)
2596 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2598 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2601 f := v.Interface().(func(...Point) int)
2602 i = int64(f(points[0], points[1], points[2]))
2604 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2606 i = int64(f(points...))
2608 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2612 type DirectIfaceT struct {
2616 func (d DirectIfaceT) M() int { return *d.p }
2618 func TestDirectIfaceMethod(t *testing.T) {
2620 v := DirectIfaceT{&x}
2622 m, ok := typ.MethodByName("M")
2624 t.Fatalf("cannot find method M")
2626 in := []Value{ValueOf(v)}
2627 out := m.Func.Call(in)
2628 if got := out[0].Int(); got != 42 {
2629 t.Errorf("Call with value receiver got %d, want 42", got)
2634 m, ok = typ.MethodByName("M")
2636 t.Fatalf("cannot find method M")
2638 in = []Value{ValueOf(pv)}
2639 out = m.Func.Call(in)
2640 if got := out[0].Int(); got != 42 {
2641 t.Errorf("Call with pointer receiver got %d, want 42", got)
2645 // Reflect version of $GOROOT/test/method5.go
2647 // Concrete types implementing M method.
2648 // Smaller than a word, word-sized, larger than a word.
2649 // Value and pointer receivers.
2651 type Tinter interface {
2652 M(int, byte) (byte, int)
2657 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2661 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2665 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2669 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2671 type Tbigv [2]uintptr
2673 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2675 type Tbigp [2]uintptr
2677 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2679 type tinter interface {
2680 m(int, byte) (byte, int)
2683 // Embedding via pointer.
2700 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2702 func TestMethod5(t *testing.T) {
2703 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2705 if b != 99 || x != 1000+inc {
2706 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2710 CheckV := func(name string, i Value, inc int) {
2711 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2712 b := bx[0].Interface()
2713 x := bx[1].Interface()
2714 if b != byte(99) || x != 1000+inc {
2715 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2718 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2721 var TinterType = TypeOf(new(Tinter)).Elem()
2723 CheckI := func(name string, i any, inc int) {
2725 CheckV(name, v, inc)
2726 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2731 CheckI("&sv", &sv, 1)
2734 CheckI("&sp", &sp, 2)
2738 CheckI("&wv", &wv, 3)
2741 CheckI("&wp", &wp, 4)
2743 bv := Tbigv([2]uintptr{5, 6})
2744 CheckI("bv", bv, 11)
2745 CheckI("&bv", &bv, 11)
2747 bp := Tbigp([2]uintptr{7, 8})
2748 CheckI("&bp", &bp, 15)
2754 CheckI("t4", t4, 40)
2755 CheckI("&t4", &t4, 40)
2756 CheckI("t3", t3, 40)
2757 CheckI("&t3", &t3, 40)
2758 CheckI("t2", t2, 40)
2759 CheckI("&t2", &t2, 40)
2760 CheckI("t1", t1, 40)
2761 CheckI("&t1", &t1, 40)
2764 vnil := ValueOf(&tnil).Elem()
2765 shouldPanic("Method", func() { vnil.Method(0) })
2768 func TestInterfaceSet(t *testing.T) {
2777 sv := ValueOf(&s).Elem()
2778 sv.Field(0).Set(ValueOf(p))
2779 if q := s.I.(*Point); q != p {
2780 t.Errorf("i: have %p want %p", q, p)
2785 if q := s.P.(*Point); q != p {
2786 t.Errorf("i: have %p want %p", q, p)
2789 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2791 t.Errorf("Interface Method returned %d; want 250", i)
2800 func TestAnonymousFields(t *testing.T) {
2801 var field StructField
2805 if field, ok = type1.FieldByName("int"); !ok {
2806 t.Fatal("no field 'int'")
2808 if field.Index[0] != 1 {
2809 t.Error("field index should be 1; is", field.Index)
2863 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2885 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2904 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2918 var fieldTests = []FTest{
2919 {struct{}{}, "", nil, 0},
2920 {struct{}{}, "Foo", nil, 0},
2921 {S0{A: 'a'}, "A", []int{0}, 'a'},
2922 {S0{}, "D", nil, 0},
2923 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2924 {S1{B: 'b'}, "B", []int{0}, 'b'},
2925 {S1{}, "S0", []int{1}, 0},
2926 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2927 {S2{A: 'a'}, "A", []int{0}, 'a'},
2928 {S2{}, "S1", []int{1}, 0},
2929 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2930 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2931 {S2{}, "D", nil, 0},
2932 {S3{}, "S1", nil, 0},
2933 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2934 {S3{}, "B", nil, 0},
2935 {S3{D: 'd'}, "D", []int{2}, 0},
2936 {S3{E: 'e'}, "E", []int{3}, 'e'},
2937 {S4{A: 'a'}, "A", []int{1}, 'a'},
2938 {S4{}, "B", nil, 0},
2939 {S5{}, "X", nil, 0},
2940 {S5{}, "Y", []int{2, 0, 1}, 0},
2941 {S10{}, "X", nil, 0},
2942 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2943 {S14{}, "X", nil, 0},
2946 func TestFieldByIndex(t *testing.T) {
2947 for _, test := range fieldTests {
2949 f := s.FieldByIndex(test.index)
2951 if test.index != nil {
2952 if f.Name != test.name {
2953 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2956 t.Errorf("%s.%s found", s.Name(), f.Name)
2958 } else if len(test.index) > 0 {
2959 t.Errorf("%s.%s not found", s.Name(), test.name)
2962 if test.value != 0 {
2963 v := ValueOf(test.s).FieldByIndex(test.index)
2965 if x, ok := v.Interface().(int); ok {
2966 if x != test.value {
2967 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2970 t.Errorf("%s%v value not an int", s.Name(), test.index)
2973 t.Errorf("%s%v value not found", s.Name(), test.index)
2979 func TestFieldByName(t *testing.T) {
2980 for _, test := range fieldTests {
2982 f, found := s.FieldByName(test.name)
2984 if test.index != nil {
2985 // Verify field depth and index.
2986 if len(f.Index) != len(test.index) {
2987 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)
2989 for i, x := range f.Index {
2990 if x != test.index[i] {
2991 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2996 t.Errorf("%s.%s found", s.Name(), f.Name)
2998 } else if len(test.index) > 0 {
2999 t.Errorf("%s.%s not found", s.Name(), test.name)
3002 if test.value != 0 {
3003 v := ValueOf(test.s).FieldByName(test.name)
3005 if x, ok := v.Interface().(int); ok {
3006 if x != test.value {
3007 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3010 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3013 t.Errorf("%s.%s value not found", s.Name(), test.name)
3019 func TestImportPath(t *testing.T) {
3024 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3025 {TypeOf(int(0)), ""},
3026 {TypeOf(int8(0)), ""},
3027 {TypeOf(int16(0)), ""},
3028 {TypeOf(int32(0)), ""},
3029 {TypeOf(int64(0)), ""},
3030 {TypeOf(uint(0)), ""},
3031 {TypeOf(uint8(0)), ""},
3032 {TypeOf(uint16(0)), ""},
3033 {TypeOf(uint32(0)), ""},
3034 {TypeOf(uint64(0)), ""},
3035 {TypeOf(uintptr(0)), ""},
3036 {TypeOf(float32(0)), ""},
3037 {TypeOf(float64(0)), ""},
3038 {TypeOf(complex64(0)), ""},
3039 {TypeOf(complex128(0)), ""},
3040 {TypeOf(byte(0)), ""},
3041 {TypeOf(rune(0)), ""},
3042 {TypeOf([]byte(nil)), ""},
3043 {TypeOf([]rune(nil)), ""},
3044 {TypeOf(string("")), ""},
3045 {TypeOf((*any)(nil)).Elem(), ""},
3046 {TypeOf((*byte)(nil)), ""},
3047 {TypeOf((*rune)(nil)), ""},
3048 {TypeOf((*int64)(nil)), ""},
3049 {TypeOf(map[string]int{}), ""},
3050 {TypeOf((*error)(nil)).Elem(), ""},
3051 {TypeOf((*Point)(nil)), ""},
3052 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3054 for _, test := range tests {
3055 if path := test.t.PkgPath(); path != test.path {
3056 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3061 func TestFieldPkgPath(t *testing.T) {
3063 typ := TypeOf(struct {
3071 type pkgpathTest struct {
3078 checkPkgPath := func(name string, s []pkgpathTest) {
3079 for _, test := range s {
3080 f := typ.FieldByIndex(test.index)
3081 if got, want := f.PkgPath, test.pkgPath; got != want {
3082 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3084 if got, want := f.Anonymous, test.embedded; got != want {
3085 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3087 if got, want := f.IsExported(), test.exported; got != want {
3088 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3093 checkPkgPath("testStruct", []pkgpathTest{
3094 {[]int{0}, "", false, true}, // Exported
3095 {[]int{1}, "reflect_test", false, false}, // unexported
3096 {[]int{2}, "", true, true}, // OtherPkgFields
3097 {[]int{2, 0}, "", false, true}, // OtherExported
3098 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3099 {[]int{3}, "reflect_test", true, false}, // int
3100 {[]int{4}, "reflect_test", true, false}, // *x
3103 type localOtherPkgFields OtherPkgFields
3104 typ = TypeOf(localOtherPkgFields{})
3105 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3106 {[]int{0}, "", false, true}, // OtherExported
3107 {[]int{1}, "reflect", false, false}, // otherUnexported
3111 func TestMethodPkgPath(t *testing.T) {
3116 typ := TypeOf((*interface {
3129 {"x", "reflect_test", false},
3130 {"y", "reflect_test", false},
3133 for _, test := range tests {
3134 m, _ := typ.MethodByName(test.name)
3135 if got, want := m.PkgPath, test.pkgPath; got != want {
3136 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3138 if got, want := m.IsExported(), test.exported; got != want {
3139 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3144 func TestVariadicType(t *testing.T) {
3145 // Test example from Type documentation.
3146 var f func(x int, y ...float64)
3148 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3150 if sl.Kind() == Slice {
3151 if sl.Elem() == TypeOf(0.0) {
3159 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3160 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3161 for i := 0; i < typ.NumIn(); i++ {
3162 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3176 func (*inner) M() {}
3177 func (*outer) M() {}
3179 func TestNestedMethods(t *testing.T) {
3180 typ := TypeOf((*outer)(nil))
3181 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3182 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3183 for i := 0; i < typ.NumMethod(); i++ {
3185 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3192 func (*unexp) f() (int32, int8) { return 7, 7 }
3193 func (*unexp) g() (int64, int8) { return 8, 8 }
3195 type unexpI interface {
3199 var unexpi unexpI = new(unexp)
3201 func TestUnexportedMethods(t *testing.T) {
3202 typ := TypeOf(unexpi)
3204 if got := typ.NumMethod(); got != 0 {
3205 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3209 type InnerInt struct {
3213 type OuterInt struct {
3218 func (i *InnerInt) M() int {
3222 func TestEmbeddedMethods(t *testing.T) {
3223 typ := TypeOf((*OuterInt)(nil))
3224 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3225 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3226 for i := 0; i < typ.NumMethod(); i++ {
3228 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3233 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3234 t.Errorf("i.M() = %d, want 3", v)
3237 o := &OuterInt{1, InnerInt{2}}
3238 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3239 t.Errorf("i.M() = %d, want 2", v)
3243 if v := f(o); v != 2 {
3244 t.Errorf("f(o) = %d, want 2", v)
3248 type FuncDDD func(...any) error
3250 func (f FuncDDD) M() {}
3252 func TestNumMethodOnDDD(t *testing.T) {
3253 rv := ValueOf((FuncDDD)(nil))
3254 if n := rv.NumMethod(); n != 1 {
3255 t.Fatalf("NumMethod()=%d, want 1", n)
3259 func TestPtrTo(t *testing.T) {
3260 // This block of code means that the ptrToThis field of the
3261 // reflect data for *unsafe.Pointer is non zero, see
3262 // https://golang.org/issue/19003
3263 var x unsafe.Pointer
3270 for i = 0; i < 100; i++ {
3271 typ = PointerTo(typ)
3273 for i = 0; i < 100; i++ {
3276 if typ != TypeOf(z) {
3277 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3281 func TestPtrToGC(t *testing.T) {
3283 tt := TypeOf(T(nil))
3287 for i := 0; i < n; i++ {
3292 v.Elem().Set(ValueOf(p).Convert(pt))
3293 x = append(x, v.Interface())
3297 for i, xi := range x {
3298 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3299 if k != uintptr(i) {
3300 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3305 func TestAddr(t *testing.T) {
3317 t.Errorf("Addr.Elem.Set failed to set value")
3320 // Again but take address of the ValueOf value.
3321 // Exercises generation of PtrTypes not present in the binary.
3323 v = ValueOf(&q).Elem()
3332 t.Errorf("Addr.Elem.Set failed to set value")
3335 // Starting without pointer we should get changed value
3338 v = ValueOf(&qq).Elem()
3344 if p.X != 3 { // should be unchanged from last time
3345 t.Errorf("somehow value Set changed original p")
3347 p = v0.Interface().(struct {
3351 t.Errorf("Addr.Elem.Set valued to set value in top value")
3354 // Verify that taking the address of a type gives us a pointer
3355 // which we can convert back using the usual interface
3360 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3361 *(ps.(**bool)) = new(bool)
3363 t.Errorf("Addr.Interface direct assignment failed")
3367 func noAlloc(t *testing.T, n int, f func(int)) {
3368 if testing.Short() {
3369 t.Skip("skipping malloc count in short mode")
3371 if runtime.GOMAXPROCS(0) > 1 {
3372 t.Skip("skipping; GOMAXPROCS>1")
3375 allocs := testing.AllocsPerRun(n, func() {
3380 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3384 func TestAllocations(t *testing.T) {
3385 noAlloc(t, 100, func(j int) {
3389 // We can uncomment this when compiler escape analysis
3390 // is good enough to see that the integer assigned to i
3391 // does not escape and therefore need not be allocated.
3395 // if int(v.Int()) != 42+j {
3396 // panic("wrong int")
3399 i = func(j int) int { return j }
3401 if v.Interface().(func(int) int)(j) != j {
3402 panic("wrong result")
3407 func TestSmallNegativeInt(t *testing.T) {
3411 t.Errorf("int16(-1).Int() returned %v", v.Int())
3415 func TestIndex(t *testing.T) {
3416 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3417 v := ValueOf(xs).Index(3).Interface().(byte)
3419 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3421 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3422 v = ValueOf(xa).Index(2).Interface().(byte)
3424 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3427 v = ValueOf(s).Index(3).Interface().(byte)
3429 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3433 func TestSlice(t *testing.T) {
3434 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3435 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3437 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3440 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3442 if !DeepEqual(v[0:5], xs[3:]) {
3443 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3445 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3446 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3448 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3451 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3453 if !DeepEqual(v[0:6], xa[2:]) {
3454 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3457 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3459 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3462 rv := ValueOf(&xs).Elem()
3464 ptr2 := rv.UnsafePointer()
3466 ptr3 := rv.UnsafePointer()
3468 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3472 func TestSlice3(t *testing.T) {
3473 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3474 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3476 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3479 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3481 if !DeepEqual(v[0:4], xs[3:7:7]) {
3482 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3484 rv := ValueOf(&xs).Elem()
3485 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3486 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3487 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3489 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3490 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3492 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3495 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3497 if !DeepEqual(v[0:4], xa[2:6:6]) {
3498 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3500 rv = ValueOf(&xa).Elem()
3501 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3502 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3503 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3506 rv = ValueOf(&s).Elem()
3507 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3509 rv = ValueOf(&xs).Elem()
3510 rv = rv.Slice3(3, 5, 7)
3511 ptr2 := rv.UnsafePointer()
3512 rv = rv.Slice3(4, 4, 4)
3513 ptr3 := rv.UnsafePointer()
3515 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3519 func TestSetLenCap(t *testing.T) {
3520 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3521 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3523 vs := ValueOf(&xs).Elem()
3524 shouldPanic("SetLen", func() { vs.SetLen(10) })
3525 shouldPanic("SetCap", func() { vs.SetCap(10) })
3526 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3527 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3528 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3530 if len(xs) != 5 || cap(xs) != 8 {
3531 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3534 if len(xs) != 5 || cap(xs) != 6 {
3535 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3538 if len(xs) != 5 || cap(xs) != 5 {
3539 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3541 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3542 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3544 va := ValueOf(&xa).Elem()
3545 shouldPanic("SetLen", func() { va.SetLen(8) })
3546 shouldPanic("SetCap", func() { va.SetCap(8) })
3549 func TestVariadic(t *testing.T) {
3550 var b strings.Builder
3554 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3555 if b.String() != "hello, 42 world" {
3556 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3560 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3561 if b.String() != "hello, 42 world" {
3562 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3566 func TestFuncArg(t *testing.T) {
3567 f1 := func(i int, f func(int) int) int { return f(i) }
3568 f2 := func(i int) int { return i + 1 }
3569 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3570 if r[0].Int() != 101 {
3571 t.Errorf("function returned %d, want 101", r[0].Int())
3575 func TestStructArg(t *testing.T) {
3576 type padded struct {
3583 wantA = padded{"3", 4}
3586 f := func(a padded, b uint32) {
3589 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3590 if gotA != wantA || gotB != wantB {
3591 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3595 var tagGetTests = []struct {
3600 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3601 {`protobuf:"PB(1,2)"`, `foo`, ``},
3602 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3603 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3604 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3605 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3606 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3609 func TestTagGet(t *testing.T) {
3610 for _, tt := range tagGetTests {
3611 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3612 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3617 func TestBytes(t *testing.T) {
3618 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3619 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3623 y := ValueOf(x).Bytes()
3624 if !bytes.Equal(x, y) {
3625 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3628 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3633 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3634 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3635 b := ValueOf(&a).Elem().Bytes()
3636 if !bytes.Equal(a[:], y) {
3637 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3640 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3643 // Per issue #24746, it was decided that Bytes can be called on byte slices
3644 // that normally cannot be converted from per Go language semantics.
3648 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3649 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3650 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3651 ValueOf(new(AB)).Elem().Bytes() // should not panic
3654 func TestSetBytes(t *testing.T) {
3657 y := []byte{1, 2, 3, 4}
3658 ValueOf(&x).Elem().SetBytes(y)
3659 if !bytes.Equal(x, y) {
3660 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3663 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3667 type Private struct {
3673 func (p *Private) m() {
3676 type private struct {
3684 func (p *private) P() {
3687 type Public struct {
3693 func (p *Public) M() {
3696 func TestUnexported(t *testing.T) {
3701 isValid(v.Elem().Field(0))
3702 isValid(v.Elem().Field(1))
3703 isValid(v.Elem().Field(2))
3704 isValid(v.Elem().FieldByName("X"))
3705 isValid(v.Elem().FieldByName("Y"))
3706 isValid(v.Elem().FieldByName("Z"))
3707 isValid(v.Type().Method(0).Func)
3708 m, _ := v.Type().MethodByName("M")
3710 m, _ = v.Type().MethodByName("P")
3712 isNonNil(v.Elem().Field(0).Interface())
3713 isNonNil(v.Elem().Field(1).Interface())
3714 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3715 isNonNil(v.Elem().FieldByName("X").Interface())
3716 isNonNil(v.Elem().FieldByName("Y").Interface())
3717 isNonNil(v.Elem().FieldByName("Z").Interface())
3718 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3719 isNonNil(v.Type().Method(0).Func.Interface())
3720 m, _ = v.Type().MethodByName("P")
3721 isNonNil(m.Func.Interface())
3725 isValid(v.Elem().Field(0))
3726 isValid(v.Elem().Field(1))
3727 isValid(v.Elem().FieldByName("x"))
3728 isValid(v.Elem().FieldByName("y"))
3729 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3730 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3731 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3732 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3733 shouldPanic("Method", func() { v.Type().Method(0) })
3736 func TestSetPanic(t *testing.T) {
3737 ok := func(f func()) { f() }
3738 bad := func(f func()) { shouldPanic("Set", f) }
3739 clear := func(v Value) { v.Set(Zero(v.Type())) }
3767 bad(func() { clear(v.Field(0)) }) // .X
3768 bad(func() { clear(v.Field(1)) }) // .t1
3769 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3770 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3771 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3772 bad(func() { clear(v.Field(2)) }) // .T2
3773 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3774 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3775 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3776 bad(func() { clear(v.Field(3)) }) // .NamedT1
3777 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3778 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3779 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3780 bad(func() { clear(v.Field(4)) }) // .NamedT2
3781 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3782 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3783 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3784 bad(func() { clear(v.Field(5)) }) // .namedT1
3785 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3786 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3787 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3788 bad(func() { clear(v.Field(6)) }) // .namedT2
3789 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3790 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3791 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3794 v = ValueOf(&T{}).Elem()
3795 ok(func() { clear(v.Field(0)) }) // .X
3796 bad(func() { clear(v.Field(1)) }) // .t1
3797 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3798 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3799 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3800 ok(func() { clear(v.Field(2)) }) // .T2
3801 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3802 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3803 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3804 ok(func() { clear(v.Field(3)) }) // .NamedT1
3805 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3806 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3807 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3808 ok(func() { clear(v.Field(4)) }) // .NamedT2
3809 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3810 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3811 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3812 bad(func() { clear(v.Field(5)) }) // .namedT1
3813 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3814 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3815 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3816 bad(func() { clear(v.Field(6)) }) // .namedT2
3817 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3818 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3819 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3824 func (t timp) W() {}
3825 func (t timp) Y() {}
3826 func (t timp) w() {}
3827 func (t timp) y() {}
3829 func TestCallPanic(t *testing.T) {
3854 ok := func(f func()) { f() }
3855 badCall := func(f func()) { shouldPanic("Call", f) }
3856 badMethod := func(f func()) { shouldPanic("Method", f) }
3857 call := func(v Value) { v.Call(nil) }
3860 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3861 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3862 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3863 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3864 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3865 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3866 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3867 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3868 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3870 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3871 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3872 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3873 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3875 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3876 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3877 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3878 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3880 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3881 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3882 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3883 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3885 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3886 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3887 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3888 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3890 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3891 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3892 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3893 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3895 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3896 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3897 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3898 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3901 func TestValuePanic(t *testing.T) {
3903 shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
3904 shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
3905 shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
3906 shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
3907 shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
3908 shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
3909 shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
3910 shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
3911 shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
3912 shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
3913 shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
3914 shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
3915 shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
3916 shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
3917 shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
3918 shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
3919 shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
3920 shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
3921 shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
3922 shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
3923 shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
3924 shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
3925 shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
3926 shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
3927 shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
3928 shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
3929 shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
3930 shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
3931 shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
3932 shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
3933 shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
3934 shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
3935 shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
3936 shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
3937 shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
3938 shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
3939 shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
3940 shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
3941 shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
3942 shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
3943 shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
3946 func shouldPanic(expect string, f func()) {
3950 panic("did not panic")
3954 switch r := r.(type) {
3960 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3962 if !strings.HasPrefix(s, "reflect") {
3963 panic(`panic string does not start with "reflect": ` + s)
3965 if !strings.Contains(s, expect) {
3966 panic(`panic string does not contain "` + expect + `": ` + s)
3973 func isNonNil(x any) {
3975 panic("nil interface")
3979 func isValid(v Value) {
3985 func TestAlias(t *testing.T) {
3986 x := string("hello")
3987 v := ValueOf(&x).Elem()
3988 oldvalue := v.Interface()
3989 v.SetString("world")
3990 newvalue := v.Interface()
3992 if oldvalue != "hello" || newvalue != "world" {
3993 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3999 func EmptyInterfaceV(x any) Value {
4000 return ValueOf(&x).Elem()
4003 func ReaderV(x io.Reader) Value {
4004 return ValueOf(&x).Elem()
4007 func ReadWriterV(x io.ReadWriter) Value {
4008 return ValueOf(&x).Elem()
4012 type MyStruct struct {
4015 type MyStruct1 struct {
4020 type MyStruct2 struct {
4025 type MyString string
4027 type MyBytesArrayPtr0 *[0]byte
4028 type MyBytesArrayPtr *[4]byte
4029 type MyBytesArray0 [0]byte
4030 type MyBytesArray [4]byte
4031 type MyRunes []int32
4035 type IntChan chan int
4036 type IntChanRecv <-chan int
4037 type IntChanSend chan<- int
4038 type BytesChan chan []byte
4039 type BytesChanRecv <-chan []byte
4040 type BytesChanSend chan<- []byte
4042 var convertTests = []struct {
4048 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4054 var numbers = []string{
4055 "int8", "uint8", "int16", "uint16",
4056 "int32", "uint32", "int64", "uint64",
4057 "int", "uint", "uintptr",
4058 "float32", "float64",
4062 // all pairs but in an unusual order,
4063 // to emit all the int8, uint8 cases
4064 // before n grows too big.
4066 for i, f := range numbers {
4067 for _, g := range numbers[i:] {
4068 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4071 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4078 {V(int8(1)), V(int8(1))},
4079 {V(int8(2)), V(uint8(2))},
4080 {V(uint8(3)), V(int8(3))},
4081 {V(int8(4)), V(int16(4))},
4082 {V(int16(5)), V(int8(5))},
4083 {V(int8(6)), V(uint16(6))},
4084 {V(uint16(7)), V(int8(7))},
4085 {V(int8(8)), V(int32(8))},
4086 {V(int32(9)), V(int8(9))},
4087 {V(int8(10)), V(uint32(10))},
4088 {V(uint32(11)), V(int8(11))},
4089 {V(int8(12)), V(int64(12))},
4090 {V(int64(13)), V(int8(13))},
4091 {V(int8(14)), V(uint64(14))},
4092 {V(uint64(15)), V(int8(15))},
4093 {V(int8(16)), V(int(16))},
4094 {V(int(17)), V(int8(17))},
4095 {V(int8(18)), V(uint(18))},
4096 {V(uint(19)), V(int8(19))},
4097 {V(int8(20)), V(uintptr(20))},
4098 {V(uintptr(21)), V(int8(21))},
4099 {V(int8(22)), V(float32(22))},
4100 {V(float32(23)), V(int8(23))},
4101 {V(int8(24)), V(float64(24))},
4102 {V(float64(25)), V(int8(25))},
4103 {V(uint8(26)), V(uint8(26))},
4104 {V(uint8(27)), V(int16(27))},
4105 {V(int16(28)), V(uint8(28))},
4106 {V(uint8(29)), V(uint16(29))},
4107 {V(uint16(30)), V(uint8(30))},
4108 {V(uint8(31)), V(int32(31))},
4109 {V(int32(32)), V(uint8(32))},
4110 {V(uint8(33)), V(uint32(33))},
4111 {V(uint32(34)), V(uint8(34))},
4112 {V(uint8(35)), V(int64(35))},
4113 {V(int64(36)), V(uint8(36))},
4114 {V(uint8(37)), V(uint64(37))},
4115 {V(uint64(38)), V(uint8(38))},
4116 {V(uint8(39)), V(int(39))},
4117 {V(int(40)), V(uint8(40))},
4118 {V(uint8(41)), V(uint(41))},
4119 {V(uint(42)), V(uint8(42))},
4120 {V(uint8(43)), V(uintptr(43))},
4121 {V(uintptr(44)), V(uint8(44))},
4122 {V(uint8(45)), V(float32(45))},
4123 {V(float32(46)), V(uint8(46))},
4124 {V(uint8(47)), V(float64(47))},
4125 {V(float64(48)), V(uint8(48))},
4126 {V(int16(49)), V(int16(49))},
4127 {V(int16(50)), V(uint16(50))},
4128 {V(uint16(51)), V(int16(51))},
4129 {V(int16(52)), V(int32(52))},
4130 {V(int32(53)), V(int16(53))},
4131 {V(int16(54)), V(uint32(54))},
4132 {V(uint32(55)), V(int16(55))},
4133 {V(int16(56)), V(int64(56))},
4134 {V(int64(57)), V(int16(57))},
4135 {V(int16(58)), V(uint64(58))},
4136 {V(uint64(59)), V(int16(59))},
4137 {V(int16(60)), V(int(60))},
4138 {V(int(61)), V(int16(61))},
4139 {V(int16(62)), V(uint(62))},
4140 {V(uint(63)), V(int16(63))},
4141 {V(int16(64)), V(uintptr(64))},
4142 {V(uintptr(65)), V(int16(65))},
4143 {V(int16(66)), V(float32(66))},
4144 {V(float32(67)), V(int16(67))},
4145 {V(int16(68)), V(float64(68))},
4146 {V(float64(69)), V(int16(69))},
4147 {V(uint16(70)), V(uint16(70))},
4148 {V(uint16(71)), V(int32(71))},
4149 {V(int32(72)), V(uint16(72))},
4150 {V(uint16(73)), V(uint32(73))},
4151 {V(uint32(74)), V(uint16(74))},
4152 {V(uint16(75)), V(int64(75))},
4153 {V(int64(76)), V(uint16(76))},
4154 {V(uint16(77)), V(uint64(77))},
4155 {V(uint64(78)), V(uint16(78))},
4156 {V(uint16(79)), V(int(79))},
4157 {V(int(80)), V(uint16(80))},
4158 {V(uint16(81)), V(uint(81))},
4159 {V(uint(82)), V(uint16(82))},
4160 {V(uint16(83)), V(uintptr(83))},
4161 {V(uintptr(84)), V(uint16(84))},
4162 {V(uint16(85)), V(float32(85))},
4163 {V(float32(86)), V(uint16(86))},
4164 {V(uint16(87)), V(float64(87))},
4165 {V(float64(88)), V(uint16(88))},
4166 {V(int32(89)), V(int32(89))},
4167 {V(int32(90)), V(uint32(90))},
4168 {V(uint32(91)), V(int32(91))},
4169 {V(int32(92)), V(int64(92))},
4170 {V(int64(93)), V(int32(93))},
4171 {V(int32(94)), V(uint64(94))},
4172 {V(uint64(95)), V(int32(95))},
4173 {V(int32(96)), V(int(96))},
4174 {V(int(97)), V(int32(97))},
4175 {V(int32(98)), V(uint(98))},
4176 {V(uint(99)), V(int32(99))},
4177 {V(int32(100)), V(uintptr(100))},
4178 {V(uintptr(101)), V(int32(101))},
4179 {V(int32(102)), V(float32(102))},
4180 {V(float32(103)), V(int32(103))},
4181 {V(int32(104)), V(float64(104))},
4182 {V(float64(105)), V(int32(105))},
4183 {V(uint32(106)), V(uint32(106))},
4184 {V(uint32(107)), V(int64(107))},
4185 {V(int64(108)), V(uint32(108))},
4186 {V(uint32(109)), V(uint64(109))},
4187 {V(uint64(110)), V(uint32(110))},
4188 {V(uint32(111)), V(int(111))},
4189 {V(int(112)), V(uint32(112))},
4190 {V(uint32(113)), V(uint(113))},
4191 {V(uint(114)), V(uint32(114))},
4192 {V(uint32(115)), V(uintptr(115))},
4193 {V(uintptr(116)), V(uint32(116))},
4194 {V(uint32(117)), V(float32(117))},
4195 {V(float32(118)), V(uint32(118))},
4196 {V(uint32(119)), V(float64(119))},
4197 {V(float64(120)), V(uint32(120))},
4198 {V(int64(121)), V(int64(121))},
4199 {V(int64(122)), V(uint64(122))},
4200 {V(uint64(123)), V(int64(123))},
4201 {V(int64(124)), V(int(124))},
4202 {V(int(125)), V(int64(125))},
4203 {V(int64(126)), V(uint(126))},
4204 {V(uint(127)), V(int64(127))},
4205 {V(int64(128)), V(uintptr(128))},
4206 {V(uintptr(129)), V(int64(129))},
4207 {V(int64(130)), V(float32(130))},
4208 {V(float32(131)), V(int64(131))},
4209 {V(int64(132)), V(float64(132))},
4210 {V(float64(133)), V(int64(133))},
4211 {V(uint64(134)), V(uint64(134))},
4212 {V(uint64(135)), V(int(135))},
4213 {V(int(136)), V(uint64(136))},
4214 {V(uint64(137)), V(uint(137))},
4215 {V(uint(138)), V(uint64(138))},
4216 {V(uint64(139)), V(uintptr(139))},
4217 {V(uintptr(140)), V(uint64(140))},
4218 {V(uint64(141)), V(float32(141))},
4219 {V(float32(142)), V(uint64(142))},
4220 {V(uint64(143)), V(float64(143))},
4221 {V(float64(144)), V(uint64(144))},
4222 {V(int(145)), V(int(145))},
4223 {V(int(146)), V(uint(146))},
4224 {V(uint(147)), V(int(147))},
4225 {V(int(148)), V(uintptr(148))},
4226 {V(uintptr(149)), V(int(149))},
4227 {V(int(150)), V(float32(150))},
4228 {V(float32(151)), V(int(151))},
4229 {V(int(152)), V(float64(152))},
4230 {V(float64(153)), V(int(153))},
4231 {V(uint(154)), V(uint(154))},
4232 {V(uint(155)), V(uintptr(155))},
4233 {V(uintptr(156)), V(uint(156))},
4234 {V(uint(157)), V(float32(157))},
4235 {V(float32(158)), V(uint(158))},
4236 {V(uint(159)), V(float64(159))},
4237 {V(float64(160)), V(uint(160))},
4238 {V(uintptr(161)), V(uintptr(161))},
4239 {V(uintptr(162)), V(float32(162))},
4240 {V(float32(163)), V(uintptr(163))},
4241 {V(uintptr(164)), V(float64(164))},
4242 {V(float64(165)), V(uintptr(165))},
4243 {V(float32(166)), V(float32(166))},
4244 {V(float32(167)), V(float64(167))},
4245 {V(float64(168)), V(float32(168))},
4246 {V(float64(169)), V(float64(169))},
4249 {V(float64(1.5)), V(int(1))},
4252 {V(complex64(1i)), V(complex64(1i))},
4253 {V(complex64(2i)), V(complex128(2i))},
4254 {V(complex128(3i)), V(complex64(3i))},
4255 {V(complex128(4i)), V(complex128(4i))},
4258 {V(string("hello")), V(string("hello"))},
4259 {V(string("bytes1")), V([]byte("bytes1"))},
4260 {V([]byte("bytes2")), V(string("bytes2"))},
4261 {V([]byte("bytes3")), V([]byte("bytes3"))},
4262 {V(string("runes♝")), V([]rune("runes♝"))},
4263 {V([]rune("runes♕")), V(string("runes♕"))},
4264 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4265 {V(int('a')), V(string("a"))},
4266 {V(int8('a')), V(string("a"))},
4267 {V(int16('a')), V(string("a"))},
4268 {V(int32('a')), V(string("a"))},
4269 {V(int64('a')), V(string("a"))},
4270 {V(uint('a')), V(string("a"))},
4271 {V(uint8('a')), V(string("a"))},
4272 {V(uint16('a')), V(string("a"))},
4273 {V(uint32('a')), V(string("a"))},
4274 {V(uint64('a')), V(string("a"))},
4275 {V(uintptr('a')), V(string("a"))},
4276 {V(int(-1)), V(string("\uFFFD"))},
4277 {V(int8(-2)), V(string("\uFFFD"))},
4278 {V(int16(-3)), V(string("\uFFFD"))},
4279 {V(int32(-4)), V(string("\uFFFD"))},
4280 {V(int64(-5)), V(string("\uFFFD"))},
4281 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4282 {V(int64(1 << 32)), V(string("\uFFFD"))},
4283 {V(uint(0x110001)), V(string("\uFFFD"))},
4284 {V(uint32(0x110002)), V(string("\uFFFD"))},
4285 {V(uint64(0x110003)), V(string("\uFFFD"))},
4286 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4287 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4290 {V(MyString("hello")), V(string("hello"))},
4291 {V(string("hello")), V(MyString("hello"))},
4292 {V(string("hello")), V(string("hello"))},
4293 {V(MyString("hello")), V(MyString("hello"))},
4294 {V(MyString("bytes1")), V([]byte("bytes1"))},
4295 {V([]byte("bytes2")), V(MyString("bytes2"))},
4296 {V([]byte("bytes3")), V([]byte("bytes3"))},
4297 {V(MyString("runes♝")), V([]rune("runes♝"))},
4298 {V([]rune("runes♕")), V(MyString("runes♕"))},
4299 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4300 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4301 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4302 {V(int('a')), V(MyString("a"))},
4303 {V(int8('a')), V(MyString("a"))},
4304 {V(int16('a')), V(MyString("a"))},
4305 {V(int32('a')), V(MyString("a"))},
4306 {V(int64('a')), V(MyString("a"))},
4307 {V(uint('a')), V(MyString("a"))},
4308 {V(uint8('a')), V(MyString("a"))},
4309 {V(uint16('a')), V(MyString("a"))},
4310 {V(uint32('a')), V(MyString("a"))},
4311 {V(uint64('a')), V(MyString("a"))},
4312 {V(uintptr('a')), V(MyString("a"))},
4313 {V(int(-1)), V(MyString("\uFFFD"))},
4314 {V(int8(-2)), V(MyString("\uFFFD"))},
4315 {V(int16(-3)), V(MyString("\uFFFD"))},
4316 {V(int32(-4)), V(MyString("\uFFFD"))},
4317 {V(int64(-5)), V(MyString("\uFFFD"))},
4318 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4319 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4320 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4321 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4324 {V(string("bytes1")), V(MyBytes("bytes1"))},
4325 {V(MyBytes("bytes2")), V(string("bytes2"))},
4326 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4327 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4328 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4331 {V(string("runes♝")), V(MyRunes("runes♝"))},
4332 {V(MyRunes("runes♕")), V(string("runes♕"))},
4333 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4334 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4335 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4338 {V([]byte(nil)), V([0]byte{})},
4339 {V([]byte{}), V([0]byte{})},
4340 {V([]byte{1}), V([1]byte{1})},
4341 {V([]byte{1, 2}), V([2]byte{1, 2})},
4342 {V([]byte{1, 2, 3}), V([3]byte{1, 2, 3})},
4343 {V(MyBytes([]byte(nil))), V([0]byte{})},
4344 {V(MyBytes{}), V([0]byte{})},
4345 {V(MyBytes{1}), V([1]byte{1})},
4346 {V(MyBytes{1, 2}), V([2]byte{1, 2})},
4347 {V(MyBytes{1, 2, 3}), V([3]byte{1, 2, 3})},
4348 {V([]byte(nil)), V(MyBytesArray0{})},
4349 {V([]byte{}), V(MyBytesArray0([0]byte{}))},
4350 {V([]byte{1, 2, 3, 4}), V(MyBytesArray([4]byte{1, 2, 3, 4}))},
4351 {V(MyBytes{}), V(MyBytesArray0([0]byte{}))},
4352 {V(MyBytes{5, 6, 7, 8}), V(MyBytesArray([4]byte{5, 6, 7, 8}))},
4353 {V([]MyByte{}), V([0]MyByte{})},
4354 {V([]MyByte{1, 2}), V([2]MyByte{1, 2})},
4356 // slice to array pointer
4357 {V([]byte(nil)), V((*[0]byte)(nil))},
4358 {V([]byte{}), V(new([0]byte))},
4359 {V([]byte{7}), V(&[1]byte{7})},
4360 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4361 {V(MyBytes([]byte{})), V(new([0]byte))},
4362 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4363 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4364 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4365 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4366 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4367 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4369 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4370 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4371 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4372 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4373 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4374 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4375 {V(new([0]byte)), V(new(MyBytesArray0))},
4376 {V(new(MyBytesArray0)), V(new([0]byte))},
4377 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4378 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4380 // named types and equal underlying types
4381 {V(new(int)), V(new(integer))},
4382 {V(new(integer)), V(new(int))},
4383 {V(Empty{}), V(struct{}{})},
4384 {V(new(Empty)), V(new(struct{}))},
4385 {V(struct{}{}), V(Empty{})},
4386 {V(new(struct{})), V(new(Empty))},
4387 {V(Empty{}), V(Empty{})},
4388 {V(MyBytes{}), V([]byte{})},
4389 {V([]byte{}), V(MyBytes{})},
4390 {V((func())(nil)), V(MyFunc(nil))},
4391 {V((MyFunc)(nil)), V((func())(nil))},
4393 // structs with different tags
4406 {V(MyStruct{}), V(struct {
4412 }{}), V(MyStruct{})},
4414 {V(MyStruct{}), V(struct {
4420 }{}), V(MyStruct{})},
4422 {V(MyStruct1{}), V(MyStruct2{})},
4423 {V(MyStruct2{}), V(MyStruct1{})},
4425 // can convert *byte and *MyByte
4426 {V((*byte)(nil)), V((*MyByte)(nil))},
4427 {V((*MyByte)(nil)), V((*byte)(nil))},
4429 // cannot convert mismatched array sizes
4430 {V([2]byte{}), V([2]byte{})},
4431 {V([3]byte{}), V([3]byte{})},
4432 {V(MyBytesArray0{}), V([0]byte{})},
4433 {V([0]byte{}), V(MyBytesArray0{})},
4435 // cannot convert other instances
4436 {V((**byte)(nil)), V((**byte)(nil))},
4437 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4438 {V((chan byte)(nil)), V((chan byte)(nil))},
4439 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4440 {V(([]byte)(nil)), V(([]byte)(nil))},
4441 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4442 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4443 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4444 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4445 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4446 {V([2]byte{}), V([2]byte{})},
4447 {V([2]MyByte{}), V([2]MyByte{})},
4450 {V((***int)(nil)), V((***int)(nil))},
4451 {V((***byte)(nil)), V((***byte)(nil))},
4452 {V((***int32)(nil)), V((***int32)(nil))},
4453 {V((***int64)(nil)), V((***int64)(nil))},
4454 {V((chan byte)(nil)), V((chan byte)(nil))},
4455 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4456 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4457 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4458 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4459 {V([]uint(nil)), V([]uint(nil))},
4460 {V([]int(nil)), V([]int(nil))},
4461 {V(new(any)), V(new(any))},
4462 {V(new(io.Reader)), V(new(io.Reader))},
4463 {V(new(io.Writer)), V(new(io.Writer))},
4466 {V(IntChan(nil)), V((chan<- int)(nil))},
4467 {V(IntChan(nil)), V((<-chan int)(nil))},
4468 {V((chan int)(nil)), V(IntChanRecv(nil))},
4469 {V((chan int)(nil)), V(IntChanSend(nil))},
4470 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4471 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4472 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4473 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4474 {V(IntChan(nil)), V((chan int)(nil))},
4475 {V((chan int)(nil)), V(IntChan(nil))},
4476 {V((chan int)(nil)), V((<-chan int)(nil))},
4477 {V((chan int)(nil)), V((chan<- int)(nil))},
4478 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4479 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4480 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4481 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4482 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4483 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4484 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4485 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4486 {V(BytesChan(nil)), V((chan []byte)(nil))},
4487 {V((chan []byte)(nil)), V(BytesChan(nil))},
4488 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4489 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4491 // cannot convert other instances (channels)
4492 {V(IntChan(nil)), V(IntChan(nil))},
4493 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4494 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4495 {V(BytesChan(nil)), V(BytesChan(nil))},
4496 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4497 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4500 {V(int(1)), EmptyInterfaceV(int(1))},
4501 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4502 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4503 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4504 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4507 func TestConvert(t *testing.T) {
4508 canConvert := map[[2]Type]bool{}
4509 all := map[Type]bool{}
4511 for _, tt := range convertTests {
4513 if !t1.ConvertibleTo(t1) {
4514 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4519 if !t1.ConvertibleTo(t2) {
4520 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4526 canConvert[[2]Type{t1, t2}] = true
4528 // vout1 represents the in value converted to the in type.
4530 if !v1.CanConvert(t1) {
4531 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4533 vout1 := v1.Convert(t1)
4534 out1 := vout1.Interface()
4535 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4536 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4539 // vout2 represents the in value converted to the out type.
4540 if !v1.CanConvert(t2) {
4541 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4543 vout2 := v1.Convert(t2)
4544 out2 := vout2.Interface()
4545 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4546 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4548 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4549 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4552 // vout3 represents a new value of the out type, set to vout2. This makes
4553 // sure the converted value vout2 is really usable as a regular value.
4554 vout3 := New(t2).Elem()
4556 out3 := vout3.Interface()
4557 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4558 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4562 t.Errorf("table entry %v is RO, should not be", v1)
4565 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4568 t.Errorf("conversion output %v is RO, should not be", vout2)
4571 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4573 if !IsRO(MakeRO(v1).Convert(t1)) {
4574 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4576 if !IsRO(MakeRO(v1).Convert(t2)) {
4577 t.Errorf("RO conversion output %v is not RO, should be", v1)
4581 // Assume that of all the types we saw during the tests,
4582 // if there wasn't an explicit entry for a conversion between
4583 // a pair of types, then it's not to be allowed. This checks for
4584 // things like 'int64' converting to '*int'.
4585 for t1 := range all {
4586 for t2 := range all {
4587 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4588 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4589 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4595 func TestConvertPanic(t *testing.T) {
4596 s := make([]byte, 4)
4600 if !v.Type().ConvertibleTo(pt) {
4601 t.Errorf("[]byte should be convertible to *[8]byte")
4603 if v.CanConvert(pt) {
4604 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4606 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4610 if v.CanConvert(pt.Elem()) {
4611 t.Errorf("slice with length 4 should not be convertible to [8]byte")
4613 shouldPanic("reflect: cannot convert slice with length 4 to array with length 8", func() {
4614 _ = v.Convert(pt.Elem())
4618 func TestConvertSlice2Array(t *testing.T) {
4624 // Converting a slice to non-empty array needs to return
4625 // a non-addressable copy of the original memory.
4627 t.Fatalf("convert slice to non-empty array returns a addressable copy array")
4630 ov.Index(i).Set(ValueOf(i + 1))
4633 if v.Index(i).Int() != 0 {
4634 t.Fatalf("slice (%v) mutation visible in converted result (%v)", ov, v)
4639 var gFloat32 float32
4641 const snan uint32 = 0x7f800001
4643 func TestConvertNaNs(t *testing.T) {
4644 // Test to see if a store followed by a load of a signaling NaN
4645 // maintains the signaling bit. (This used to fail on the 387 port.)
4646 gFloat32 = math.Float32frombits(snan)
4647 runtime.Gosched() // make sure we don't optimize the store/load away
4648 if got := math.Float32bits(gFloat32); got != snan {
4649 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4651 // Test reflect's conversion between float32s. See issue 36400.
4652 type myFloat32 float32
4653 x := V(myFloat32(math.Float32frombits(snan)))
4654 y := x.Convert(TypeOf(float32(0)))
4655 z := y.Interface().(float32)
4656 if got := math.Float32bits(z); got != snan {
4657 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4661 type ComparableStruct struct {
4665 type NonComparableStruct struct {
4670 var comparableTests = []struct {
4675 {TypeOf("hello"), true},
4676 {TypeOf(new(byte)), true},
4677 {TypeOf((func())(nil)), false},
4678 {TypeOf([]byte{}), false},
4679 {TypeOf(map[string]int{}), false},
4680 {TypeOf(make(chan int)), true},
4681 {TypeOf(1.5), true},
4682 {TypeOf(false), true},
4684 {TypeOf(ComparableStruct{}), true},
4685 {TypeOf(NonComparableStruct{}), false},
4686 {TypeOf([10]map[string]int{}), false},
4687 {TypeOf([10]string{}), true},
4688 {TypeOf(new(any)).Elem(), true},
4691 func TestComparable(t *testing.T) {
4692 for _, tt := range comparableTests {
4693 if ok := tt.typ.Comparable(); ok != tt.ok {
4694 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4699 func TestOverflow(t *testing.T) {
4700 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4701 t.Errorf("%v wrongly overflows float64", 1e300)
4704 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4705 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4706 t.Errorf("%v wrongly overflows float32", maxFloat32)
4708 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4709 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4710 t.Errorf("%v should overflow float32", ovfFloat32)
4712 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4713 t.Errorf("%v should overflow float32", -ovfFloat32)
4716 maxInt32 := int64(0x7fffffff)
4717 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4718 t.Errorf("%v wrongly overflows int32", maxInt32)
4720 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4721 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4723 ovfInt32 := int64(1 << 31)
4724 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4725 t.Errorf("%v should overflow int32", ovfInt32)
4728 maxUint32 := uint64(0xffffffff)
4729 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4730 t.Errorf("%v wrongly overflows uint32", maxUint32)
4732 ovfUint32 := uint64(1 << 32)
4733 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4734 t.Errorf("%v should overflow uint32", ovfUint32)
4738 func checkSameType(t *testing.T, x Type, y any) {
4739 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4740 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4744 func TestArrayOf(t *testing.T) {
4745 // check construction and use of type not in binary
4748 value func(i int) any
4754 value: func(i int) any { type Tint int; return Tint(i) },
4760 value: func(i int) any { type Tint int; return Tint(i) },
4762 want: "[0 1 2 3 4 5 6 7 8 9]",
4766 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4768 want: "[0 1 2 3 4 5 6 7 8 9]",
4772 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4774 want: "[0 1 2 3 4 5 6 7 8 9]",
4778 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4780 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4784 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4786 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4790 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4792 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4796 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4798 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4802 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4804 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4808 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4810 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4814 value: func(i int) any {
4815 type TstructUV struct {
4819 return TstructUV{i, float64(i)}
4822 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4826 for _, table := range tests {
4827 at := ArrayOf(table.n, TypeOf(table.value(0)))
4829 vok := New(at).Elem()
4830 vnot := New(at).Elem()
4831 for i := 0; i < v.Len(); i++ {
4832 v.Index(i).Set(ValueOf(table.value(i)))
4833 vok.Index(i).Set(ValueOf(table.value(i)))
4838 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4840 s := fmt.Sprint(v.Interface())
4841 if s != table.want {
4842 t.Errorf("constructed array = %s, want %s", s, table.want)
4845 if table.comparable != at.Comparable() {
4846 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4848 if table.comparable {
4850 if DeepEqual(vnot.Interface(), v.Interface()) {
4852 "arrays (%#v) compare ok (but should not)",
4857 if !DeepEqual(vok.Interface(), v.Interface()) {
4859 "arrays (%#v) compare NOT-ok (but should)",
4866 // check that type already in binary is found
4868 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4871 func TestArrayOfGC(t *testing.T) {
4873 tt := TypeOf(T(nil))
4876 for i := 0; i < n; i++ {
4877 v := New(ArrayOf(n, tt)).Elem()
4878 for j := 0; j < v.Len(); j++ {
4880 *p = uintptr(i*n + j)
4881 v.Index(j).Set(ValueOf(p).Convert(tt))
4883 x = append(x, v.Interface())
4887 for i, xi := range x {
4889 for j := 0; j < v.Len(); j++ {
4890 k := v.Index(j).Elem().Interface()
4891 if k != uintptr(i*n+j) {
4892 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4898 func TestArrayOfAlg(t *testing.T) {
4899 at := ArrayOf(6, TypeOf(byte(0)))
4900 v1 := New(at).Elem()
4901 v2 := New(at).Elem()
4902 if v1.Interface() != v1.Interface() {
4903 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4905 v1.Index(5).Set(ValueOf(byte(1)))
4906 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4907 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4910 at = ArrayOf(6, TypeOf([]int(nil)))
4912 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4915 func TestArrayOfGenericAlg(t *testing.T) {
4916 at1 := ArrayOf(5, TypeOf(string("")))
4917 at := ArrayOf(6, at1)
4918 v1 := New(at).Elem()
4919 v2 := New(at).Elem()
4920 if v1.Interface() != v1.Interface() {
4921 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4924 v1.Index(0).Index(0).Set(ValueOf("abc"))
4925 v2.Index(0).Index(0).Set(ValueOf("efg"))
4926 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4927 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4930 v1.Index(0).Index(0).Set(ValueOf("abc"))
4931 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4932 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4933 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4937 m := MakeMap(MapOf(at, TypeOf(int(0))))
4938 m.SetMapIndex(v1, ValueOf(1))
4939 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4940 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4944 func TestArrayOfDirectIface(t *testing.T) {
4947 i1 := Zero(TypeOf(T{})).Interface()
4948 v1 := ValueOf(&i1).Elem()
4949 p1 := v1.InterfaceData()[1]
4951 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
4952 v2 := ValueOf(&i2).Elem()
4953 p2 := v2.InterfaceData()[1]
4956 t.Errorf("got p1=%v. want=%v", p1, nil)
4960 t.Errorf("got p2=%v. want=%v", p2, nil)
4965 i1 := Zero(TypeOf(T{})).Interface()
4966 v1 := ValueOf(&i1).Elem()
4967 p1 := v1.InterfaceData()[1]
4969 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
4970 v2 := ValueOf(&i2).Elem()
4971 p2 := v2.InterfaceData()[1]
4974 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4978 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4983 // Ensure passing in negative lengths panics.
4984 // See https://golang.org/issue/43603
4985 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4986 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4987 ArrayOf(-1, TypeOf(byte(0)))
4991 func TestSliceOf(t *testing.T) {
4992 // check construction and use of type not in binary
4994 st := SliceOf(TypeOf(T(1)))
4995 if got, want := st.String(), "[]reflect_test.T"; got != want {
4996 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4998 v := MakeSlice(st, 10, 10)
5000 for i := 0; i < v.Len(); i++ {
5001 v.Index(i).Set(ValueOf(T(i)))
5004 s := fmt.Sprint(v.Interface())
5005 want := "[0 1 2 3 4 5 6 7 8 9]"
5007 t.Errorf("constructed slice = %s, want %s", s, want)
5010 // check that type already in binary is found
5012 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
5015 func TestSliceOverflow(t *testing.T) {
5016 // check that MakeSlice panics when size of slice overflows uint
5019 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5021 t.Fatal("slice size does not overflow")
5024 st := SliceOf(TypeOf(x))
5028 t.Fatal("slice overflow does not panic")
5031 MakeSlice(st, int(l), int(l))
5034 func TestSliceOfGC(t *testing.T) {
5036 tt := TypeOf(T(nil))
5040 for i := 0; i < n; i++ {
5041 v := MakeSlice(st, n, n)
5042 for j := 0; j < v.Len(); j++ {
5044 *p = uintptr(i*n + j)
5045 v.Index(j).Set(ValueOf(p).Convert(tt))
5047 x = append(x, v.Interface())
5051 for i, xi := range x {
5053 for j := 0; j < v.Len(); j++ {
5054 k := v.Index(j).Elem().Interface()
5055 if k != uintptr(i*n+j) {
5056 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5062 func TestStructOfFieldName(t *testing.T) {
5063 // invalid field name "1nvalid"
5064 shouldPanic("has invalid name", func() {
5065 StructOf([]StructField{
5066 {Name: "Valid", Type: TypeOf("")},
5067 {Name: "1nvalid", Type: TypeOf("")},
5071 // invalid field name "+"
5072 shouldPanic("has invalid name", func() {
5073 StructOf([]StructField{
5074 {Name: "Val1d", Type: TypeOf("")},
5075 {Name: "+", Type: TypeOf("")},
5080 shouldPanic("has no name", func() {
5081 StructOf([]StructField{
5082 {Name: "", Type: TypeOf("")},
5086 // verify creation of a struct with valid struct fields
5087 validFields := []StructField{
5102 validStruct := StructOf(validFields)
5104 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5105 if got, want := validStruct.String(), structStr; got != want {
5106 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5110 func TestStructOf(t *testing.T) {
5111 // check construction and use of type not in binary
5112 fields := []StructField{
5121 Type: TypeOf(byte(0)),
5125 Type: TypeOf(uint64(0)),
5129 Type: TypeOf([3]uint16{}),
5133 st := StructOf(fields)
5136 v.FieldByName("X").Set(ValueOf(byte(2)))
5137 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5140 s := fmt.Sprint(v.Interface())
5141 want := `{ 1 0 [0 0 0]}`
5143 t.Errorf("constructed struct = %s, want %s", s, want)
5145 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5146 if got, want := st.String(), stStr; got != want {
5147 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5150 // check the size, alignment and field offsets
5151 stt := TypeOf(struct {
5157 if st.Size() != stt.Size() {
5158 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5160 if st.Align() != stt.Align() {
5161 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5163 if st.FieldAlign() != stt.FieldAlign() {
5164 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5166 for i := 0; i < st.NumField(); i++ {
5167 o1 := st.Field(i).Offset
5168 o2 := stt.Field(i).Offset
5170 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5174 // Check size and alignment with a trailing zero-sized field.
5175 st = StructOf([]StructField{
5178 Type: TypeOf(byte(0)),
5182 Type: TypeOf([0]*byte{}),
5185 stt = TypeOf(struct {
5189 if st.Size() != stt.Size() {
5190 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5192 if st.Align() != stt.Align() {
5193 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5195 if st.FieldAlign() != stt.FieldAlign() {
5196 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5198 for i := 0; i < st.NumField(); i++ {
5199 o1 := st.Field(i).Offset
5200 o2 := stt.Field(i).Offset
5202 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5206 // check duplicate names
5207 shouldPanic("duplicate field", func() {
5208 StructOf([]StructField{
5209 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5210 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5213 shouldPanic("has no name", func() {
5214 StructOf([]StructField{
5216 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5219 shouldPanic("has no name", func() {
5220 StructOf([]StructField{
5225 // check that type already in binary is found
5226 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5228 // gccgo used to fail this test.
5229 type structFieldType any
5231 StructOf([]StructField{
5234 Type: TypeOf((*structFieldType)(nil)).Elem(),
5237 struct{ F structFieldType }{})
5240 func TestStructOfExportRules(t *testing.T) {
5246 testPanic := func(i int, mustPanic bool, f func()) {
5249 if err == nil && mustPanic {
5250 t.Errorf("test-%d did not panic", i)
5252 if err != nil && !mustPanic {
5253 t.Errorf("test-%d panicked: %v\n", i, err)
5265 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5269 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5273 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5277 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5281 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5285 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5289 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5293 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5297 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5301 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5305 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5308 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5311 field: StructField{Name: "S", Type: TypeOf(S1{})},
5315 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5319 field: StructField{Name: "S", Type: TypeOf(s2{})},
5323 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5327 field: StructField{Name: "s", Type: TypeOf(S1{})},
5331 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5335 field: StructField{Name: "s", Type: TypeOf(s2{})},
5339 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5343 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5346 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5349 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5352 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5355 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5359 field: StructField{Name: "", Type: TypeOf(φType{})},
5363 field: StructField{Name: "Φ", Type: TypeOf(0)},
5367 field: StructField{Name: "φ", Type: TypeOf(0)},
5372 for i, test := range tests {
5373 testPanic(i, test.mustPanic, func() {
5374 typ := StructOf([]StructField{test.field})
5376 t.Errorf("test-%d: error creating struct type", i)
5379 field := typ.Field(0)
5382 panic("field.Name must not be empty")
5384 exported := token.IsExported(n)
5385 if exported != test.exported {
5386 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5388 if field.PkgPath != test.field.PkgPath {
5389 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5395 func TestStructOfGC(t *testing.T) {
5397 tt := TypeOf(T(nil))
5398 fields := []StructField{
5399 {Name: "X", Type: tt},
5400 {Name: "Y", Type: tt},
5402 st := StructOf(fields)
5406 for i := 0; i < n; i++ {
5408 for j := 0; j < v.NumField(); j++ {
5410 *p = uintptr(i*n + j)
5411 v.Field(j).Set(ValueOf(p).Convert(tt))
5413 x = append(x, v.Interface())
5417 for i, xi := range x {
5419 for j := 0; j < v.NumField(); j++ {
5420 k := v.Field(j).Elem().Interface()
5421 if k != uintptr(i*n+j) {
5422 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5428 func TestStructOfAlg(t *testing.T) {
5429 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5430 v1 := New(st).Elem()
5431 v2 := New(st).Elem()
5432 if !DeepEqual(v1.Interface(), v1.Interface()) {
5433 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5435 v1.FieldByName("X").Set(ValueOf(int(1)))
5436 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5437 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5440 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5442 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5445 func TestStructOfGenericAlg(t *testing.T) {
5446 st1 := StructOf([]StructField{
5447 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5448 {Name: "Y", Type: TypeOf(string(""))},
5450 st := StructOf([]StructField{
5451 {Name: "S0", Type: st1},
5452 {Name: "S1", Type: st1},
5470 {Name: "XX", Type: TypeOf([0]int{})},
5471 {Name: "YY", Type: TypeOf("")},
5479 {Name: "XX", Type: TypeOf([0]int{})},
5480 {Name: "YY", Type: TypeOf("")},
5481 {Name: "ZZ", Type: TypeOf([2]int{})},
5489 {Name: "XX", Type: TypeOf([1]int{})},
5490 {Name: "YY", Type: TypeOf("")},
5498 {Name: "XX", Type: TypeOf([1]int{})},
5499 {Name: "YY", Type: TypeOf("")},
5500 {Name: "ZZ", Type: TypeOf([1]int{})},
5508 {Name: "XX", Type: TypeOf([2]int{})},
5509 {Name: "YY", Type: TypeOf("")},
5510 {Name: "ZZ", Type: TypeOf([2]int{})},
5518 {Name: "XX", Type: TypeOf(int64(0))},
5519 {Name: "YY", Type: TypeOf(byte(0))},
5520 {Name: "ZZ", Type: TypeOf("")},
5528 {Name: "XX", Type: TypeOf(int64(0))},
5529 {Name: "YY", Type: TypeOf(int64(0))},
5530 {Name: "ZZ", Type: TypeOf("")},
5531 {Name: "AA", Type: TypeOf([1]int64{})},
5538 for _, table := range tests {
5539 v1 := New(table.rt).Elem()
5540 v2 := New(table.rt).Elem()
5542 if !DeepEqual(v1.Interface(), v1.Interface()) {
5543 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5546 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5547 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5548 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5549 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5553 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5554 val := "+" + abc + "-"
5555 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5556 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5557 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5561 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5562 m.SetMapIndex(v1, ValueOf(1))
5563 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5564 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5567 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5568 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5569 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5572 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5573 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5578 func TestStructOfDirectIface(t *testing.T) {
5580 type T struct{ X [1]*byte }
5581 i1 := Zero(TypeOf(T{})).Interface()
5582 v1 := ValueOf(&i1).Elem()
5583 p1 := v1.InterfaceData()[1]
5585 i2 := Zero(StructOf([]StructField{
5588 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5591 v2 := ValueOf(&i2).Elem()
5592 p2 := v2.InterfaceData()[1]
5595 t.Errorf("got p1=%v. want=%v", p1, nil)
5599 t.Errorf("got p2=%v. want=%v", p2, nil)
5603 type T struct{ X [0]*byte }
5604 i1 := Zero(TypeOf(T{})).Interface()
5605 v1 := ValueOf(&i1).Elem()
5606 p1 := v1.InterfaceData()[1]
5608 i2 := Zero(StructOf([]StructField{
5611 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5614 v2 := ValueOf(&i2).Elem()
5615 p2 := v2.InterfaceData()[1]
5618 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5622 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5629 func (i StructI) Get() int { return int(i) }
5633 func (i *StructIPtr) Get() int { return int(*i) }
5634 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5636 type SettableStruct struct {
5640 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5642 type SettablePointer struct {
5646 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5648 func TestStructOfWithInterface(t *testing.T) {
5650 type Iface interface {
5653 type IfaceSet interface {
5664 typ: TypeOf(StructI(want)),
5665 val: ValueOf(StructI(want)),
5670 typ: PointerTo(TypeOf(StructI(want))),
5671 val: ValueOf(func() any {
5679 typ: PointerTo(TypeOf(StructIPtr(want))),
5680 val: ValueOf(func() any {
5681 v := StructIPtr(want)
5688 typ: TypeOf(StructIPtr(want)),
5689 val: ValueOf(StructIPtr(want)),
5693 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5694 // val: ValueOf(StructI(want)),
5699 for i, table := range tests {
5700 for j := 0; j < 2; j++ {
5701 var fields []StructField
5703 fields = append(fields, StructField{
5706 Type: TypeOf(int(0)),
5709 fields = append(fields, StructField{
5716 // We currently do not correctly implement methods
5717 // for embedded fields other than the first.
5718 // Therefore, for now, we expect those methods
5719 // to not exist. See issues 15924 and 20824.
5720 // When those issues are fixed, this test of panic
5721 // should be removed.
5722 if j == 1 && table.impl {
5725 if err := recover(); err == nil {
5726 t.Errorf("test-%d-%d did not panic", i, j)
5729 _ = StructOf(fields)
5734 rt := StructOf(fields)
5735 rv := New(rt).Elem()
5736 rv.Field(j).Set(table.val)
5738 if _, ok := rv.Interface().(Iface); ok != table.impl {
5740 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5742 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5751 v := rv.Interface().(Iface).Get()
5753 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5756 fct := rv.MethodByName("Get")
5757 out := fct.Call(nil)
5758 if !DeepEqual(out[0].Interface(), want) {
5759 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5764 // Test an embedded nil pointer with pointer methods.
5765 fields := []StructField{{
5768 Type: PointerTo(TypeOf(StructIPtr(want))),
5770 rt := StructOf(fields)
5771 rv := New(rt).Elem()
5772 // This should panic since the pointer is nil.
5773 shouldPanic("", func() {
5774 rv.Interface().(IfaceSet).Set(want)
5777 // Test an embedded nil pointer to a struct with pointer methods.
5779 fields = []StructField{{
5780 Name: "SettableStruct",
5782 Type: PointerTo(TypeOf(SettableStruct{})),
5784 rt = StructOf(fields)
5786 // This should panic since the pointer is nil.
5787 shouldPanic("", func() {
5788 rv.Interface().(IfaceSet).Set(want)
5791 // The behavior is different if there is a second field,
5792 // since now an interface value holds a pointer to the struct
5793 // rather than just holding a copy of the struct.
5794 fields = []StructField{
5796 Name: "SettableStruct",
5798 Type: PointerTo(TypeOf(SettableStruct{})),
5801 Name: "EmptyStruct",
5803 Type: StructOf(nil),
5806 // With the current implementation this is expected to panic.
5807 // Ideally it should work and we should be able to see a panic
5808 // if we call the Set method.
5809 shouldPanic("", func() {
5813 // Embed a field that can be stored directly in an interface,
5814 // with a second field.
5815 fields = []StructField{
5817 Name: "SettablePointer",
5819 Type: TypeOf(SettablePointer{}),
5822 Name: "EmptyStruct",
5824 Type: StructOf(nil),
5827 // With the current implementation this is expected to panic.
5828 // Ideally it should work and we should be able to call the
5829 // Set and Get methods.
5830 shouldPanic("", func() {
5835 func TestStructOfTooManyFields(t *testing.T) {
5836 // Bug Fix: #25402 - this should not panic
5837 tt := StructOf([]StructField{
5838 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5841 if _, present := tt.MethodByName("After"); !present {
5842 t.Errorf("Expected method `After` to be found")
5846 func TestStructOfDifferentPkgPath(t *testing.T) {
5847 fields := []StructField{
5851 Type: TypeOf(int(0)),
5856 Type: TypeOf(int(0)),
5859 shouldPanic("different PkgPath", func() {
5864 func TestStructOfTooLarge(t *testing.T) {
5865 t1 := TypeOf(byte(0))
5866 t2 := TypeOf(int16(0))
5867 t4 := TypeOf(int32(0))
5868 t0 := ArrayOf(0, t1)
5870 // 2^64-3 sized type (or 2^32-3 on 32-bit archs)
5871 bigType := StructOf([]StructField{
5872 {Name: "F1", Type: ArrayOf(int(^uintptr(0)>>1), t1)},
5873 {Name: "F2", Type: ArrayOf(int(^uintptr(0)>>1-1), t1)},
5878 fields []StructField
5883 shouldPanic: false, // 2^64-1, ok
5884 fields: []StructField{
5885 {Name: "F1", Type: bigType},
5886 {Name: "F2", Type: ArrayOf(2, t1)},
5890 shouldPanic: true, // overflow in total size
5891 fields: []StructField{
5892 {Name: "F1", Type: bigType},
5893 {Name: "F2", Type: ArrayOf(3, t1)},
5897 shouldPanic: true, // overflow while aligning F2
5898 fields: []StructField{
5899 {Name: "F1", Type: bigType},
5900 {Name: "F2", Type: t4},
5904 shouldPanic: true, // overflow while adding trailing byte for zero-sized fields
5905 fields: []StructField{
5906 {Name: "F1", Type: bigType},
5907 {Name: "F2", Type: ArrayOf(2, t1)},
5908 {Name: "F3", Type: t0},
5912 shouldPanic: true, // overflow while aligning total size
5913 fields: []StructField{
5914 {Name: "F1", Type: t2},
5915 {Name: "F2", Type: bigType},
5920 for i, tt := range tests {
5924 if !tt.shouldPanic {
5926 t.Errorf("test %d should not panic, got %s", i, err)
5931 t.Errorf("test %d expected to panic", i)
5934 s := fmt.Sprintf("%s", err)
5935 if s != "reflect.StructOf: struct size would exceed virtual address space" {
5936 t.Errorf("test %d wrong panic message: %s", i, s)
5940 _ = StructOf(tt.fields)
5945 func TestChanOf(t *testing.T) {
5946 // check construction and use of type not in binary
5948 ct := ChanOf(BothDir, TypeOf(T("")))
5949 v := MakeChan(ct, 2)
5951 v.Send(ValueOf(T("hello")))
5953 v.Send(ValueOf(T("world")))
5960 if s1 != "hello" || s2 != "world" {
5961 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5964 // check that type already in binary is found
5966 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5968 // Check arrow token association in undefined chan types.
5969 var left chan<- chan T
5970 var right chan (<-chan T)
5971 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5972 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5973 if tLeft != TypeOf(left) {
5974 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5976 if tRight != TypeOf(right) {
5977 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5981 func TestChanOfDir(t *testing.T) {
5982 // check construction and use of type not in binary
5984 crt := ChanOf(RecvDir, TypeOf(T("")))
5985 cst := ChanOf(SendDir, TypeOf(T("")))
5987 // check that type already in binary is found
5989 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5990 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5992 // check String form of ChanDir
5993 if crt.ChanDir().String() != "<-chan" {
5994 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5996 if cst.ChanDir().String() != "chan<-" {
5997 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
6001 func TestChanOfGC(t *testing.T) {
6002 done := make(chan bool, 1)
6006 case <-time.After(5 * time.Second):
6007 panic("deadlock in TestChanOfGC")
6016 tt := TypeOf(T(nil))
6017 ct := ChanOf(BothDir, tt)
6019 // NOTE: The garbage collector handles allocated channels specially,
6020 // so we have to save pointers to channels in x; the pointer code will
6021 // use the gc info in the newly constructed chan type.
6024 for i := 0; i < n; i++ {
6025 v := MakeChan(ct, n)
6026 for j := 0; j < n; j++ {
6028 *p = uintptr(i*n + j)
6029 v.Send(ValueOf(p).Convert(tt))
6033 x = append(x, pv.Interface())
6037 for i, xi := range x {
6038 v := ValueOf(xi).Elem()
6039 for j := 0; j < n; j++ {
6041 k := pv.Elem().Interface()
6042 if k != uintptr(i*n+j) {
6043 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6049 func TestMapOf(t *testing.T) {
6050 // check construction and use of type not in binary
6054 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
6056 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
6059 s := fmt.Sprint(v.Interface())
6062 t.Errorf("constructed map = %s, want %s", s, want)
6065 // check that type already in binary is found
6066 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
6068 // check that invalid key type panics
6069 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
6072 func TestMapOfGCKeys(t *testing.T) {
6074 tt := TypeOf(T(nil))
6075 mt := MapOf(tt, TypeOf(false))
6077 // NOTE: The garbage collector handles allocated maps specially,
6078 // so we have to save pointers to maps in x; the pointer code will
6079 // use the gc info in the newly constructed map type.
6082 for i := 0; i < n; i++ {
6084 for j := 0; j < n; j++ {
6086 *p = uintptr(i*n + j)
6087 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
6091 x = append(x, pv.Interface())
6095 for i, xi := range x {
6096 v := ValueOf(xi).Elem()
6098 for _, kv := range v.MapKeys() {
6099 out = append(out, int(kv.Elem().Interface().(uintptr)))
6102 for j, k := range out {
6104 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6110 func TestMapOfGCValues(t *testing.T) {
6112 tt := TypeOf(T(nil))
6113 mt := MapOf(TypeOf(1), tt)
6115 // NOTE: The garbage collector handles allocated maps specially,
6116 // so we have to save pointers to maps in x; the pointer code will
6117 // use the gc info in the newly constructed map type.
6120 for i := 0; i < n; i++ {
6122 for j := 0; j < n; j++ {
6124 *p = uintptr(i*n + j)
6125 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6129 x = append(x, pv.Interface())
6133 for i, xi := range x {
6134 v := ValueOf(xi).Elem()
6135 for j := 0; j < n; j++ {
6136 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6137 if k != uintptr(i*n+j) {
6138 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6144 func TestTypelinksSorted(t *testing.T) {
6146 for i, n := range TypeLinks() {
6148 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6154 func TestFuncOf(t *testing.T) {
6155 // check construction and use of type not in binary
6159 fn := func(args []Value) []Value {
6161 t.Errorf("args == %v, want exactly one arg", args)
6162 } else if args[0].Type() != TypeOf(K("")) {
6163 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6164 } else if args[0].String() != "gopher" {
6165 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6167 return []Value{ValueOf(V(3.14))}
6169 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6171 outs := v.Call([]Value{ValueOf(K("gopher"))})
6173 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6174 } else if outs[0].Type() != TypeOf(V(0)) {
6175 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6177 f := outs[0].Float()
6179 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6182 // check that types already in binary are found
6184 testCases := []struct {
6189 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6190 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6191 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6192 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6193 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6195 for _, tt := range testCases {
6196 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6199 // check that variadic requires last element be a slice.
6200 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6201 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6202 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6204 //testcase for #54669
6206 for i := 0; i < 51; i++ {
6207 in = append(in, TypeOf(1))
6209 FuncOf(in, nil, false)
6282 func TestEmbed(t *testing.T) {
6284 f, ok := typ.FieldByName("X")
6286 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6290 func TestAllocsInterfaceBig(t *testing.T) {
6291 if testing.Short() {
6292 t.Skip("skipping malloc count in short mode")
6295 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6296 t.Error("allocs:", allocs)
6300 func TestAllocsInterfaceSmall(t *testing.T) {
6301 if testing.Short() {
6302 t.Skip("skipping malloc count in short mode")
6304 v := ValueOf(int64(0))
6305 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6306 t.Error("allocs:", allocs)
6310 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6311 // The basic usage is:
6314 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6317 // Each iteration of the loop returns a different set of results, until all
6318 // possible result sets have been explored. It is okay for different code paths
6319 // to make different method call sequences on x, but there must be no
6320 // other source of non-determinism in the call sequences.
6322 // When faced with a new decision, x chooses randomly. Future explorations
6323 // of that path will choose successive values for the result. Thus, stopping
6324 // the loop after a fixed number of iterations gives somewhat stochastic
6330 // v := make([]bool, x.Choose(4))
6331 // for i := range v {
6337 // prints (in some order):
6346 // [false false false]
6349 // [false false false false]
6351 // [true true true true]
6352 type exhaustive struct {
6358 type choice struct {
6364 func (x *exhaustive) Next() bool {
6366 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6373 for i := len(x.last) - 1; i >= 0; i-- {
6377 x.last = x.last[:i+1]
6384 func (x *exhaustive) Choose(max int) int {
6385 if x.pos >= len(x.last) {
6386 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6391 panic("inconsistent use of exhaustive tester")
6393 return (c.n + c.off) % max
6396 func (x *exhaustive) Maybe() bool {
6397 return x.Choose(2) == 1
6400 func GCFunc(args []Value) []Value {
6405 func TestReflectFuncTraceback(t *testing.T) {
6406 f := MakeFunc(TypeOf(func() {}), GCFunc)
6410 func TestReflectMethodTraceback(t *testing.T) {
6412 m := ValueOf(p).MethodByName("GCMethod")
6413 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6415 t.Errorf("Call returned %d; want 8", i)
6419 func TestSmallZero(t *testing.T) {
6422 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6423 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6427 func TestBigZero(t *testing.T) {
6428 const size = 1 << 10
6430 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6431 for i := 0; i < size; i++ {
6433 t.Fatalf("Zero object not all zero, index %d", i)
6438 func TestZeroSet(t *testing.T) {
6446 a: 0xaaaaaaaaaaaaaaaa,
6447 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6448 b: 0xbbbbbbbbbbbbbbbb,
6450 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6452 a: 0xaaaaaaaaaaaaaaaa,
6453 b: 0xbbbbbbbbbbbbbbbb,
6455 t.Fatalf("Setting a field to a Zero value didn't work")
6459 func TestFieldByIndexNil(t *testing.T) {
6468 v.FieldByName("P") // should be fine
6471 if err := recover(); err == nil {
6472 t.Fatalf("no error")
6473 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6474 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6477 v.FieldByName("F") // should panic
6479 t.Fatalf("did not panic")
6483 // type Outer struct {
6487 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6488 // The implementation is logically:
6489 // func (p *Outer) M() {
6492 // but since the only change here is the replacement of one pointer receiver with another,
6493 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6494 // then jumps to the M method expecting the *Inner receiver.
6496 // During reflect.Value.Call, we create an argument frame and the associated data structures
6497 // to describe it to the garbage collector, populate the frame, call reflect.call to
6498 // run a function call using that frame, and then copy the results back out of the frame.
6499 // The reflect.call function does a memmove of the frame structure onto the
6500 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6501 // the frame structure (to preserve the outputs).
6503 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6504 // were for the full stack frame. However, in the case where the called function was
6505 // one of these wrappers, the rewritten receiver is almost certainly a different type
6506 // than the original receiver. This is not a problem on the stack, where we use the
6507 // program counter to determine the type information and understand that
6508 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6509 // memory word is now an *Inner. But in the statically typed argument frame created
6510 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6511 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6512 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6513 // memory as if it were an *Outer. If the two have different memory layouts, the
6514 // collection will interpret the memory incorrectly.
6516 // One such possible incorrect interpretation is to treat two arbitrary memory words
6517 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6518 // an interface requires dereferencing the itab word, the misinterpretation will try to
6519 // deference Inner.P1, causing a crash during garbage collection.
6521 // This came up in a real program in issue 7725.
6534 func (pi *Inner) M() {
6535 // Clear references to pi so that the only way the
6536 // garbage collection will find the pointer is in the
6537 // argument frame, typed as a *Outer.
6540 // Set up an interface value that will cause a crash.
6541 // P1 = 1 is a non-zero, so the interface looks non-nil.
6542 // P2 = pi ensures that the data word points into the
6543 // allocated heap; if not the collection skips the interface
6544 // value as irrelevant, without dereferencing P1.
6546 pi.P2 = uintptr(unsafe.Pointer(pi))
6549 func TestCallMethodJump(t *testing.T) {
6550 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6551 // returns but before the args frame has been discarded.
6552 // This is a little clumsy but makes the failure repeatable.
6555 p := &Outer{Inner: new(Inner)}
6557 ValueOf(p).Method(0).Call(nil)
6559 // Stop garbage collecting during reflect.call.
6563 func TestCallArgLive(t *testing.T) {
6564 type T struct{ X, Y *string } // pointerful aggregate
6566 F := func(t T) { *t.X = "ok" }
6568 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6569 // between marshaling argument and the actual call.
6573 runtime.SetFinalizer(x, func(p *string) {
6575 t.Errorf("x dead prematurely")
6580 ValueOf(F).Call([]Value{ValueOf(v)})
6582 // Stop garbage collecting during reflect.call.
6586 func TestMakeFuncStackCopy(t *testing.T) {
6587 target := func(in []Value) []Value {
6590 return []Value{ValueOf(9)}
6593 var concrete func(*int, int) int
6594 fn := MakeFunc(ValueOf(concrete).Type(), target)
6595 ValueOf(&concrete).Elem().Set(fn)
6596 x := concrete(nil, 7)
6598 t.Errorf("have %#q want 9", x)
6602 // use about n KB of stack
6603 func useStack(n int) {
6607 var b [1024]byte // makes frame about 1KB
6608 useStack(n - 1 + int(b[99]))
6615 func TestValueString(t *testing.T) {
6616 rv := ValueOf(Impl{})
6617 if rv.String() != "<reflect_test.Impl Value>" {
6618 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6621 method := rv.Method(0)
6622 if method.String() != "<func() Value>" {
6623 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6627 func TestInvalid(t *testing.T) {
6628 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6629 type T struct{ v any }
6631 v := ValueOf(T{}).Field(0)
6632 if v.IsValid() != true || v.Kind() != Interface {
6633 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6636 if v.IsValid() != false || v.Kind() != Invalid {
6637 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6642 func TestLargeGCProg(t *testing.T) {
6643 fv := ValueOf(func([256]*byte) {})
6644 fv.Call([]Value{ValueOf([256]*byte{})})
6647 func fieldIndexRecover(t Type, i int) (recovered any) {
6649 recovered = recover()
6657 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6658 typ := TypeOf(struct{ X int }{10})
6659 testIndices := [...]struct {
6668 for i, tt := range testIndices {
6669 recoveredErr := fieldIndexRecover(typ, tt.i)
6671 if recoveredErr == nil {
6672 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6675 if recoveredErr != nil {
6676 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6683 func TestCallGC(t *testing.T) {
6684 f := func(a, b, c, d, e string) {
6686 g := func(in []Value) []Value {
6690 typ := ValueOf(f).Type()
6691 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6692 f2("four", "five5", "six666", "seven77", "eight888")
6695 // Issue 18635 (function version).
6696 func TestKeepFuncLive(t *testing.T) {
6697 // Test that we keep makeFuncImpl live as long as it is
6698 // referenced on the stack.
6699 typ := TypeOf(func(i int) {})
6700 var f, g func(in []Value) []Value
6701 f = func(in []Value) []Value {
6703 i := int(in[0].Int())
6705 // We can't use Value.Call here because
6706 // runtime.call* will keep the makeFuncImpl
6707 // alive. However, by converting it to an
6708 // interface value and calling that,
6709 // reflect.callReflect is the only thing that
6710 // can keep the makeFuncImpl live.
6712 // Alternate between f and g so that if we do
6713 // reuse the memory prematurely it's more
6714 // likely to get obviously corrupted.
6715 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6719 g = func(in []Value) []Value {
6721 i := int(in[0].Int())
6722 MakeFunc(typ, f).Interface().(func(i int))(i)
6725 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6728 type UnExportedFirst int
6730 func (i UnExportedFirst) ΦExported() {}
6731 func (i UnExportedFirst) unexported() {}
6734 func TestMethodByNameUnExportedFirst(t *testing.T) {
6736 if recover() != nil {
6737 t.Errorf("should not panic")
6740 typ := TypeOf(UnExportedFirst(0))
6741 m, _ := typ.MethodByName("ΦExported")
6742 if m.Name != "ΦExported" {
6743 t.Errorf("got %s, expected ΦExported", m.Name)
6747 // Issue 18635 (method version).
6748 type KeepMethodLive struct{}
6750 func (k KeepMethodLive) Method1(i int) {
6753 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6757 func (k KeepMethodLive) Method2(i int) {
6759 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6762 func TestKeepMethodLive(t *testing.T) {
6763 // Test that we keep methodValue live as long as it is
6764 // referenced on the stack.
6765 KeepMethodLive{}.Method1(10)
6768 // clobber tries to clobber unreachable memory.
6771 for i := 1; i < 32; i++ {
6772 for j := 0; j < 10; j++ {
6773 obj := make([]*byte, i)
6780 func TestFuncLayout(t *testing.T) {
6781 align := func(x uintptr) uintptr {
6782 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6785 if goarch.PtrSize == 4 {
6786 r = []byte{0, 0, 0, 1}
6798 size, argsize, retOffset uintptr
6799 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6800 intRegs, floatRegs int
6801 floatRegSize uintptr
6805 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6806 size: 6 * goarch.PtrSize,
6807 argsize: 4 * goarch.PtrSize,
6808 retOffset: 4 * goarch.PtrSize,
6809 stack: []byte{1, 0, 1, 0, 1},
6810 gc: []byte{1, 0, 1, 0, 1},
6813 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6814 size: align(align(3*4) + goarch.PtrSize + 2),
6815 argsize: align(3*4) + goarch.PtrSize + 2,
6816 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6821 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6822 size: 4 * goarch.PtrSize,
6823 argsize: 4 * goarch.PtrSize,
6824 retOffset: 4 * goarch.PtrSize,
6825 stack: []byte{1, 0, 1, 1},
6826 gc: []byte{1, 0, 1, 1},
6829 typ: ValueOf(func(a S) {}).Type(),
6830 size: 4 * goarch.PtrSize,
6831 argsize: 4 * goarch.PtrSize,
6832 retOffset: 4 * goarch.PtrSize,
6833 stack: []byte{0, 0, 1, 1},
6834 gc: []byte{0, 0, 1, 1},
6837 rcvr: ValueOf((*byte)(nil)).Type(),
6838 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6839 size: 3 * goarch.PtrSize,
6840 argsize: 3 * goarch.PtrSize,
6841 retOffset: 3 * goarch.PtrSize,
6842 stack: []byte{1, 0, 1},
6843 gc: []byte{1, 0, 1},
6846 typ: ValueOf(func(a uintptr) {}).Type(),
6847 size: goarch.PtrSize,
6848 argsize: goarch.PtrSize,
6849 retOffset: goarch.PtrSize,
6854 typ: ValueOf(func() uintptr { return 0 }).Type(),
6855 size: goarch.PtrSize,
6862 rcvr: ValueOf(uintptr(0)).Type(),
6863 typ: ValueOf(func(a uintptr) {}).Type(),
6864 size: 2 * goarch.PtrSize,
6865 argsize: 2 * goarch.PtrSize,
6866 retOffset: 2 * goarch.PtrSize,
6869 // Note: this one is tricky, as the receiver is not a pointer. But we
6870 // pass the receiver by reference to the autogenerated pointer-receiver
6871 // version of the function.
6873 // TODO(mknyszek): Add tests for non-zero register count.
6875 for _, lt := range tests {
6876 name := lt.typ.String()
6878 name = lt.rcvr.String() + "." + name
6880 t.Run(name, func(t *testing.T) {
6881 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6883 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6884 if typ.Size() != lt.size {
6885 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6887 if argsize != lt.argsize {
6888 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6890 if retOffset != lt.retOffset {
6891 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6893 if !bytes.Equal(stack, lt.stack) {
6894 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6896 if !bytes.Equal(gc, lt.gc) {
6897 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6899 if !bytes.Equal(inRegs, lt.inRegs) {
6900 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6902 if !bytes.Equal(outRegs, lt.outRegs) {
6903 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6905 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6906 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6912 // trimBitmap removes trailing 0 elements from b and returns the result.
6913 func trimBitmap(b []byte) []byte {
6914 for len(b) > 0 && b[len(b)-1] == 0 {
6920 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6921 heapBits := GCBits(New(typ).Interface())
6923 // Trim scalars at the end, as bits might end in zero,
6924 // e.g. with rep(2, lit(1, 0)).
6925 bits = trimBitmap(bits)
6927 if !bytes.Equal(heapBits, bits) {
6928 _, _, line, _ := runtime.Caller(1)
6929 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6933 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6934 // Creating a slice causes the runtime to repeat a bitmap,
6935 // which exercises a different path from making the compiler
6936 // repeat a bitmap for a small array or executing a repeat in
6938 val := MakeSlice(typ, 0, cap)
6939 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
6940 heapBits := GCBits(data.Interface())
6941 // Repeat the bitmap for the slice size, trimming scalars in
6942 // the last element.
6943 bits = trimBitmap(rep(cap, bits))
6944 if !bytes.Equal(heapBits, bits) {
6945 _, _, line, _ := runtime.Caller(1)
6946 t.Errorf("line %d: heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", line, typ, cap, heapBits, bits)
6950 func TestGCBits(t *testing.T) {
6951 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6953 // Building blocks for types seen by the compiler (like [2]Xscalar).
6954 // The compiler will create the type structures for the derived types,
6955 // including their GC metadata.
6956 type Xscalar struct{ x uintptr }
6957 type Xptr struct{ x *byte }
6958 type Xptrscalar struct {
6962 type Xscalarptr struct {
6966 type Xbigptrscalar struct {
6971 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6973 // Building blocks for types constructed by reflect.
6974 // This code is in a separate block so that code below
6975 // cannot accidentally refer to these.
6976 // The compiler must NOT see types derived from these
6977 // (for example, [2]Scalar must NOT appear in the program),
6978 // or else reflect will use it instead of having to construct one.
6979 // The goal is to test the construction.
6980 type Scalar struct{ x uintptr }
6981 type Ptr struct{ x *byte }
6982 type Ptrscalar struct {
6986 type Scalarptr struct {
6990 type Bigptrscalar struct {
6995 Tscalar = TypeOf(Scalar{})
6996 Tint64 = TypeOf(Int64(0))
6997 Tptr = TypeOf(Ptr{})
6998 Tscalarptr = TypeOf(Scalarptr{})
6999 Tptrscalar = TypeOf(Ptrscalar{})
7000 Tbigptrscalar = TypeOf(Bigptrscalar{})
7005 verifyGCBits(t, TypeOf(Xscalar{}), empty)
7006 verifyGCBits(t, Tscalar, empty)
7007 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
7008 verifyGCBits(t, Tptr, lit(1))
7009 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
7010 verifyGCBits(t, Tscalarptr, lit(0, 1))
7011 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
7012 verifyGCBits(t, Tptrscalar, lit(1))
7014 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
7015 verifyGCBits(t, ArrayOf(0, Tptr), empty)
7016 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
7017 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
7018 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
7019 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
7020 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
7021 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
7022 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
7023 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
7024 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
7025 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
7026 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
7027 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
7028 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
7029 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
7030 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
7031 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
7032 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7033 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
7034 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7035 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
7036 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
7037 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
7038 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7039 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7041 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
7042 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
7043 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
7044 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
7045 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
7046 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
7047 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
7048 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
7049 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
7050 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
7051 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
7052 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
7053 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
7054 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
7055 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
7056 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
7057 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
7058 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
7059 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
7060 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7061 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7062 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7063 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7064 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7065 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7066 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7068 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7069 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7071 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7072 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7074 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7075 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7077 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7078 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7080 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7081 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7083 hdr := make([]byte, 8/goarch.PtrSize)
7085 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7086 verifyGCBits(t, MapBucketOf(k, e), want)
7087 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7091 map[Xscalar]Xptr(nil),
7092 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7095 map[Xscalarptr]Xptr(nil),
7096 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7097 verifyMapBucket(t, Tint64, Tptr,
7098 map[int64]Xptr(nil),
7099 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7102 map[Xscalar]Xscalar(nil),
7105 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7106 map[[2]Xscalarptr][3]Xptrscalar(nil),
7107 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7109 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7110 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7111 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7113 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7114 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7115 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7117 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7118 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7119 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7121 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7122 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7123 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7126 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7127 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7128 func lit(x ...byte) []byte { return x }
7130 func TestTypeOfTypeOf(t *testing.T) {
7131 // Check that all the type constructors return concrete *rtype implementations.
7132 // It's difficult to test directly because the reflect package is only at arm's length.
7133 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7134 check := func(name string, typ Type) {
7135 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7136 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7140 type T struct{ int }
7141 check("TypeOf", TypeOf(T{}))
7143 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7144 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7145 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7146 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7147 check("PtrTo", PointerTo(TypeOf(T{})))
7148 check("SliceOf", SliceOf(TypeOf(T{})))
7151 type XM struct{ _ bool }
7153 func (*XM) String() string { return "" }
7155 func TestPtrToMethods(t *testing.T) {
7157 yp := New(TypeOf(y)).Interface()
7158 _, ok := yp.(fmt.Stringer)
7160 t.Fatal("does not implement Stringer, but should")
7164 func TestMapAlloc(t *testing.T) {
7165 m := ValueOf(make(map[int]int, 10))
7168 allocs := testing.AllocsPerRun(100, func() {
7172 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7177 val := ValueOf(&tmp).Elem()
7178 allocs = testing.AllocsPerRun(100, func() {
7179 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7180 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7181 for i := 0; i < size/2; i++ {
7182 val.SetInt(int64(i))
7183 mv.SetMapIndex(val, val)
7187 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7189 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7190 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7191 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7194 func TestChanAlloc(t *testing.T) {
7195 // Note: for a chan int, the return Value must be allocated, so we
7196 // use a chan *int instead.
7197 c := ValueOf(make(chan *int, 1))
7198 v := ValueOf(new(int))
7199 allocs := testing.AllocsPerRun(100, func() {
7203 if allocs < 0.5 || allocs > 1.5 {
7204 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7206 // Note: there is one allocation in reflect.recv which seems to be
7207 // a limitation of escape analysis. If that is ever fixed the
7208 // allocs < 0.5 condition will trigger and this test should be fixed.
7211 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7213 type nameTest struct {
7218 var nameTests = []nameTest{
7219 {(*int32)(nil), "int32"},
7222 {(*chan D1)(nil), ""},
7223 {(*func() D1)(nil), ""},
7224 {(*<-chan D1)(nil), ""},
7225 {(*chan<- D1)(nil), ""},
7230 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7233 func TestNames(t *testing.T) {
7234 for _, test := range nameTests {
7235 typ := TypeOf(test.v).Elem()
7236 if got := typ.Name(); got != test.want {
7237 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7242 func TestExported(t *testing.T) {
7243 type ΦExported struct{}
7244 type φUnexported struct{}
7251 type exportTest struct {
7255 exportTests := []exportTest{
7259 {(*big)(nil), false},
7260 {(BigP)(nil), true},
7261 {(*BigP)(nil), true},
7262 {ΦExported{}, true},
7263 {φUnexported{}, false},
7270 for i, test := range exportTests {
7271 typ := TypeOf(test.v)
7272 if got := IsExported(typ); got != test.want {
7273 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7278 func TestTypeStrings(t *testing.T) {
7279 type stringTest struct {
7283 stringTests := []stringTest{
7284 {TypeOf(func(int) {}), "func(int)"},
7285 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7286 {TypeOf(XM{}), "reflect_test.XM"},
7287 {TypeOf(new(XM)), "*reflect_test.XM"},
7288 {TypeOf(new(XM).String), "func() string"},
7289 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7290 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7291 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7292 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7293 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7296 for i, test := range stringTests {
7297 if got, want := test.typ.String(), test.want; got != want {
7298 t.Errorf("type %d String()=%q, want %q", i, got, want)
7303 func TestOffsetLock(t *testing.T) {
7304 var wg sync.WaitGroup
7305 for i := 0; i < 4; i++ {
7309 for j := 0; j < 50; j++ {
7310 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7318 func TestSwapper(t *testing.T) {
7324 type pairPtr struct {
7336 in: []int{1, 20, 300},
7339 want: []int{300, 20, 1},
7342 in: []uintptr{1, 20, 300},
7345 want: []uintptr{300, 20, 1},
7348 in: []int16{1, 20, 300},
7351 want: []int16{300, 20, 1},
7354 in: []int8{1, 20, 100},
7357 want: []int8{100, 20, 1},
7360 in: []*I{&a, &b, &c},
7363 want: []*I{&c, &b, &a},
7366 in: []string{"eric", "sergey", "larry"},
7369 want: []string{"larry", "sergey", "eric"},
7372 in: []S{"eric", "sergey", "larry"},
7375 want: []S{"larry", "sergey", "eric"},
7378 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7381 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7384 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7387 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7391 for i, tt := range tests {
7392 inStr := fmt.Sprint(tt.in)
7393 Swapper(tt.in)(tt.i, tt.j)
7394 if !DeepEqual(tt.in, tt.want) {
7395 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7400 // TestUnaddressableField tests that the reflect package will not allow
7401 // a type from another package to be used as a named type with an
7402 // unexported field.
7404 // This ensures that unexported fields cannot be modified by other packages.
7405 func TestUnaddressableField(t *testing.T) {
7406 var b Buffer // type defined in reflect, a different package
7407 var localBuffer struct {
7410 lv := ValueOf(&localBuffer).Elem()
7412 shouldPanic("Set", func() {
7421 type Talias1 struct {
7429 type Talias2 struct {
7434 func TestAliasNames(t *testing.T) {
7435 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7436 out := fmt.Sprintf("%#v", t1)
7437 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7439 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7442 t2 := Talias2{Tint: 1, Tint2: 2}
7443 out = fmt.Sprintf("%#v", t2)
7444 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7446 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7450 func TestIssue22031(t *testing.T) {
7451 type s []struct{ C int }
7454 type t2 struct{ f s }
7457 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7458 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7461 for i, test := range tests {
7463 t.Errorf("%d: CanSet: got true, want false", i)
7468 type NonExportedFirst int
7470 func (i NonExportedFirst) ΦExported() {}
7471 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7473 func TestIssue22073(t *testing.T) {
7474 m := ValueOf(NonExportedFirst(0)).Method(0)
7476 if got := m.Type().NumOut(); got != 0 {
7477 t.Errorf("NumOut: got %v, want 0", got)
7484 func TestMapIterNonEmptyMap(t *testing.T) {
7485 m := map[string]int{"one": 1, "two": 2, "three": 3}
7486 iter := ValueOf(m).MapRange()
7487 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7488 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7492 func TestMapIterNilMap(t *testing.T) {
7493 var m map[string]int
7494 iter := ValueOf(m).MapRange()
7495 if got, want := iterateToString(iter), `[]`; got != want {
7496 t.Errorf("non-empty result iteratoring nil map: %s", got)
7500 func TestMapIterReset(t *testing.T) {
7501 iter := new(MapIter)
7503 // Use of zero iterator should panic.
7505 defer func() { recover() }()
7507 t.Error("Next did not panic")
7510 // Reset to new Map should work.
7511 m := map[string]int{"one": 1, "two": 2, "three": 3}
7512 iter.Reset(ValueOf(m))
7513 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7514 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7517 // Reset to Zero value should work, but iterating over it should panic.
7520 defer func() { recover() }()
7522 t.Error("Next did not panic")
7525 // Reset to a different Map with different types should work.
7526 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7527 iter.Reset(ValueOf(m2))
7528 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7529 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7532 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7533 m3 := map[uint64]uint64{
7538 kv := New(TypeOf(uint64(0))).Elem()
7539 for i := 0; i < 5; i++ {
7540 var seenk, seenv uint64
7541 iter.Reset(ValueOf(m3))
7545 kv.SetIterValue(iter)
7549 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7551 if seenv != 0b1110 {
7552 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7556 // Reset should not allocate.
7557 n := int(testing.AllocsPerRun(10, func() {
7558 iter.Reset(ValueOf(m2))
7562 t.Errorf("MapIter.Reset allocated %d times", n)
7566 func TestMapIterSafety(t *testing.T) {
7567 // Using a zero MapIter causes a panic, but not a crash.
7569 defer func() { recover() }()
7571 t.Fatal("Key did not panic")
7574 defer func() { recover() }()
7575 new(MapIter).Value()
7576 t.Fatal("Value did not panic")
7579 defer func() { recover() }()
7581 t.Fatal("Next did not panic")
7584 // Calling Key/Value on a MapIter before Next
7585 // causes a panic, but not a crash.
7586 var m map[string]int
7587 iter := ValueOf(m).MapRange()
7590 defer func() { recover() }()
7592 t.Fatal("Key did not panic")
7595 defer func() { recover() }()
7597 t.Fatal("Value did not panic")
7600 // Calling Next, Key, or Value on an exhausted iterator
7601 // causes a panic, but not a crash.
7602 iter.Next() // -> false
7604 defer func() { recover() }()
7606 t.Fatal("Key did not panic")
7609 defer func() { recover() }()
7611 t.Fatal("Value did not panic")
7614 defer func() { recover() }()
7616 t.Fatal("Next did not panic")
7620 func TestMapIterNext(t *testing.T) {
7621 // The first call to Next should reflect any
7622 // insertions to the map since the iterator was created.
7623 m := map[string]int{}
7624 iter := ValueOf(m).MapRange()
7626 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7627 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7631 func TestMapIterDelete0(t *testing.T) {
7632 // Delete all elements before first iteration.
7633 m := map[string]int{"one": 1, "two": 2, "three": 3}
7634 iter := ValueOf(m).MapRange()
7638 if got, want := iterateToString(iter), `[]`; got != want {
7639 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7643 func TestMapIterDelete1(t *testing.T) {
7644 // Delete all elements after first iteration.
7645 m := map[string]int{"one": 1, "two": 2, "three": 3}
7646 iter := ValueOf(m).MapRange()
7649 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7655 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7659 // iterateToString returns the set of elements
7660 // returned by an iterator in readable form.
7661 func iterateToString(it *MapIter) string {
7664 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7665 got = append(got, line)
7668 return "[" + strings.Join(got, ", ") + "]"
7671 func TestConvertibleTo(t *testing.T) {
7672 t1 := ValueOf(example1.MyStruct{}).Type()
7673 t2 := ValueOf(example2.MyStruct{}).Type()
7675 // Shouldn't raise stack overflow
7676 if t1.ConvertibleTo(t2) {
7677 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7680 t3 := ValueOf([]example1.MyStruct{}).Type()
7681 t4 := ValueOf([]example2.MyStruct{}).Type()
7683 if t3.ConvertibleTo(t4) {
7684 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7688 func TestSetIter(t *testing.T) {
7689 data := map[string]int{
7697 k := New(TypeOf("")).Elem()
7698 v := New(TypeOf(0)).Elem()
7699 shouldPanic("Value.SetIterKey called before Next", func() {
7702 shouldPanic("Value.SetIterValue called before Next", func() {
7705 data2 := map[string]int{}
7709 data2[k.Interface().(string)] = v.Interface().(int)
7711 if !DeepEqual(data, data2) {
7712 t.Errorf("maps not equal, got %v want %v", data2, data)
7714 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7717 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7723 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7724 ValueOf("").SetIterKey(i)
7726 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7727 ValueOf(0).SetIterValue(i)
7729 shouldPanic("value of type string is not assignable to type int", func() {
7730 New(TypeOf(0)).Elem().SetIterKey(i)
7732 shouldPanic("value of type int is not assignable to type string", func() {
7733 New(TypeOf("")).Elem().SetIterValue(i)
7736 // Make sure assignment conversion works.
7738 y := ValueOf(&x).Elem()
7740 if _, ok := data[x.(string)]; !ok {
7741 t.Errorf("got key %s which is not in map", x)
7744 if x.(int) < 1 || x.(int) > 3 {
7745 t.Errorf("got value %d which is not in map", x)
7748 // Try some key/value types which are direct interfaces.
7751 pp := map[*int]*int{
7754 i = ValueOf(pp).MapRange()
7757 if got := *y.Interface().(*int); got != a {
7758 t.Errorf("pointer incorrect: got %d want %d", got, a)
7761 if got := *y.Interface().(*int); got != b {
7762 t.Errorf("pointer incorrect: got %d want %d", got, b)
7765 // Make sure we panic assigning from an unexported field.
7766 m = ValueOf(struct{ m map[string]int }{data}).Field(0)
7767 for iter := m.MapRange(); iter.Next(); {
7768 shouldPanic("using value obtained using unexported field", func() {
7771 shouldPanic("using value obtained using unexported field", func() {
7772 v.SetIterValue(iter)
7777 func TestMethodCallValueCodePtr(t *testing.T) {
7778 m := ValueOf(Point{}).Method(1)
7779 want := MethodValueCallCodePtr()
7780 if got := uintptr(m.UnsafePointer()); got != want {
7781 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7783 if got := m.Pointer(); got != want {
7784 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7789 type B[T any] struct{}
7791 func TestIssue50208(t *testing.T) {
7792 want1 := "B[reflect_test.A]"
7793 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7794 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7796 want2 := "B[reflect_test.B[reflect_test.A]]"
7797 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7798 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7802 func TestNegativeKindString(t *testing.T) {
7804 s := Kind(x).String()
7807 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
7816 func TestValue_Cap(t *testing.T) {
7817 a := &[3]int{1, 2, 3}
7819 if v.Cap() != cap(a) {
7820 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7825 if v.Cap() != cap(a) {
7826 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7829 getError := func(f func()) (errorStr string) {
7832 if str, ok := e.(string); ok {
7839 e := getError(func() {
7843 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
7845 t.Errorf("error is %q, want %q", e, wantStr)
7849 func TestValue_Len(t *testing.T) {
7850 a := &[3]int{1, 2, 3}
7852 if v.Len() != len(a) {
7853 t.Errorf("Len = %d want %d", v.Len(), len(a))
7858 if v.Len() != len(a) {
7859 t.Errorf("Len = %d want %d", v.Len(), len(a))
7862 getError := func(f func()) (errorStr string) {
7865 if str, ok := e.(string); ok {
7872 e := getError(func() {
7876 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
7878 t.Errorf("error is %q, want %q", e, wantStr)
7882 func TestValue_Comparable(t *testing.T) {
7885 var i interface{} = a
7886 var iSlice interface{} = s
7887 var iArrayFalse interface{} = [2]interface{}{1, map[int]int{}}
7888 var iArrayTrue interface{} = [2]interface{}{1, struct{ I interface{} }{1}}
7889 var testcases = []struct {
7940 ValueOf(float32(1)),
7945 ValueOf(float64(1)),
7950 ValueOf(complex(float32(1), float32(1))),
7955 ValueOf(complex(float64(1), float64(1))),
7970 ValueOf(map[int]int{}),
8010 ValueOf([2]map[int]int{}),
8015 ValueOf([0]func(){}),
8020 ValueOf([2]struct{ I interface{} }{{1}, {1}}),
8025 ValueOf([2]struct{ I interface{} }{{[]int{}}, {1}}),
8030 ValueOf([2]interface{}{1, struct{ I int }{1}}),
8035 ValueOf([2]interface{}{[1]interface{}{map[int]int{}}, struct{ I int }{1}}),
8040 ValueOf(&iArrayFalse),
8045 ValueOf(&iArrayTrue),
8051 for _, cas := range testcases {
8056 got := v.Comparable()
8057 if got != cas.comparable {
8058 t.Errorf("%T.Comparable = %t, want %t", v, got, cas.comparable)
8063 type ValueEqualTest struct {
8069 var equalI interface{} = 1
8070 var equalSlice interface{} = []int{1}
8071 var nilInterface interface{}
8072 var mapInterface interface{} = map[int]int{}
8074 var valueEqualTests = []ValueEqualTest{
8121 uint16(1), uint16(1),
8126 uint32(1), uint32(1),
8131 uint64(1), uint64(1),
8136 float32(1), float32(1),
8141 float64(1), float64(1),
8146 complex(1, 1), complex(1, 1),
8151 complex128(1 + 1i), complex128(1 + 1i),
8166 &equalSlice, []int{1},
8171 map[int]int{}, map[int]int{},
8176 (chan int)(nil), nil,
8181 (chan int)(nil), (chan int)(nil),
8191 struct{ i int }{1}, struct{ i int }{1},
8196 struct{ i int }{1}, struct{ i int }{2},
8201 &nilInterface, &nilInterface,
8206 1, ValueOf(struct{ i int }{1}).Field(0),
8211 &mapInterface, &mapInterface,
8217 func TestValue_Equal(t *testing.T) {
8218 for _, test := range valueEqualTests {
8220 if vv, ok := test.v.(Value); ok {
8226 if uu, ok := test.u.(Value); ok {
8239 if r := v.Equal(u); r != test.eq {
8240 t.Errorf("%s == %s got %t, want %t", v.Type(), u.Type(), r, test.eq)
8245 func TestInitFuncTypes(t *testing.T) {
8247 var wg sync.WaitGroup
8250 for i := 0; i < n; i++ {
8253 ipT := TypeOf(net.IP{})
8254 for i := 0; i < ipT.NumMethod(); i++ {