1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
20 "reflect/internal/example1"
21 "reflect/internal/example2"
35 func TestBool(t *testing.T) {
38 t.Fatal("ValueOf(true).Bool() = false")
55 func assert(t *testing.T, s, want string) {
57 t.Errorf("have %#q want %#q", s, want)
61 var typeTests = []pair{
62 {struct{ x int }{}, "int"},
63 {struct{ x int8 }{}, "int8"},
64 {struct{ x int16 }{}, "int16"},
65 {struct{ x int32 }{}, "int32"},
66 {struct{ x int64 }{}, "int64"},
67 {struct{ x uint }{}, "uint"},
68 {struct{ x uint8 }{}, "uint8"},
69 {struct{ x uint16 }{}, "uint16"},
70 {struct{ x uint32 }{}, "uint32"},
71 {struct{ x uint64 }{}, "uint64"},
72 {struct{ x float32 }{}, "float32"},
73 {struct{ x float64 }{}, "float64"},
74 {struct{ x int8 }{}, "int8"},
75 {struct{ x (**int8) }{}, "**int8"},
76 {struct{ x (**integer) }{}, "**reflect_test.integer"},
77 {struct{ x ([32]int32) }{}, "[32]int32"},
78 {struct{ x ([]int8) }{}, "[]int8"},
79 {struct{ x (map[string]int32) }{}, "map[string]int32"},
80 {struct{ x (chan<- string) }{}, "chan<- string"},
81 {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
82 {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
83 {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
84 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
91 "struct { c chan *int32; d float32 }",
93 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
96 c func(chan *integer, *int8)
99 "struct { c func(chan *reflect_test.integer, *int8) }",
107 "struct { a int8; b int32 }",
116 "struct { a int8; b int8; c int32 }",
126 "struct { a int8; b int8; c int8; d int32 }",
137 "struct { a int8; b int8; c int8; d int8; e int32 }",
149 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
153 a int8 `reflect:"hi there"`
156 `struct { a int8 "reflect:\"hi there\"" }`,
160 a int8 `reflect:"hi \x00there\t\n\"\\"`
163 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
170 "struct { f func(...int) }",
174 a(func(func(int) int) func(func(int)) int)
178 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
186 "struct { int32; int64 }",
190 var valueTests = []pair{
201 {new(float32), "256.25"},
202 {new(float64), "512.125"},
203 {new(complex64), "532.125+10i"},
204 {new(complex128), "564.25+1i"},
205 {new(string), "stringy cheese"},
207 {new(*int8), "*int8(0)"},
208 {new(**int8), "**int8(0)"},
209 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
210 {new(**integer), "**reflect_test.integer(0)"},
211 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
212 {new(chan<- string), "chan<- string"},
213 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
218 "struct { c chan *int32; d float32 }{chan *int32, 0}",
220 {new(struct{ c func(chan *integer, *int8) }),
221 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
227 "struct { a int8; b int32 }{0, 0}",
234 "struct { a int8; b int8; c int32 }{0, 0, 0}",
238 func testType(t *testing.T, i int, typ Type, want string) {
241 t.Errorf("#%d: have %#q, want %#q", i, s, want)
245 func TestTypes(t *testing.T) {
246 for i, tt := range typeTests {
247 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
251 func TestSet(t *testing.T) {
252 for i, tt := range valueTests {
281 v.SetComplex(532.125 + 10i)
283 v.SetComplex(564.25 + 1i)
285 v.SetString("stringy cheese")
289 s := valueToString(v)
291 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
296 func TestSetValue(t *testing.T) {
297 for i, tt := range valueTests {
298 v := ValueOf(tt.i).Elem()
301 v.Set(ValueOf(int(132)))
303 v.Set(ValueOf(int8(8)))
305 v.Set(ValueOf(int16(16)))
307 v.Set(ValueOf(int32(32)))
309 v.Set(ValueOf(int64(64)))
311 v.Set(ValueOf(uint(132)))
313 v.Set(ValueOf(uint8(8)))
315 v.Set(ValueOf(uint16(16)))
317 v.Set(ValueOf(uint32(32)))
319 v.Set(ValueOf(uint64(64)))
321 v.Set(ValueOf(float32(256.25)))
323 v.Set(ValueOf(512.125))
325 v.Set(ValueOf(complex64(532.125 + 10i)))
327 v.Set(ValueOf(complex128(564.25 + 1i)))
329 v.Set(ValueOf("stringy cheese"))
333 s := valueToString(v)
335 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
340 func TestMapIterSet(t *testing.T) {
341 m := make(map[string]any, len(valueTests))
342 for _, tt := range valueTests {
347 k := New(v.Type().Key()).Elem()
348 e := New(v.Type().Elem()).Elem()
354 want := m[k.String()]
357 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
359 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
360 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
362 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
363 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
367 if strings.HasSuffix(testenv.Builder(), "-noopt") {
368 return // no inlining with the noopt builder
371 got := int(testing.AllocsPerRun(10, func() {
378 // Calling MapRange should not allocate even though it returns a *MapIter.
379 // The function is inlineable, so if the local usage does not escape
380 // the *MapIter, it can remain stack allocated.
383 t.Errorf("wanted %d alloc, got %d", want, got)
387 func TestCanIntUintFloatComplex(t *testing.T) {
391 type complex complex128
393 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
395 var testCases = []struct {
400 {132, [...]bool{true, false, false, false}},
401 {int8(8), [...]bool{true, false, false, false}},
402 {int16(16), [...]bool{true, false, false, false}},
403 {int32(32), [...]bool{true, false, false, false}},
404 {int64(64), [...]bool{true, false, false, false}},
406 {uint(132), [...]bool{false, true, false, false}},
407 {uint8(8), [...]bool{false, true, false, false}},
408 {uint16(16), [...]bool{false, true, false, false}},
409 {uint32(32), [...]bool{false, true, false, false}},
410 {uint64(64), [...]bool{false, true, false, false}},
411 {uintptr(0xABCD), [...]bool{false, true, false, false}},
413 {float32(256.25), [...]bool{false, false, true, false}},
414 {float64(512.125), [...]bool{false, false, true, false}},
416 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
417 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
419 {integer(-132), [...]bool{true, false, false, false}},
420 {uinteger(132), [...]bool{false, true, false, false}},
421 {float(256.25), [...]bool{false, false, true, false}},
422 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
424 {"hello world", [...]bool{false, false, false, false}},
425 {new(int), [...]bool{false, false, false, false}},
426 {new(uint), [...]bool{false, false, false, false}},
427 {new(float64), [...]bool{false, false, false, false}},
428 {new(complex64), [...]bool{false, false, false, false}},
429 {new([5]int), [...]bool{false, false, false, false}},
430 {new(integer), [...]bool{false, false, false, false}},
431 {new(map[int]int), [...]bool{false, false, false, false}},
432 {new(chan<- int), [...]bool{false, false, false, false}},
433 {new(func(a int8)), [...]bool{false, false, false, false}},
434 {new(struct{ i int }), [...]bool{false, false, false, false}},
437 for i, tc := range testCases {
439 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
441 for j := range tc.want {
442 if got[j] != tc.want[j] {
444 "#%d: v.%s() returned %t for type %T, want %t",
456 func TestCanSetField(t *testing.T) {
457 type embed struct{ x, X int }
458 type Embed struct{ x, X int }
476 type testCase struct {
477 // -1 means Addr().Elem() of current value
488 {[]int{0, -1}, false},
489 {[]int{0, 0}, false},
490 {[]int{0, 0, -1}, false},
491 {[]int{0, -1, 0}, false},
492 {[]int{0, -1, 0, -1}, false},
494 {[]int{0, 1, -1}, true},
495 {[]int{0, -1, 1}, true},
496 {[]int{0, -1, 1, -1}, true},
498 {[]int{1, -1}, false},
500 {[]int{2, -1}, true},
503 val: ValueOf(&S2{embed: &embed{}}),
506 {[]int{0, -1}, false},
507 {[]int{0, 0}, false},
508 {[]int{0, 0, -1}, false},
509 {[]int{0, -1, 0}, false},
510 {[]int{0, -1, 0, -1}, false},
512 {[]int{0, 1, -1}, true},
513 {[]int{0, -1, 1}, true},
514 {[]int{0, -1, 1, -1}, true},
522 {[]int{0, -1}, true},
523 {[]int{0, 0}, false},
524 {[]int{0, 0, -1}, false},
525 {[]int{0, -1, 0}, false},
526 {[]int{0, -1, 0, -1}, false},
528 {[]int{0, 1, -1}, true},
529 {[]int{0, -1, 1}, true},
530 {[]int{0, -1, 1, -1}, true},
535 val: ValueOf(&S4{Embed: &Embed{}}),
538 {[]int{0, -1}, true},
539 {[]int{0, 0}, false},
540 {[]int{0, 0, -1}, false},
541 {[]int{0, -1, 0}, false},
542 {[]int{0, -1, 0, -1}, false},
544 {[]int{0, 1, -1}, true},
545 {[]int{0, -1, 1}, true},
546 {[]int{0, -1, 1, -1}, true},
552 for _, tt := range tests {
553 t.Run(tt.val.Type().Name(), func(t *testing.T) {
554 for _, tc := range tt.cases {
556 for _, i := range tc.index {
557 if f.Kind() == Pointer {
566 if got := f.CanSet(); got != tc.canSet {
567 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
576 var valueToStringTests = []pair{
581 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
582 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
583 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
584 {&[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})"},
585 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
586 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
589 func TestValueToString(t *testing.T) {
590 for i, test := range valueToStringTests {
591 s := valueToString(ValueOf(test.i))
593 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
598 func TestArrayElemSet(t *testing.T) {
599 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
600 v.Index(4).SetInt(123)
601 s := valueToString(v)
602 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
604 t.Errorf("[10]int: have %#q want %#q", s, want)
607 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
608 v.Index(4).SetInt(123)
610 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
612 t.Errorf("[]int: have %#q want %#q", s, want1)
616 func TestPtrPointTo(t *testing.T) {
620 vi := ValueOf(&i).Elem()
621 vip.Elem().Set(vi.Addr())
623 t.Errorf("got %d, want 1234", *ip)
627 vp := ValueOf(&ip).Elem()
628 vp.Set(Zero(vp.Type()))
630 t.Errorf("got non-nil (%p), want nil", ip)
634 func TestPtrSetNil(t *testing.T) {
638 vip.Elem().Set(Zero(vip.Elem().Type()))
640 t.Errorf("got non-nil (%d), want nil", *ip)
644 func TestMapSetNil(t *testing.T) {
645 m := make(map[string]int)
647 vm.Elem().Set(Zero(vm.Elem().Type()))
649 t.Errorf("got non-nil (%p), want nil", m)
653 func TestAll(t *testing.T) {
654 testType(t, 1, TypeOf((int8)(0)), "int8")
655 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
657 typ := TypeOf((*struct {
661 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
663 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
666 testType(t, 5, f.Type, "chan *int32")
668 f, present := styp.FieldByName("d")
670 t.Errorf("FieldByName says present field is absent")
672 testType(t, 6, f.Type, "float32")
674 f, present = styp.FieldByName("absent")
676 t.Errorf("FieldByName says absent field is present")
679 typ = TypeOf([32]int32{})
680 testType(t, 7, typ, "[32]int32")
681 testType(t, 8, typ.Elem(), "int32")
683 typ = TypeOf((map[string]*int32)(nil))
684 testType(t, 9, typ, "map[string]*int32")
686 testType(t, 10, mtyp.Key(), "string")
687 testType(t, 11, mtyp.Elem(), "*int32")
689 typ = TypeOf((chan<- string)(nil))
690 testType(t, 12, typ, "chan<- string")
691 testType(t, 13, typ.Elem(), "string")
693 // make sure tag strings are not part of element type
694 typ = TypeOf(struct {
695 d []uint32 `reflect:"TAG"`
697 testType(t, 14, typ, "[]uint32")
700 func TestInterfaceGet(t *testing.T) {
705 v1 := ValueOf(&inter)
706 v2 := v1.Elem().Field(0)
707 assert(t, v2.Type().String(), "interface {}")
710 assert(t, v3.Type().String(), "float64")
713 func TestInterfaceValue(t *testing.T) {
718 v1 := ValueOf(&inter)
719 v2 := v1.Elem().Field(0)
720 assert(t, v2.Type().String(), "interface {}")
722 assert(t, v3.Type().String(), "float64")
725 if _, ok := i3.(float64); !ok {
726 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
730 func TestFunctionValue(t *testing.T) {
731 var x any = func() {}
733 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
734 t.Fatalf("TestFunction returned wrong pointer")
736 assert(t, v.Type().String(), "func()")
739 var appendTests = []struct {
742 {make([]int, 2, 4), []int{22}},
743 {make([]int, 2, 4), []int{22, 33, 44}},
746 func sameInts(x, y []int) bool {
747 if len(x) != len(y) {
750 for i, xx := range x {
758 func TestAppend(t *testing.T) {
759 for i, test := range appendTests {
760 origLen, extraLen := len(test.orig), len(test.extra)
761 want := append(test.orig, test.extra...)
762 // Convert extra from []int to []Value.
763 e0 := make([]Value, len(test.extra))
764 for j, e := range test.extra {
767 // Convert extra from []int to *SliceValue.
768 e1 := ValueOf(test.extra)
770 a0 := ValueOf(test.orig)
771 have0 := Append(a0, e0...).Interface().([]int)
772 if !sameInts(have0, want) {
773 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
775 // Check that the orig and extra slices were not modified.
776 if len(test.orig) != origLen {
777 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
779 if len(test.extra) != extraLen {
780 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
783 a1 := ValueOf(test.orig)
784 have1 := AppendSlice(a1, e1).Interface().([]int)
785 if !sameInts(have1, want) {
786 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
788 // Check that the orig and extra slices were not modified.
789 if len(test.orig) != origLen {
790 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
792 if len(test.extra) != extraLen {
793 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
798 func TestCopy(t *testing.T) {
799 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
800 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
801 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
802 for i := 0; i < len(b); i++ {
804 t.Fatalf("b != c before test")
809 aa := ValueOf(&a1).Elem()
810 ab := ValueOf(&b1).Elem()
811 for tocopy := 1; tocopy <= 7; tocopy++ {
815 for i := 0; i < tocopy; i++ {
817 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
818 tocopy, i, a[i], i, b[i])
821 for i := tocopy; i < len(b); i++ {
824 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
825 tocopy, i, a[i], i, b[i], i, c[i])
827 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
828 tocopy, i, b[i], i, c[i])
831 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
837 func TestCopyString(t *testing.T) {
838 t.Run("Slice", func(t *testing.T) {
839 s := bytes.Repeat([]byte{'_'}, 8)
842 n := Copy(val, ValueOf(""))
843 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
844 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
847 n = Copy(val, ValueOf("hello"))
848 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
849 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
852 n = Copy(val, ValueOf("helloworld"))
853 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
854 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
857 t.Run("Array", func(t *testing.T) {
858 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
859 val := ValueOf(&s).Elem()
861 n := Copy(val, ValueOf(""))
862 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
863 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
866 n = Copy(val, ValueOf("hello"))
867 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
868 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
871 n = Copy(val, ValueOf("helloworld"))
872 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
873 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
878 func TestCopyArray(t *testing.T) {
879 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
880 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
882 aa := ValueOf(&a).Elem()
883 ab := ValueOf(&b).Elem()
885 for i := 0; i < len(a); i++ {
887 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
890 for i := len(a); i < len(b); i++ {
892 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
894 t.Logf("elem %d is okay\n", i)
899 func TestBigUnnamedStruct(t *testing.T) {
900 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
902 b1 := v.Interface().(struct {
905 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
906 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
914 func TestBigStruct(t *testing.T) {
915 b := big{1, 2, 3, 4, 5}
917 b1 := v.Interface().(big)
918 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
919 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
930 type DeepEqualTest struct {
935 // Simple functions for DeepEqual tests.
939 fn3 = func() { fn1() } // Not nil.
947 var loop1, loop2 Loop
948 var loopy1, loopy2 Loopy
949 var cycleMap1, cycleMap2, cycleMap3 map[string]any
951 type structWithSelfPtr struct {
963 cycleMap1 = map[string]any{}
964 cycleMap1["cycle"] = cycleMap1
965 cycleMap2 = map[string]any{}
966 cycleMap2["cycle"] = cycleMap2
967 cycleMap3 = map[string]any{}
968 cycleMap3["different"] = cycleMap3
971 var deepEqualTests = []DeepEqualTest{
975 {int32(1), int32(1), true},
977 {float32(0.5), float32(0.5), true},
978 {"hello", "hello", true},
979 {make([]int, 10), make([]int, 10), true},
980 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
981 {Basic{1, 0.5}, Basic{1, 0.5}, true},
982 {error(nil), error(nil), true},
983 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
985 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
986 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
987 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
991 {int32(1), int32(2), false},
993 {float32(0.5), float32(0.6), false},
994 {"hello", "hey", false},
995 {make([]int, 10), make([]int, 11), false},
996 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
997 {Basic{1, 0.5}, Basic{1, 0.6}, false},
998 {Basic{1, 0}, Basic{2, 0}, false},
999 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
1000 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
1001 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
1002 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
1007 {[][]int{{1}}, [][]int{{2}}, false},
1008 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1010 // Fun with floating point.
1011 {math.NaN(), math.NaN(), false},
1012 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1013 {&[1]float64{math.NaN()}, self{}, true},
1014 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1015 {[]float64{math.NaN()}, self{}, true},
1016 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1017 {map[float64]float64{math.NaN(): 1}, self{}, true},
1019 // Nil vs empty: not the same.
1020 {[]int{}, []int(nil), false},
1021 {[]int{}, []int{}, true},
1022 {[]int(nil), []int(nil), true},
1023 {map[int]int{}, map[int]int(nil), false},
1024 {map[int]int{}, map[int]int{}, true},
1025 {map[int]int(nil), map[int]int(nil), true},
1029 {int32(1), int64(1), false},
1030 {0.5, "hello", false},
1031 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1032 {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
1033 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1034 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1035 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1036 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1037 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1040 {&loop1, &loop1, true},
1041 {&loop1, &loop2, true},
1042 {&loopy1, &loopy1, true},
1043 {&loopy1, &loopy2, true},
1044 {&cycleMap1, &cycleMap2, true},
1045 {&cycleMap1, &cycleMap3, false},
1048 func TestDeepEqual(t *testing.T) {
1049 for _, test := range deepEqualTests {
1050 if test.b == (self{}) {
1053 if r := DeepEqual(test.a, test.b); r != test.eq {
1054 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1059 func TestTypeOf(t *testing.T) {
1060 // Special case for nil
1061 if typ := TypeOf(nil); typ != nil {
1062 t.Errorf("expected nil type for nil value; got %v", typ)
1064 for _, test := range deepEqualTests {
1065 v := ValueOf(test.a)
1069 typ := TypeOf(test.a)
1070 if typ != v.Type() {
1071 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1076 type Recursive struct {
1081 func TestDeepEqualRecursiveStruct(t *testing.T) {
1082 a, b := new(Recursive), new(Recursive)
1083 *a = Recursive{12, a}
1084 *b = Recursive{12, b}
1085 if !DeepEqual(a, b) {
1086 t.Error("DeepEqual(recursive same) = false, want true")
1090 type _Complex struct {
1094 d map[float64]float64
1097 func TestDeepEqualComplexStruct(t *testing.T) {
1098 m := make(map[float64]float64)
1099 stra, strb := "hello", "hello"
1100 a, b := new(_Complex), new(_Complex)
1101 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1102 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1103 if !DeepEqual(a, b) {
1104 t.Error("DeepEqual(complex same) = false, want true")
1108 func TestDeepEqualComplexStructInequality(t *testing.T) {
1109 m := make(map[float64]float64)
1110 stra, strb := "hello", "helloo" // Difference is here
1111 a, b := new(_Complex), new(_Complex)
1112 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1113 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1114 if DeepEqual(a, b) {
1115 t.Error("DeepEqual(complex different) = true, want false")
1119 type UnexpT struct {
1123 func TestDeepEqualUnexportedMap(t *testing.T) {
1124 // Check that DeepEqual can look at unexported fields.
1125 x1 := UnexpT{map[int]int{1: 2}}
1126 x2 := UnexpT{map[int]int{1: 2}}
1127 if !DeepEqual(&x1, &x2) {
1128 t.Error("DeepEqual(x1, x2) = false, want true")
1131 y1 := UnexpT{map[int]int{2: 3}}
1132 if DeepEqual(&x1, &y1) {
1133 t.Error("DeepEqual(x1, y1) = true, want false")
1137 var deepEqualPerfTests = []struct {
1140 {x: int8(99), y: int8(99)},
1141 {x: []int8{99}, y: []int8{99}},
1142 {x: int16(99), y: int16(99)},
1143 {x: []int16{99}, y: []int16{99}},
1144 {x: int32(99), y: int32(99)},
1145 {x: []int32{99}, y: []int32{99}},
1146 {x: int64(99), y: int64(99)},
1147 {x: []int64{99}, y: []int64{99}},
1148 {x: int(999999), y: int(999999)},
1149 {x: []int{999999}, y: []int{999999}},
1151 {x: uint8(99), y: uint8(99)},
1152 {x: []uint8{99}, y: []uint8{99}},
1153 {x: uint16(99), y: uint16(99)},
1154 {x: []uint16{99}, y: []uint16{99}},
1155 {x: uint32(99), y: uint32(99)},
1156 {x: []uint32{99}, y: []uint32{99}},
1157 {x: uint64(99), y: uint64(99)},
1158 {x: []uint64{99}, y: []uint64{99}},
1159 {x: uint(999999), y: uint(999999)},
1160 {x: []uint{999999}, y: []uint{999999}},
1161 {x: uintptr(999999), y: uintptr(999999)},
1162 {x: []uintptr{999999}, y: []uintptr{999999}},
1164 {x: float32(1.414), y: float32(1.414)},
1165 {x: []float32{1.414}, y: []float32{1.414}},
1166 {x: float64(1.414), y: float64(1.414)},
1167 {x: []float64{1.414}, y: []float64{1.414}},
1169 {x: complex64(1.414), y: complex64(1.414)},
1170 {x: []complex64{1.414}, y: []complex64{1.414}},
1171 {x: complex128(1.414), y: complex128(1.414)},
1172 {x: []complex128{1.414}, y: []complex128{1.414}},
1175 {x: []bool{true}, y: []bool{true}},
1177 {x: "abcdef", y: "abcdef"},
1178 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1180 {x: []byte("abcdef"), y: []byte("abcdef")},
1181 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1183 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1184 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1187 func TestDeepEqualAllocs(t *testing.T) {
1188 for _, tt := range deepEqualPerfTests {
1189 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1190 got := testing.AllocsPerRun(100, func() {
1191 if !DeepEqual(tt.x, tt.y) {
1192 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1196 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1202 func BenchmarkDeepEqual(b *testing.B) {
1203 for _, bb := range deepEqualPerfTests {
1204 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1206 for i := 0; i < b.N; i++ {
1207 sink = DeepEqual(bb.x, bb.y)
1213 func check2ndField(x any, offs uintptr, t *testing.T) {
1215 f := s.Type().Field(1)
1216 if f.Offset != offs {
1217 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1221 // Check that structure alignment & offsets viewed through reflect agree with those
1222 // from the compiler itself.
1223 func TestAlignment(t *testing.T) {
1224 type T1inner struct {
1231 type T2inner struct {
1239 x := T1{T1inner{2}, 17}
1240 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1242 x1 := T2{T2inner{2, 3}, 17}
1243 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1246 func Nil(a any, t *testing.T) {
1247 n := ValueOf(a).Field(0)
1249 t.Errorf("%v should be nil", a)
1253 func NotNil(a any, t *testing.T) {
1254 n := ValueOf(a).Field(0)
1256 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1260 func TestIsNil(t *testing.T) {
1261 // These implement IsNil.
1262 // Wrap in extra struct to hide interface type.
1266 struct{ x map[string]int }{},
1267 struct{ x func() bool }{},
1268 struct{ x chan int }{},
1269 struct{ x []string }{},
1270 struct{ x unsafe.Pointer }{},
1272 for _, ts := range doNil {
1273 ty := TypeOf(ts).Field(0).Type
1275 v.IsNil() // panics if not okay to call
1278 // Check the implementations
1290 si.x = make([]int, 10)
1297 ci.x = make(chan int)
1304 mi.x = make(map[int]int)
1315 x func(t *testing.T)
1322 func TestIsZero(t *testing.T) {
1323 for i, tt := range []struct {
1352 {float32(1.2), false},
1354 {float64(1.2), false},
1355 {math.Copysign(0, -1), false},
1356 {complex64(0), true},
1357 {complex64(1.2), false},
1358 {complex128(0), true},
1359 {complex128(1.2), false},
1360 {complex(math.Copysign(0, -1), 0), false},
1361 {complex(0, math.Copysign(0, -1)), false},
1362 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1364 {uintptr(128), false},
1366 {Zero(TypeOf([5]string{})).Interface(), true},
1367 {[5]string{"", "", "", "", ""}, true},
1368 {[5]string{}, true},
1369 {[5]string{"", "", "", "a", ""}, false},
1371 {(chan string)(nil), true},
1372 {make(chan string), false},
1373 {time.After(1), false},
1375 {(func())(nil), true},
1378 {New(TypeOf(new(error)).Elem()).Elem(), true},
1379 {(io.Reader)(strings.NewReader("")), false},
1381 {(map[string]string)(nil), true},
1382 {map[string]string{}, false},
1383 {make(map[string]string), false},
1385 {(*func())(nil), true},
1386 {(*int)(nil), true},
1389 {[]string{}, false},
1390 {([]string)(nil), true},
1391 {make([]string, 0), false},
1394 {"not-zero", false},
1397 {T{123, 456.75, "hello", &_i}, false},
1399 {(unsafe.Pointer)(nil), true},
1400 {(unsafe.Pointer)(new(int)), false},
1403 if v, ok := tt.x.(Value); ok {
1411 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1414 if !Zero(TypeOf(tt.x)).IsZero() {
1415 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1421 if r := recover(); r == nil {
1422 t.Error("should panic for invalid value")
1429 func TestInterfaceExtraction(t *testing.T) {
1435 v := Indirect(ValueOf(&s)).Field(0).Interface()
1437 t.Error("Interface() on interface: ", v, s.W)
1441 func TestNilPtrValueSub(t *testing.T) {
1443 if pv := ValueOf(pi); pv.Elem().IsValid() {
1444 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1448 func TestMap(t *testing.T) {
1449 m := map[string]int{"a": 1, "b": 2}
1451 if n := mv.Len(); n != len(m) {
1452 t.Errorf("Len = %d, want %d", n, len(m))
1454 keys := mv.MapKeys()
1455 newmap := MakeMap(mv.Type())
1456 for k, v := range m {
1457 // Check that returned Keys match keys in range.
1458 // These aren't required to be in the same order.
1460 for _, kv := range keys {
1461 if kv.String() == k {
1467 t.Errorf("Missing key %q", k)
1470 // Check that value lookup is correct.
1471 vv := mv.MapIndex(ValueOf(k))
1472 if vi := vv.Int(); vi != int64(v) {
1473 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1476 // Copy into new map.
1477 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1479 vv := mv.MapIndex(ValueOf("not-present"))
1481 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1484 newm := newmap.Interface().(map[string]int)
1485 if len(newm) != len(m) {
1486 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1489 for k, v := range newm {
1492 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1496 newmap.SetMapIndex(ValueOf("a"), Value{})
1499 t.Errorf("newm[\"a\"] = %d after delete", v)
1502 mv = ValueOf(&m).Elem()
1503 mv.Set(Zero(mv.Type()))
1505 t.Errorf("mv.Set(nil) failed")
1509 shouldPanic("not assignable", func() { mv.MapIndex(ValueOf(S("key"))) })
1510 shouldPanic("not assignable", func() { mv.SetMapIndex(ValueOf(S("key")), ValueOf(0)) })
1513 func TestNilMap(t *testing.T) {
1514 var m map[string]int
1516 keys := mv.MapKeys()
1518 t.Errorf(">0 keys for nil map: %v", keys)
1521 // Check that value for missing key is zero.
1522 x := mv.MapIndex(ValueOf("hello"))
1523 if x.Kind() != Invalid {
1524 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1527 // Check big value too.
1528 var mbig map[string][10 << 20]byte
1529 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1530 if x.Kind() != Invalid {
1531 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1534 // Test that deletes from a nil map succeed.
1535 mv.SetMapIndex(ValueOf("hi"), Value{})
1538 func TestChan(t *testing.T) {
1539 for loop := 0; loop < 2; loop++ {
1543 // check both ways to allocate channels
1546 c = make(chan int, 1)
1549 cv = MakeChan(TypeOf(c), 1)
1550 c = cv.Interface().(chan int)
1555 if i := <-c; i != 2 {
1556 t.Errorf("reflect Send 2, native recv %d", i)
1561 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1562 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1566 val, ok := cv.TryRecv()
1567 if val.IsValid() || ok {
1568 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1573 val, ok = cv.TryRecv()
1575 t.Errorf("TryRecv on ready chan got nil")
1576 } else if i := val.Int(); i != 4 || !ok {
1577 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1582 ok = cv.TrySend(ValueOf(5))
1585 t.Errorf("TrySend on full chan succeeded: value %d", i)
1589 ok = cv.TrySend(ValueOf(6))
1591 t.Errorf("TrySend on empty chan failed")
1594 t.Errorf("TrySend failed but it did send %d", x)
1598 if i = <-c; i != 6 {
1599 t.Errorf("TrySend 6, recv %d", i)
1606 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1607 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1609 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1610 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1614 // check creation of unbuffered channel
1616 cv := MakeChan(TypeOf(c), 0)
1617 c = cv.Interface().(chan int)
1618 if cv.TrySend(ValueOf(7)) {
1619 t.Errorf("TrySend on sync chan succeeded")
1621 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1622 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1626 cv = MakeChan(TypeOf(c), 10)
1627 c = cv.Interface().(chan int)
1628 for i := 0; i < 3; i++ {
1631 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1632 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1636 // caseInfo describes a single case in a select test.
1637 type caseInfo struct {
1646 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1648 func TestSelect(t *testing.T) {
1649 selectWatch.once.Do(func() { go selectWatcher() })
1653 newop := func(n int, cap int) (ch, val Value) {
1656 c := make(chan int, cap)
1660 c := make(chan string, cap)
1662 val = ValueOf(fmt.Sprint(n))
1667 for n := 0; x.Next(); n++ {
1668 if testing.Short() && n >= 1000 {
1671 if n >= 100000 && !*allselect {
1674 if n%100000 == 0 && testing.Verbose() {
1675 println("TestSelect", n)
1677 var cases []SelectCase
1682 ch, val := newop(len(cases), 1)
1683 cases = append(cases, SelectCase{
1688 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1693 ch, val := newop(len(cases), 1)
1695 cases = append(cases, SelectCase{
1699 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1704 ch, val := newop(len(cases), 0)
1705 cases = append(cases, SelectCase{
1712 f := func() { ch.Recv() }
1713 info = append(info, caseInfo{desc: "blocking send", helper: f})
1715 info = append(info, caseInfo{desc: "blocking send"})
1721 ch, val := newop(len(cases), 0)
1722 cases = append(cases, SelectCase{
1728 f := func() { ch.Send(val) }
1729 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1731 info = append(info, caseInfo{desc: "blocking recv"})
1737 // Maybe include value to send.
1742 cases = append(cases, SelectCase{
1746 info = append(info, caseInfo{desc: "zero Chan send"})
1749 // Zero Chan receive.
1751 cases = append(cases, SelectCase{
1754 info = append(info, caseInfo{desc: "zero Chan recv"})
1759 cases = append(cases, SelectCase{
1761 Chan: ValueOf((chan int)(nil)),
1764 info = append(info, caseInfo{desc: "nil Chan send"})
1769 cases = append(cases, SelectCase{
1771 Chan: ValueOf((chan int)(nil)),
1773 info = append(info, caseInfo{desc: "nil Chan recv"})
1776 // closed Chan send.
1778 ch := make(chan int)
1780 cases = append(cases, SelectCase{
1785 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1788 // closed Chan recv.
1790 ch, val := newop(len(cases), 0)
1792 val = Zero(val.Type())
1793 cases = append(cases, SelectCase{
1797 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1800 var helper func() // goroutine to help the select complete
1802 // Add default? Must be last case here, but will permute.
1803 // Add the default if the select would otherwise
1804 // block forever, and maybe add it anyway.
1810 for i, c := range info {
1818 } else if c.helper != nil {
1820 helpers = append(helpers, i)
1823 if !canProceed || x.Maybe() {
1824 cases = append(cases, SelectCase{
1827 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1829 } else if canBlock {
1830 // Select needs to communicate with another goroutine.
1831 cas := &info[helpers[x.Choose(len(helpers))]]
1833 cas.canSelect = true
1837 // Permute cases and case info.
1838 // Doing too much here makes the exhaustive loop
1839 // too exhausting, so just do two swaps.
1840 for loop := 0; loop < 2; loop++ {
1841 i := x.Choose(len(cases))
1842 j := x.Choose(len(cases))
1843 cases[i], cases[j] = cases[j], cases[i]
1844 info[i], info[j] = info[j], info[i]
1848 // We wait before kicking off a goroutine to satisfy a blocked select.
1849 // The pause needs to be big enough to let the select block before
1850 // we run the helper, but if we lose that race once in a while it's okay: the
1851 // select will just proceed immediately. Not a big deal.
1852 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1853 pause := 10 * time.Microsecond
1854 if testing.Short() {
1855 pause = 100 * time.Microsecond
1857 time.AfterFunc(pause, helper)
1861 i, recv, recvOK, panicErr := runSelect(cases, info)
1862 if panicErr != nil && !canPanic {
1863 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1865 if panicErr == nil && canPanic && numCanSelect == 1 {
1866 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1868 if panicErr != nil {
1876 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1878 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1882 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1886 if cases[i].Dir == SelectRecv {
1887 if !recv.IsValid() {
1888 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1890 if !cas.recv.IsValid() {
1891 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1893 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1894 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1895 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1897 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1900 if recv.IsValid() || recvOK {
1901 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1907 func TestSelectMaxCases(t *testing.T) {
1908 var sCases []SelectCase
1909 channel := make(chan int)
1911 for i := 0; i < 65536; i++ {
1912 sCases = append(sCases, SelectCase{
1914 Chan: ValueOf(channel),
1918 _, _, _ = Select(sCases)
1919 sCases = append(sCases, SelectCase{
1921 Chan: ValueOf(channel),
1924 if err := recover(); err != nil {
1925 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1926 t.Fatalf("unexpected error from select call with greater than max supported cases")
1929 t.Fatalf("expected select call to panic with greater than max supported cases")
1933 _, _, _ = Select(sCases)
1936 func TestSelectNop(t *testing.T) {
1937 // "select { default: }" should always return the default case.
1938 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1940 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1944 func BenchmarkSelect(b *testing.B) {
1945 channel := make(chan int)
1947 var cases []SelectCase
1948 for i := 0; i < 8; i++ {
1949 cases = append(cases, SelectCase{
1951 Chan: ValueOf(channel),
1954 for _, numCases := range []int{1, 4, 8} {
1955 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1957 for i := 0; i < b.N; i++ {
1958 _, _, _ = Select(cases[:numCases])
1964 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1965 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1966 // an error describing the select and panics the entire test binary.
1967 var selectWatch struct {
1974 func selectWatcher() {
1976 time.Sleep(1 * time.Second)
1978 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1979 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1980 panic("select stuck")
1982 selectWatch.Unlock()
1986 // runSelect runs a single select test.
1987 // It returns the values returned by Select but also returns
1988 // a panic value if the Select panics.
1989 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
1991 panicErr = recover()
1994 selectWatch.info = nil
1995 selectWatch.Unlock()
1999 selectWatch.now = time.Now()
2000 selectWatch.info = info
2001 selectWatch.Unlock()
2003 chosen, recv, recvOK = Select(cases)
2007 // fmtSelect formats the information about a single select test.
2008 func fmtSelect(info []caseInfo) string {
2009 var buf bytes.Buffer
2010 fmt.Fprintf(&buf, "\nselect {\n")
2011 for i, cas := range info {
2012 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2013 if cas.recv.IsValid() {
2014 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2017 fmt.Fprintf(&buf, " canselect")
2020 fmt.Fprintf(&buf, " panic")
2022 fmt.Fprintf(&buf, "\n")
2024 fmt.Fprintf(&buf, "}")
2030 // Difficult test for function call because of
2031 // implicit padding between arguments.
2032 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) {
2033 return b, c, d, e, f, g, h
2036 func TestFunc(t *testing.T) {
2037 ret := ValueOf(dummy).Call([]Value{
2041 ValueOf(two{40, 50}),
2043 ValueOf(float32(70)),
2047 t.Fatalf("Call returned %d values, want 7", len(ret))
2050 i := byte(ret[0].Uint())
2051 j := int(ret[1].Int())
2052 k := byte(ret[2].Uint())
2053 l := ret[3].Interface().(two)
2054 m := byte(ret[4].Uint())
2055 n := float32(ret[5].Float())
2056 o := byte(ret[6].Uint())
2058 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2059 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)
2062 for i, v := range ret {
2064 t.Errorf("result %d is addressable", i)
2069 func TestCallConvert(t *testing.T) {
2070 v := ValueOf(new(io.ReadWriter)).Elem()
2071 f := ValueOf(func(r io.Reader) io.Reader { return r })
2072 out := f.Call([]Value{v})
2073 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2074 t.Errorf("expected [nil], got %v", out)
2078 type emptyStruct struct{}
2080 type nonEmptyStruct struct {
2084 func returnEmpty() emptyStruct {
2085 return emptyStruct{}
2088 func takesEmpty(e emptyStruct) {
2091 func returnNonEmpty(i int) nonEmptyStruct {
2092 return nonEmptyStruct{member: i}
2095 func takesNonEmpty(n nonEmptyStruct) int {
2099 func TestCallWithStruct(t *testing.T) {
2100 r := ValueOf(returnEmpty).Call(nil)
2101 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2102 t.Errorf("returning empty struct returned %#v instead", r)
2104 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2106 t.Errorf("takesEmpty returned values: %#v", r)
2108 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2109 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2110 t.Errorf("returnNonEmpty returned %#v", r)
2112 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2113 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2114 t.Errorf("takesNonEmpty returned %#v", r)
2118 func TestCallReturnsEmpty(t *testing.T) {
2119 // Issue 21717: past-the-end pointer write in Call with
2120 // nonzero-sized frame and zero-sized return value.
2122 var finalized uint32
2123 f := func() (emptyStruct, *[2]int64) {
2124 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2125 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2126 return emptyStruct{}, i
2128 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2129 timeout := time.After(5 * time.Second)
2130 for atomic.LoadUint32(&finalized) == 0 {
2133 t.Fatal("finalizer did not run")
2139 runtime.KeepAlive(v)
2142 func BenchmarkCall(b *testing.B) {
2143 fv := ValueOf(func(a, b string) {})
2145 b.RunParallel(func(pb *testing.PB) {
2146 args := []Value{ValueOf("a"), ValueOf("b")}
2155 func (i *myint) inc() {
2159 func BenchmarkCallMethod(b *testing.B) {
2164 for i := 0; i < b.N; i++ {
2169 func BenchmarkCallArgCopy(b *testing.B) {
2170 byteArray := func(n int) Value {
2171 return Zero(ArrayOf(n, TypeOf(byte(0))))
2173 sizes := [...]struct {
2177 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2178 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2179 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2180 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2181 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2183 for _, size := range sizes {
2184 bench := func(b *testing.B) {
2185 args := []Value{size.arg}
2186 b.SetBytes(int64(size.arg.Len()))
2188 b.RunParallel(func(pb *testing.PB) {
2194 name := fmt.Sprintf("size=%v", size.arg.Len())
2199 func TestMakeFunc(t *testing.T) {
2201 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2202 ValueOf(&f).Elem().Set(fv)
2204 // Call g with small arguments so that there is
2205 // something predictable (and different from the
2206 // correct results) in those positions on the stack.
2208 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2210 // Call constructed function f.
2211 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2212 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2213 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)
2217 func TestMakeFuncInterface(t *testing.T) {
2218 fn := func(i int) int { return i }
2219 incr := func(in []Value) []Value {
2220 return []Value{ValueOf(int(in[0].Int() + 1))}
2222 fv := MakeFunc(TypeOf(fn), incr)
2223 ValueOf(&fn).Elem().Set(fv)
2224 if r := fn(2); r != 3 {
2225 t.Errorf("Call returned %d, want 3", r)
2227 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2228 t.Errorf("Call returned %d, want 15", r)
2230 if r := fv.Interface().(func(int) int)(26); r != 27 {
2231 t.Errorf("Call returned %d, want 27", r)
2235 func TestMakeFuncVariadic(t *testing.T) {
2236 // Test that variadic arguments are packed into a slice and passed as last arg
2237 fn := func(_ int, is ...int) []int { return nil }
2238 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2239 ValueOf(&fn).Elem().Set(fv)
2242 if r[0] != 2 || r[1] != 3 {
2243 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2246 r = fn(1, []int{2, 3}...)
2247 if r[0] != 2 || r[1] != 3 {
2248 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2251 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2252 if r[0] != 2 || r[1] != 3 {
2253 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2256 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2257 if r[0] != 2 || r[1] != 3 {
2258 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2261 f := fv.Interface().(func(int, ...int) []int)
2264 if r[0] != 2 || r[1] != 3 {
2265 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2267 r = f(1, []int{2, 3}...)
2268 if r[0] != 2 || r[1] != 3 {
2269 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2273 // Dummy type that implements io.WriteCloser
2277 func (w *WC) Write(p []byte) (n int, err error) {
2280 func (w *WC) Close() error {
2284 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2285 // reflect.Values returned from the wrapped function should be assignment-converted
2286 // to the types returned by the result of MakeFunc.
2288 // Concrete types should be promotable to interfaces they implement.
2290 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2291 return []Value{ValueOf(io.EOF)}
2292 }).Interface().(func() error)
2295 // Super-interfaces should be promotable to simpler interfaces.
2296 var g func() io.Writer
2297 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2298 var w io.WriteCloser = &WC{}
2299 return []Value{ValueOf(&w).Elem()}
2300 }).Interface().(func() io.Writer)
2303 // Channels should be promotable to directional channels.
2304 var h func() <-chan int
2305 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2306 return []Value{ValueOf(make(chan int))}
2307 }).Interface().(func() <-chan int)
2310 // Unnamed types should be promotable to named types.
2311 type T struct{ a, b, c int }
2313 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2314 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2315 }).Interface().(func() T)
2319 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2320 // Type doesn't implement the required interface.
2321 shouldPanic("", func() {
2323 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2324 return []Value{ValueOf(int(7))}
2325 }).Interface().(func() error)
2328 // Assigning to an interface with additional methods.
2329 shouldPanic("", func() {
2330 var f func() io.ReadWriteCloser
2331 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2332 var w io.WriteCloser = &WC{}
2333 return []Value{ValueOf(&w).Elem()}
2334 }).Interface().(func() io.ReadWriteCloser)
2337 // Directional channels can't be assigned to bidirectional ones.
2338 shouldPanic("", func() {
2339 var f func() chan int
2340 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2341 var c <-chan int = make(chan int)
2342 return []Value{ValueOf(c)}
2343 }).Interface().(func() chan int)
2346 // Two named types which are otherwise identical.
2347 shouldPanic("", func() {
2348 type T struct{ a, b, c int }
2349 type U struct{ a, b, c int }
2351 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2352 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2353 }).Interface().(func() T)
2362 // This will be index 0.
2363 func (p Point) AnotherMethod(scale int) int {
2367 // This will be index 1.
2368 func (p Point) Dist(scale int) int {
2369 //println("Point.Dist", p.x, p.y, scale)
2370 return p.x*p.x*scale + p.y*p.y*scale
2373 // This will be index 2.
2374 func (p Point) GCMethod(k int) int {
2379 // This will be index 3.
2380 func (p Point) NoArgs() {
2381 // Exercise no-argument/no-result paths.
2384 // This will be index 4.
2385 func (p Point) TotalDist(points ...Point) int {
2387 for _, q := range points {
2390 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2396 // This will be index 5.
2397 func (p *Point) Int64Method(x int64) int64 {
2401 // This will be index 6.
2402 func (p *Point) Int32Method(x int32) int32 {
2406 func TestMethod(t *testing.T) {
2407 // Non-curried method of type.
2409 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2411 t.Errorf("Type Method returned %d; want 250", i)
2414 m, ok := TypeOf(p).MethodByName("Dist")
2416 t.Fatalf("method by name failed")
2418 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2420 t.Errorf("Type MethodByName returned %d; want 275", i)
2423 m, ok = TypeOf(p).MethodByName("NoArgs")
2425 t.Fatalf("method by name failed")
2427 n := len(m.Func.Call([]Value{ValueOf(p)}))
2429 t.Errorf("NoArgs returned %d values; want 0", n)
2432 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2434 t.Errorf("Pointer Type Method returned %d; want 300", i)
2437 m, ok = TypeOf(&p).MethodByName("Dist")
2439 t.Fatalf("ptr method by name failed")
2441 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2443 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2446 m, ok = TypeOf(&p).MethodByName("NoArgs")
2448 t.Fatalf("method by name failed")
2450 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2452 t.Errorf("NoArgs returned %d values; want 0", n)
2455 // Curried method of value.
2456 tfunc := TypeOf((func(int) int)(nil))
2457 v := ValueOf(p).Method(1)
2458 if tt := v.Type(); tt != tfunc {
2459 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2461 i = v.Call([]Value{ValueOf(14)})[0].Int()
2463 t.Errorf("Value Method returned %d; want 350", i)
2465 v = ValueOf(p).MethodByName("Dist")
2466 if tt := v.Type(); tt != tfunc {
2467 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2469 i = v.Call([]Value{ValueOf(15)})[0].Int()
2471 t.Errorf("Value MethodByName returned %d; want 375", i)
2473 v = ValueOf(p).MethodByName("NoArgs")
2476 // Curried method of pointer.
2477 v = ValueOf(&p).Method(1)
2478 if tt := v.Type(); tt != tfunc {
2479 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2481 i = v.Call([]Value{ValueOf(16)})[0].Int()
2483 t.Errorf("Pointer Value Method returned %d; want 400", i)
2485 v = ValueOf(&p).MethodByName("Dist")
2486 if tt := v.Type(); tt != tfunc {
2487 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2489 i = v.Call([]Value{ValueOf(17)})[0].Int()
2491 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2493 v = ValueOf(&p).MethodByName("NoArgs")
2496 // Curried method of interface value.
2497 // Have to wrap interface value in a struct to get at it.
2498 // Passing it to ValueOf directly would
2499 // access the underlying Point, not the interface.
2503 pv := ValueOf(&x).Elem()
2505 if tt := v.Type(); tt != tfunc {
2506 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2508 i = v.Call([]Value{ValueOf(18)})[0].Int()
2510 t.Errorf("Interface Method returned %d; want 450", i)
2512 v = pv.MethodByName("Dist")
2513 if tt := v.Type(); tt != tfunc {
2514 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2516 i = v.Call([]Value{ValueOf(19)})[0].Int()
2518 t.Errorf("Interface MethodByName returned %d; want 475", i)
2522 func TestMethodValue(t *testing.T) {
2526 // Check that method value have the same underlying code pointers.
2527 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2528 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2531 // Curried method of value.
2532 tfunc := TypeOf((func(int) int)(nil))
2533 v := ValueOf(p).Method(1)
2534 if tt := v.Type(); tt != tfunc {
2535 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2537 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2539 t.Errorf("Value Method returned %d; want 250", i)
2541 v = ValueOf(p).MethodByName("Dist")
2542 if tt := v.Type(); tt != tfunc {
2543 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2545 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2547 t.Errorf("Value MethodByName returned %d; want 275", i)
2549 v = ValueOf(p).MethodByName("NoArgs")
2550 ValueOf(v.Interface()).Call(nil)
2551 v.Interface().(func())()
2553 // Curried method of pointer.
2554 v = ValueOf(&p).Method(1)
2555 if tt := v.Type(); tt != tfunc {
2556 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2558 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2560 t.Errorf("Pointer Value Method returned %d; want 300", i)
2562 v = ValueOf(&p).MethodByName("Dist")
2563 if tt := v.Type(); tt != tfunc {
2564 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2566 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2568 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2570 v = ValueOf(&p).MethodByName("NoArgs")
2571 ValueOf(v.Interface()).Call(nil)
2572 v.Interface().(func())()
2574 // Curried method of pointer to pointer.
2576 v = ValueOf(&pp).Elem().Method(1)
2577 if tt := v.Type(); tt != tfunc {
2578 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2580 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2582 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2584 v = ValueOf(&pp).Elem().MethodByName("Dist")
2585 if tt := v.Type(); tt != tfunc {
2586 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2588 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2590 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2593 // Curried method of interface value.
2594 // Have to wrap interface value in a struct to get at it.
2595 // Passing it to ValueOf directly would
2596 // access the underlying Point, not the interface.
2602 pv := ValueOf(s).Field(0)
2604 if tt := v.Type(); tt != tfunc {
2605 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2607 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2609 t.Errorf("Interface Method returned %d; want 400", i)
2611 v = pv.MethodByName("Dist")
2612 if tt := v.Type(); tt != tfunc {
2613 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2615 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2617 t.Errorf("Interface MethodByName returned %d; want 425", i)
2620 // For issue #33628: method args are not stored at the right offset
2622 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2623 if x := m64(123); x != 123 {
2624 t.Errorf("Int64Method returned %d; want 123", x)
2626 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2627 if x := m32(456); x != 456 {
2628 t.Errorf("Int32Method returned %d; want 456", x)
2632 func TestVariadicMethodValue(t *testing.T) {
2634 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2635 want := int64(p.TotalDist(points[0], points[1], points[2]))
2637 // Variadic method of type.
2638 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2639 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2640 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2643 // Curried method of value.
2644 tfunc = TypeOf((func(...Point) int)(nil))
2645 v := ValueOf(p).Method(4)
2646 if tt := v.Type(); tt != tfunc {
2647 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2649 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2651 t.Errorf("Variadic Method returned %d; want %d", i, want)
2653 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2655 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2658 f := v.Interface().(func(...Point) int)
2659 i = int64(f(points[0], points[1], points[2]))
2661 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2663 i = int64(f(points...))
2665 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2669 type DirectIfaceT struct {
2673 func (d DirectIfaceT) M() int { return *d.p }
2675 func TestDirectIfaceMethod(t *testing.T) {
2677 v := DirectIfaceT{&x}
2679 m, ok := typ.MethodByName("M")
2681 t.Fatalf("cannot find method M")
2683 in := []Value{ValueOf(v)}
2684 out := m.Func.Call(in)
2685 if got := out[0].Int(); got != 42 {
2686 t.Errorf("Call with value receiver got %d, want 42", got)
2691 m, ok = typ.MethodByName("M")
2693 t.Fatalf("cannot find method M")
2695 in = []Value{ValueOf(pv)}
2696 out = m.Func.Call(in)
2697 if got := out[0].Int(); got != 42 {
2698 t.Errorf("Call with pointer receiver got %d, want 42", got)
2702 // Reflect version of $GOROOT/test/method5.go
2704 // Concrete types implementing M method.
2705 // Smaller than a word, word-sized, larger than a word.
2706 // Value and pointer receivers.
2708 type Tinter interface {
2709 M(int, byte) (byte, int)
2714 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2718 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2722 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2726 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2728 type Tbigv [2]uintptr
2730 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2732 type Tbigp [2]uintptr
2734 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2736 type tinter interface {
2737 m(int, byte) (byte, int)
2740 // Embedding via pointer.
2757 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2759 func TestMethod5(t *testing.T) {
2760 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2762 if b != 99 || x != 1000+inc {
2763 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2767 CheckV := func(name string, i Value, inc int) {
2768 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2769 b := bx[0].Interface()
2770 x := bx[1].Interface()
2771 if b != byte(99) || x != 1000+inc {
2772 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2775 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2778 var TinterType = TypeOf(new(Tinter)).Elem()
2780 CheckI := func(name string, i any, inc int) {
2782 CheckV(name, v, inc)
2783 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2788 CheckI("&sv", &sv, 1)
2791 CheckI("&sp", &sp, 2)
2795 CheckI("&wv", &wv, 3)
2798 CheckI("&wp", &wp, 4)
2800 bv := Tbigv([2]uintptr{5, 6})
2801 CheckI("bv", bv, 11)
2802 CheckI("&bv", &bv, 11)
2804 bp := Tbigp([2]uintptr{7, 8})
2805 CheckI("&bp", &bp, 15)
2811 CheckI("t4", t4, 40)
2812 CheckI("&t4", &t4, 40)
2813 CheckI("t3", t3, 40)
2814 CheckI("&t3", &t3, 40)
2815 CheckI("t2", t2, 40)
2816 CheckI("&t2", &t2, 40)
2817 CheckI("t1", t1, 40)
2818 CheckI("&t1", &t1, 40)
2821 vnil := ValueOf(&tnil).Elem()
2822 shouldPanic("Method", func() { vnil.Method(0) })
2825 func TestInterfaceSet(t *testing.T) {
2834 sv := ValueOf(&s).Elem()
2835 sv.Field(0).Set(ValueOf(p))
2836 if q := s.I.(*Point); q != p {
2837 t.Errorf("i: have %p want %p", q, p)
2842 if q := s.P.(*Point); q != p {
2843 t.Errorf("i: have %p want %p", q, p)
2846 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2848 t.Errorf("Interface Method returned %d; want 250", i)
2857 func TestAnonymousFields(t *testing.T) {
2858 var field StructField
2862 if field, ok = type1.FieldByName("int"); !ok {
2863 t.Fatal("no field 'int'")
2865 if field.Index[0] != 1 {
2866 t.Error("field index should be 1; is", field.Index)
2920 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2942 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2961 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2975 var fieldTests = []FTest{
2976 {struct{}{}, "", nil, 0},
2977 {struct{}{}, "Foo", nil, 0},
2978 {S0{A: 'a'}, "A", []int{0}, 'a'},
2979 {S0{}, "D", nil, 0},
2980 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2981 {S1{B: 'b'}, "B", []int{0}, 'b'},
2982 {S1{}, "S0", []int{1}, 0},
2983 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2984 {S2{A: 'a'}, "A", []int{0}, 'a'},
2985 {S2{}, "S1", []int{1}, 0},
2986 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2987 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2988 {S2{}, "D", nil, 0},
2989 {S3{}, "S1", nil, 0},
2990 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2991 {S3{}, "B", nil, 0},
2992 {S3{D: 'd'}, "D", []int{2}, 0},
2993 {S3{E: 'e'}, "E", []int{3}, 'e'},
2994 {S4{A: 'a'}, "A", []int{1}, 'a'},
2995 {S4{}, "B", nil, 0},
2996 {S5{}, "X", nil, 0},
2997 {S5{}, "Y", []int{2, 0, 1}, 0},
2998 {S10{}, "X", nil, 0},
2999 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
3000 {S14{}, "X", nil, 0},
3003 func TestFieldByIndex(t *testing.T) {
3004 for _, test := range fieldTests {
3006 f := s.FieldByIndex(test.index)
3008 if test.index != nil {
3009 if f.Name != test.name {
3010 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3013 t.Errorf("%s.%s found", s.Name(), f.Name)
3015 } else if len(test.index) > 0 {
3016 t.Errorf("%s.%s not found", s.Name(), test.name)
3019 if test.value != 0 {
3020 v := ValueOf(test.s).FieldByIndex(test.index)
3022 if x, ok := v.Interface().(int); ok {
3023 if x != test.value {
3024 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3027 t.Errorf("%s%v value not an int", s.Name(), test.index)
3030 t.Errorf("%s%v value not found", s.Name(), test.index)
3036 func TestFieldByName(t *testing.T) {
3037 for _, test := range fieldTests {
3039 f, found := s.FieldByName(test.name)
3041 if test.index != nil {
3042 // Verify field depth and index.
3043 if len(f.Index) != len(test.index) {
3044 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)
3046 for i, x := range f.Index {
3047 if x != test.index[i] {
3048 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3053 t.Errorf("%s.%s found", s.Name(), f.Name)
3055 } else if len(test.index) > 0 {
3056 t.Errorf("%s.%s not found", s.Name(), test.name)
3059 if test.value != 0 {
3060 v := ValueOf(test.s).FieldByName(test.name)
3062 if x, ok := v.Interface().(int); ok {
3063 if x != test.value {
3064 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3067 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3070 t.Errorf("%s.%s value not found", s.Name(), test.name)
3076 func TestImportPath(t *testing.T) {
3081 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3082 {TypeOf(int(0)), ""},
3083 {TypeOf(int8(0)), ""},
3084 {TypeOf(int16(0)), ""},
3085 {TypeOf(int32(0)), ""},
3086 {TypeOf(int64(0)), ""},
3087 {TypeOf(uint(0)), ""},
3088 {TypeOf(uint8(0)), ""},
3089 {TypeOf(uint16(0)), ""},
3090 {TypeOf(uint32(0)), ""},
3091 {TypeOf(uint64(0)), ""},
3092 {TypeOf(uintptr(0)), ""},
3093 {TypeOf(float32(0)), ""},
3094 {TypeOf(float64(0)), ""},
3095 {TypeOf(complex64(0)), ""},
3096 {TypeOf(complex128(0)), ""},
3097 {TypeOf(byte(0)), ""},
3098 {TypeOf(rune(0)), ""},
3099 {TypeOf([]byte(nil)), ""},
3100 {TypeOf([]rune(nil)), ""},
3101 {TypeOf(string("")), ""},
3102 {TypeOf((*any)(nil)).Elem(), ""},
3103 {TypeOf((*byte)(nil)), ""},
3104 {TypeOf((*rune)(nil)), ""},
3105 {TypeOf((*int64)(nil)), ""},
3106 {TypeOf(map[string]int{}), ""},
3107 {TypeOf((*error)(nil)).Elem(), ""},
3108 {TypeOf((*Point)(nil)), ""},
3109 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3111 for _, test := range tests {
3112 if path := test.t.PkgPath(); path != test.path {
3113 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3118 func TestFieldPkgPath(t *testing.T) {
3120 typ := TypeOf(struct {
3128 type pkgpathTest struct {
3135 checkPkgPath := func(name string, s []pkgpathTest) {
3136 for _, test := range s {
3137 f := typ.FieldByIndex(test.index)
3138 if got, want := f.PkgPath, test.pkgPath; got != want {
3139 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3141 if got, want := f.Anonymous, test.embedded; got != want {
3142 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3144 if got, want := f.IsExported(), test.exported; got != want {
3145 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3150 checkPkgPath("testStruct", []pkgpathTest{
3151 {[]int{0}, "", false, true}, // Exported
3152 {[]int{1}, "reflect_test", false, false}, // unexported
3153 {[]int{2}, "", true, true}, // OtherPkgFields
3154 {[]int{2, 0}, "", false, true}, // OtherExported
3155 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3156 {[]int{3}, "reflect_test", true, false}, // int
3157 {[]int{4}, "reflect_test", true, false}, // *x
3160 type localOtherPkgFields OtherPkgFields
3161 typ = TypeOf(localOtherPkgFields{})
3162 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3163 {[]int{0}, "", false, true}, // OtherExported
3164 {[]int{1}, "reflect", false, false}, // otherUnexported
3168 func TestMethodPkgPath(t *testing.T) {
3173 typ := TypeOf((*interface {
3186 {"x", "reflect_test", false},
3187 {"y", "reflect_test", false},
3190 for _, test := range tests {
3191 m, _ := typ.MethodByName(test.name)
3192 if got, want := m.PkgPath, test.pkgPath; got != want {
3193 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3195 if got, want := m.IsExported(), test.exported; got != want {
3196 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3201 func TestVariadicType(t *testing.T) {
3202 // Test example from Type documentation.
3203 var f func(x int, y ...float64)
3205 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3207 if sl.Kind() == Slice {
3208 if sl.Elem() == TypeOf(0.0) {
3216 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3217 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3218 for i := 0; i < typ.NumIn(); i++ {
3219 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3233 func (*inner) M() {}
3234 func (*outer) M() {}
3236 func TestNestedMethods(t *testing.T) {
3237 typ := TypeOf((*outer)(nil))
3238 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3239 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3240 for i := 0; i < typ.NumMethod(); i++ {
3242 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3249 func (*unexp) f() (int32, int8) { return 7, 7 }
3250 func (*unexp) g() (int64, int8) { return 8, 8 }
3252 type unexpI interface {
3256 var unexpi unexpI = new(unexp)
3258 func TestUnexportedMethods(t *testing.T) {
3259 typ := TypeOf(unexpi)
3261 if got := typ.NumMethod(); got != 0 {
3262 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3266 type InnerInt struct {
3270 type OuterInt struct {
3275 func (i *InnerInt) M() int {
3279 func TestEmbeddedMethods(t *testing.T) {
3280 typ := TypeOf((*OuterInt)(nil))
3281 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3282 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3283 for i := 0; i < typ.NumMethod(); i++ {
3285 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3290 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3291 t.Errorf("i.M() = %d, want 3", v)
3294 o := &OuterInt{1, InnerInt{2}}
3295 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3296 t.Errorf("i.M() = %d, want 2", v)
3300 if v := f(o); v != 2 {
3301 t.Errorf("f(o) = %d, want 2", v)
3305 type FuncDDD func(...any) error
3307 func (f FuncDDD) M() {}
3309 func TestNumMethodOnDDD(t *testing.T) {
3310 rv := ValueOf((FuncDDD)(nil))
3311 if n := rv.NumMethod(); n != 1 {
3312 t.Fatalf("NumMethod()=%d, want 1", n)
3316 func TestPtrTo(t *testing.T) {
3317 // This block of code means that the ptrToThis field of the
3318 // reflect data for *unsafe.Pointer is non zero, see
3319 // https://golang.org/issue/19003
3320 var x unsafe.Pointer
3327 for i = 0; i < 100; i++ {
3328 typ = PointerTo(typ)
3330 for i = 0; i < 100; i++ {
3333 if typ != TypeOf(z) {
3334 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3338 func TestPtrToGC(t *testing.T) {
3340 tt := TypeOf(T(nil))
3344 for i := 0; i < n; i++ {
3349 v.Elem().Set(ValueOf(p).Convert(pt))
3350 x = append(x, v.Interface())
3354 for i, xi := range x {
3355 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3356 if k != uintptr(i) {
3357 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3362 func BenchmarkPtrTo(b *testing.B) {
3363 // Construct a type with a zero ptrToThis.
3364 type T struct{ int }
3365 t := SliceOf(TypeOf(T{}))
3366 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3367 if !ptrToThis.IsValid() {
3368 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3370 if ptrToThis.Int() != 0 {
3371 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3375 // Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on
3377 b.RunParallel(func(pb *testing.PB) {
3384 func TestAddr(t *testing.T) {
3396 t.Errorf("Addr.Elem.Set failed to set value")
3399 // Again but take address of the ValueOf value.
3400 // Exercises generation of PtrTypes not present in the binary.
3402 v = ValueOf(&q).Elem()
3411 t.Errorf("Addr.Elem.Set failed to set value")
3414 // Starting without pointer we should get changed value
3417 v = ValueOf(&qq).Elem()
3423 if p.X != 3 { // should be unchanged from last time
3424 t.Errorf("somehow value Set changed original p")
3426 p = v0.Interface().(struct {
3430 t.Errorf("Addr.Elem.Set valued to set value in top value")
3433 // Verify that taking the address of a type gives us a pointer
3434 // which we can convert back using the usual interface
3439 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3440 *(ps.(**bool)) = new(bool)
3442 t.Errorf("Addr.Interface direct assignment failed")
3446 func noAlloc(t *testing.T, n int, f func(int)) {
3447 if testing.Short() {
3448 t.Skip("skipping malloc count in short mode")
3450 if runtime.GOMAXPROCS(0) > 1 {
3451 t.Skip("skipping; GOMAXPROCS>1")
3454 allocs := testing.AllocsPerRun(n, func() {
3459 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3463 func TestAllocations(t *testing.T) {
3464 noAlloc(t, 100, func(j int) {
3468 // We can uncomment this when compiler escape analysis
3469 // is good enough to see that the integer assigned to i
3470 // does not escape and therefore need not be allocated.
3474 // if int(v.Int()) != 42+j {
3475 // panic("wrong int")
3478 i = func(j int) int { return j }
3480 if v.Interface().(func(int) int)(j) != j {
3481 panic("wrong result")
3486 func TestSmallNegativeInt(t *testing.T) {
3490 t.Errorf("int16(-1).Int() returned %v", v.Int())
3494 func TestIndex(t *testing.T) {
3495 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3496 v := ValueOf(xs).Index(3).Interface().(byte)
3498 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3500 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3501 v = ValueOf(xa).Index(2).Interface().(byte)
3503 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3506 v = ValueOf(s).Index(3).Interface().(byte)
3508 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3512 func TestSlice(t *testing.T) {
3513 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3514 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3516 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3519 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3521 if !DeepEqual(v[0:5], xs[3:]) {
3522 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3524 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3525 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3527 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3530 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3532 if !DeepEqual(v[0:6], xa[2:]) {
3533 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3536 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3538 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3541 rv := ValueOf(&xs).Elem()
3543 ptr2 := rv.UnsafePointer()
3545 ptr3 := rv.UnsafePointer()
3547 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3551 func TestSlice3(t *testing.T) {
3552 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3553 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3555 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3558 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3560 if !DeepEqual(v[0:4], xs[3:7:7]) {
3561 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3563 rv := ValueOf(&xs).Elem()
3564 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3565 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3566 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3568 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3569 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3571 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3574 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3576 if !DeepEqual(v[0:4], xa[2:6:6]) {
3577 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3579 rv = ValueOf(&xa).Elem()
3580 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3581 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3582 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3585 rv = ValueOf(&s).Elem()
3586 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3588 rv = ValueOf(&xs).Elem()
3589 rv = rv.Slice3(3, 5, 7)
3590 ptr2 := rv.UnsafePointer()
3591 rv = rv.Slice3(4, 4, 4)
3592 ptr3 := rv.UnsafePointer()
3594 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3598 func TestSetLenCap(t *testing.T) {
3599 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3600 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3602 vs := ValueOf(&xs).Elem()
3603 shouldPanic("SetLen", func() { vs.SetLen(10) })
3604 shouldPanic("SetCap", func() { vs.SetCap(10) })
3605 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3606 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3607 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3609 if len(xs) != 5 || cap(xs) != 8 {
3610 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3613 if len(xs) != 5 || cap(xs) != 6 {
3614 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3617 if len(xs) != 5 || cap(xs) != 5 {
3618 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3620 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3621 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3623 va := ValueOf(&xa).Elem()
3624 shouldPanic("SetLen", func() { va.SetLen(8) })
3625 shouldPanic("SetCap", func() { va.SetCap(8) })
3628 func TestVariadic(t *testing.T) {
3633 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3634 if b.String() != "hello, 42 world" {
3635 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3639 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3640 if b.String() != "hello, 42 world" {
3641 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3645 func TestFuncArg(t *testing.T) {
3646 f1 := func(i int, f func(int) int) int { return f(i) }
3647 f2 := func(i int) int { return i + 1 }
3648 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3649 if r[0].Int() != 101 {
3650 t.Errorf("function returned %d, want 101", r[0].Int())
3654 func TestStructArg(t *testing.T) {
3655 type padded struct {
3662 wantA = padded{"3", 4}
3665 f := func(a padded, b uint32) {
3668 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3669 if gotA != wantA || gotB != wantB {
3670 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3674 var tagGetTests = []struct {
3679 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3680 {`protobuf:"PB(1,2)"`, `foo`, ``},
3681 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3682 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3683 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3684 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3685 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3688 func TestTagGet(t *testing.T) {
3689 for _, tt := range tagGetTests {
3690 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3691 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3696 func TestBytes(t *testing.T) {
3697 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3698 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3702 y := ValueOf(x).Bytes()
3703 if !bytes.Equal(x, y) {
3704 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3707 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3712 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3713 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3714 b := ValueOf(&a).Elem().Bytes()
3715 if !bytes.Equal(a[:], y) {
3716 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3719 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3722 // Per issue #24746, it was decided that Bytes can be called on byte slices
3723 // that normally cannot be converted from per Go language semantics.
3727 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3728 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3729 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3730 ValueOf(new(AB)).Elem().Bytes() // should not panic
3733 func TestSetBytes(t *testing.T) {
3736 y := []byte{1, 2, 3, 4}
3737 ValueOf(&x).Elem().SetBytes(y)
3738 if !bytes.Equal(x, y) {
3739 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3742 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3746 type Private struct {
3752 func (p *Private) m() {
3755 type private struct {
3763 func (p *private) P() {
3766 type Public struct {
3772 func (p *Public) M() {
3775 func TestUnexported(t *testing.T) {
3780 isValid(v.Elem().Field(0))
3781 isValid(v.Elem().Field(1))
3782 isValid(v.Elem().Field(2))
3783 isValid(v.Elem().FieldByName("X"))
3784 isValid(v.Elem().FieldByName("Y"))
3785 isValid(v.Elem().FieldByName("Z"))
3786 isValid(v.Type().Method(0).Func)
3787 m, _ := v.Type().MethodByName("M")
3789 m, _ = v.Type().MethodByName("P")
3791 isNonNil(v.Elem().Field(0).Interface())
3792 isNonNil(v.Elem().Field(1).Interface())
3793 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3794 isNonNil(v.Elem().FieldByName("X").Interface())
3795 isNonNil(v.Elem().FieldByName("Y").Interface())
3796 isNonNil(v.Elem().FieldByName("Z").Interface())
3797 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3798 isNonNil(v.Type().Method(0).Func.Interface())
3799 m, _ = v.Type().MethodByName("P")
3800 isNonNil(m.Func.Interface())
3804 isValid(v.Elem().Field(0))
3805 isValid(v.Elem().Field(1))
3806 isValid(v.Elem().FieldByName("x"))
3807 isValid(v.Elem().FieldByName("y"))
3808 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3809 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3810 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3811 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3812 shouldPanic("Method", func() { v.Type().Method(0) })
3815 func TestSetPanic(t *testing.T) {
3816 ok := func(f func()) { f() }
3817 bad := func(f func()) { shouldPanic("Set", f) }
3818 clear := func(v Value) { v.Set(Zero(v.Type())) }
3846 bad(func() { clear(v.Field(0)) }) // .X
3847 bad(func() { clear(v.Field(1)) }) // .t1
3848 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3849 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3850 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3851 bad(func() { clear(v.Field(2)) }) // .T2
3852 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3853 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3854 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3855 bad(func() { clear(v.Field(3)) }) // .NamedT1
3856 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3857 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3858 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3859 bad(func() { clear(v.Field(4)) }) // .NamedT2
3860 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3861 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3862 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3863 bad(func() { clear(v.Field(5)) }) // .namedT1
3864 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3865 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3866 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3867 bad(func() { clear(v.Field(6)) }) // .namedT2
3868 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3869 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3870 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3873 v = ValueOf(&T{}).Elem()
3874 ok(func() { clear(v.Field(0)) }) // .X
3875 bad(func() { clear(v.Field(1)) }) // .t1
3876 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3877 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3878 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3879 ok(func() { clear(v.Field(2)) }) // .T2
3880 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3881 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3882 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3883 ok(func() { clear(v.Field(3)) }) // .NamedT1
3884 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3885 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3886 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3887 ok(func() { clear(v.Field(4)) }) // .NamedT2
3888 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3889 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3890 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3891 bad(func() { clear(v.Field(5)) }) // .namedT1
3892 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3893 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3894 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3895 bad(func() { clear(v.Field(6)) }) // .namedT2
3896 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3897 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3898 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3903 func (t timp) W() {}
3904 func (t timp) Y() {}
3905 func (t timp) w() {}
3906 func (t timp) y() {}
3908 func TestCallPanic(t *testing.T) {
3933 ok := func(f func()) { f() }
3934 badCall := func(f func()) { shouldPanic("Call", f) }
3935 badMethod := func(f func()) { shouldPanic("Method", f) }
3936 call := func(v Value) { v.Call(nil) }
3939 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3940 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3941 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3942 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3943 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3944 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3945 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3946 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3947 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3949 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3950 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3951 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3952 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3954 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3955 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3956 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3957 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3959 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3960 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3961 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3962 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3964 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3965 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3966 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3967 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3969 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3970 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3971 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3972 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3974 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3975 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3976 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3977 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3980 func TestValuePanic(t *testing.T) {
3982 shouldPanic("reflect.Value.Addr of unaddressable value", func() { vo(0).Addr() })
3983 shouldPanic("call of reflect.Value.Bool on float64 Value", func() { vo(0.0).Bool() })
3984 shouldPanic("call of reflect.Value.Bytes on string Value", func() { vo("").Bytes() })
3985 shouldPanic("call of reflect.Value.Call on bool Value", func() { vo(true).Call(nil) })
3986 shouldPanic("call of reflect.Value.CallSlice on int Value", func() { vo(0).CallSlice(nil) })
3987 shouldPanic("call of reflect.Value.Close on string Value", func() { vo("").Close() })
3988 shouldPanic("call of reflect.Value.Complex on float64 Value", func() { vo(0.0).Complex() })
3989 shouldPanic("call of reflect.Value.Elem on bool Value", func() { vo(false).Elem() })
3990 shouldPanic("call of reflect.Value.Field on int Value", func() { vo(0).Field(0) })
3991 shouldPanic("call of reflect.Value.Float on string Value", func() { vo("").Float() })
3992 shouldPanic("call of reflect.Value.Index on float64 Value", func() { vo(0.0).Index(0) })
3993 shouldPanic("call of reflect.Value.Int on bool Value", func() { vo(false).Int() })
3994 shouldPanic("call of reflect.Value.IsNil on int Value", func() { vo(0).IsNil() })
3995 shouldPanic("call of reflect.Value.Len on bool Value", func() { vo(false).Len() })
3996 shouldPanic("call of reflect.Value.MapIndex on float64 Value", func() { vo(0.0).MapIndex(vo(0.0)) })
3997 shouldPanic("call of reflect.Value.MapKeys on string Value", func() { vo("").MapKeys() })
3998 shouldPanic("call of reflect.Value.MapRange on int Value", func() { vo(0).MapRange() })
3999 shouldPanic("call of reflect.Value.Method on zero Value", func() { vo(nil).Method(0) })
4000 shouldPanic("call of reflect.Value.NumField on string Value", func() { vo("").NumField() })
4001 shouldPanic("call of reflect.Value.NumMethod on zero Value", func() { vo(nil).NumMethod() })
4002 shouldPanic("call of reflect.Value.OverflowComplex on float64 Value", func() { vo(float64(0)).OverflowComplex(0) })
4003 shouldPanic("call of reflect.Value.OverflowFloat on int64 Value", func() { vo(int64(0)).OverflowFloat(0) })
4004 shouldPanic("call of reflect.Value.OverflowInt on uint64 Value", func() { vo(uint64(0)).OverflowInt(0) })
4005 shouldPanic("call of reflect.Value.OverflowUint on complex64 Value", func() { vo(complex64(0)).OverflowUint(0) })
4006 shouldPanic("call of reflect.Value.Recv on string Value", func() { vo("").Recv() })
4007 shouldPanic("call of reflect.Value.Send on bool Value", func() { vo(true).Send(vo(true)) })
4008 shouldPanic("value of type string is not assignable to type bool", func() { vo(new(bool)).Elem().Set(vo("")) })
4009 shouldPanic("call of reflect.Value.SetBool on string Value", func() { vo(new(string)).Elem().SetBool(false) })
4010 shouldPanic("reflect.Value.SetBytes using unaddressable value", func() { vo("").SetBytes(nil) })
4011 shouldPanic("call of reflect.Value.SetCap on string Value", func() { vo(new(string)).Elem().SetCap(0) })
4012 shouldPanic("call of reflect.Value.SetComplex on string Value", func() { vo(new(string)).Elem().SetComplex(0) })
4013 shouldPanic("call of reflect.Value.SetFloat on string Value", func() { vo(new(string)).Elem().SetFloat(0) })
4014 shouldPanic("call of reflect.Value.SetInt on string Value", func() { vo(new(string)).Elem().SetInt(0) })
4015 shouldPanic("call of reflect.Value.SetLen on string Value", func() { vo(new(string)).Elem().SetLen(0) })
4016 shouldPanic("call of reflect.Value.SetString on int Value", func() { vo(new(int)).Elem().SetString("") })
4017 shouldPanic("reflect.Value.SetUint using unaddressable value", func() { vo(0.0).SetUint(0) })
4018 shouldPanic("call of reflect.Value.Slice on bool Value", func() { vo(true).Slice(1, 2) })
4019 shouldPanic("call of reflect.Value.Slice3 on int Value", func() { vo(0).Slice3(1, 2, 3) })
4020 shouldPanic("call of reflect.Value.TryRecv on bool Value", func() { vo(true).TryRecv() })
4021 shouldPanic("call of reflect.Value.TrySend on string Value", func() { vo("").TrySend(vo("")) })
4022 shouldPanic("call of reflect.Value.Uint on float64 Value", func() { vo(0.0).Uint() })
4025 func shouldPanic(expect string, f func()) {
4029 panic("did not panic")
4033 switch r := r.(type) {
4039 panic(fmt.Sprintf("panicked with unexpected type %T", r))
4041 if !strings.HasPrefix(s, "reflect") {
4042 panic(`panic string does not start with "reflect": ` + s)
4044 if !strings.Contains(s, expect) {
4045 panic(`panic string does not contain "` + expect + `": ` + s)
4052 func isNonNil(x any) {
4054 panic("nil interface")
4058 func isValid(v Value) {
4064 func TestAlias(t *testing.T) {
4065 x := string("hello")
4066 v := ValueOf(&x).Elem()
4067 oldvalue := v.Interface()
4068 v.SetString("world")
4069 newvalue := v.Interface()
4071 if oldvalue != "hello" || newvalue != "world" {
4072 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
4078 func EmptyInterfaceV(x any) Value {
4079 return ValueOf(&x).Elem()
4082 func ReaderV(x io.Reader) Value {
4083 return ValueOf(&x).Elem()
4086 func ReadWriterV(x io.ReadWriter) Value {
4087 return ValueOf(&x).Elem()
4091 type MyStruct struct {
4094 type MyStruct1 struct {
4099 type MyStruct2 struct {
4104 type MyString string
4106 type MyBytesArrayPtr0 *[0]byte
4107 type MyBytesArrayPtr *[4]byte
4108 type MyBytesArray0 [0]byte
4109 type MyBytesArray [4]byte
4110 type MyRunes []int32
4114 type IntChan chan int
4115 type IntChanRecv <-chan int
4116 type IntChanSend chan<- int
4117 type BytesChan chan []byte
4118 type BytesChanRecv <-chan []byte
4119 type BytesChanSend chan<- []byte
4121 var convertTests = []struct {
4127 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4133 var numbers = []string{
4134 "int8", "uint8", "int16", "uint16",
4135 "int32", "uint32", "int64", "uint64",
4136 "int", "uint", "uintptr",
4137 "float32", "float64",
4141 // all pairs but in an unusual order,
4142 // to emit all the int8, uint8 cases
4143 // before n grows too big.
4145 for i, f := range numbers {
4146 for _, g := range numbers[i:] {
4147 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4150 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4157 {V(int8(1)), V(int8(1))},
4158 {V(int8(2)), V(uint8(2))},
4159 {V(uint8(3)), V(int8(3))},
4160 {V(int8(4)), V(int16(4))},
4161 {V(int16(5)), V(int8(5))},
4162 {V(int8(6)), V(uint16(6))},
4163 {V(uint16(7)), V(int8(7))},
4164 {V(int8(8)), V(int32(8))},
4165 {V(int32(9)), V(int8(9))},
4166 {V(int8(10)), V(uint32(10))},
4167 {V(uint32(11)), V(int8(11))},
4168 {V(int8(12)), V(int64(12))},
4169 {V(int64(13)), V(int8(13))},
4170 {V(int8(14)), V(uint64(14))},
4171 {V(uint64(15)), V(int8(15))},
4172 {V(int8(16)), V(int(16))},
4173 {V(int(17)), V(int8(17))},
4174 {V(int8(18)), V(uint(18))},
4175 {V(uint(19)), V(int8(19))},
4176 {V(int8(20)), V(uintptr(20))},
4177 {V(uintptr(21)), V(int8(21))},
4178 {V(int8(22)), V(float32(22))},
4179 {V(float32(23)), V(int8(23))},
4180 {V(int8(24)), V(float64(24))},
4181 {V(float64(25)), V(int8(25))},
4182 {V(uint8(26)), V(uint8(26))},
4183 {V(uint8(27)), V(int16(27))},
4184 {V(int16(28)), V(uint8(28))},
4185 {V(uint8(29)), V(uint16(29))},
4186 {V(uint16(30)), V(uint8(30))},
4187 {V(uint8(31)), V(int32(31))},
4188 {V(int32(32)), V(uint8(32))},
4189 {V(uint8(33)), V(uint32(33))},
4190 {V(uint32(34)), V(uint8(34))},
4191 {V(uint8(35)), V(int64(35))},
4192 {V(int64(36)), V(uint8(36))},
4193 {V(uint8(37)), V(uint64(37))},
4194 {V(uint64(38)), V(uint8(38))},
4195 {V(uint8(39)), V(int(39))},
4196 {V(int(40)), V(uint8(40))},
4197 {V(uint8(41)), V(uint(41))},
4198 {V(uint(42)), V(uint8(42))},
4199 {V(uint8(43)), V(uintptr(43))},
4200 {V(uintptr(44)), V(uint8(44))},
4201 {V(uint8(45)), V(float32(45))},
4202 {V(float32(46)), V(uint8(46))},
4203 {V(uint8(47)), V(float64(47))},
4204 {V(float64(48)), V(uint8(48))},
4205 {V(int16(49)), V(int16(49))},
4206 {V(int16(50)), V(uint16(50))},
4207 {V(uint16(51)), V(int16(51))},
4208 {V(int16(52)), V(int32(52))},
4209 {V(int32(53)), V(int16(53))},
4210 {V(int16(54)), V(uint32(54))},
4211 {V(uint32(55)), V(int16(55))},
4212 {V(int16(56)), V(int64(56))},
4213 {V(int64(57)), V(int16(57))},
4214 {V(int16(58)), V(uint64(58))},
4215 {V(uint64(59)), V(int16(59))},
4216 {V(int16(60)), V(int(60))},
4217 {V(int(61)), V(int16(61))},
4218 {V(int16(62)), V(uint(62))},
4219 {V(uint(63)), V(int16(63))},
4220 {V(int16(64)), V(uintptr(64))},
4221 {V(uintptr(65)), V(int16(65))},
4222 {V(int16(66)), V(float32(66))},
4223 {V(float32(67)), V(int16(67))},
4224 {V(int16(68)), V(float64(68))},
4225 {V(float64(69)), V(int16(69))},
4226 {V(uint16(70)), V(uint16(70))},
4227 {V(uint16(71)), V(int32(71))},
4228 {V(int32(72)), V(uint16(72))},
4229 {V(uint16(73)), V(uint32(73))},
4230 {V(uint32(74)), V(uint16(74))},
4231 {V(uint16(75)), V(int64(75))},
4232 {V(int64(76)), V(uint16(76))},
4233 {V(uint16(77)), V(uint64(77))},
4234 {V(uint64(78)), V(uint16(78))},
4235 {V(uint16(79)), V(int(79))},
4236 {V(int(80)), V(uint16(80))},
4237 {V(uint16(81)), V(uint(81))},
4238 {V(uint(82)), V(uint16(82))},
4239 {V(uint16(83)), V(uintptr(83))},
4240 {V(uintptr(84)), V(uint16(84))},
4241 {V(uint16(85)), V(float32(85))},
4242 {V(float32(86)), V(uint16(86))},
4243 {V(uint16(87)), V(float64(87))},
4244 {V(float64(88)), V(uint16(88))},
4245 {V(int32(89)), V(int32(89))},
4246 {V(int32(90)), V(uint32(90))},
4247 {V(uint32(91)), V(int32(91))},
4248 {V(int32(92)), V(int64(92))},
4249 {V(int64(93)), V(int32(93))},
4250 {V(int32(94)), V(uint64(94))},
4251 {V(uint64(95)), V(int32(95))},
4252 {V(int32(96)), V(int(96))},
4253 {V(int(97)), V(int32(97))},
4254 {V(int32(98)), V(uint(98))},
4255 {V(uint(99)), V(int32(99))},
4256 {V(int32(100)), V(uintptr(100))},
4257 {V(uintptr(101)), V(int32(101))},
4258 {V(int32(102)), V(float32(102))},
4259 {V(float32(103)), V(int32(103))},
4260 {V(int32(104)), V(float64(104))},
4261 {V(float64(105)), V(int32(105))},
4262 {V(uint32(106)), V(uint32(106))},
4263 {V(uint32(107)), V(int64(107))},
4264 {V(int64(108)), V(uint32(108))},
4265 {V(uint32(109)), V(uint64(109))},
4266 {V(uint64(110)), V(uint32(110))},
4267 {V(uint32(111)), V(int(111))},
4268 {V(int(112)), V(uint32(112))},
4269 {V(uint32(113)), V(uint(113))},
4270 {V(uint(114)), V(uint32(114))},
4271 {V(uint32(115)), V(uintptr(115))},
4272 {V(uintptr(116)), V(uint32(116))},
4273 {V(uint32(117)), V(float32(117))},
4274 {V(float32(118)), V(uint32(118))},
4275 {V(uint32(119)), V(float64(119))},
4276 {V(float64(120)), V(uint32(120))},
4277 {V(int64(121)), V(int64(121))},
4278 {V(int64(122)), V(uint64(122))},
4279 {V(uint64(123)), V(int64(123))},
4280 {V(int64(124)), V(int(124))},
4281 {V(int(125)), V(int64(125))},
4282 {V(int64(126)), V(uint(126))},
4283 {V(uint(127)), V(int64(127))},
4284 {V(int64(128)), V(uintptr(128))},
4285 {V(uintptr(129)), V(int64(129))},
4286 {V(int64(130)), V(float32(130))},
4287 {V(float32(131)), V(int64(131))},
4288 {V(int64(132)), V(float64(132))},
4289 {V(float64(133)), V(int64(133))},
4290 {V(uint64(134)), V(uint64(134))},
4291 {V(uint64(135)), V(int(135))},
4292 {V(int(136)), V(uint64(136))},
4293 {V(uint64(137)), V(uint(137))},
4294 {V(uint(138)), V(uint64(138))},
4295 {V(uint64(139)), V(uintptr(139))},
4296 {V(uintptr(140)), V(uint64(140))},
4297 {V(uint64(141)), V(float32(141))},
4298 {V(float32(142)), V(uint64(142))},
4299 {V(uint64(143)), V(float64(143))},
4300 {V(float64(144)), V(uint64(144))},
4301 {V(int(145)), V(int(145))},
4302 {V(int(146)), V(uint(146))},
4303 {V(uint(147)), V(int(147))},
4304 {V(int(148)), V(uintptr(148))},
4305 {V(uintptr(149)), V(int(149))},
4306 {V(int(150)), V(float32(150))},
4307 {V(float32(151)), V(int(151))},
4308 {V(int(152)), V(float64(152))},
4309 {V(float64(153)), V(int(153))},
4310 {V(uint(154)), V(uint(154))},
4311 {V(uint(155)), V(uintptr(155))},
4312 {V(uintptr(156)), V(uint(156))},
4313 {V(uint(157)), V(float32(157))},
4314 {V(float32(158)), V(uint(158))},
4315 {V(uint(159)), V(float64(159))},
4316 {V(float64(160)), V(uint(160))},
4317 {V(uintptr(161)), V(uintptr(161))},
4318 {V(uintptr(162)), V(float32(162))},
4319 {V(float32(163)), V(uintptr(163))},
4320 {V(uintptr(164)), V(float64(164))},
4321 {V(float64(165)), V(uintptr(165))},
4322 {V(float32(166)), V(float32(166))},
4323 {V(float32(167)), V(float64(167))},
4324 {V(float64(168)), V(float32(168))},
4325 {V(float64(169)), V(float64(169))},
4328 {V(float64(1.5)), V(int(1))},
4331 {V(complex64(1i)), V(complex64(1i))},
4332 {V(complex64(2i)), V(complex128(2i))},
4333 {V(complex128(3i)), V(complex64(3i))},
4334 {V(complex128(4i)), V(complex128(4i))},
4337 {V(string("hello")), V(string("hello"))},
4338 {V(string("bytes1")), V([]byte("bytes1"))},
4339 {V([]byte("bytes2")), V(string("bytes2"))},
4340 {V([]byte("bytes3")), V([]byte("bytes3"))},
4341 {V(string("runes♝")), V([]rune("runes♝"))},
4342 {V([]rune("runes♕")), V(string("runes♕"))},
4343 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4344 {V(int('a')), V(string("a"))},
4345 {V(int8('a')), V(string("a"))},
4346 {V(int16('a')), V(string("a"))},
4347 {V(int32('a')), V(string("a"))},
4348 {V(int64('a')), V(string("a"))},
4349 {V(uint('a')), V(string("a"))},
4350 {V(uint8('a')), V(string("a"))},
4351 {V(uint16('a')), V(string("a"))},
4352 {V(uint32('a')), V(string("a"))},
4353 {V(uint64('a')), V(string("a"))},
4354 {V(uintptr('a')), V(string("a"))},
4355 {V(int(-1)), V(string("\uFFFD"))},
4356 {V(int8(-2)), V(string("\uFFFD"))},
4357 {V(int16(-3)), V(string("\uFFFD"))},
4358 {V(int32(-4)), V(string("\uFFFD"))},
4359 {V(int64(-5)), V(string("\uFFFD"))},
4360 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4361 {V(int64(1 << 32)), V(string("\uFFFD"))},
4362 {V(uint(0x110001)), V(string("\uFFFD"))},
4363 {V(uint32(0x110002)), V(string("\uFFFD"))},
4364 {V(uint64(0x110003)), V(string("\uFFFD"))},
4365 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4366 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4369 {V(MyString("hello")), V(string("hello"))},
4370 {V(string("hello")), V(MyString("hello"))},
4371 {V(string("hello")), V(string("hello"))},
4372 {V(MyString("hello")), V(MyString("hello"))},
4373 {V(MyString("bytes1")), V([]byte("bytes1"))},
4374 {V([]byte("bytes2")), V(MyString("bytes2"))},
4375 {V([]byte("bytes3")), V([]byte("bytes3"))},
4376 {V(MyString("runes♝")), V([]rune("runes♝"))},
4377 {V([]rune("runes♕")), V(MyString("runes♕"))},
4378 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4379 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4380 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4381 {V(int('a')), V(MyString("a"))},
4382 {V(int8('a')), V(MyString("a"))},
4383 {V(int16('a')), V(MyString("a"))},
4384 {V(int32('a')), V(MyString("a"))},
4385 {V(int64('a')), V(MyString("a"))},
4386 {V(uint('a')), V(MyString("a"))},
4387 {V(uint8('a')), V(MyString("a"))},
4388 {V(uint16('a')), V(MyString("a"))},
4389 {V(uint32('a')), V(MyString("a"))},
4390 {V(uint64('a')), V(MyString("a"))},
4391 {V(uintptr('a')), V(MyString("a"))},
4392 {V(int(-1)), V(MyString("\uFFFD"))},
4393 {V(int8(-2)), V(MyString("\uFFFD"))},
4394 {V(int16(-3)), V(MyString("\uFFFD"))},
4395 {V(int32(-4)), V(MyString("\uFFFD"))},
4396 {V(int64(-5)), V(MyString("\uFFFD"))},
4397 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4398 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4399 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4400 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4403 {V(string("bytes1")), V(MyBytes("bytes1"))},
4404 {V(MyBytes("bytes2")), V(string("bytes2"))},
4405 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4406 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4407 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4410 {V(string("runes♝")), V(MyRunes("runes♝"))},
4411 {V(MyRunes("runes♕")), V(string("runes♕"))},
4412 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4413 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4414 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4416 // slice to array pointer
4417 {V([]byte(nil)), V((*[0]byte)(nil))},
4418 {V([]byte{}), V(new([0]byte))},
4419 {V([]byte{7}), V(&[1]byte{7})},
4420 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4421 {V(MyBytes([]byte{})), V(new([0]byte))},
4422 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4423 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4424 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4425 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4426 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4427 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4429 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4430 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4431 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4432 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4433 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4434 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4435 {V(new([0]byte)), V(new(MyBytesArray0))},
4436 {V(new(MyBytesArray0)), V(new([0]byte))},
4437 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4438 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4440 // named types and equal underlying types
4441 {V(new(int)), V(new(integer))},
4442 {V(new(integer)), V(new(int))},
4443 {V(Empty{}), V(struct{}{})},
4444 {V(new(Empty)), V(new(struct{}))},
4445 {V(struct{}{}), V(Empty{})},
4446 {V(new(struct{})), V(new(Empty))},
4447 {V(Empty{}), V(Empty{})},
4448 {V(MyBytes{}), V([]byte{})},
4449 {V([]byte{}), V(MyBytes{})},
4450 {V((func())(nil)), V(MyFunc(nil))},
4451 {V((MyFunc)(nil)), V((func())(nil))},
4453 // structs with different tags
4466 {V(MyStruct{}), V(struct {
4472 }{}), V(MyStruct{})},
4474 {V(MyStruct{}), V(struct {
4480 }{}), V(MyStruct{})},
4482 {V(MyStruct1{}), V(MyStruct2{})},
4483 {V(MyStruct2{}), V(MyStruct1{})},
4485 // can convert *byte and *MyByte
4486 {V((*byte)(nil)), V((*MyByte)(nil))},
4487 {V((*MyByte)(nil)), V((*byte)(nil))},
4489 // cannot convert mismatched array sizes
4490 {V([2]byte{}), V([2]byte{})},
4491 {V([3]byte{}), V([3]byte{})},
4493 // cannot convert other instances
4494 {V((**byte)(nil)), V((**byte)(nil))},
4495 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4496 {V((chan byte)(nil)), V((chan byte)(nil))},
4497 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4498 {V(([]byte)(nil)), V(([]byte)(nil))},
4499 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4500 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4501 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4502 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4503 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4504 {V([2]byte{}), V([2]byte{})},
4505 {V([2]MyByte{}), V([2]MyByte{})},
4508 {V((***int)(nil)), V((***int)(nil))},
4509 {V((***byte)(nil)), V((***byte)(nil))},
4510 {V((***int32)(nil)), V((***int32)(nil))},
4511 {V((***int64)(nil)), V((***int64)(nil))},
4512 {V((chan byte)(nil)), V((chan byte)(nil))},
4513 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4514 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4515 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4516 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4517 {V([]uint(nil)), V([]uint(nil))},
4518 {V([]int(nil)), V([]int(nil))},
4519 {V(new(any)), V(new(any))},
4520 {V(new(io.Reader)), V(new(io.Reader))},
4521 {V(new(io.Writer)), V(new(io.Writer))},
4524 {V(IntChan(nil)), V((chan<- int)(nil))},
4525 {V(IntChan(nil)), V((<-chan int)(nil))},
4526 {V((chan int)(nil)), V(IntChanRecv(nil))},
4527 {V((chan int)(nil)), V(IntChanSend(nil))},
4528 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4529 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4530 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4531 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4532 {V(IntChan(nil)), V((chan int)(nil))},
4533 {V((chan int)(nil)), V(IntChan(nil))},
4534 {V((chan int)(nil)), V((<-chan int)(nil))},
4535 {V((chan int)(nil)), V((chan<- int)(nil))},
4536 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4537 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4538 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4539 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4540 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4541 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4542 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4543 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4544 {V(BytesChan(nil)), V((chan []byte)(nil))},
4545 {V((chan []byte)(nil)), V(BytesChan(nil))},
4546 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4547 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4549 // cannot convert other instances (channels)
4550 {V(IntChan(nil)), V(IntChan(nil))},
4551 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4552 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4553 {V(BytesChan(nil)), V(BytesChan(nil))},
4554 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4555 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4558 {V(int(1)), EmptyInterfaceV(int(1))},
4559 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4560 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4561 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4562 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4565 func TestConvert(t *testing.T) {
4566 canConvert := map[[2]Type]bool{}
4567 all := map[Type]bool{}
4569 for _, tt := range convertTests {
4571 if !t1.ConvertibleTo(t1) {
4572 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4577 if !t1.ConvertibleTo(t2) {
4578 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4584 canConvert[[2]Type{t1, t2}] = true
4586 // vout1 represents the in value converted to the in type.
4588 if !v1.CanConvert(t1) {
4589 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4591 vout1 := v1.Convert(t1)
4592 out1 := vout1.Interface()
4593 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4594 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4597 // vout2 represents the in value converted to the out type.
4598 if !v1.CanConvert(t2) {
4599 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4601 vout2 := v1.Convert(t2)
4602 out2 := vout2.Interface()
4603 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4604 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4606 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4607 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4610 // vout3 represents a new value of the out type, set to vout2. This makes
4611 // sure the converted value vout2 is really usable as a regular value.
4612 vout3 := New(t2).Elem()
4614 out3 := vout3.Interface()
4615 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4616 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4620 t.Errorf("table entry %v is RO, should not be", v1)
4623 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4626 t.Errorf("conversion output %v is RO, should not be", vout2)
4629 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4631 if !IsRO(MakeRO(v1).Convert(t1)) {
4632 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4634 if !IsRO(MakeRO(v1).Convert(t2)) {
4635 t.Errorf("RO conversion output %v is not RO, should be", v1)
4639 // Assume that of all the types we saw during the tests,
4640 // if there wasn't an explicit entry for a conversion between
4641 // a pair of types, then it's not to be allowed. This checks for
4642 // things like 'int64' converting to '*int'.
4643 for t1 := range all {
4644 for t2 := range all {
4645 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4646 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4647 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4653 func TestConvertPanic(t *testing.T) {
4654 s := make([]byte, 4)
4658 if !v.Type().ConvertibleTo(pt) {
4659 t.Errorf("[]byte should be convertible to *[8]byte")
4661 if v.CanConvert(pt) {
4662 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4664 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4669 var gFloat32 float32
4671 const snan uint32 = 0x7f800001
4673 func TestConvertNaNs(t *testing.T) {
4674 // Test to see if a store followed by a load of a signaling NaN
4675 // maintains the signaling bit. (This used to fail on the 387 port.)
4676 gFloat32 = math.Float32frombits(snan)
4677 runtime.Gosched() // make sure we don't optimize the store/load away
4678 if got := math.Float32bits(gFloat32); got != snan {
4679 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4681 // Test reflect's conversion between float32s. See issue 36400.
4682 type myFloat32 float32
4683 x := V(myFloat32(math.Float32frombits(snan)))
4684 y := x.Convert(TypeOf(float32(0)))
4685 z := y.Interface().(float32)
4686 if got := math.Float32bits(z); got != snan {
4687 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4691 type ComparableStruct struct {
4695 type NonComparableStruct struct {
4700 var comparableTests = []struct {
4705 {TypeOf("hello"), true},
4706 {TypeOf(new(byte)), true},
4707 {TypeOf((func())(nil)), false},
4708 {TypeOf([]byte{}), false},
4709 {TypeOf(map[string]int{}), false},
4710 {TypeOf(make(chan int)), true},
4711 {TypeOf(1.5), true},
4712 {TypeOf(false), true},
4714 {TypeOf(ComparableStruct{}), true},
4715 {TypeOf(NonComparableStruct{}), false},
4716 {TypeOf([10]map[string]int{}), false},
4717 {TypeOf([10]string{}), true},
4718 {TypeOf(new(any)).Elem(), true},
4721 func TestComparable(t *testing.T) {
4722 for _, tt := range comparableTests {
4723 if ok := tt.typ.Comparable(); ok != tt.ok {
4724 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4729 func TestOverflow(t *testing.T) {
4730 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4731 t.Errorf("%v wrongly overflows float64", 1e300)
4734 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4735 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4736 t.Errorf("%v wrongly overflows float32", maxFloat32)
4738 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4739 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4740 t.Errorf("%v should overflow float32", ovfFloat32)
4742 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4743 t.Errorf("%v should overflow float32", -ovfFloat32)
4746 maxInt32 := int64(0x7fffffff)
4747 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4748 t.Errorf("%v wrongly overflows int32", maxInt32)
4750 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4751 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4753 ovfInt32 := int64(1 << 31)
4754 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4755 t.Errorf("%v should overflow int32", ovfInt32)
4758 maxUint32 := uint64(0xffffffff)
4759 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4760 t.Errorf("%v wrongly overflows uint32", maxUint32)
4762 ovfUint32 := uint64(1 << 32)
4763 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4764 t.Errorf("%v should overflow uint32", ovfUint32)
4768 func checkSameType(t *testing.T, x Type, y any) {
4769 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4770 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4774 func TestArrayOf(t *testing.T) {
4775 // check construction and use of type not in binary
4778 value func(i int) any
4784 value: func(i int) any { type Tint int; return Tint(i) },
4790 value: func(i int) any { type Tint int; return Tint(i) },
4792 want: "[0 1 2 3 4 5 6 7 8 9]",
4796 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4798 want: "[0 1 2 3 4 5 6 7 8 9]",
4802 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4804 want: "[0 1 2 3 4 5 6 7 8 9]",
4808 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4810 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4814 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4816 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4820 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4822 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4826 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4828 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4832 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4834 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4838 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4840 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4844 value: func(i int) any {
4845 type TstructUV struct {
4849 return TstructUV{i, float64(i)}
4852 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4856 for _, table := range tests {
4857 at := ArrayOf(table.n, TypeOf(table.value(0)))
4859 vok := New(at).Elem()
4860 vnot := New(at).Elem()
4861 for i := 0; i < v.Len(); i++ {
4862 v.Index(i).Set(ValueOf(table.value(i)))
4863 vok.Index(i).Set(ValueOf(table.value(i)))
4868 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4870 s := fmt.Sprint(v.Interface())
4871 if s != table.want {
4872 t.Errorf("constructed array = %s, want %s", s, table.want)
4875 if table.comparable != at.Comparable() {
4876 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4878 if table.comparable {
4880 if DeepEqual(vnot.Interface(), v.Interface()) {
4882 "arrays (%#v) compare ok (but should not)",
4887 if !DeepEqual(vok.Interface(), v.Interface()) {
4889 "arrays (%#v) compare NOT-ok (but should)",
4896 // check that type already in binary is found
4898 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4901 func TestArrayOfGC(t *testing.T) {
4903 tt := TypeOf(T(nil))
4906 for i := 0; i < n; i++ {
4907 v := New(ArrayOf(n, tt)).Elem()
4908 for j := 0; j < v.Len(); j++ {
4910 *p = uintptr(i*n + j)
4911 v.Index(j).Set(ValueOf(p).Convert(tt))
4913 x = append(x, v.Interface())
4917 for i, xi := range x {
4919 for j := 0; j < v.Len(); j++ {
4920 k := v.Index(j).Elem().Interface()
4921 if k != uintptr(i*n+j) {
4922 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4928 func TestArrayOfAlg(t *testing.T) {
4929 at := ArrayOf(6, TypeOf(byte(0)))
4930 v1 := New(at).Elem()
4931 v2 := New(at).Elem()
4932 if v1.Interface() != v1.Interface() {
4933 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4935 v1.Index(5).Set(ValueOf(byte(1)))
4936 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4937 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4940 at = ArrayOf(6, TypeOf([]int(nil)))
4942 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4945 func TestArrayOfGenericAlg(t *testing.T) {
4946 at1 := ArrayOf(5, TypeOf(string("")))
4947 at := ArrayOf(6, at1)
4948 v1 := New(at).Elem()
4949 v2 := New(at).Elem()
4950 if v1.Interface() != v1.Interface() {
4951 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4954 v1.Index(0).Index(0).Set(ValueOf("abc"))
4955 v2.Index(0).Index(0).Set(ValueOf("efg"))
4956 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4957 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4960 v1.Index(0).Index(0).Set(ValueOf("abc"))
4961 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4962 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4963 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4967 m := MakeMap(MapOf(at, TypeOf(int(0))))
4968 m.SetMapIndex(v1, ValueOf(1))
4969 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4970 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4974 func TestArrayOfDirectIface(t *testing.T) {
4977 i1 := Zero(TypeOf(T{})).Interface()
4978 v1 := ValueOf(&i1).Elem()
4979 p1 := v1.InterfaceData()[1]
4981 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
4982 v2 := ValueOf(&i2).Elem()
4983 p2 := v2.InterfaceData()[1]
4986 t.Errorf("got p1=%v. want=%v", p1, nil)
4990 t.Errorf("got p2=%v. want=%v", p2, nil)
4995 i1 := Zero(TypeOf(T{})).Interface()
4996 v1 := ValueOf(&i1).Elem()
4997 p1 := v1.InterfaceData()[1]
4999 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
5000 v2 := ValueOf(&i2).Elem()
5001 p2 := v2.InterfaceData()[1]
5004 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5008 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5013 // Ensure passing in negative lengths panics.
5014 // See https://golang.org/issue/43603
5015 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
5016 shouldPanic("reflect: negative length passed to ArrayOf", func() {
5017 ArrayOf(-1, TypeOf(byte(0)))
5021 func TestSliceOf(t *testing.T) {
5022 // check construction and use of type not in binary
5024 st := SliceOf(TypeOf(T(1)))
5025 if got, want := st.String(), "[]reflect_test.T"; got != want {
5026 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
5028 v := MakeSlice(st, 10, 10)
5030 for i := 0; i < v.Len(); i++ {
5031 v.Index(i).Set(ValueOf(T(i)))
5034 s := fmt.Sprint(v.Interface())
5035 want := "[0 1 2 3 4 5 6 7 8 9]"
5037 t.Errorf("constructed slice = %s, want %s", s, want)
5040 // check that type already in binary is found
5042 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
5045 func TestSliceOverflow(t *testing.T) {
5046 // check that MakeSlice panics when size of slice overflows uint
5049 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5051 t.Fatal("slice size does not overflow")
5054 st := SliceOf(TypeOf(x))
5058 t.Fatal("slice overflow does not panic")
5061 MakeSlice(st, int(l), int(l))
5064 func TestSliceOfGC(t *testing.T) {
5066 tt := TypeOf(T(nil))
5070 for i := 0; i < n; i++ {
5071 v := MakeSlice(st, n, n)
5072 for j := 0; j < v.Len(); j++ {
5074 *p = uintptr(i*n + j)
5075 v.Index(j).Set(ValueOf(p).Convert(tt))
5077 x = append(x, v.Interface())
5081 for i, xi := range x {
5083 for j := 0; j < v.Len(); j++ {
5084 k := v.Index(j).Elem().Interface()
5085 if k != uintptr(i*n+j) {
5086 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5092 func TestStructOfFieldName(t *testing.T) {
5093 // invalid field name "1nvalid"
5094 shouldPanic("has invalid name", func() {
5095 StructOf([]StructField{
5096 {Name: "Valid", Type: TypeOf("")},
5097 {Name: "1nvalid", Type: TypeOf("")},
5101 // invalid field name "+"
5102 shouldPanic("has invalid name", func() {
5103 StructOf([]StructField{
5104 {Name: "Val1d", Type: TypeOf("")},
5105 {Name: "+", Type: TypeOf("")},
5110 shouldPanic("has no name", func() {
5111 StructOf([]StructField{
5112 {Name: "", Type: TypeOf("")},
5116 // verify creation of a struct with valid struct fields
5117 validFields := []StructField{
5132 validStruct := StructOf(validFields)
5134 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5135 if got, want := validStruct.String(), structStr; got != want {
5136 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5140 func TestStructOf(t *testing.T) {
5141 // check construction and use of type not in binary
5142 fields := []StructField{
5151 Type: TypeOf(byte(0)),
5155 Type: TypeOf(uint64(0)),
5159 Type: TypeOf([3]uint16{}),
5163 st := StructOf(fields)
5166 v.FieldByName("X").Set(ValueOf(byte(2)))
5167 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5170 s := fmt.Sprint(v.Interface())
5171 want := `{ 1 0 [0 0 0]}`
5173 t.Errorf("constructed struct = %s, want %s", s, want)
5175 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5176 if got, want := st.String(), stStr; got != want {
5177 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5180 // check the size, alignment and field offsets
5181 stt := TypeOf(struct {
5187 if st.Size() != stt.Size() {
5188 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5190 if st.Align() != stt.Align() {
5191 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5193 if st.FieldAlign() != stt.FieldAlign() {
5194 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5196 for i := 0; i < st.NumField(); i++ {
5197 o1 := st.Field(i).Offset
5198 o2 := stt.Field(i).Offset
5200 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5204 // Check size and alignment with a trailing zero-sized field.
5205 st = StructOf([]StructField{
5208 Type: TypeOf(byte(0)),
5212 Type: TypeOf([0]*byte{}),
5215 stt = TypeOf(struct {
5219 if st.Size() != stt.Size() {
5220 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5222 if st.Align() != stt.Align() {
5223 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5225 if st.FieldAlign() != stt.FieldAlign() {
5226 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5228 for i := 0; i < st.NumField(); i++ {
5229 o1 := st.Field(i).Offset
5230 o2 := stt.Field(i).Offset
5232 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5236 // check duplicate names
5237 shouldPanic("duplicate field", func() {
5238 StructOf([]StructField{
5239 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5240 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5243 shouldPanic("has no name", func() {
5244 StructOf([]StructField{
5246 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5249 shouldPanic("has no name", func() {
5250 StructOf([]StructField{
5255 // check that type already in binary is found
5256 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5258 // gccgo used to fail this test.
5259 type structFieldType any
5261 StructOf([]StructField{
5264 Type: TypeOf((*structFieldType)(nil)).Elem(),
5267 struct{ F structFieldType }{})
5270 func TestStructOfExportRules(t *testing.T) {
5276 testPanic := func(i int, mustPanic bool, f func()) {
5279 if err == nil && mustPanic {
5280 t.Errorf("test-%d did not panic", i)
5282 if err != nil && !mustPanic {
5283 t.Errorf("test-%d panicked: %v\n", i, err)
5295 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5299 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5303 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5307 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5311 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5315 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5319 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5323 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5327 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5331 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5335 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5338 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5341 field: StructField{Name: "S", Type: TypeOf(S1{})},
5345 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5349 field: StructField{Name: "S", Type: TypeOf(s2{})},
5353 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5357 field: StructField{Name: "s", Type: TypeOf(S1{})},
5361 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5365 field: StructField{Name: "s", Type: TypeOf(s2{})},
5369 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5373 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5376 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5379 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5382 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5385 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5389 field: StructField{Name: "", Type: TypeOf(φType{})},
5393 field: StructField{Name: "Φ", Type: TypeOf(0)},
5397 field: StructField{Name: "φ", Type: TypeOf(0)},
5402 for i, test := range tests {
5403 testPanic(i, test.mustPanic, func() {
5404 typ := StructOf([]StructField{test.field})
5406 t.Errorf("test-%d: error creating struct type", i)
5409 field := typ.Field(0)
5412 panic("field.Name must not be empty")
5414 exported := token.IsExported(n)
5415 if exported != test.exported {
5416 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5418 if field.PkgPath != test.field.PkgPath {
5419 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5425 func TestStructOfGC(t *testing.T) {
5427 tt := TypeOf(T(nil))
5428 fields := []StructField{
5429 {Name: "X", Type: tt},
5430 {Name: "Y", Type: tt},
5432 st := StructOf(fields)
5436 for i := 0; i < n; i++ {
5438 for j := 0; j < v.NumField(); j++ {
5440 *p = uintptr(i*n + j)
5441 v.Field(j).Set(ValueOf(p).Convert(tt))
5443 x = append(x, v.Interface())
5447 for i, xi := range x {
5449 for j := 0; j < v.NumField(); j++ {
5450 k := v.Field(j).Elem().Interface()
5451 if k != uintptr(i*n+j) {
5452 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5458 func TestStructOfAlg(t *testing.T) {
5459 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5460 v1 := New(st).Elem()
5461 v2 := New(st).Elem()
5462 if !DeepEqual(v1.Interface(), v1.Interface()) {
5463 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5465 v1.FieldByName("X").Set(ValueOf(int(1)))
5466 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5467 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5470 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5472 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5475 func TestStructOfGenericAlg(t *testing.T) {
5476 st1 := StructOf([]StructField{
5477 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5478 {Name: "Y", Type: TypeOf(string(""))},
5480 st := StructOf([]StructField{
5481 {Name: "S0", Type: st1},
5482 {Name: "S1", Type: st1},
5500 {Name: "XX", Type: TypeOf([0]int{})},
5501 {Name: "YY", Type: TypeOf("")},
5509 {Name: "XX", Type: TypeOf([0]int{})},
5510 {Name: "YY", Type: TypeOf("")},
5511 {Name: "ZZ", Type: TypeOf([2]int{})},
5519 {Name: "XX", Type: TypeOf([1]int{})},
5520 {Name: "YY", Type: TypeOf("")},
5528 {Name: "XX", Type: TypeOf([1]int{})},
5529 {Name: "YY", Type: TypeOf("")},
5530 {Name: "ZZ", Type: TypeOf([1]int{})},
5538 {Name: "XX", Type: TypeOf([2]int{})},
5539 {Name: "YY", Type: TypeOf("")},
5540 {Name: "ZZ", Type: TypeOf([2]int{})},
5548 {Name: "XX", Type: TypeOf(int64(0))},
5549 {Name: "YY", Type: TypeOf(byte(0))},
5550 {Name: "ZZ", Type: TypeOf("")},
5558 {Name: "XX", Type: TypeOf(int64(0))},
5559 {Name: "YY", Type: TypeOf(int64(0))},
5560 {Name: "ZZ", Type: TypeOf("")},
5561 {Name: "AA", Type: TypeOf([1]int64{})},
5568 for _, table := range tests {
5569 v1 := New(table.rt).Elem()
5570 v2 := New(table.rt).Elem()
5572 if !DeepEqual(v1.Interface(), v1.Interface()) {
5573 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5576 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5577 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5578 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5579 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5583 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5584 val := "+" + abc + "-"
5585 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5586 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5587 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5591 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5592 m.SetMapIndex(v1, ValueOf(1))
5593 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5594 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5597 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5598 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5599 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5602 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5603 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5608 func TestStructOfDirectIface(t *testing.T) {
5610 type T struct{ X [1]*byte }
5611 i1 := Zero(TypeOf(T{})).Interface()
5612 v1 := ValueOf(&i1).Elem()
5613 p1 := v1.InterfaceData()[1]
5615 i2 := Zero(StructOf([]StructField{
5618 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5621 v2 := ValueOf(&i2).Elem()
5622 p2 := v2.InterfaceData()[1]
5625 t.Errorf("got p1=%v. want=%v", p1, nil)
5629 t.Errorf("got p2=%v. want=%v", p2, nil)
5633 type T struct{ X [0]*byte }
5634 i1 := Zero(TypeOf(T{})).Interface()
5635 v1 := ValueOf(&i1).Elem()
5636 p1 := v1.InterfaceData()[1]
5638 i2 := Zero(StructOf([]StructField{
5641 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5644 v2 := ValueOf(&i2).Elem()
5645 p2 := v2.InterfaceData()[1]
5648 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5652 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5659 func (i StructI) Get() int { return int(i) }
5663 func (i *StructIPtr) Get() int { return int(*i) }
5664 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5666 type SettableStruct struct {
5670 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5672 type SettablePointer struct {
5676 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5678 func TestStructOfWithInterface(t *testing.T) {
5680 type Iface interface {
5683 type IfaceSet interface {
5694 typ: TypeOf(StructI(want)),
5695 val: ValueOf(StructI(want)),
5700 typ: PointerTo(TypeOf(StructI(want))),
5701 val: ValueOf(func() any {
5709 typ: PointerTo(TypeOf(StructIPtr(want))),
5710 val: ValueOf(func() any {
5711 v := StructIPtr(want)
5718 typ: TypeOf(StructIPtr(want)),
5719 val: ValueOf(StructIPtr(want)),
5723 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5724 // val: ValueOf(StructI(want)),
5729 for i, table := range tests {
5730 for j := 0; j < 2; j++ {
5731 var fields []StructField
5733 fields = append(fields, StructField{
5736 Type: TypeOf(int(0)),
5739 fields = append(fields, StructField{
5746 // We currently do not correctly implement methods
5747 // for embedded fields other than the first.
5748 // Therefore, for now, we expect those methods
5749 // to not exist. See issues 15924 and 20824.
5750 // When those issues are fixed, this test of panic
5751 // should be removed.
5752 if j == 1 && table.impl {
5755 if err := recover(); err == nil {
5756 t.Errorf("test-%d-%d did not panic", i, j)
5759 _ = StructOf(fields)
5764 rt := StructOf(fields)
5765 rv := New(rt).Elem()
5766 rv.Field(j).Set(table.val)
5768 if _, ok := rv.Interface().(Iface); ok != table.impl {
5770 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5772 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5781 v := rv.Interface().(Iface).Get()
5783 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5786 fct := rv.MethodByName("Get")
5787 out := fct.Call(nil)
5788 if !DeepEqual(out[0].Interface(), want) {
5789 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5794 // Test an embedded nil pointer with pointer methods.
5795 fields := []StructField{{
5798 Type: PointerTo(TypeOf(StructIPtr(want))),
5800 rt := StructOf(fields)
5801 rv := New(rt).Elem()
5802 // This should panic since the pointer is nil.
5803 shouldPanic("", func() {
5804 rv.Interface().(IfaceSet).Set(want)
5807 // Test an embedded nil pointer to a struct with pointer methods.
5809 fields = []StructField{{
5810 Name: "SettableStruct",
5812 Type: PointerTo(TypeOf(SettableStruct{})),
5814 rt = StructOf(fields)
5816 // This should panic since the pointer is nil.
5817 shouldPanic("", func() {
5818 rv.Interface().(IfaceSet).Set(want)
5821 // The behavior is different if there is a second field,
5822 // since now an interface value holds a pointer to the struct
5823 // rather than just holding a copy of the struct.
5824 fields = []StructField{
5826 Name: "SettableStruct",
5828 Type: PointerTo(TypeOf(SettableStruct{})),
5831 Name: "EmptyStruct",
5833 Type: StructOf(nil),
5836 // With the current implementation this is expected to panic.
5837 // Ideally it should work and we should be able to see a panic
5838 // if we call the Set method.
5839 shouldPanic("", func() {
5843 // Embed a field that can be stored directly in an interface,
5844 // with a second field.
5845 fields = []StructField{
5847 Name: "SettablePointer",
5849 Type: TypeOf(SettablePointer{}),
5852 Name: "EmptyStruct",
5854 Type: StructOf(nil),
5857 // With the current implementation this is expected to panic.
5858 // Ideally it should work and we should be able to call the
5859 // Set and Get methods.
5860 shouldPanic("", func() {
5865 func TestStructOfTooManyFields(t *testing.T) {
5866 // Bug Fix: #25402 - this should not panic
5867 tt := StructOf([]StructField{
5868 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5871 if _, present := tt.MethodByName("After"); !present {
5872 t.Errorf("Expected method `After` to be found")
5876 func TestStructOfDifferentPkgPath(t *testing.T) {
5877 fields := []StructField{
5881 Type: TypeOf(int(0)),
5886 Type: TypeOf(int(0)),
5889 shouldPanic("different PkgPath", func() {
5894 func TestChanOf(t *testing.T) {
5895 // check construction and use of type not in binary
5897 ct := ChanOf(BothDir, TypeOf(T("")))
5898 v := MakeChan(ct, 2)
5900 v.Send(ValueOf(T("hello")))
5902 v.Send(ValueOf(T("world")))
5909 if s1 != "hello" || s2 != "world" {
5910 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5913 // check that type already in binary is found
5915 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5917 // Check arrow token association in undefined chan types.
5918 var left chan<- chan T
5919 var right chan (<-chan T)
5920 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5921 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5922 if tLeft != TypeOf(left) {
5923 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5925 if tRight != TypeOf(right) {
5926 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5930 func TestChanOfDir(t *testing.T) {
5931 // check construction and use of type not in binary
5933 crt := ChanOf(RecvDir, TypeOf(T("")))
5934 cst := ChanOf(SendDir, TypeOf(T("")))
5936 // check that type already in binary is found
5938 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5939 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5941 // check String form of ChanDir
5942 if crt.ChanDir().String() != "<-chan" {
5943 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5945 if cst.ChanDir().String() != "chan<-" {
5946 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5950 func TestChanOfGC(t *testing.T) {
5951 done := make(chan bool, 1)
5955 case <-time.After(5 * time.Second):
5956 panic("deadlock in TestChanOfGC")
5965 tt := TypeOf(T(nil))
5966 ct := ChanOf(BothDir, tt)
5968 // NOTE: The garbage collector handles allocated channels specially,
5969 // so we have to save pointers to channels in x; the pointer code will
5970 // use the gc info in the newly constructed chan type.
5973 for i := 0; i < n; i++ {
5974 v := MakeChan(ct, n)
5975 for j := 0; j < n; j++ {
5977 *p = uintptr(i*n + j)
5978 v.Send(ValueOf(p).Convert(tt))
5982 x = append(x, pv.Interface())
5986 for i, xi := range x {
5987 v := ValueOf(xi).Elem()
5988 for j := 0; j < n; j++ {
5990 k := pv.Elem().Interface()
5991 if k != uintptr(i*n+j) {
5992 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5998 func TestMapOf(t *testing.T) {
5999 // check construction and use of type not in binary
6003 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
6005 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
6008 s := fmt.Sprint(v.Interface())
6011 t.Errorf("constructed map = %s, want %s", s, want)
6014 // check that type already in binary is found
6015 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
6017 // check that invalid key type panics
6018 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
6021 func TestMapOfGCKeys(t *testing.T) {
6023 tt := TypeOf(T(nil))
6024 mt := MapOf(tt, TypeOf(false))
6026 // NOTE: The garbage collector handles allocated maps specially,
6027 // so we have to save pointers to maps in x; the pointer code will
6028 // use the gc info in the newly constructed map type.
6031 for i := 0; i < n; i++ {
6033 for j := 0; j < n; j++ {
6035 *p = uintptr(i*n + j)
6036 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
6040 x = append(x, pv.Interface())
6044 for i, xi := range x {
6045 v := ValueOf(xi).Elem()
6047 for _, kv := range v.MapKeys() {
6048 out = append(out, int(kv.Elem().Interface().(uintptr)))
6051 for j, k := range out {
6053 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6059 func TestMapOfGCValues(t *testing.T) {
6061 tt := TypeOf(T(nil))
6062 mt := MapOf(TypeOf(1), tt)
6064 // NOTE: The garbage collector handles allocated maps specially,
6065 // so we have to save pointers to maps in x; the pointer code will
6066 // use the gc info in the newly constructed map type.
6069 for i := 0; i < n; i++ {
6071 for j := 0; j < n; j++ {
6073 *p = uintptr(i*n + j)
6074 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6078 x = append(x, pv.Interface())
6082 for i, xi := range x {
6083 v := ValueOf(xi).Elem()
6084 for j := 0; j < n; j++ {
6085 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6086 if k != uintptr(i*n+j) {
6087 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6093 func TestTypelinksSorted(t *testing.T) {
6095 for i, n := range TypeLinks() {
6097 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6103 func TestFuncOf(t *testing.T) {
6104 // check construction and use of type not in binary
6108 fn := func(args []Value) []Value {
6110 t.Errorf("args == %v, want exactly one arg", args)
6111 } else if args[0].Type() != TypeOf(K("")) {
6112 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6113 } else if args[0].String() != "gopher" {
6114 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6116 return []Value{ValueOf(V(3.14))}
6118 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6120 outs := v.Call([]Value{ValueOf(K("gopher"))})
6122 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6123 } else if outs[0].Type() != TypeOf(V(0)) {
6124 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6126 f := outs[0].Float()
6128 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6131 // check that types already in binary are found
6133 testCases := []struct {
6138 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6139 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6140 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6141 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6142 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6144 for _, tt := range testCases {
6145 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6148 // check that variadic requires last element be a slice.
6149 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6150 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6151 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6160 func BenchmarkFieldByName1(b *testing.B) {
6162 b.RunParallel(func(pb *testing.PB) {
6169 func BenchmarkFieldByName2(b *testing.B) {
6171 b.RunParallel(func(pb *testing.PB) {
6248 func TestEmbed(t *testing.T) {
6250 f, ok := typ.FieldByName("X")
6252 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6256 func BenchmarkFieldByName3(b *testing.B) {
6258 b.RunParallel(func(pb *testing.PB) {
6270 func BenchmarkInterfaceBig(b *testing.B) {
6272 b.RunParallel(func(pb *testing.PB) {
6280 func TestAllocsInterfaceBig(t *testing.T) {
6281 if testing.Short() {
6282 t.Skip("skipping malloc count in short mode")
6285 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6286 t.Error("allocs:", allocs)
6290 func BenchmarkInterfaceSmall(b *testing.B) {
6291 v := ValueOf(int64(0))
6292 b.RunParallel(func(pb *testing.PB) {
6299 func TestAllocsInterfaceSmall(t *testing.T) {
6300 if testing.Short() {
6301 t.Skip("skipping malloc count in short mode")
6303 v := ValueOf(int64(0))
6304 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6305 t.Error("allocs:", allocs)
6309 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6310 // The basic usage is:
6313 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6316 // Each iteration of the loop returns a different set of results, until all
6317 // possible result sets have been explored. It is okay for different code paths
6318 // to make different method call sequences on x, but there must be no
6319 // other source of non-determinism in the call sequences.
6321 // When faced with a new decision, x chooses randomly. Future explorations
6322 // of that path will choose successive values for the result. Thus, stopping
6323 // the loop after a fixed number of iterations gives somewhat stochastic
6329 // v := make([]bool, x.Choose(4))
6330 // for i := range v {
6336 // prints (in some order):
6345 // [false false false]
6348 // [false false false false]
6350 // [true true true true]
6351 type exhaustive struct {
6357 type choice struct {
6363 func (x *exhaustive) Next() bool {
6365 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6372 for i := len(x.last) - 1; i >= 0; i-- {
6376 x.last = x.last[:i+1]
6383 func (x *exhaustive) Choose(max int) int {
6384 if x.pos >= len(x.last) {
6385 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6390 panic("inconsistent use of exhaustive tester")
6392 return (c.n + c.off) % max
6395 func (x *exhaustive) Maybe() bool {
6396 return x.Choose(2) == 1
6399 func GCFunc(args []Value) []Value {
6404 func TestReflectFuncTraceback(t *testing.T) {
6405 f := MakeFunc(TypeOf(func() {}), GCFunc)
6409 func TestReflectMethodTraceback(t *testing.T) {
6411 m := ValueOf(p).MethodByName("GCMethod")
6412 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6414 t.Errorf("Call returned %d; want 8", i)
6418 func TestSmallZero(t *testing.T) {
6421 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6422 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6426 func TestBigZero(t *testing.T) {
6427 const size = 1 << 10
6429 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6430 for i := 0; i < size; i++ {
6432 t.Fatalf("Zero object not all zero, index %d", i)
6437 func TestZeroSet(t *testing.T) {
6445 a: 0xaaaaaaaaaaaaaaaa,
6446 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6447 b: 0xbbbbbbbbbbbbbbbb,
6449 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6451 a: 0xaaaaaaaaaaaaaaaa,
6452 b: 0xbbbbbbbbbbbbbbbb,
6454 t.Fatalf("Setting a field to a Zero value didn't work")
6458 func TestFieldByIndexNil(t *testing.T) {
6467 v.FieldByName("P") // should be fine
6470 if err := recover(); err == nil {
6471 t.Fatalf("no error")
6472 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6473 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6476 v.FieldByName("F") // should panic
6478 t.Fatalf("did not panic")
6482 // type Outer struct {
6486 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6487 // The implementation is logically:
6488 // func (p *Outer) M() {
6491 // but since the only change here is the replacement of one pointer receiver with another,
6492 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6493 // then jumps to the M method expecting the *Inner receiver.
6495 // During reflect.Value.Call, we create an argument frame and the associated data structures
6496 // to describe it to the garbage collector, populate the frame, call reflect.call to
6497 // run a function call using that frame, and then copy the results back out of the frame.
6498 // The reflect.call function does a memmove of the frame structure onto the
6499 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6500 // the frame structure (to preserve the outputs).
6502 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6503 // were for the full stack frame. However, in the case where the called function was
6504 // one of these wrappers, the rewritten receiver is almost certainly a different type
6505 // than the original receiver. This is not a problem on the stack, where we use the
6506 // program counter to determine the type information and understand that
6507 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6508 // memory word is now an *Inner. But in the statically typed argument frame created
6509 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6510 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6511 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6512 // memory as if it were an *Outer. If the two have different memory layouts, the
6513 // collection will interpret the memory incorrectly.
6515 // One such possible incorrect interpretation is to treat two arbitrary memory words
6516 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6517 // an interface requires dereferencing the itab word, the misinterpretation will try to
6518 // deference Inner.P1, causing a crash during garbage collection.
6520 // This came up in a real program in issue 7725.
6533 func (pi *Inner) M() {
6534 // Clear references to pi so that the only way the
6535 // garbage collection will find the pointer is in the
6536 // argument frame, typed as a *Outer.
6539 // Set up an interface value that will cause a crash.
6540 // P1 = 1 is a non-zero, so the interface looks non-nil.
6541 // P2 = pi ensures that the data word points into the
6542 // allocated heap; if not the collection skips the interface
6543 // value as irrelevant, without dereferencing P1.
6545 pi.P2 = uintptr(unsafe.Pointer(pi))
6548 func TestCallMethodJump(t *testing.T) {
6549 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6550 // returns but before the args frame has been discarded.
6551 // This is a little clumsy but makes the failure repeatable.
6554 p := &Outer{Inner: new(Inner)}
6556 ValueOf(p).Method(0).Call(nil)
6558 // Stop garbage collecting during reflect.call.
6562 func TestCallArgLive(t *testing.T) {
6563 type T struct{ X, Y *string } // pointerful aggregate
6565 F := func(t T) { *t.X = "ok" }
6567 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6568 // between marshaling argument and the actual call.
6572 runtime.SetFinalizer(x, func(p *string) {
6574 t.Errorf("x dead prematurely")
6579 ValueOf(F).Call([]Value{ValueOf(v)})
6581 // Stop garbage collecting during reflect.call.
6585 func TestMakeFuncStackCopy(t *testing.T) {
6586 target := func(in []Value) []Value {
6589 return []Value{ValueOf(9)}
6592 var concrete func(*int, int) int
6593 fn := MakeFunc(ValueOf(concrete).Type(), target)
6594 ValueOf(&concrete).Elem().Set(fn)
6595 x := concrete(nil, 7)
6597 t.Errorf("have %#q want 9", x)
6601 // use about n KB of stack
6602 func useStack(n int) {
6606 var b [1024]byte // makes frame about 1KB
6607 useStack(n - 1 + int(b[99]))
6614 func TestValueString(t *testing.T) {
6615 rv := ValueOf(Impl{})
6616 if rv.String() != "<reflect_test.Impl Value>" {
6617 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6620 method := rv.Method(0)
6621 if method.String() != "<func() Value>" {
6622 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6626 func TestInvalid(t *testing.T) {
6627 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6628 type T struct{ v any }
6630 v := ValueOf(T{}).Field(0)
6631 if v.IsValid() != true || v.Kind() != Interface {
6632 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6635 if v.IsValid() != false || v.Kind() != Invalid {
6636 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6641 func TestLargeGCProg(t *testing.T) {
6642 fv := ValueOf(func([256]*byte) {})
6643 fv.Call([]Value{ValueOf([256]*byte{})})
6646 func fieldIndexRecover(t Type, i int) (recovered any) {
6648 recovered = recover()
6656 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6657 typ := TypeOf(struct{ X int }{10})
6658 testIndices := [...]struct {
6667 for i, tt := range testIndices {
6668 recoveredErr := fieldIndexRecover(typ, tt.i)
6670 if recoveredErr == nil {
6671 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6674 if recoveredErr != nil {
6675 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6682 func TestCallGC(t *testing.T) {
6683 f := func(a, b, c, d, e string) {
6685 g := func(in []Value) []Value {
6689 typ := ValueOf(f).Type()
6690 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6691 f2("four", "five5", "six666", "seven77", "eight888")
6694 // Issue 18635 (function version).
6695 func TestKeepFuncLive(t *testing.T) {
6696 // Test that we keep makeFuncImpl live as long as it is
6697 // referenced on the stack.
6698 typ := TypeOf(func(i int) {})
6699 var f, g func(in []Value) []Value
6700 f = func(in []Value) []Value {
6702 i := int(in[0].Int())
6704 // We can't use Value.Call here because
6705 // runtime.call* will keep the makeFuncImpl
6706 // alive. However, by converting it to an
6707 // interface value and calling that,
6708 // reflect.callReflect is the only thing that
6709 // can keep the makeFuncImpl live.
6711 // Alternate between f and g so that if we do
6712 // reuse the memory prematurely it's more
6713 // likely to get obviously corrupted.
6714 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6718 g = func(in []Value) []Value {
6720 i := int(in[0].Int())
6721 MakeFunc(typ, f).Interface().(func(i int))(i)
6724 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6727 type UnExportedFirst int
6729 func (i UnExportedFirst) ΦExported() {}
6730 func (i UnExportedFirst) unexported() {}
6733 func TestMethodByNameUnExportedFirst(t *testing.T) {
6735 if recover() != nil {
6736 t.Errorf("should not panic")
6739 typ := TypeOf(UnExportedFirst(0))
6740 m, _ := typ.MethodByName("ΦExported")
6741 if m.Name != "ΦExported" {
6742 t.Errorf("got %s, expected ΦExported", m.Name)
6746 // Issue 18635 (method version).
6747 type KeepMethodLive struct{}
6749 func (k KeepMethodLive) Method1(i int) {
6752 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6756 func (k KeepMethodLive) Method2(i int) {
6758 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6761 func TestKeepMethodLive(t *testing.T) {
6762 // Test that we keep methodValue live as long as it is
6763 // referenced on the stack.
6764 KeepMethodLive{}.Method1(10)
6767 // clobber tries to clobber unreachable memory.
6770 for i := 1; i < 32; i++ {
6771 for j := 0; j < 10; j++ {
6772 obj := make([]*byte, i)
6779 func TestFuncLayout(t *testing.T) {
6780 align := func(x uintptr) uintptr {
6781 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6784 if goarch.PtrSize == 4 {
6785 r = []byte{0, 0, 0, 1}
6797 size, argsize, retOffset uintptr
6798 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6799 intRegs, floatRegs int
6800 floatRegSize uintptr
6804 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6805 size: 6 * goarch.PtrSize,
6806 argsize: 4 * goarch.PtrSize,
6807 retOffset: 4 * goarch.PtrSize,
6808 stack: []byte{1, 0, 1, 0, 1},
6809 gc: []byte{1, 0, 1, 0, 1},
6812 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6813 size: align(align(3*4) + goarch.PtrSize + 2),
6814 argsize: align(3*4) + goarch.PtrSize + 2,
6815 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6820 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6821 size: 4 * goarch.PtrSize,
6822 argsize: 4 * goarch.PtrSize,
6823 retOffset: 4 * goarch.PtrSize,
6824 stack: []byte{1, 0, 1, 1},
6825 gc: []byte{1, 0, 1, 1},
6828 typ: ValueOf(func(a S) {}).Type(),
6829 size: 4 * goarch.PtrSize,
6830 argsize: 4 * goarch.PtrSize,
6831 retOffset: 4 * goarch.PtrSize,
6832 stack: []byte{0, 0, 1, 1},
6833 gc: []byte{0, 0, 1, 1},
6836 rcvr: ValueOf((*byte)(nil)).Type(),
6837 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6838 size: 3 * goarch.PtrSize,
6839 argsize: 3 * goarch.PtrSize,
6840 retOffset: 3 * goarch.PtrSize,
6841 stack: []byte{1, 0, 1},
6842 gc: []byte{1, 0, 1},
6845 typ: ValueOf(func(a uintptr) {}).Type(),
6846 size: goarch.PtrSize,
6847 argsize: goarch.PtrSize,
6848 retOffset: goarch.PtrSize,
6853 typ: ValueOf(func() uintptr { return 0 }).Type(),
6854 size: goarch.PtrSize,
6861 rcvr: ValueOf(uintptr(0)).Type(),
6862 typ: ValueOf(func(a uintptr) {}).Type(),
6863 size: 2 * goarch.PtrSize,
6864 argsize: 2 * goarch.PtrSize,
6865 retOffset: 2 * goarch.PtrSize,
6868 // Note: this one is tricky, as the receiver is not a pointer. But we
6869 // pass the receiver by reference to the autogenerated pointer-receiver
6870 // version of the function.
6872 // TODO(mknyszek): Add tests for non-zero register count.
6874 for _, lt := range tests {
6875 name := lt.typ.String()
6877 name = lt.rcvr.String() + "." + name
6879 t.Run(name, func(t *testing.T) {
6880 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6882 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6883 if typ.Size() != lt.size {
6884 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6886 if argsize != lt.argsize {
6887 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6889 if retOffset != lt.retOffset {
6890 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6892 if !bytes.Equal(stack, lt.stack) {
6893 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6895 if !bytes.Equal(gc, lt.gc) {
6896 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6898 if !bytes.Equal(inRegs, lt.inRegs) {
6899 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6901 if !bytes.Equal(outRegs, lt.outRegs) {
6902 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6904 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6905 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6911 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6912 heapBits := GCBits(New(typ).Interface())
6913 if !bytes.Equal(heapBits, bits) {
6914 _, _, line, _ := runtime.Caller(1)
6915 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6919 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6920 // Creating a slice causes the runtime to repeat a bitmap,
6921 // which exercises a different path from making the compiler
6922 // repeat a bitmap for a small array or executing a repeat in
6924 val := MakeSlice(typ, 0, cap)
6925 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
6926 heapBits := GCBits(data.Interface())
6927 // Repeat the bitmap for the slice size, trimming scalars in
6928 // the last element.
6929 bits = rep(cap, bits)
6930 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6931 bits = bits[:len(bits)-1]
6933 if !bytes.Equal(heapBits, bits) {
6934 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6938 func TestGCBits(t *testing.T) {
6939 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6941 // Building blocks for types seen by the compiler (like [2]Xscalar).
6942 // The compiler will create the type structures for the derived types,
6943 // including their GC metadata.
6944 type Xscalar struct{ x uintptr }
6945 type Xptr struct{ x *byte }
6946 type Xptrscalar struct {
6950 type Xscalarptr struct {
6954 type Xbigptrscalar struct {
6959 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6961 // Building blocks for types constructed by reflect.
6962 // This code is in a separate block so that code below
6963 // cannot accidentally refer to these.
6964 // The compiler must NOT see types derived from these
6965 // (for example, [2]Scalar must NOT appear in the program),
6966 // or else reflect will use it instead of having to construct one.
6967 // The goal is to test the construction.
6968 type Scalar struct{ x uintptr }
6969 type Ptr struct{ x *byte }
6970 type Ptrscalar struct {
6974 type Scalarptr struct {
6978 type Bigptrscalar struct {
6983 Tscalar = TypeOf(Scalar{})
6984 Tint64 = TypeOf(Int64(0))
6985 Tptr = TypeOf(Ptr{})
6986 Tscalarptr = TypeOf(Scalarptr{})
6987 Tptrscalar = TypeOf(Ptrscalar{})
6988 Tbigptrscalar = TypeOf(Bigptrscalar{})
6993 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6994 verifyGCBits(t, Tscalar, empty)
6995 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6996 verifyGCBits(t, Tptr, lit(1))
6997 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6998 verifyGCBits(t, Tscalarptr, lit(0, 1))
6999 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
7000 verifyGCBits(t, Tptrscalar, lit(1))
7002 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
7003 verifyGCBits(t, ArrayOf(0, Tptr), empty)
7004 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
7005 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
7006 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
7007 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
7008 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
7009 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
7010 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
7011 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
7012 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
7013 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
7014 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
7015 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
7016 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
7017 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
7018 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
7019 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
7020 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7021 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
7022 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
7023 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
7024 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
7025 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
7026 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7027 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
7029 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
7030 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
7031 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
7032 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
7033 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
7034 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
7035 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
7036 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
7037 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
7038 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
7039 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
7040 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
7041 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
7042 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
7043 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
7044 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
7045 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
7046 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
7047 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
7048 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7049 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7050 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7051 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7052 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7053 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7054 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7056 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7057 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7059 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7060 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7062 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7063 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7065 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7066 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7068 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7069 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7071 hdr := make([]byte, 8/goarch.PtrSize)
7073 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7074 verifyGCBits(t, MapBucketOf(k, e), want)
7075 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7079 map[Xscalar]Xptr(nil),
7080 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7083 map[Xscalarptr]Xptr(nil),
7084 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7085 verifyMapBucket(t, Tint64, Tptr,
7086 map[int64]Xptr(nil),
7087 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7090 map[Xscalar]Xscalar(nil),
7093 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7094 map[[2]Xscalarptr][3]Xptrscalar(nil),
7095 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7097 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7098 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7099 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7101 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7102 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7103 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7105 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7106 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7107 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7109 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7110 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7111 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7114 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7115 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7116 func lit(x ...byte) []byte { return x }
7118 func TestTypeOfTypeOf(t *testing.T) {
7119 // Check that all the type constructors return concrete *rtype implementations.
7120 // It's difficult to test directly because the reflect package is only at arm's length.
7121 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7122 check := func(name string, typ Type) {
7123 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7124 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7128 type T struct{ int }
7129 check("TypeOf", TypeOf(T{}))
7131 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7132 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7133 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7134 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7135 check("PtrTo", PointerTo(TypeOf(T{})))
7136 check("SliceOf", SliceOf(TypeOf(T{})))
7139 type XM struct{ _ bool }
7141 func (*XM) String() string { return "" }
7143 func TestPtrToMethods(t *testing.T) {
7145 yp := New(TypeOf(y)).Interface()
7146 _, ok := yp.(fmt.Stringer)
7148 t.Fatal("does not implement Stringer, but should")
7152 func TestMapAlloc(t *testing.T) {
7153 m := ValueOf(make(map[int]int, 10))
7156 allocs := testing.AllocsPerRun(100, func() {
7160 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7165 val := ValueOf(&tmp).Elem()
7166 allocs = testing.AllocsPerRun(100, func() {
7167 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7168 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7169 for i := 0; i < size/2; i++ {
7170 val.SetInt(int64(i))
7171 mv.SetMapIndex(val, val)
7175 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7177 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7178 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7179 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7182 func TestChanAlloc(t *testing.T) {
7183 // Note: for a chan int, the return Value must be allocated, so we
7184 // use a chan *int instead.
7185 c := ValueOf(make(chan *int, 1))
7186 v := ValueOf(new(int))
7187 allocs := testing.AllocsPerRun(100, func() {
7191 if allocs < 0.5 || allocs > 1.5 {
7192 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7194 // Note: there is one allocation in reflect.recv which seems to be
7195 // a limitation of escape analysis. If that is ever fixed the
7196 // allocs < 0.5 condition will trigger and this test should be fixed.
7199 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7201 type nameTest struct {
7206 var nameTests = []nameTest{
7207 {(*int32)(nil), "int32"},
7210 {(*chan D1)(nil), ""},
7211 {(*func() D1)(nil), ""},
7212 {(*<-chan D1)(nil), ""},
7213 {(*chan<- D1)(nil), ""},
7218 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7221 func TestNames(t *testing.T) {
7222 for _, test := range nameTests {
7223 typ := TypeOf(test.v).Elem()
7224 if got := typ.Name(); got != test.want {
7225 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7230 func TestExported(t *testing.T) {
7231 type ΦExported struct{}
7232 type φUnexported struct{}
7239 type exportTest struct {
7243 exportTests := []exportTest{
7247 {(*big)(nil), false},
7248 {(BigP)(nil), true},
7249 {(*BigP)(nil), true},
7250 {ΦExported{}, true},
7251 {φUnexported{}, false},
7258 for i, test := range exportTests {
7259 typ := TypeOf(test.v)
7260 if got := IsExported(typ); got != test.want {
7261 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7266 func TestTypeStrings(t *testing.T) {
7267 type stringTest struct {
7271 stringTests := []stringTest{
7272 {TypeOf(func(int) {}), "func(int)"},
7273 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7274 {TypeOf(XM{}), "reflect_test.XM"},
7275 {TypeOf(new(XM)), "*reflect_test.XM"},
7276 {TypeOf(new(XM).String), "func() string"},
7277 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7278 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7279 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7280 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7281 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7284 for i, test := range stringTests {
7285 if got, want := test.typ.String(), test.want; got != want {
7286 t.Errorf("type %d String()=%q, want %q", i, got, want)
7291 func TestOffsetLock(t *testing.T) {
7292 var wg sync.WaitGroup
7293 for i := 0; i < 4; i++ {
7297 for j := 0; j < 50; j++ {
7298 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7306 func BenchmarkNew(b *testing.B) {
7308 b.RunParallel(func(pb *testing.PB) {
7315 func BenchmarkMap(b *testing.B) {
7318 value := ValueOf((V)(nil))
7319 stringKeys := []string{}
7320 mapOfStrings := map[string]V{}
7321 uint64Keys := []uint64{}
7322 mapOfUint64s := map[uint64]V{}
7323 userStringKeys := []S{}
7324 mapOfUserStrings := map[S]V{}
7325 for i := 0; i < 100; i++ {
7326 stringKey := fmt.Sprintf("key%d", i)
7327 stringKeys = append(stringKeys, stringKey)
7328 mapOfStrings[stringKey] = nil
7330 uint64Key := uint64(i)
7331 uint64Keys = append(uint64Keys, uint64Key)
7332 mapOfUint64s[uint64Key] = nil
7334 userStringKey := S(fmt.Sprintf("key%d", i))
7335 userStringKeys = append(userStringKeys, userStringKey)
7336 mapOfUserStrings[userStringKey] = nil
7341 m, keys, value Value
7343 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7344 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7345 {"UserStringKeys", ValueOf(mapOfUserStrings), ValueOf(userStringKeys), value},
7348 for _, tt := range tests {
7349 b.Run(tt.label, func(b *testing.B) {
7350 b.Run("MapIndex", func(b *testing.B) {
7352 for i := 0; i < b.N; i++ {
7353 for j := tt.keys.Len() - 1; j >= 0; j-- {
7354 tt.m.MapIndex(tt.keys.Index(j))
7358 b.Run("SetMapIndex", func(b *testing.B) {
7360 for i := 0; i < b.N; i++ {
7361 for j := tt.keys.Len() - 1; j >= 0; j-- {
7362 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7370 func TestSwapper(t *testing.T) {
7376 type pairPtr struct {
7388 in: []int{1, 20, 300},
7391 want: []int{300, 20, 1},
7394 in: []uintptr{1, 20, 300},
7397 want: []uintptr{300, 20, 1},
7400 in: []int16{1, 20, 300},
7403 want: []int16{300, 20, 1},
7406 in: []int8{1, 20, 100},
7409 want: []int8{100, 20, 1},
7412 in: []*I{&a, &b, &c},
7415 want: []*I{&c, &b, &a},
7418 in: []string{"eric", "sergey", "larry"},
7421 want: []string{"larry", "sergey", "eric"},
7424 in: []S{"eric", "sergey", "larry"},
7427 want: []S{"larry", "sergey", "eric"},
7430 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7433 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7436 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7439 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7443 for i, tt := range tests {
7444 inStr := fmt.Sprint(tt.in)
7445 Swapper(tt.in)(tt.i, tt.j)
7446 if !DeepEqual(tt.in, tt.want) {
7447 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7452 // TestUnaddressableField tests that the reflect package will not allow
7453 // a type from another package to be used as a named type with an
7454 // unexported field.
7456 // This ensures that unexported fields cannot be modified by other packages.
7457 func TestUnaddressableField(t *testing.T) {
7458 var b Buffer // type defined in reflect, a different package
7459 var localBuffer struct {
7462 lv := ValueOf(&localBuffer).Elem()
7464 shouldPanic("Set", func() {
7473 type Talias1 struct {
7481 type Talias2 struct {
7486 func TestAliasNames(t *testing.T) {
7487 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7488 out := fmt.Sprintf("%#v", t1)
7489 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7491 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7494 t2 := Talias2{Tint: 1, Tint2: 2}
7495 out = fmt.Sprintf("%#v", t2)
7496 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7498 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7502 func TestIssue22031(t *testing.T) {
7503 type s []struct{ C int }
7506 type t2 struct{ f s }
7509 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7510 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7513 for i, test := range tests {
7515 t.Errorf("%d: CanSet: got true, want false", i)
7520 type NonExportedFirst int
7522 func (i NonExportedFirst) ΦExported() {}
7523 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7525 func TestIssue22073(t *testing.T) {
7526 m := ValueOf(NonExportedFirst(0)).Method(0)
7528 if got := m.Type().NumOut(); got != 0 {
7529 t.Errorf("NumOut: got %v, want 0", got)
7536 func TestMapIterNonEmptyMap(t *testing.T) {
7537 m := map[string]int{"one": 1, "two": 2, "three": 3}
7538 iter := ValueOf(m).MapRange()
7539 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7540 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7544 func TestMapIterNilMap(t *testing.T) {
7545 var m map[string]int
7546 iter := ValueOf(m).MapRange()
7547 if got, want := iterateToString(iter), `[]`; got != want {
7548 t.Errorf("non-empty result iteratoring nil map: %s", got)
7552 func TestMapIterReset(t *testing.T) {
7553 iter := new(MapIter)
7555 // Use of zero iterator should panic.
7557 defer func() { recover() }()
7559 t.Error("Next did not panic")
7562 // Reset to new Map should work.
7563 m := map[string]int{"one": 1, "two": 2, "three": 3}
7564 iter.Reset(ValueOf(m))
7565 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7566 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7569 // Reset to Zero value should work, but iterating over it should panic.
7572 defer func() { recover() }()
7574 t.Error("Next did not panic")
7577 // Reset to a different Map with different types should work.
7578 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7579 iter.Reset(ValueOf(m2))
7580 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7581 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7584 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7585 m3 := map[uint64]uint64{
7590 kv := New(TypeOf(uint64(0))).Elem()
7591 for i := 0; i < 5; i++ {
7592 var seenk, seenv uint64
7593 iter.Reset(ValueOf(m3))
7597 kv.SetIterValue(iter)
7601 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7603 if seenv != 0b1110 {
7604 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7608 // Reset should not allocate.
7609 n := int(testing.AllocsPerRun(10, func() {
7610 iter.Reset(ValueOf(m2))
7614 t.Errorf("MapIter.Reset allocated %d times", n)
7618 func TestMapIterSafety(t *testing.T) {
7619 // Using a zero MapIter causes a panic, but not a crash.
7621 defer func() { recover() }()
7623 t.Fatal("Key did not panic")
7626 defer func() { recover() }()
7627 new(MapIter).Value()
7628 t.Fatal("Value did not panic")
7631 defer func() { recover() }()
7633 t.Fatal("Next did not panic")
7636 // Calling Key/Value on a MapIter before Next
7637 // causes a panic, but not a crash.
7638 var m map[string]int
7639 iter := ValueOf(m).MapRange()
7642 defer func() { recover() }()
7644 t.Fatal("Key did not panic")
7647 defer func() { recover() }()
7649 t.Fatal("Value did not panic")
7652 // Calling Next, Key, or Value on an exhausted iterator
7653 // causes a panic, but not a crash.
7654 iter.Next() // -> false
7656 defer func() { recover() }()
7658 t.Fatal("Key did not panic")
7661 defer func() { recover() }()
7663 t.Fatal("Value did not panic")
7666 defer func() { recover() }()
7668 t.Fatal("Next did not panic")
7672 func TestMapIterNext(t *testing.T) {
7673 // The first call to Next should reflect any
7674 // insertions to the map since the iterator was created.
7675 m := map[string]int{}
7676 iter := ValueOf(m).MapRange()
7678 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7679 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7683 func BenchmarkMapIterNext(b *testing.B) {
7684 m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3})
7686 for i := 0; i < b.N; i++ {
7693 func TestMapIterDelete0(t *testing.T) {
7694 // Delete all elements before first iteration.
7695 m := map[string]int{"one": 1, "two": 2, "three": 3}
7696 iter := ValueOf(m).MapRange()
7700 if got, want := iterateToString(iter), `[]`; got != want {
7701 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7705 func TestMapIterDelete1(t *testing.T) {
7706 // Delete all elements after first iteration.
7707 m := map[string]int{"one": 1, "two": 2, "three": 3}
7708 iter := ValueOf(m).MapRange()
7711 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7717 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7721 // iterateToString returns the set of elements
7722 // returned by an iterator in readable form.
7723 func iterateToString(it *MapIter) string {
7726 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7727 got = append(got, line)
7730 return "[" + strings.Join(got, ", ") + "]"
7733 func TestConvertibleTo(t *testing.T) {
7734 t1 := ValueOf(example1.MyStruct{}).Type()
7735 t2 := ValueOf(example2.MyStruct{}).Type()
7737 // Shouldn't raise stack overflow
7738 if t1.ConvertibleTo(t2) {
7739 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7742 t3 := ValueOf([]example1.MyStruct{}).Type()
7743 t4 := ValueOf([]example2.MyStruct{}).Type()
7745 if t3.ConvertibleTo(t4) {
7746 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7750 func TestSetIter(t *testing.T) {
7751 data := map[string]int{
7759 k := New(TypeOf("")).Elem()
7760 v := New(TypeOf(0)).Elem()
7761 shouldPanic("Value.SetIterKey called before Next", func() {
7764 shouldPanic("Value.SetIterValue called before Next", func() {
7767 data2 := map[string]int{}
7771 data2[k.Interface().(string)] = v.Interface().(int)
7773 if !DeepEqual(data, data2) {
7774 t.Errorf("maps not equal, got %v want %v", data2, data)
7776 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7779 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7785 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7786 ValueOf("").SetIterKey(i)
7788 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7789 ValueOf(0).SetIterValue(i)
7791 shouldPanic("value of type string is not assignable to type int", func() {
7792 New(TypeOf(0)).Elem().SetIterKey(i)
7794 shouldPanic("value of type int is not assignable to type string", func() {
7795 New(TypeOf("")).Elem().SetIterValue(i)
7798 // Make sure assignment conversion works.
7800 y := ValueOf(&x).Elem()
7802 if _, ok := data[x.(string)]; !ok {
7803 t.Errorf("got key %s which is not in map", x)
7806 if x.(int) < 1 || x.(int) > 3 {
7807 t.Errorf("got value %d which is not in map", x)
7810 // Try some key/value types which are direct interfaces.
7813 pp := map[*int]*int{
7816 i = ValueOf(pp).MapRange()
7819 if got := *y.Interface().(*int); got != a {
7820 t.Errorf("pointer incorrect: got %d want %d", got, a)
7823 if got := *y.Interface().(*int); got != b {
7824 t.Errorf("pointer incorrect: got %d want %d", got, b)
7829 type nih struct{ x int }
7831 var global_nih = nih{x: 7}
7833 func TestNotInHeapDeref(t *testing.T) {
7835 v := ValueOf((*nih)(nil))
7837 shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
7839 v = ValueOf(&global_nih)
7840 if got := v.Elem().Field(0).Int(); got != 7 {
7841 t.Fatalf("got %d, want 7", got)
7844 v = ValueOf((*nih)(unsafe.Pointer(new(int))))
7845 shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
7846 shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() })
7847 shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() })
7850 func TestMethodCallValueCodePtr(t *testing.T) {
7851 m := ValueOf(Point{}).Method(1)
7852 want := MethodValueCallCodePtr()
7853 if got := uintptr(m.UnsafePointer()); got != want {
7854 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7856 if got := m.Pointer(); got != want {
7857 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7862 type B[T any] struct{}
7864 func TestIssue50208(t *testing.T) {
7865 want1 := "B[reflect_test.A]"
7866 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7867 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7869 want2 := "B[reflect_test.B[reflect_test.A]]"
7870 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7871 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7875 func TestNegativeKindString(t *testing.T) {
7877 s := Kind(x).String()
7880 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
7889 var sourceAll = struct {
7898 Bool: ValueOf(new(bool)).Elem(),
7899 String: ValueOf(new(string)).Elem(),
7900 Bytes: ValueOf(new([]byte)).Elem(),
7901 NamedBytes: ValueOf(new(namedBytes)).Elem(),
7902 BytesArray: ValueOf(new([32]byte)).Elem(),
7903 SliceAny: ValueOf(new([]any)).Elem(),
7904 MapStringAny: ValueOf(new(map[string]any)).Elem(),
7907 var sinkAll struct {
7914 func BenchmarkBool(b *testing.B) {
7915 for i := 0; i < b.N; i++ {
7916 sinkAll.RawBool = sourceAll.Bool.Bool()
7920 func BenchmarkString(b *testing.B) {
7921 for i := 0; i < b.N; i++ {
7922 sinkAll.RawString = sourceAll.String.String()
7926 func BenchmarkBytes(b *testing.B) {
7927 for i := 0; i < b.N; i++ {
7928 sinkAll.RawBytes = sourceAll.Bytes.Bytes()
7932 func BenchmarkNamedBytes(b *testing.B) {
7933 for i := 0; i < b.N; i++ {
7934 sinkAll.RawBytes = sourceAll.NamedBytes.Bytes()
7938 func BenchmarkBytesArray(b *testing.B) {
7939 for i := 0; i < b.N; i++ {
7940 sinkAll.RawBytes = sourceAll.BytesArray.Bytes()
7944 func BenchmarkSliceLen(b *testing.B) {
7945 for i := 0; i < b.N; i++ {
7946 sinkAll.RawInt = sourceAll.SliceAny.Len()
7950 func BenchmarkMapLen(b *testing.B) {
7951 for i := 0; i < b.N; i++ {
7952 sinkAll.RawInt = sourceAll.MapStringAny.Len()
7956 func BenchmarkStringLen(b *testing.B) {
7957 for i := 0; i < b.N; i++ {
7958 sinkAll.RawInt = sourceAll.String.Len()
7962 func BenchmarkArrayLen(b *testing.B) {
7963 for i := 0; i < b.N; i++ {
7964 sinkAll.RawInt = sourceAll.BytesArray.Len()
7968 func BenchmarkSliceCap(b *testing.B) {
7969 for i := 0; i < b.N; i++ {
7970 sinkAll.RawInt = sourceAll.SliceAny.Cap()
7974 func TestValue_Cap(t *testing.T) {
7975 a := &[3]int{1, 2, 3}
7977 if v.Cap() != cap(a) {
7978 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7983 if v.Cap() != cap(a) {
7984 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7987 getError := func(f func()) (errorStr string) {
7990 if str, ok := e.(string); ok {
7997 e := getError(func() {
8001 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
8003 t.Errorf("error is %q, want %q", e, wantStr)
8007 func TestValue_Len(t *testing.T) {
8008 a := &[3]int{1, 2, 3}
8010 if v.Len() != len(a) {
8011 t.Errorf("Len = %d want %d", v.Len(), len(a))
8016 if v.Len() != len(a) {
8017 t.Errorf("Len = %d want %d", v.Len(), len(a))
8020 getError := func(f func()) (errorStr string) {
8023 if str, ok := e.(string); ok {
8030 e := getError(func() {
8034 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
8036 t.Errorf("error is %q, want %q", e, wantStr)