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 func TestNilMap(t *testing.T) {
1510 var m map[string]int
1512 keys := mv.MapKeys()
1514 t.Errorf(">0 keys for nil map: %v", keys)
1517 // Check that value for missing key is zero.
1518 x := mv.MapIndex(ValueOf("hello"))
1519 if x.Kind() != Invalid {
1520 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1523 // Check big value too.
1524 var mbig map[string][10 << 20]byte
1525 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1526 if x.Kind() != Invalid {
1527 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1530 // Test that deletes from a nil map succeed.
1531 mv.SetMapIndex(ValueOf("hi"), Value{})
1534 func TestChan(t *testing.T) {
1535 for loop := 0; loop < 2; loop++ {
1539 // check both ways to allocate channels
1542 c = make(chan int, 1)
1545 cv = MakeChan(TypeOf(c), 1)
1546 c = cv.Interface().(chan int)
1551 if i := <-c; i != 2 {
1552 t.Errorf("reflect Send 2, native recv %d", i)
1557 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1558 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1562 val, ok := cv.TryRecv()
1563 if val.IsValid() || ok {
1564 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1569 val, ok = cv.TryRecv()
1571 t.Errorf("TryRecv on ready chan got nil")
1572 } else if i := val.Int(); i != 4 || !ok {
1573 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1578 ok = cv.TrySend(ValueOf(5))
1581 t.Errorf("TrySend on full chan succeeded: value %d", i)
1585 ok = cv.TrySend(ValueOf(6))
1587 t.Errorf("TrySend on empty chan failed")
1590 t.Errorf("TrySend failed but it did send %d", x)
1594 if i = <-c; i != 6 {
1595 t.Errorf("TrySend 6, recv %d", i)
1602 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1603 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1605 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1606 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1610 // check creation of unbuffered channel
1612 cv := MakeChan(TypeOf(c), 0)
1613 c = cv.Interface().(chan int)
1614 if cv.TrySend(ValueOf(7)) {
1615 t.Errorf("TrySend on sync chan succeeded")
1617 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1618 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1622 cv = MakeChan(TypeOf(c), 10)
1623 c = cv.Interface().(chan int)
1624 for i := 0; i < 3; i++ {
1627 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1628 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1632 // caseInfo describes a single case in a select test.
1633 type caseInfo struct {
1642 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1644 func TestSelect(t *testing.T) {
1645 selectWatch.once.Do(func() { go selectWatcher() })
1649 newop := func(n int, cap int) (ch, val Value) {
1652 c := make(chan int, cap)
1656 c := make(chan string, cap)
1658 val = ValueOf(fmt.Sprint(n))
1663 for n := 0; x.Next(); n++ {
1664 if testing.Short() && n >= 1000 {
1667 if n >= 100000 && !*allselect {
1670 if n%100000 == 0 && testing.Verbose() {
1671 println("TestSelect", n)
1673 var cases []SelectCase
1678 ch, val := newop(len(cases), 1)
1679 cases = append(cases, SelectCase{
1684 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1689 ch, val := newop(len(cases), 1)
1691 cases = append(cases, SelectCase{
1695 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1700 ch, val := newop(len(cases), 0)
1701 cases = append(cases, SelectCase{
1708 f := func() { ch.Recv() }
1709 info = append(info, caseInfo{desc: "blocking send", helper: f})
1711 info = append(info, caseInfo{desc: "blocking send"})
1717 ch, val := newop(len(cases), 0)
1718 cases = append(cases, SelectCase{
1724 f := func() { ch.Send(val) }
1725 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1727 info = append(info, caseInfo{desc: "blocking recv"})
1733 // Maybe include value to send.
1738 cases = append(cases, SelectCase{
1742 info = append(info, caseInfo{desc: "zero Chan send"})
1745 // Zero Chan receive.
1747 cases = append(cases, SelectCase{
1750 info = append(info, caseInfo{desc: "zero Chan recv"})
1755 cases = append(cases, SelectCase{
1757 Chan: ValueOf((chan int)(nil)),
1760 info = append(info, caseInfo{desc: "nil Chan send"})
1765 cases = append(cases, SelectCase{
1767 Chan: ValueOf((chan int)(nil)),
1769 info = append(info, caseInfo{desc: "nil Chan recv"})
1772 // closed Chan send.
1774 ch := make(chan int)
1776 cases = append(cases, SelectCase{
1781 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1784 // closed Chan recv.
1786 ch, val := newop(len(cases), 0)
1788 val = Zero(val.Type())
1789 cases = append(cases, SelectCase{
1793 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1796 var helper func() // goroutine to help the select complete
1798 // Add default? Must be last case here, but will permute.
1799 // Add the default if the select would otherwise
1800 // block forever, and maybe add it anyway.
1806 for i, c := range info {
1814 } else if c.helper != nil {
1816 helpers = append(helpers, i)
1819 if !canProceed || x.Maybe() {
1820 cases = append(cases, SelectCase{
1823 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1825 } else if canBlock {
1826 // Select needs to communicate with another goroutine.
1827 cas := &info[helpers[x.Choose(len(helpers))]]
1829 cas.canSelect = true
1833 // Permute cases and case info.
1834 // Doing too much here makes the exhaustive loop
1835 // too exhausting, so just do two swaps.
1836 for loop := 0; loop < 2; loop++ {
1837 i := x.Choose(len(cases))
1838 j := x.Choose(len(cases))
1839 cases[i], cases[j] = cases[j], cases[i]
1840 info[i], info[j] = info[j], info[i]
1844 // We wait before kicking off a goroutine to satisfy a blocked select.
1845 // The pause needs to be big enough to let the select block before
1846 // we run the helper, but if we lose that race once in a while it's okay: the
1847 // select will just proceed immediately. Not a big deal.
1848 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1849 pause := 10 * time.Microsecond
1850 if testing.Short() {
1851 pause = 100 * time.Microsecond
1853 time.AfterFunc(pause, helper)
1857 i, recv, recvOK, panicErr := runSelect(cases, info)
1858 if panicErr != nil && !canPanic {
1859 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1861 if panicErr == nil && canPanic && numCanSelect == 1 {
1862 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1864 if panicErr != nil {
1872 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1874 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1878 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1882 if cases[i].Dir == SelectRecv {
1883 if !recv.IsValid() {
1884 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1886 if !cas.recv.IsValid() {
1887 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1889 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1890 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1891 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1893 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1896 if recv.IsValid() || recvOK {
1897 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1903 func TestSelectMaxCases(t *testing.T) {
1904 var sCases []SelectCase
1905 channel := make(chan int)
1907 for i := 0; i < 65536; i++ {
1908 sCases = append(sCases, SelectCase{
1910 Chan: ValueOf(channel),
1914 _, _, _ = Select(sCases)
1915 sCases = append(sCases, SelectCase{
1917 Chan: ValueOf(channel),
1920 if err := recover(); err != nil {
1921 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1922 t.Fatalf("unexpected error from select call with greater than max supported cases")
1925 t.Fatalf("expected select call to panic with greater than max supported cases")
1929 _, _, _ = Select(sCases)
1932 func TestSelectNop(t *testing.T) {
1933 // "select { default: }" should always return the default case.
1934 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1936 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1940 func BenchmarkSelect(b *testing.B) {
1941 channel := make(chan int)
1943 var cases []SelectCase
1944 for i := 0; i < 8; i++ {
1945 cases = append(cases, SelectCase{
1947 Chan: ValueOf(channel),
1950 for _, numCases := range []int{1, 4, 8} {
1951 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1953 for i := 0; i < b.N; i++ {
1954 _, _, _ = Select(cases[:numCases])
1960 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1961 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1962 // an error describing the select and panics the entire test binary.
1963 var selectWatch struct {
1970 func selectWatcher() {
1972 time.Sleep(1 * time.Second)
1974 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1975 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1976 panic("select stuck")
1978 selectWatch.Unlock()
1982 // runSelect runs a single select test.
1983 // It returns the values returned by Select but also returns
1984 // a panic value if the Select panics.
1985 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
1987 panicErr = recover()
1990 selectWatch.info = nil
1991 selectWatch.Unlock()
1995 selectWatch.now = time.Now()
1996 selectWatch.info = info
1997 selectWatch.Unlock()
1999 chosen, recv, recvOK = Select(cases)
2003 // fmtSelect formats the information about a single select test.
2004 func fmtSelect(info []caseInfo) string {
2005 var buf bytes.Buffer
2006 fmt.Fprintf(&buf, "\nselect {\n")
2007 for i, cas := range info {
2008 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2009 if cas.recv.IsValid() {
2010 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2013 fmt.Fprintf(&buf, " canselect")
2016 fmt.Fprintf(&buf, " panic")
2018 fmt.Fprintf(&buf, "\n")
2020 fmt.Fprintf(&buf, "}")
2026 // Difficult test for function call because of
2027 // implicit padding between arguments.
2028 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) {
2029 return b, c, d, e, f, g, h
2032 func TestFunc(t *testing.T) {
2033 ret := ValueOf(dummy).Call([]Value{
2037 ValueOf(two{40, 50}),
2039 ValueOf(float32(70)),
2043 t.Fatalf("Call returned %d values, want 7", len(ret))
2046 i := byte(ret[0].Uint())
2047 j := int(ret[1].Int())
2048 k := byte(ret[2].Uint())
2049 l := ret[3].Interface().(two)
2050 m := byte(ret[4].Uint())
2051 n := float32(ret[5].Float())
2052 o := byte(ret[6].Uint())
2054 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2055 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)
2058 for i, v := range ret {
2060 t.Errorf("result %d is addressable", i)
2065 func TestCallConvert(t *testing.T) {
2066 v := ValueOf(new(io.ReadWriter)).Elem()
2067 f := ValueOf(func(r io.Reader) io.Reader { return r })
2068 out := f.Call([]Value{v})
2069 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2070 t.Errorf("expected [nil], got %v", out)
2074 type emptyStruct struct{}
2076 type nonEmptyStruct struct {
2080 func returnEmpty() emptyStruct {
2081 return emptyStruct{}
2084 func takesEmpty(e emptyStruct) {
2087 func returnNonEmpty(i int) nonEmptyStruct {
2088 return nonEmptyStruct{member: i}
2091 func takesNonEmpty(n nonEmptyStruct) int {
2095 func TestCallWithStruct(t *testing.T) {
2096 r := ValueOf(returnEmpty).Call(nil)
2097 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2098 t.Errorf("returning empty struct returned %#v instead", r)
2100 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2102 t.Errorf("takesEmpty returned values: %#v", r)
2104 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2105 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2106 t.Errorf("returnNonEmpty returned %#v", r)
2108 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2109 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2110 t.Errorf("takesNonEmpty returned %#v", r)
2114 func TestCallReturnsEmpty(t *testing.T) {
2115 // Issue 21717: past-the-end pointer write in Call with
2116 // nonzero-sized frame and zero-sized return value.
2118 var finalized uint32
2119 f := func() (emptyStruct, *[2]int64) {
2120 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2121 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2122 return emptyStruct{}, i
2124 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2125 timeout := time.After(5 * time.Second)
2126 for atomic.LoadUint32(&finalized) == 0 {
2129 t.Fatal("finalizer did not run")
2135 runtime.KeepAlive(v)
2138 func BenchmarkCall(b *testing.B) {
2139 fv := ValueOf(func(a, b string) {})
2141 b.RunParallel(func(pb *testing.PB) {
2142 args := []Value{ValueOf("a"), ValueOf("b")}
2151 func (i *myint) inc() {
2155 func BenchmarkCallMethod(b *testing.B) {
2160 for i := 0; i < b.N; i++ {
2165 func BenchmarkCallArgCopy(b *testing.B) {
2166 byteArray := func(n int) Value {
2167 return Zero(ArrayOf(n, TypeOf(byte(0))))
2169 sizes := [...]struct {
2173 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2174 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2175 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2176 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2177 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2179 for _, size := range sizes {
2180 bench := func(b *testing.B) {
2181 args := []Value{size.arg}
2182 b.SetBytes(int64(size.arg.Len()))
2184 b.RunParallel(func(pb *testing.PB) {
2190 name := fmt.Sprintf("size=%v", size.arg.Len())
2195 func TestMakeFunc(t *testing.T) {
2197 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2198 ValueOf(&f).Elem().Set(fv)
2200 // Call g with small arguments so that there is
2201 // something predictable (and different from the
2202 // correct results) in those positions on the stack.
2204 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2206 // Call constructed function f.
2207 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2208 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2209 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)
2213 func TestMakeFuncInterface(t *testing.T) {
2214 fn := func(i int) int { return i }
2215 incr := func(in []Value) []Value {
2216 return []Value{ValueOf(int(in[0].Int() + 1))}
2218 fv := MakeFunc(TypeOf(fn), incr)
2219 ValueOf(&fn).Elem().Set(fv)
2220 if r := fn(2); r != 3 {
2221 t.Errorf("Call returned %d, want 3", r)
2223 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2224 t.Errorf("Call returned %d, want 15", r)
2226 if r := fv.Interface().(func(int) int)(26); r != 27 {
2227 t.Errorf("Call returned %d, want 27", r)
2231 func TestMakeFuncVariadic(t *testing.T) {
2232 // Test that variadic arguments are packed into a slice and passed as last arg
2233 fn := func(_ int, is ...int) []int { return nil }
2234 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2235 ValueOf(&fn).Elem().Set(fv)
2238 if r[0] != 2 || r[1] != 3 {
2239 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2242 r = fn(1, []int{2, 3}...)
2243 if r[0] != 2 || r[1] != 3 {
2244 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2247 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2248 if r[0] != 2 || r[1] != 3 {
2249 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2252 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2253 if r[0] != 2 || r[1] != 3 {
2254 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2257 f := fv.Interface().(func(int, ...int) []int)
2260 if r[0] != 2 || r[1] != 3 {
2261 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2263 r = f(1, []int{2, 3}...)
2264 if r[0] != 2 || r[1] != 3 {
2265 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2269 // Dummy type that implements io.WriteCloser
2273 func (w *WC) Write(p []byte) (n int, err error) {
2276 func (w *WC) Close() error {
2280 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2281 // reflect.Values returned from the wrapped function should be assignment-converted
2282 // to the types returned by the result of MakeFunc.
2284 // Concrete types should be promotable to interfaces they implement.
2286 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2287 return []Value{ValueOf(io.EOF)}
2288 }).Interface().(func() error)
2291 // Super-interfaces should be promotable to simpler interfaces.
2292 var g func() io.Writer
2293 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2294 var w io.WriteCloser = &WC{}
2295 return []Value{ValueOf(&w).Elem()}
2296 }).Interface().(func() io.Writer)
2299 // Channels should be promotable to directional channels.
2300 var h func() <-chan int
2301 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2302 return []Value{ValueOf(make(chan int))}
2303 }).Interface().(func() <-chan int)
2306 // Unnamed types should be promotable to named types.
2307 type T struct{ a, b, c int }
2309 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2310 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2311 }).Interface().(func() T)
2315 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2316 // Type doesn't implement the required interface.
2317 shouldPanic("", func() {
2319 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2320 return []Value{ValueOf(int(7))}
2321 }).Interface().(func() error)
2324 // Assigning to an interface with additional methods.
2325 shouldPanic("", func() {
2326 var f func() io.ReadWriteCloser
2327 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2328 var w io.WriteCloser = &WC{}
2329 return []Value{ValueOf(&w).Elem()}
2330 }).Interface().(func() io.ReadWriteCloser)
2333 // Directional channels can't be assigned to bidirectional ones.
2334 shouldPanic("", func() {
2335 var f func() chan int
2336 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2337 var c <-chan int = make(chan int)
2338 return []Value{ValueOf(c)}
2339 }).Interface().(func() chan int)
2342 // Two named types which are otherwise identical.
2343 shouldPanic("", func() {
2344 type T struct{ a, b, c int }
2345 type U struct{ a, b, c int }
2347 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2348 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2349 }).Interface().(func() T)
2358 // This will be index 0.
2359 func (p Point) AnotherMethod(scale int) int {
2363 // This will be index 1.
2364 func (p Point) Dist(scale int) int {
2365 //println("Point.Dist", p.x, p.y, scale)
2366 return p.x*p.x*scale + p.y*p.y*scale
2369 // This will be index 2.
2370 func (p Point) GCMethod(k int) int {
2375 // This will be index 3.
2376 func (p Point) NoArgs() {
2377 // Exercise no-argument/no-result paths.
2380 // This will be index 4.
2381 func (p Point) TotalDist(points ...Point) int {
2383 for _, q := range points {
2386 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2392 // This will be index 5.
2393 func (p *Point) Int64Method(x int64) int64 {
2397 // This will be index 6.
2398 func (p *Point) Int32Method(x int32) int32 {
2402 func TestMethod(t *testing.T) {
2403 // Non-curried method of type.
2405 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2407 t.Errorf("Type Method returned %d; want 250", i)
2410 m, ok := TypeOf(p).MethodByName("Dist")
2412 t.Fatalf("method by name failed")
2414 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2416 t.Errorf("Type MethodByName returned %d; want 275", i)
2419 m, ok = TypeOf(p).MethodByName("NoArgs")
2421 t.Fatalf("method by name failed")
2423 n := len(m.Func.Call([]Value{ValueOf(p)}))
2425 t.Errorf("NoArgs returned %d values; want 0", n)
2428 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2430 t.Errorf("Pointer Type Method returned %d; want 300", i)
2433 m, ok = TypeOf(&p).MethodByName("Dist")
2435 t.Fatalf("ptr method by name failed")
2437 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2439 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2442 m, ok = TypeOf(&p).MethodByName("NoArgs")
2444 t.Fatalf("method by name failed")
2446 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2448 t.Errorf("NoArgs returned %d values; want 0", n)
2451 // Curried method of value.
2452 tfunc := TypeOf((func(int) int)(nil))
2453 v := ValueOf(p).Method(1)
2454 if tt := v.Type(); tt != tfunc {
2455 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2457 i = v.Call([]Value{ValueOf(14)})[0].Int()
2459 t.Errorf("Value Method returned %d; want 350", i)
2461 v = ValueOf(p).MethodByName("Dist")
2462 if tt := v.Type(); tt != tfunc {
2463 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2465 i = v.Call([]Value{ValueOf(15)})[0].Int()
2467 t.Errorf("Value MethodByName returned %d; want 375", i)
2469 v = ValueOf(p).MethodByName("NoArgs")
2472 // Curried method of pointer.
2473 v = ValueOf(&p).Method(1)
2474 if tt := v.Type(); tt != tfunc {
2475 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2477 i = v.Call([]Value{ValueOf(16)})[0].Int()
2479 t.Errorf("Pointer Value Method returned %d; want 400", i)
2481 v = ValueOf(&p).MethodByName("Dist")
2482 if tt := v.Type(); tt != tfunc {
2483 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2485 i = v.Call([]Value{ValueOf(17)})[0].Int()
2487 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2489 v = ValueOf(&p).MethodByName("NoArgs")
2492 // Curried method of interface value.
2493 // Have to wrap interface value in a struct to get at it.
2494 // Passing it to ValueOf directly would
2495 // access the underlying Point, not the interface.
2499 pv := ValueOf(&x).Elem()
2501 if tt := v.Type(); tt != tfunc {
2502 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2504 i = v.Call([]Value{ValueOf(18)})[0].Int()
2506 t.Errorf("Interface Method returned %d; want 450", i)
2508 v = pv.MethodByName("Dist")
2509 if tt := v.Type(); tt != tfunc {
2510 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2512 i = v.Call([]Value{ValueOf(19)})[0].Int()
2514 t.Errorf("Interface MethodByName returned %d; want 475", i)
2518 func TestMethodValue(t *testing.T) {
2522 // Check that method value have the same underlying code pointers.
2523 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2524 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2527 // Curried method of value.
2528 tfunc := TypeOf((func(int) int)(nil))
2529 v := ValueOf(p).Method(1)
2530 if tt := v.Type(); tt != tfunc {
2531 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2533 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2535 t.Errorf("Value Method returned %d; want 250", i)
2537 v = ValueOf(p).MethodByName("Dist")
2538 if tt := v.Type(); tt != tfunc {
2539 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2541 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2543 t.Errorf("Value MethodByName returned %d; want 275", i)
2545 v = ValueOf(p).MethodByName("NoArgs")
2546 ValueOf(v.Interface()).Call(nil)
2547 v.Interface().(func())()
2549 // Curried method of pointer.
2550 v = ValueOf(&p).Method(1)
2551 if tt := v.Type(); tt != tfunc {
2552 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2554 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2556 t.Errorf("Pointer Value Method returned %d; want 300", i)
2558 v = ValueOf(&p).MethodByName("Dist")
2559 if tt := v.Type(); tt != tfunc {
2560 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2562 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2564 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2566 v = ValueOf(&p).MethodByName("NoArgs")
2567 ValueOf(v.Interface()).Call(nil)
2568 v.Interface().(func())()
2570 // Curried method of pointer to pointer.
2572 v = ValueOf(&pp).Elem().Method(1)
2573 if tt := v.Type(); tt != tfunc {
2574 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2576 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2578 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2580 v = ValueOf(&pp).Elem().MethodByName("Dist")
2581 if tt := v.Type(); tt != tfunc {
2582 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2584 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2586 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2589 // Curried method of interface value.
2590 // Have to wrap interface value in a struct to get at it.
2591 // Passing it to ValueOf directly would
2592 // access the underlying Point, not the interface.
2598 pv := ValueOf(s).Field(0)
2600 if tt := v.Type(); tt != tfunc {
2601 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2603 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2605 t.Errorf("Interface Method returned %d; want 400", i)
2607 v = pv.MethodByName("Dist")
2608 if tt := v.Type(); tt != tfunc {
2609 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2611 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2613 t.Errorf("Interface MethodByName returned %d; want 425", i)
2616 // For issue #33628: method args are not stored at the right offset
2618 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2619 if x := m64(123); x != 123 {
2620 t.Errorf("Int64Method returned %d; want 123", x)
2622 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2623 if x := m32(456); x != 456 {
2624 t.Errorf("Int32Method returned %d; want 456", x)
2628 func TestVariadicMethodValue(t *testing.T) {
2630 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2631 want := int64(p.TotalDist(points[0], points[1], points[2]))
2633 // Variadic method of type.
2634 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2635 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2636 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2639 // Curried method of value.
2640 tfunc = TypeOf((func(...Point) int)(nil))
2641 v := ValueOf(p).Method(4)
2642 if tt := v.Type(); tt != tfunc {
2643 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2645 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2647 t.Errorf("Variadic Method returned %d; want %d", i, want)
2649 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2651 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2654 f := v.Interface().(func(...Point) int)
2655 i = int64(f(points[0], points[1], points[2]))
2657 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2659 i = int64(f(points...))
2661 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2665 type DirectIfaceT struct {
2669 func (d DirectIfaceT) M() int { return *d.p }
2671 func TestDirectIfaceMethod(t *testing.T) {
2673 v := DirectIfaceT{&x}
2675 m, ok := typ.MethodByName("M")
2677 t.Fatalf("cannot find method M")
2679 in := []Value{ValueOf(v)}
2680 out := m.Func.Call(in)
2681 if got := out[0].Int(); got != 42 {
2682 t.Errorf("Call with value receiver got %d, want 42", got)
2687 m, ok = typ.MethodByName("M")
2689 t.Fatalf("cannot find method M")
2691 in = []Value{ValueOf(pv)}
2692 out = m.Func.Call(in)
2693 if got := out[0].Int(); got != 42 {
2694 t.Errorf("Call with pointer receiver got %d, want 42", got)
2698 // Reflect version of $GOROOT/test/method5.go
2700 // Concrete types implementing M method.
2701 // Smaller than a word, word-sized, larger than a word.
2702 // Value and pointer receivers.
2704 type Tinter interface {
2705 M(int, byte) (byte, int)
2710 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2714 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2718 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2722 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2724 type Tbigv [2]uintptr
2726 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2728 type Tbigp [2]uintptr
2730 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2732 type tinter interface {
2733 m(int, byte) (byte, int)
2736 // Embedding via pointer.
2753 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2755 func TestMethod5(t *testing.T) {
2756 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2758 if b != 99 || x != 1000+inc {
2759 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2763 CheckV := func(name string, i Value, inc int) {
2764 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2765 b := bx[0].Interface()
2766 x := bx[1].Interface()
2767 if b != byte(99) || x != 1000+inc {
2768 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2771 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2774 var TinterType = TypeOf(new(Tinter)).Elem()
2776 CheckI := func(name string, i any, inc int) {
2778 CheckV(name, v, inc)
2779 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2784 CheckI("&sv", &sv, 1)
2787 CheckI("&sp", &sp, 2)
2791 CheckI("&wv", &wv, 3)
2794 CheckI("&wp", &wp, 4)
2796 bv := Tbigv([2]uintptr{5, 6})
2797 CheckI("bv", bv, 11)
2798 CheckI("&bv", &bv, 11)
2800 bp := Tbigp([2]uintptr{7, 8})
2801 CheckI("&bp", &bp, 15)
2807 CheckI("t4", t4, 40)
2808 CheckI("&t4", &t4, 40)
2809 CheckI("t3", t3, 40)
2810 CheckI("&t3", &t3, 40)
2811 CheckI("t2", t2, 40)
2812 CheckI("&t2", &t2, 40)
2813 CheckI("t1", t1, 40)
2814 CheckI("&t1", &t1, 40)
2817 vnil := ValueOf(&tnil).Elem()
2818 shouldPanic("Method", func() { vnil.Method(0) })
2821 func TestInterfaceSet(t *testing.T) {
2830 sv := ValueOf(&s).Elem()
2831 sv.Field(0).Set(ValueOf(p))
2832 if q := s.I.(*Point); q != p {
2833 t.Errorf("i: have %p want %p", q, p)
2838 if q := s.P.(*Point); q != p {
2839 t.Errorf("i: have %p want %p", q, p)
2842 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2844 t.Errorf("Interface Method returned %d; want 250", i)
2853 func TestAnonymousFields(t *testing.T) {
2854 var field StructField
2858 if field, ok = type1.FieldByName("int"); !ok {
2859 t.Fatal("no field 'int'")
2861 if field.Index[0] != 1 {
2862 t.Error("field index should be 1; is", field.Index)
2916 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2938 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2957 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2971 var fieldTests = []FTest{
2972 {struct{}{}, "", nil, 0},
2973 {struct{}{}, "Foo", nil, 0},
2974 {S0{A: 'a'}, "A", []int{0}, 'a'},
2975 {S0{}, "D", nil, 0},
2976 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2977 {S1{B: 'b'}, "B", []int{0}, 'b'},
2978 {S1{}, "S0", []int{1}, 0},
2979 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2980 {S2{A: 'a'}, "A", []int{0}, 'a'},
2981 {S2{}, "S1", []int{1}, 0},
2982 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2983 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2984 {S2{}, "D", nil, 0},
2985 {S3{}, "S1", nil, 0},
2986 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2987 {S3{}, "B", nil, 0},
2988 {S3{D: 'd'}, "D", []int{2}, 0},
2989 {S3{E: 'e'}, "E", []int{3}, 'e'},
2990 {S4{A: 'a'}, "A", []int{1}, 'a'},
2991 {S4{}, "B", nil, 0},
2992 {S5{}, "X", nil, 0},
2993 {S5{}, "Y", []int{2, 0, 1}, 0},
2994 {S10{}, "X", nil, 0},
2995 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2996 {S14{}, "X", nil, 0},
2999 func TestFieldByIndex(t *testing.T) {
3000 for _, test := range fieldTests {
3002 f := s.FieldByIndex(test.index)
3004 if test.index != nil {
3005 if f.Name != test.name {
3006 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3009 t.Errorf("%s.%s found", s.Name(), f.Name)
3011 } else if len(test.index) > 0 {
3012 t.Errorf("%s.%s not found", s.Name(), test.name)
3015 if test.value != 0 {
3016 v := ValueOf(test.s).FieldByIndex(test.index)
3018 if x, ok := v.Interface().(int); ok {
3019 if x != test.value {
3020 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3023 t.Errorf("%s%v value not an int", s.Name(), test.index)
3026 t.Errorf("%s%v value not found", s.Name(), test.index)
3032 func TestFieldByName(t *testing.T) {
3033 for _, test := range fieldTests {
3035 f, found := s.FieldByName(test.name)
3037 if test.index != nil {
3038 // Verify field depth and index.
3039 if len(f.Index) != len(test.index) {
3040 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)
3042 for i, x := range f.Index {
3043 if x != test.index[i] {
3044 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3049 t.Errorf("%s.%s found", s.Name(), f.Name)
3051 } else if len(test.index) > 0 {
3052 t.Errorf("%s.%s not found", s.Name(), test.name)
3055 if test.value != 0 {
3056 v := ValueOf(test.s).FieldByName(test.name)
3058 if x, ok := v.Interface().(int); ok {
3059 if x != test.value {
3060 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3063 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3066 t.Errorf("%s.%s value not found", s.Name(), test.name)
3072 func TestImportPath(t *testing.T) {
3077 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3078 {TypeOf(int(0)), ""},
3079 {TypeOf(int8(0)), ""},
3080 {TypeOf(int16(0)), ""},
3081 {TypeOf(int32(0)), ""},
3082 {TypeOf(int64(0)), ""},
3083 {TypeOf(uint(0)), ""},
3084 {TypeOf(uint8(0)), ""},
3085 {TypeOf(uint16(0)), ""},
3086 {TypeOf(uint32(0)), ""},
3087 {TypeOf(uint64(0)), ""},
3088 {TypeOf(uintptr(0)), ""},
3089 {TypeOf(float32(0)), ""},
3090 {TypeOf(float64(0)), ""},
3091 {TypeOf(complex64(0)), ""},
3092 {TypeOf(complex128(0)), ""},
3093 {TypeOf(byte(0)), ""},
3094 {TypeOf(rune(0)), ""},
3095 {TypeOf([]byte(nil)), ""},
3096 {TypeOf([]rune(nil)), ""},
3097 {TypeOf(string("")), ""},
3098 {TypeOf((*any)(nil)).Elem(), ""},
3099 {TypeOf((*byte)(nil)), ""},
3100 {TypeOf((*rune)(nil)), ""},
3101 {TypeOf((*int64)(nil)), ""},
3102 {TypeOf(map[string]int{}), ""},
3103 {TypeOf((*error)(nil)).Elem(), ""},
3104 {TypeOf((*Point)(nil)), ""},
3105 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3107 for _, test := range tests {
3108 if path := test.t.PkgPath(); path != test.path {
3109 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3114 func TestFieldPkgPath(t *testing.T) {
3116 typ := TypeOf(struct {
3124 type pkgpathTest struct {
3131 checkPkgPath := func(name string, s []pkgpathTest) {
3132 for _, test := range s {
3133 f := typ.FieldByIndex(test.index)
3134 if got, want := f.PkgPath, test.pkgPath; got != want {
3135 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3137 if got, want := f.Anonymous, test.embedded; got != want {
3138 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3140 if got, want := f.IsExported(), test.exported; got != want {
3141 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3146 checkPkgPath("testStruct", []pkgpathTest{
3147 {[]int{0}, "", false, true}, // Exported
3148 {[]int{1}, "reflect_test", false, false}, // unexported
3149 {[]int{2}, "", true, true}, // OtherPkgFields
3150 {[]int{2, 0}, "", false, true}, // OtherExported
3151 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3152 {[]int{3}, "reflect_test", true, false}, // int
3153 {[]int{4}, "reflect_test", true, false}, // *x
3156 type localOtherPkgFields OtherPkgFields
3157 typ = TypeOf(localOtherPkgFields{})
3158 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3159 {[]int{0}, "", false, true}, // OtherExported
3160 {[]int{1}, "reflect", false, false}, // otherUnexported
3164 func TestMethodPkgPath(t *testing.T) {
3169 typ := TypeOf((*interface {
3182 {"x", "reflect_test", false},
3183 {"y", "reflect_test", false},
3186 for _, test := range tests {
3187 m, _ := typ.MethodByName(test.name)
3188 if got, want := m.PkgPath, test.pkgPath; got != want {
3189 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3191 if got, want := m.IsExported(), test.exported; got != want {
3192 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3197 func TestVariadicType(t *testing.T) {
3198 // Test example from Type documentation.
3199 var f func(x int, y ...float64)
3201 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3203 if sl.Kind() == Slice {
3204 if sl.Elem() == TypeOf(0.0) {
3212 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3213 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3214 for i := 0; i < typ.NumIn(); i++ {
3215 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3229 func (*inner) M() {}
3230 func (*outer) M() {}
3232 func TestNestedMethods(t *testing.T) {
3233 typ := TypeOf((*outer)(nil))
3234 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3235 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3236 for i := 0; i < typ.NumMethod(); i++ {
3238 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3245 func (*unexp) f() (int32, int8) { return 7, 7 }
3246 func (*unexp) g() (int64, int8) { return 8, 8 }
3248 type unexpI interface {
3252 var unexpi unexpI = new(unexp)
3254 func TestUnexportedMethods(t *testing.T) {
3255 typ := TypeOf(unexpi)
3257 if got := typ.NumMethod(); got != 0 {
3258 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3262 type InnerInt struct {
3266 type OuterInt struct {
3271 func (i *InnerInt) M() int {
3275 func TestEmbeddedMethods(t *testing.T) {
3276 typ := TypeOf((*OuterInt)(nil))
3277 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3278 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3279 for i := 0; i < typ.NumMethod(); i++ {
3281 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3286 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3287 t.Errorf("i.M() = %d, want 3", v)
3290 o := &OuterInt{1, InnerInt{2}}
3291 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3292 t.Errorf("i.M() = %d, want 2", v)
3296 if v := f(o); v != 2 {
3297 t.Errorf("f(o) = %d, want 2", v)
3301 type FuncDDD func(...any) error
3303 func (f FuncDDD) M() {}
3305 func TestNumMethodOnDDD(t *testing.T) {
3306 rv := ValueOf((FuncDDD)(nil))
3307 if n := rv.NumMethod(); n != 1 {
3308 t.Fatalf("NumMethod()=%d, want 1", n)
3312 func TestPtrTo(t *testing.T) {
3313 // This block of code means that the ptrToThis field of the
3314 // reflect data for *unsafe.Pointer is non zero, see
3315 // https://golang.org/issue/19003
3316 var x unsafe.Pointer
3323 for i = 0; i < 100; i++ {
3324 typ = PointerTo(typ)
3326 for i = 0; i < 100; i++ {
3329 if typ != TypeOf(z) {
3330 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3334 func TestPtrToGC(t *testing.T) {
3336 tt := TypeOf(T(nil))
3340 for i := 0; i < n; i++ {
3345 v.Elem().Set(ValueOf(p).Convert(pt))
3346 x = append(x, v.Interface())
3350 for i, xi := range x {
3351 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3352 if k != uintptr(i) {
3353 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3358 func BenchmarkPtrTo(b *testing.B) {
3359 // Construct a type with a zero ptrToThis.
3360 type T struct{ int }
3361 t := SliceOf(TypeOf(T{}))
3362 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3363 if !ptrToThis.IsValid() {
3364 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3366 if ptrToThis.Int() != 0 {
3367 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3371 // Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on
3373 b.RunParallel(func(pb *testing.PB) {
3380 func TestAddr(t *testing.T) {
3392 t.Errorf("Addr.Elem.Set failed to set value")
3395 // Again but take address of the ValueOf value.
3396 // Exercises generation of PtrTypes not present in the binary.
3398 v = ValueOf(&q).Elem()
3407 t.Errorf("Addr.Elem.Set failed to set value")
3410 // Starting without pointer we should get changed value
3413 v = ValueOf(&qq).Elem()
3419 if p.X != 3 { // should be unchanged from last time
3420 t.Errorf("somehow value Set changed original p")
3422 p = v0.Interface().(struct {
3426 t.Errorf("Addr.Elem.Set valued to set value in top value")
3429 // Verify that taking the address of a type gives us a pointer
3430 // which we can convert back using the usual interface
3435 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3436 *(ps.(**bool)) = new(bool)
3438 t.Errorf("Addr.Interface direct assignment failed")
3442 func noAlloc(t *testing.T, n int, f func(int)) {
3443 if testing.Short() {
3444 t.Skip("skipping malloc count in short mode")
3446 if runtime.GOMAXPROCS(0) > 1 {
3447 t.Skip("skipping; GOMAXPROCS>1")
3450 allocs := testing.AllocsPerRun(n, func() {
3455 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3459 func TestAllocations(t *testing.T) {
3460 noAlloc(t, 100, func(j int) {
3464 // We can uncomment this when compiler escape analysis
3465 // is good enough to see that the integer assigned to i
3466 // does not escape and therefore need not be allocated.
3470 // if int(v.Int()) != 42+j {
3471 // panic("wrong int")
3474 i = func(j int) int { return j }
3476 if v.Interface().(func(int) int)(j) != j {
3477 panic("wrong result")
3482 func TestSmallNegativeInt(t *testing.T) {
3486 t.Errorf("int16(-1).Int() returned %v", v.Int())
3490 func TestIndex(t *testing.T) {
3491 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3492 v := ValueOf(xs).Index(3).Interface().(byte)
3494 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3496 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3497 v = ValueOf(xa).Index(2).Interface().(byte)
3499 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3502 v = ValueOf(s).Index(3).Interface().(byte)
3504 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3508 func TestSlice(t *testing.T) {
3509 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3510 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3512 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3515 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3517 if !DeepEqual(v[0:5], xs[3:]) {
3518 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3520 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3521 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3523 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3526 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3528 if !DeepEqual(v[0:6], xa[2:]) {
3529 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3532 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3534 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3537 rv := ValueOf(&xs).Elem()
3539 ptr2 := rv.UnsafePointer()
3541 ptr3 := rv.UnsafePointer()
3543 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3547 func TestSlice3(t *testing.T) {
3548 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3549 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3551 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3554 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3556 if !DeepEqual(v[0:4], xs[3:7:7]) {
3557 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3559 rv := ValueOf(&xs).Elem()
3560 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3561 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3562 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3564 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3565 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3567 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3570 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3572 if !DeepEqual(v[0:4], xa[2:6:6]) {
3573 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3575 rv = ValueOf(&xa).Elem()
3576 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3577 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3578 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3581 rv = ValueOf(&s).Elem()
3582 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3584 rv = ValueOf(&xs).Elem()
3585 rv = rv.Slice3(3, 5, 7)
3586 ptr2 := rv.UnsafePointer()
3587 rv = rv.Slice3(4, 4, 4)
3588 ptr3 := rv.UnsafePointer()
3590 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3594 func TestSetLenCap(t *testing.T) {
3595 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3596 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3598 vs := ValueOf(&xs).Elem()
3599 shouldPanic("SetLen", func() { vs.SetLen(10) })
3600 shouldPanic("SetCap", func() { vs.SetCap(10) })
3601 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3602 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3603 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3605 if len(xs) != 5 || cap(xs) != 8 {
3606 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3609 if len(xs) != 5 || cap(xs) != 6 {
3610 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3613 if len(xs) != 5 || cap(xs) != 5 {
3614 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3616 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3617 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3619 va := ValueOf(&xa).Elem()
3620 shouldPanic("SetLen", func() { va.SetLen(8) })
3621 shouldPanic("SetCap", func() { va.SetCap(8) })
3624 func TestVariadic(t *testing.T) {
3629 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3630 if b.String() != "hello, 42 world" {
3631 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3635 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3636 if b.String() != "hello, 42 world" {
3637 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3641 func TestFuncArg(t *testing.T) {
3642 f1 := func(i int, f func(int) int) int { return f(i) }
3643 f2 := func(i int) int { return i + 1 }
3644 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3645 if r[0].Int() != 101 {
3646 t.Errorf("function returned %d, want 101", r[0].Int())
3650 func TestStructArg(t *testing.T) {
3651 type padded struct {
3658 wantA = padded{"3", 4}
3661 f := func(a padded, b uint32) {
3664 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3665 if gotA != wantA || gotB != wantB {
3666 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3670 var tagGetTests = []struct {
3675 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3676 {`protobuf:"PB(1,2)"`, `foo`, ``},
3677 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3678 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3679 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3680 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3681 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3684 func TestTagGet(t *testing.T) {
3685 for _, tt := range tagGetTests {
3686 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3687 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3692 func TestBytes(t *testing.T) {
3693 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3694 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3698 y := ValueOf(x).Bytes()
3699 if !bytes.Equal(x, y) {
3700 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3703 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3708 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3709 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3710 b := ValueOf(&a).Elem().Bytes()
3711 if !bytes.Equal(a[:], y) {
3712 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3715 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3718 // Per issue #24746, it was decided that Bytes can be called on byte slices
3719 // that normally cannot be converted from per Go language semantics.
3723 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3724 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3725 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3726 ValueOf(new(AB)).Elem().Bytes() // should not panic
3729 func TestSetBytes(t *testing.T) {
3732 y := []byte{1, 2, 3, 4}
3733 ValueOf(&x).Elem().SetBytes(y)
3734 if !bytes.Equal(x, y) {
3735 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3738 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3742 type Private struct {
3748 func (p *Private) m() {
3751 type private struct {
3759 func (p *private) P() {
3762 type Public struct {
3768 func (p *Public) M() {
3771 func TestUnexported(t *testing.T) {
3776 isValid(v.Elem().Field(0))
3777 isValid(v.Elem().Field(1))
3778 isValid(v.Elem().Field(2))
3779 isValid(v.Elem().FieldByName("X"))
3780 isValid(v.Elem().FieldByName("Y"))
3781 isValid(v.Elem().FieldByName("Z"))
3782 isValid(v.Type().Method(0).Func)
3783 m, _ := v.Type().MethodByName("M")
3785 m, _ = v.Type().MethodByName("P")
3787 isNonNil(v.Elem().Field(0).Interface())
3788 isNonNil(v.Elem().Field(1).Interface())
3789 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3790 isNonNil(v.Elem().FieldByName("X").Interface())
3791 isNonNil(v.Elem().FieldByName("Y").Interface())
3792 isNonNil(v.Elem().FieldByName("Z").Interface())
3793 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3794 isNonNil(v.Type().Method(0).Func.Interface())
3795 m, _ = v.Type().MethodByName("P")
3796 isNonNil(m.Func.Interface())
3800 isValid(v.Elem().Field(0))
3801 isValid(v.Elem().Field(1))
3802 isValid(v.Elem().FieldByName("x"))
3803 isValid(v.Elem().FieldByName("y"))
3804 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3805 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3806 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3807 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3808 shouldPanic("Method", func() { v.Type().Method(0) })
3811 func TestSetPanic(t *testing.T) {
3812 ok := func(f func()) { f() }
3813 bad := func(f func()) { shouldPanic("Set", f) }
3814 clear := func(v Value) { v.Set(Zero(v.Type())) }
3842 bad(func() { clear(v.Field(0)) }) // .X
3843 bad(func() { clear(v.Field(1)) }) // .t1
3844 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3845 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3846 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3847 bad(func() { clear(v.Field(2)) }) // .T2
3848 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3849 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3850 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3851 bad(func() { clear(v.Field(3)) }) // .NamedT1
3852 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3853 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3854 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3855 bad(func() { clear(v.Field(4)) }) // .NamedT2
3856 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3857 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3858 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3859 bad(func() { clear(v.Field(5)) }) // .namedT1
3860 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3861 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3862 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3863 bad(func() { clear(v.Field(6)) }) // .namedT2
3864 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3865 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3866 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3869 v = ValueOf(&T{}).Elem()
3870 ok(func() { clear(v.Field(0)) }) // .X
3871 bad(func() { clear(v.Field(1)) }) // .t1
3872 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3873 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3874 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3875 ok(func() { clear(v.Field(2)) }) // .T2
3876 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3877 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3878 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3879 ok(func() { clear(v.Field(3)) }) // .NamedT1
3880 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3881 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3882 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3883 ok(func() { clear(v.Field(4)) }) // .NamedT2
3884 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3885 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3886 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3887 bad(func() { clear(v.Field(5)) }) // .namedT1
3888 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3889 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3890 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3891 bad(func() { clear(v.Field(6)) }) // .namedT2
3892 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3893 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3894 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3899 func (t timp) W() {}
3900 func (t timp) Y() {}
3901 func (t timp) w() {}
3902 func (t timp) y() {}
3904 func TestCallPanic(t *testing.T) {
3929 ok := func(f func()) { f() }
3930 badCall := func(f func()) { shouldPanic("Call", f) }
3931 badMethod := func(f func()) { shouldPanic("Method", f) }
3932 call := func(v Value) { v.Call(nil) }
3935 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3936 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3937 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3938 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3939 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3940 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3941 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3942 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3943 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3945 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3946 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3947 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3948 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3950 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3951 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3952 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3953 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3955 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3956 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3957 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3958 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3960 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3961 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3962 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3963 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3965 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3966 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3967 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3968 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3970 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3971 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3972 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3973 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3976 func shouldPanic(expect string, f func()) {
3980 panic("did not panic")
3984 switch r := r.(type) {
3990 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3992 if !strings.HasPrefix(s, "reflect") {
3993 panic(`panic string does not start with "reflect": ` + s)
3995 if !strings.Contains(s, expect) {
3996 panic(`panic string does not contain "` + expect + `": ` + s)
4003 func isNonNil(x any) {
4005 panic("nil interface")
4009 func isValid(v Value) {
4015 func TestAlias(t *testing.T) {
4016 x := string("hello")
4017 v := ValueOf(&x).Elem()
4018 oldvalue := v.Interface()
4019 v.SetString("world")
4020 newvalue := v.Interface()
4022 if oldvalue != "hello" || newvalue != "world" {
4023 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
4029 func EmptyInterfaceV(x any) Value {
4030 return ValueOf(&x).Elem()
4033 func ReaderV(x io.Reader) Value {
4034 return ValueOf(&x).Elem()
4037 func ReadWriterV(x io.ReadWriter) Value {
4038 return ValueOf(&x).Elem()
4042 type MyStruct struct {
4045 type MyStruct1 struct {
4050 type MyStruct2 struct {
4055 type MyString string
4057 type MyBytesArrayPtr0 *[0]byte
4058 type MyBytesArrayPtr *[4]byte
4059 type MyBytesArray0 [0]byte
4060 type MyBytesArray [4]byte
4061 type MyRunes []int32
4065 type IntChan chan int
4066 type IntChanRecv <-chan int
4067 type IntChanSend chan<- int
4068 type BytesChan chan []byte
4069 type BytesChanRecv <-chan []byte
4070 type BytesChanSend chan<- []byte
4072 var convertTests = []struct {
4078 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4084 var numbers = []string{
4085 "int8", "uint8", "int16", "uint16",
4086 "int32", "uint32", "int64", "uint64",
4087 "int", "uint", "uintptr",
4088 "float32", "float64",
4092 // all pairs but in an unusual order,
4093 // to emit all the int8, uint8 cases
4094 // before n grows too big.
4096 for i, f := range numbers {
4097 for _, g := range numbers[i:] {
4098 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4101 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4108 {V(int8(1)), V(int8(1))},
4109 {V(int8(2)), V(uint8(2))},
4110 {V(uint8(3)), V(int8(3))},
4111 {V(int8(4)), V(int16(4))},
4112 {V(int16(5)), V(int8(5))},
4113 {V(int8(6)), V(uint16(6))},
4114 {V(uint16(7)), V(int8(7))},
4115 {V(int8(8)), V(int32(8))},
4116 {V(int32(9)), V(int8(9))},
4117 {V(int8(10)), V(uint32(10))},
4118 {V(uint32(11)), V(int8(11))},
4119 {V(int8(12)), V(int64(12))},
4120 {V(int64(13)), V(int8(13))},
4121 {V(int8(14)), V(uint64(14))},
4122 {V(uint64(15)), V(int8(15))},
4123 {V(int8(16)), V(int(16))},
4124 {V(int(17)), V(int8(17))},
4125 {V(int8(18)), V(uint(18))},
4126 {V(uint(19)), V(int8(19))},
4127 {V(int8(20)), V(uintptr(20))},
4128 {V(uintptr(21)), V(int8(21))},
4129 {V(int8(22)), V(float32(22))},
4130 {V(float32(23)), V(int8(23))},
4131 {V(int8(24)), V(float64(24))},
4132 {V(float64(25)), V(int8(25))},
4133 {V(uint8(26)), V(uint8(26))},
4134 {V(uint8(27)), V(int16(27))},
4135 {V(int16(28)), V(uint8(28))},
4136 {V(uint8(29)), V(uint16(29))},
4137 {V(uint16(30)), V(uint8(30))},
4138 {V(uint8(31)), V(int32(31))},
4139 {V(int32(32)), V(uint8(32))},
4140 {V(uint8(33)), V(uint32(33))},
4141 {V(uint32(34)), V(uint8(34))},
4142 {V(uint8(35)), V(int64(35))},
4143 {V(int64(36)), V(uint8(36))},
4144 {V(uint8(37)), V(uint64(37))},
4145 {V(uint64(38)), V(uint8(38))},
4146 {V(uint8(39)), V(int(39))},
4147 {V(int(40)), V(uint8(40))},
4148 {V(uint8(41)), V(uint(41))},
4149 {V(uint(42)), V(uint8(42))},
4150 {V(uint8(43)), V(uintptr(43))},
4151 {V(uintptr(44)), V(uint8(44))},
4152 {V(uint8(45)), V(float32(45))},
4153 {V(float32(46)), V(uint8(46))},
4154 {V(uint8(47)), V(float64(47))},
4155 {V(float64(48)), V(uint8(48))},
4156 {V(int16(49)), V(int16(49))},
4157 {V(int16(50)), V(uint16(50))},
4158 {V(uint16(51)), V(int16(51))},
4159 {V(int16(52)), V(int32(52))},
4160 {V(int32(53)), V(int16(53))},
4161 {V(int16(54)), V(uint32(54))},
4162 {V(uint32(55)), V(int16(55))},
4163 {V(int16(56)), V(int64(56))},
4164 {V(int64(57)), V(int16(57))},
4165 {V(int16(58)), V(uint64(58))},
4166 {V(uint64(59)), V(int16(59))},
4167 {V(int16(60)), V(int(60))},
4168 {V(int(61)), V(int16(61))},
4169 {V(int16(62)), V(uint(62))},
4170 {V(uint(63)), V(int16(63))},
4171 {V(int16(64)), V(uintptr(64))},
4172 {V(uintptr(65)), V(int16(65))},
4173 {V(int16(66)), V(float32(66))},
4174 {V(float32(67)), V(int16(67))},
4175 {V(int16(68)), V(float64(68))},
4176 {V(float64(69)), V(int16(69))},
4177 {V(uint16(70)), V(uint16(70))},
4178 {V(uint16(71)), V(int32(71))},
4179 {V(int32(72)), V(uint16(72))},
4180 {V(uint16(73)), V(uint32(73))},
4181 {V(uint32(74)), V(uint16(74))},
4182 {V(uint16(75)), V(int64(75))},
4183 {V(int64(76)), V(uint16(76))},
4184 {V(uint16(77)), V(uint64(77))},
4185 {V(uint64(78)), V(uint16(78))},
4186 {V(uint16(79)), V(int(79))},
4187 {V(int(80)), V(uint16(80))},
4188 {V(uint16(81)), V(uint(81))},
4189 {V(uint(82)), V(uint16(82))},
4190 {V(uint16(83)), V(uintptr(83))},
4191 {V(uintptr(84)), V(uint16(84))},
4192 {V(uint16(85)), V(float32(85))},
4193 {V(float32(86)), V(uint16(86))},
4194 {V(uint16(87)), V(float64(87))},
4195 {V(float64(88)), V(uint16(88))},
4196 {V(int32(89)), V(int32(89))},
4197 {V(int32(90)), V(uint32(90))},
4198 {V(uint32(91)), V(int32(91))},
4199 {V(int32(92)), V(int64(92))},
4200 {V(int64(93)), V(int32(93))},
4201 {V(int32(94)), V(uint64(94))},
4202 {V(uint64(95)), V(int32(95))},
4203 {V(int32(96)), V(int(96))},
4204 {V(int(97)), V(int32(97))},
4205 {V(int32(98)), V(uint(98))},
4206 {V(uint(99)), V(int32(99))},
4207 {V(int32(100)), V(uintptr(100))},
4208 {V(uintptr(101)), V(int32(101))},
4209 {V(int32(102)), V(float32(102))},
4210 {V(float32(103)), V(int32(103))},
4211 {V(int32(104)), V(float64(104))},
4212 {V(float64(105)), V(int32(105))},
4213 {V(uint32(106)), V(uint32(106))},
4214 {V(uint32(107)), V(int64(107))},
4215 {V(int64(108)), V(uint32(108))},
4216 {V(uint32(109)), V(uint64(109))},
4217 {V(uint64(110)), V(uint32(110))},
4218 {V(uint32(111)), V(int(111))},
4219 {V(int(112)), V(uint32(112))},
4220 {V(uint32(113)), V(uint(113))},
4221 {V(uint(114)), V(uint32(114))},
4222 {V(uint32(115)), V(uintptr(115))},
4223 {V(uintptr(116)), V(uint32(116))},
4224 {V(uint32(117)), V(float32(117))},
4225 {V(float32(118)), V(uint32(118))},
4226 {V(uint32(119)), V(float64(119))},
4227 {V(float64(120)), V(uint32(120))},
4228 {V(int64(121)), V(int64(121))},
4229 {V(int64(122)), V(uint64(122))},
4230 {V(uint64(123)), V(int64(123))},
4231 {V(int64(124)), V(int(124))},
4232 {V(int(125)), V(int64(125))},
4233 {V(int64(126)), V(uint(126))},
4234 {V(uint(127)), V(int64(127))},
4235 {V(int64(128)), V(uintptr(128))},
4236 {V(uintptr(129)), V(int64(129))},
4237 {V(int64(130)), V(float32(130))},
4238 {V(float32(131)), V(int64(131))},
4239 {V(int64(132)), V(float64(132))},
4240 {V(float64(133)), V(int64(133))},
4241 {V(uint64(134)), V(uint64(134))},
4242 {V(uint64(135)), V(int(135))},
4243 {V(int(136)), V(uint64(136))},
4244 {V(uint64(137)), V(uint(137))},
4245 {V(uint(138)), V(uint64(138))},
4246 {V(uint64(139)), V(uintptr(139))},
4247 {V(uintptr(140)), V(uint64(140))},
4248 {V(uint64(141)), V(float32(141))},
4249 {V(float32(142)), V(uint64(142))},
4250 {V(uint64(143)), V(float64(143))},
4251 {V(float64(144)), V(uint64(144))},
4252 {V(int(145)), V(int(145))},
4253 {V(int(146)), V(uint(146))},
4254 {V(uint(147)), V(int(147))},
4255 {V(int(148)), V(uintptr(148))},
4256 {V(uintptr(149)), V(int(149))},
4257 {V(int(150)), V(float32(150))},
4258 {V(float32(151)), V(int(151))},
4259 {V(int(152)), V(float64(152))},
4260 {V(float64(153)), V(int(153))},
4261 {V(uint(154)), V(uint(154))},
4262 {V(uint(155)), V(uintptr(155))},
4263 {V(uintptr(156)), V(uint(156))},
4264 {V(uint(157)), V(float32(157))},
4265 {V(float32(158)), V(uint(158))},
4266 {V(uint(159)), V(float64(159))},
4267 {V(float64(160)), V(uint(160))},
4268 {V(uintptr(161)), V(uintptr(161))},
4269 {V(uintptr(162)), V(float32(162))},
4270 {V(float32(163)), V(uintptr(163))},
4271 {V(uintptr(164)), V(float64(164))},
4272 {V(float64(165)), V(uintptr(165))},
4273 {V(float32(166)), V(float32(166))},
4274 {V(float32(167)), V(float64(167))},
4275 {V(float64(168)), V(float32(168))},
4276 {V(float64(169)), V(float64(169))},
4279 {V(float64(1.5)), V(int(1))},
4282 {V(complex64(1i)), V(complex64(1i))},
4283 {V(complex64(2i)), V(complex128(2i))},
4284 {V(complex128(3i)), V(complex64(3i))},
4285 {V(complex128(4i)), V(complex128(4i))},
4288 {V(string("hello")), V(string("hello"))},
4289 {V(string("bytes1")), V([]byte("bytes1"))},
4290 {V([]byte("bytes2")), V(string("bytes2"))},
4291 {V([]byte("bytes3")), V([]byte("bytes3"))},
4292 {V(string("runes♝")), V([]rune("runes♝"))},
4293 {V([]rune("runes♕")), V(string("runes♕"))},
4294 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4295 {V(int('a')), V(string("a"))},
4296 {V(int8('a')), V(string("a"))},
4297 {V(int16('a')), V(string("a"))},
4298 {V(int32('a')), V(string("a"))},
4299 {V(int64('a')), V(string("a"))},
4300 {V(uint('a')), V(string("a"))},
4301 {V(uint8('a')), V(string("a"))},
4302 {V(uint16('a')), V(string("a"))},
4303 {V(uint32('a')), V(string("a"))},
4304 {V(uint64('a')), V(string("a"))},
4305 {V(uintptr('a')), V(string("a"))},
4306 {V(int(-1)), V(string("\uFFFD"))},
4307 {V(int8(-2)), V(string("\uFFFD"))},
4308 {V(int16(-3)), V(string("\uFFFD"))},
4309 {V(int32(-4)), V(string("\uFFFD"))},
4310 {V(int64(-5)), V(string("\uFFFD"))},
4311 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4312 {V(int64(1 << 32)), V(string("\uFFFD"))},
4313 {V(uint(0x110001)), V(string("\uFFFD"))},
4314 {V(uint32(0x110002)), V(string("\uFFFD"))},
4315 {V(uint64(0x110003)), V(string("\uFFFD"))},
4316 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4317 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4320 {V(MyString("hello")), V(string("hello"))},
4321 {V(string("hello")), V(MyString("hello"))},
4322 {V(string("hello")), V(string("hello"))},
4323 {V(MyString("hello")), V(MyString("hello"))},
4324 {V(MyString("bytes1")), V([]byte("bytes1"))},
4325 {V([]byte("bytes2")), V(MyString("bytes2"))},
4326 {V([]byte("bytes3")), V([]byte("bytes3"))},
4327 {V(MyString("runes♝")), V([]rune("runes♝"))},
4328 {V([]rune("runes♕")), V(MyString("runes♕"))},
4329 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4330 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4331 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4332 {V(int('a')), V(MyString("a"))},
4333 {V(int8('a')), V(MyString("a"))},
4334 {V(int16('a')), V(MyString("a"))},
4335 {V(int32('a')), V(MyString("a"))},
4336 {V(int64('a')), V(MyString("a"))},
4337 {V(uint('a')), V(MyString("a"))},
4338 {V(uint8('a')), V(MyString("a"))},
4339 {V(uint16('a')), V(MyString("a"))},
4340 {V(uint32('a')), V(MyString("a"))},
4341 {V(uint64('a')), V(MyString("a"))},
4342 {V(uintptr('a')), V(MyString("a"))},
4343 {V(int(-1)), V(MyString("\uFFFD"))},
4344 {V(int8(-2)), V(MyString("\uFFFD"))},
4345 {V(int16(-3)), V(MyString("\uFFFD"))},
4346 {V(int32(-4)), V(MyString("\uFFFD"))},
4347 {V(int64(-5)), V(MyString("\uFFFD"))},
4348 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4349 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4350 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4351 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4354 {V(string("bytes1")), V(MyBytes("bytes1"))},
4355 {V(MyBytes("bytes2")), V(string("bytes2"))},
4356 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4357 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4358 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4361 {V(string("runes♝")), V(MyRunes("runes♝"))},
4362 {V(MyRunes("runes♕")), V(string("runes♕"))},
4363 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4364 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4365 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4367 // slice to array pointer
4368 {V([]byte(nil)), V((*[0]byte)(nil))},
4369 {V([]byte{}), V(new([0]byte))},
4370 {V([]byte{7}), V(&[1]byte{7})},
4371 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4372 {V(MyBytes([]byte{})), V(new([0]byte))},
4373 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4374 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4375 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4376 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4377 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4378 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4380 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4381 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4382 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4383 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4384 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4385 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4386 {V(new([0]byte)), V(new(MyBytesArray0))},
4387 {V(new(MyBytesArray0)), V(new([0]byte))},
4388 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4389 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4391 // named types and equal underlying types
4392 {V(new(int)), V(new(integer))},
4393 {V(new(integer)), V(new(int))},
4394 {V(Empty{}), V(struct{}{})},
4395 {V(new(Empty)), V(new(struct{}))},
4396 {V(struct{}{}), V(Empty{})},
4397 {V(new(struct{})), V(new(Empty))},
4398 {V(Empty{}), V(Empty{})},
4399 {V(MyBytes{}), V([]byte{})},
4400 {V([]byte{}), V(MyBytes{})},
4401 {V((func())(nil)), V(MyFunc(nil))},
4402 {V((MyFunc)(nil)), V((func())(nil))},
4404 // structs with different tags
4417 {V(MyStruct{}), V(struct {
4423 }{}), V(MyStruct{})},
4425 {V(MyStruct{}), V(struct {
4431 }{}), V(MyStruct{})},
4433 {V(MyStruct1{}), V(MyStruct2{})},
4434 {V(MyStruct2{}), V(MyStruct1{})},
4436 // can convert *byte and *MyByte
4437 {V((*byte)(nil)), V((*MyByte)(nil))},
4438 {V((*MyByte)(nil)), V((*byte)(nil))},
4440 // cannot convert mismatched array sizes
4441 {V([2]byte{}), V([2]byte{})},
4442 {V([3]byte{}), V([3]byte{})},
4444 // cannot convert other instances
4445 {V((**byte)(nil)), V((**byte)(nil))},
4446 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4447 {V((chan byte)(nil)), V((chan byte)(nil))},
4448 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4449 {V(([]byte)(nil)), V(([]byte)(nil))},
4450 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4451 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4452 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4453 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4454 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4455 {V([2]byte{}), V([2]byte{})},
4456 {V([2]MyByte{}), V([2]MyByte{})},
4459 {V((***int)(nil)), V((***int)(nil))},
4460 {V((***byte)(nil)), V((***byte)(nil))},
4461 {V((***int32)(nil)), V((***int32)(nil))},
4462 {V((***int64)(nil)), V((***int64)(nil))},
4463 {V((chan byte)(nil)), V((chan byte)(nil))},
4464 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4465 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4466 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4467 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4468 {V([]uint(nil)), V([]uint(nil))},
4469 {V([]int(nil)), V([]int(nil))},
4470 {V(new(any)), V(new(any))},
4471 {V(new(io.Reader)), V(new(io.Reader))},
4472 {V(new(io.Writer)), V(new(io.Writer))},
4475 {V(IntChan(nil)), V((chan<- int)(nil))},
4476 {V(IntChan(nil)), V((<-chan int)(nil))},
4477 {V((chan int)(nil)), V(IntChanRecv(nil))},
4478 {V((chan int)(nil)), V(IntChanSend(nil))},
4479 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4480 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4481 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4482 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4483 {V(IntChan(nil)), V((chan int)(nil))},
4484 {V((chan int)(nil)), V(IntChan(nil))},
4485 {V((chan int)(nil)), V((<-chan int)(nil))},
4486 {V((chan int)(nil)), V((chan<- int)(nil))},
4487 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4488 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4489 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4490 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4491 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4492 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4493 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4494 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4495 {V(BytesChan(nil)), V((chan []byte)(nil))},
4496 {V((chan []byte)(nil)), V(BytesChan(nil))},
4497 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4498 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4500 // cannot convert other instances (channels)
4501 {V(IntChan(nil)), V(IntChan(nil))},
4502 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4503 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4504 {V(BytesChan(nil)), V(BytesChan(nil))},
4505 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4506 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4509 {V(int(1)), EmptyInterfaceV(int(1))},
4510 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4511 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4512 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4513 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4516 func TestConvert(t *testing.T) {
4517 canConvert := map[[2]Type]bool{}
4518 all := map[Type]bool{}
4520 for _, tt := range convertTests {
4522 if !t1.ConvertibleTo(t1) {
4523 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4528 if !t1.ConvertibleTo(t2) {
4529 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4535 canConvert[[2]Type{t1, t2}] = true
4537 // vout1 represents the in value converted to the in type.
4539 if !v1.CanConvert(t1) {
4540 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4542 vout1 := v1.Convert(t1)
4543 out1 := vout1.Interface()
4544 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4545 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4548 // vout2 represents the in value converted to the out type.
4549 if !v1.CanConvert(t2) {
4550 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4552 vout2 := v1.Convert(t2)
4553 out2 := vout2.Interface()
4554 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4555 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4557 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4558 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4561 // vout3 represents a new value of the out type, set to vout2. This makes
4562 // sure the converted value vout2 is really usable as a regular value.
4563 vout3 := New(t2).Elem()
4565 out3 := vout3.Interface()
4566 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4567 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4571 t.Errorf("table entry %v is RO, should not be", v1)
4574 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4577 t.Errorf("conversion output %v is RO, should not be", vout2)
4580 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4582 if !IsRO(MakeRO(v1).Convert(t1)) {
4583 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4585 if !IsRO(MakeRO(v1).Convert(t2)) {
4586 t.Errorf("RO conversion output %v is not RO, should be", v1)
4590 // Assume that of all the types we saw during the tests,
4591 // if there wasn't an explicit entry for a conversion between
4592 // a pair of types, then it's not to be allowed. This checks for
4593 // things like 'int64' converting to '*int'.
4594 for t1 := range all {
4595 for t2 := range all {
4596 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4597 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4598 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4604 func TestConvertPanic(t *testing.T) {
4605 s := make([]byte, 4)
4609 if !v.Type().ConvertibleTo(pt) {
4610 t.Errorf("[]byte should be convertible to *[8]byte")
4612 if v.CanConvert(pt) {
4613 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4615 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4620 var gFloat32 float32
4622 const snan uint32 = 0x7f800001
4624 func TestConvertNaNs(t *testing.T) {
4625 // Test to see if a store followed by a load of a signaling NaN
4626 // maintains the signaling bit. (This used to fail on the 387 port.)
4627 gFloat32 = math.Float32frombits(snan)
4628 runtime.Gosched() // make sure we don't optimize the store/load away
4629 if got := math.Float32bits(gFloat32); got != snan {
4630 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4632 // Test reflect's conversion between float32s. See issue 36400.
4633 type myFloat32 float32
4634 x := V(myFloat32(math.Float32frombits(snan)))
4635 y := x.Convert(TypeOf(float32(0)))
4636 z := y.Interface().(float32)
4637 if got := math.Float32bits(z); got != snan {
4638 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4642 type ComparableStruct struct {
4646 type NonComparableStruct struct {
4651 var comparableTests = []struct {
4656 {TypeOf("hello"), true},
4657 {TypeOf(new(byte)), true},
4658 {TypeOf((func())(nil)), false},
4659 {TypeOf([]byte{}), false},
4660 {TypeOf(map[string]int{}), false},
4661 {TypeOf(make(chan int)), true},
4662 {TypeOf(1.5), true},
4663 {TypeOf(false), true},
4665 {TypeOf(ComparableStruct{}), true},
4666 {TypeOf(NonComparableStruct{}), false},
4667 {TypeOf([10]map[string]int{}), false},
4668 {TypeOf([10]string{}), true},
4669 {TypeOf(new(any)).Elem(), true},
4672 func TestComparable(t *testing.T) {
4673 for _, tt := range comparableTests {
4674 if ok := tt.typ.Comparable(); ok != tt.ok {
4675 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4680 func TestOverflow(t *testing.T) {
4681 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4682 t.Errorf("%v wrongly overflows float64", 1e300)
4685 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4686 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4687 t.Errorf("%v wrongly overflows float32", maxFloat32)
4689 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4690 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4691 t.Errorf("%v should overflow float32", ovfFloat32)
4693 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4694 t.Errorf("%v should overflow float32", -ovfFloat32)
4697 maxInt32 := int64(0x7fffffff)
4698 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4699 t.Errorf("%v wrongly overflows int32", maxInt32)
4701 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4702 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4704 ovfInt32 := int64(1 << 31)
4705 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4706 t.Errorf("%v should overflow int32", ovfInt32)
4709 maxUint32 := uint64(0xffffffff)
4710 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4711 t.Errorf("%v wrongly overflows uint32", maxUint32)
4713 ovfUint32 := uint64(1 << 32)
4714 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4715 t.Errorf("%v should overflow uint32", ovfUint32)
4719 func checkSameType(t *testing.T, x Type, y any) {
4720 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4721 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4725 func TestArrayOf(t *testing.T) {
4726 // check construction and use of type not in binary
4729 value func(i int) any
4735 value: func(i int) any { type Tint int; return Tint(i) },
4741 value: func(i int) any { type Tint int; return Tint(i) },
4743 want: "[0 1 2 3 4 5 6 7 8 9]",
4747 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4749 want: "[0 1 2 3 4 5 6 7 8 9]",
4753 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4755 want: "[0 1 2 3 4 5 6 7 8 9]",
4759 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4761 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4765 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4767 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4771 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4773 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4777 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4779 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4783 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4785 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4789 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4791 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4795 value: func(i int) any {
4796 type TstructUV struct {
4800 return TstructUV{i, float64(i)}
4803 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4807 for _, table := range tests {
4808 at := ArrayOf(table.n, TypeOf(table.value(0)))
4810 vok := New(at).Elem()
4811 vnot := New(at).Elem()
4812 for i := 0; i < v.Len(); i++ {
4813 v.Index(i).Set(ValueOf(table.value(i)))
4814 vok.Index(i).Set(ValueOf(table.value(i)))
4819 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4821 s := fmt.Sprint(v.Interface())
4822 if s != table.want {
4823 t.Errorf("constructed array = %s, want %s", s, table.want)
4826 if table.comparable != at.Comparable() {
4827 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4829 if table.comparable {
4831 if DeepEqual(vnot.Interface(), v.Interface()) {
4833 "arrays (%#v) compare ok (but should not)",
4838 if !DeepEqual(vok.Interface(), v.Interface()) {
4840 "arrays (%#v) compare NOT-ok (but should)",
4847 // check that type already in binary is found
4849 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4852 func TestArrayOfGC(t *testing.T) {
4854 tt := TypeOf(T(nil))
4857 for i := 0; i < n; i++ {
4858 v := New(ArrayOf(n, tt)).Elem()
4859 for j := 0; j < v.Len(); j++ {
4861 *p = uintptr(i*n + j)
4862 v.Index(j).Set(ValueOf(p).Convert(tt))
4864 x = append(x, v.Interface())
4868 for i, xi := range x {
4870 for j := 0; j < v.Len(); j++ {
4871 k := v.Index(j).Elem().Interface()
4872 if k != uintptr(i*n+j) {
4873 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4879 func TestArrayOfAlg(t *testing.T) {
4880 at := ArrayOf(6, TypeOf(byte(0)))
4881 v1 := New(at).Elem()
4882 v2 := New(at).Elem()
4883 if v1.Interface() != v1.Interface() {
4884 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4886 v1.Index(5).Set(ValueOf(byte(1)))
4887 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4888 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4891 at = ArrayOf(6, TypeOf([]int(nil)))
4893 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4896 func TestArrayOfGenericAlg(t *testing.T) {
4897 at1 := ArrayOf(5, TypeOf(string("")))
4898 at := ArrayOf(6, at1)
4899 v1 := New(at).Elem()
4900 v2 := New(at).Elem()
4901 if v1.Interface() != v1.Interface() {
4902 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4905 v1.Index(0).Index(0).Set(ValueOf("abc"))
4906 v2.Index(0).Index(0).Set(ValueOf("efg"))
4907 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4908 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4911 v1.Index(0).Index(0).Set(ValueOf("abc"))
4912 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4913 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4914 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4918 m := MakeMap(MapOf(at, TypeOf(int(0))))
4919 m.SetMapIndex(v1, ValueOf(1))
4920 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4921 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4925 func TestArrayOfDirectIface(t *testing.T) {
4928 i1 := Zero(TypeOf(T{})).Interface()
4929 v1 := ValueOf(&i1).Elem()
4930 p1 := v1.InterfaceData()[1]
4932 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
4933 v2 := ValueOf(&i2).Elem()
4934 p2 := v2.InterfaceData()[1]
4937 t.Errorf("got p1=%v. want=%v", p1, nil)
4941 t.Errorf("got p2=%v. want=%v", p2, nil)
4946 i1 := Zero(TypeOf(T{})).Interface()
4947 v1 := ValueOf(&i1).Elem()
4948 p1 := v1.InterfaceData()[1]
4950 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
4951 v2 := ValueOf(&i2).Elem()
4952 p2 := v2.InterfaceData()[1]
4955 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4959 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4964 // Ensure passing in negative lengths panics.
4965 // See https://golang.org/issue/43603
4966 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4967 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4968 ArrayOf(-1, TypeOf(byte(0)))
4972 func TestSliceOf(t *testing.T) {
4973 // check construction and use of type not in binary
4975 st := SliceOf(TypeOf(T(1)))
4976 if got, want := st.String(), "[]reflect_test.T"; got != want {
4977 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4979 v := MakeSlice(st, 10, 10)
4981 for i := 0; i < v.Len(); i++ {
4982 v.Index(i).Set(ValueOf(T(i)))
4985 s := fmt.Sprint(v.Interface())
4986 want := "[0 1 2 3 4 5 6 7 8 9]"
4988 t.Errorf("constructed slice = %s, want %s", s, want)
4991 // check that type already in binary is found
4993 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4996 func TestSliceOverflow(t *testing.T) {
4997 // check that MakeSlice panics when size of slice overflows uint
5000 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5002 t.Fatal("slice size does not overflow")
5005 st := SliceOf(TypeOf(x))
5009 t.Fatal("slice overflow does not panic")
5012 MakeSlice(st, int(l), int(l))
5015 func TestSliceOfGC(t *testing.T) {
5017 tt := TypeOf(T(nil))
5021 for i := 0; i < n; i++ {
5022 v := MakeSlice(st, n, n)
5023 for j := 0; j < v.Len(); j++ {
5025 *p = uintptr(i*n + j)
5026 v.Index(j).Set(ValueOf(p).Convert(tt))
5028 x = append(x, v.Interface())
5032 for i, xi := range x {
5034 for j := 0; j < v.Len(); j++ {
5035 k := v.Index(j).Elem().Interface()
5036 if k != uintptr(i*n+j) {
5037 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5043 func TestStructOfFieldName(t *testing.T) {
5044 // invalid field name "1nvalid"
5045 shouldPanic("has invalid name", func() {
5046 StructOf([]StructField{
5047 {Name: "Valid", Type: TypeOf("")},
5048 {Name: "1nvalid", Type: TypeOf("")},
5052 // invalid field name "+"
5053 shouldPanic("has invalid name", func() {
5054 StructOf([]StructField{
5055 {Name: "Val1d", Type: TypeOf("")},
5056 {Name: "+", Type: TypeOf("")},
5061 shouldPanic("has no name", func() {
5062 StructOf([]StructField{
5063 {Name: "", Type: TypeOf("")},
5067 // verify creation of a struct with valid struct fields
5068 validFields := []StructField{
5083 validStruct := StructOf(validFields)
5085 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5086 if got, want := validStruct.String(), structStr; got != want {
5087 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5091 func TestStructOf(t *testing.T) {
5092 // check construction and use of type not in binary
5093 fields := []StructField{
5102 Type: TypeOf(byte(0)),
5106 Type: TypeOf(uint64(0)),
5110 Type: TypeOf([3]uint16{}),
5114 st := StructOf(fields)
5117 v.FieldByName("X").Set(ValueOf(byte(2)))
5118 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5121 s := fmt.Sprint(v.Interface())
5122 want := `{ 1 0 [0 0 0]}`
5124 t.Errorf("constructed struct = %s, want %s", s, want)
5126 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5127 if got, want := st.String(), stStr; got != want {
5128 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5131 // check the size, alignment and field offsets
5132 stt := TypeOf(struct {
5138 if st.Size() != stt.Size() {
5139 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5141 if st.Align() != stt.Align() {
5142 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5144 if st.FieldAlign() != stt.FieldAlign() {
5145 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5147 for i := 0; i < st.NumField(); i++ {
5148 o1 := st.Field(i).Offset
5149 o2 := stt.Field(i).Offset
5151 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5155 // Check size and alignment with a trailing zero-sized field.
5156 st = StructOf([]StructField{
5159 Type: TypeOf(byte(0)),
5163 Type: TypeOf([0]*byte{}),
5166 stt = TypeOf(struct {
5170 if st.Size() != stt.Size() {
5171 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5173 if st.Align() != stt.Align() {
5174 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5176 if st.FieldAlign() != stt.FieldAlign() {
5177 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5179 for i := 0; i < st.NumField(); i++ {
5180 o1 := st.Field(i).Offset
5181 o2 := stt.Field(i).Offset
5183 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5187 // check duplicate names
5188 shouldPanic("duplicate field", func() {
5189 StructOf([]StructField{
5190 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5191 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5194 shouldPanic("has no name", func() {
5195 StructOf([]StructField{
5197 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5200 shouldPanic("has no name", func() {
5201 StructOf([]StructField{
5206 // check that type already in binary is found
5207 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5209 // gccgo used to fail this test.
5210 type structFieldType any
5212 StructOf([]StructField{
5215 Type: TypeOf((*structFieldType)(nil)).Elem(),
5218 struct{ F structFieldType }{})
5221 func TestStructOfExportRules(t *testing.T) {
5227 testPanic := func(i int, mustPanic bool, f func()) {
5230 if err == nil && mustPanic {
5231 t.Errorf("test-%d did not panic", i)
5233 if err != nil && !mustPanic {
5234 t.Errorf("test-%d panicked: %v\n", i, err)
5246 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5250 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5254 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5258 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5262 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5266 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5270 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5274 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5278 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5282 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5286 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5289 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5292 field: StructField{Name: "S", Type: TypeOf(S1{})},
5296 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5300 field: StructField{Name: "S", Type: TypeOf(s2{})},
5304 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5308 field: StructField{Name: "s", Type: TypeOf(S1{})},
5312 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5316 field: StructField{Name: "s", Type: TypeOf(s2{})},
5320 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5324 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5327 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5330 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5333 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5336 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5340 field: StructField{Name: "", Type: TypeOf(φType{})},
5344 field: StructField{Name: "Φ", Type: TypeOf(0)},
5348 field: StructField{Name: "φ", Type: TypeOf(0)},
5353 for i, test := range tests {
5354 testPanic(i, test.mustPanic, func() {
5355 typ := StructOf([]StructField{test.field})
5357 t.Errorf("test-%d: error creating struct type", i)
5360 field := typ.Field(0)
5363 panic("field.Name must not be empty")
5365 exported := token.IsExported(n)
5366 if exported != test.exported {
5367 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5369 if field.PkgPath != test.field.PkgPath {
5370 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5376 func TestStructOfGC(t *testing.T) {
5378 tt := TypeOf(T(nil))
5379 fields := []StructField{
5380 {Name: "X", Type: tt},
5381 {Name: "Y", Type: tt},
5383 st := StructOf(fields)
5387 for i := 0; i < n; i++ {
5389 for j := 0; j < v.NumField(); j++ {
5391 *p = uintptr(i*n + j)
5392 v.Field(j).Set(ValueOf(p).Convert(tt))
5394 x = append(x, v.Interface())
5398 for i, xi := range x {
5400 for j := 0; j < v.NumField(); j++ {
5401 k := v.Field(j).Elem().Interface()
5402 if k != uintptr(i*n+j) {
5403 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5409 func TestStructOfAlg(t *testing.T) {
5410 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5411 v1 := New(st).Elem()
5412 v2 := New(st).Elem()
5413 if !DeepEqual(v1.Interface(), v1.Interface()) {
5414 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5416 v1.FieldByName("X").Set(ValueOf(int(1)))
5417 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5418 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5421 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5423 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5426 func TestStructOfGenericAlg(t *testing.T) {
5427 st1 := StructOf([]StructField{
5428 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5429 {Name: "Y", Type: TypeOf(string(""))},
5431 st := StructOf([]StructField{
5432 {Name: "S0", Type: st1},
5433 {Name: "S1", Type: st1},
5451 {Name: "XX", Type: TypeOf([0]int{})},
5452 {Name: "YY", Type: TypeOf("")},
5460 {Name: "XX", Type: TypeOf([0]int{})},
5461 {Name: "YY", Type: TypeOf("")},
5462 {Name: "ZZ", Type: TypeOf([2]int{})},
5470 {Name: "XX", Type: TypeOf([1]int{})},
5471 {Name: "YY", Type: TypeOf("")},
5479 {Name: "XX", Type: TypeOf([1]int{})},
5480 {Name: "YY", Type: TypeOf("")},
5481 {Name: "ZZ", Type: TypeOf([1]int{})},
5489 {Name: "XX", Type: TypeOf([2]int{})},
5490 {Name: "YY", Type: TypeOf("")},
5491 {Name: "ZZ", Type: TypeOf([2]int{})},
5499 {Name: "XX", Type: TypeOf(int64(0))},
5500 {Name: "YY", Type: TypeOf(byte(0))},
5501 {Name: "ZZ", Type: TypeOf("")},
5509 {Name: "XX", Type: TypeOf(int64(0))},
5510 {Name: "YY", Type: TypeOf(int64(0))},
5511 {Name: "ZZ", Type: TypeOf("")},
5512 {Name: "AA", Type: TypeOf([1]int64{})},
5519 for _, table := range tests {
5520 v1 := New(table.rt).Elem()
5521 v2 := New(table.rt).Elem()
5523 if !DeepEqual(v1.Interface(), v1.Interface()) {
5524 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5527 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5528 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5529 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5530 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5534 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5535 val := "+" + abc + "-"
5536 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5537 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5538 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5542 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5543 m.SetMapIndex(v1, ValueOf(1))
5544 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5545 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5548 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5549 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5550 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5553 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5554 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5559 func TestStructOfDirectIface(t *testing.T) {
5561 type T struct{ X [1]*byte }
5562 i1 := Zero(TypeOf(T{})).Interface()
5563 v1 := ValueOf(&i1).Elem()
5564 p1 := v1.InterfaceData()[1]
5566 i2 := Zero(StructOf([]StructField{
5569 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5572 v2 := ValueOf(&i2).Elem()
5573 p2 := v2.InterfaceData()[1]
5576 t.Errorf("got p1=%v. want=%v", p1, nil)
5580 t.Errorf("got p2=%v. want=%v", p2, nil)
5584 type T struct{ X [0]*byte }
5585 i1 := Zero(TypeOf(T{})).Interface()
5586 v1 := ValueOf(&i1).Elem()
5587 p1 := v1.InterfaceData()[1]
5589 i2 := Zero(StructOf([]StructField{
5592 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5595 v2 := ValueOf(&i2).Elem()
5596 p2 := v2.InterfaceData()[1]
5599 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5603 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5610 func (i StructI) Get() int { return int(i) }
5614 func (i *StructIPtr) Get() int { return int(*i) }
5615 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5617 type SettableStruct struct {
5621 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5623 type SettablePointer struct {
5627 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5629 func TestStructOfWithInterface(t *testing.T) {
5631 type Iface interface {
5634 type IfaceSet interface {
5645 typ: TypeOf(StructI(want)),
5646 val: ValueOf(StructI(want)),
5651 typ: PointerTo(TypeOf(StructI(want))),
5652 val: ValueOf(func() any {
5660 typ: PointerTo(TypeOf(StructIPtr(want))),
5661 val: ValueOf(func() any {
5662 v := StructIPtr(want)
5669 typ: TypeOf(StructIPtr(want)),
5670 val: ValueOf(StructIPtr(want)),
5674 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5675 // val: ValueOf(StructI(want)),
5680 for i, table := range tests {
5681 for j := 0; j < 2; j++ {
5682 var fields []StructField
5684 fields = append(fields, StructField{
5687 Type: TypeOf(int(0)),
5690 fields = append(fields, StructField{
5697 // We currently do not correctly implement methods
5698 // for embedded fields other than the first.
5699 // Therefore, for now, we expect those methods
5700 // to not exist. See issues 15924 and 20824.
5701 // When those issues are fixed, this test of panic
5702 // should be removed.
5703 if j == 1 && table.impl {
5706 if err := recover(); err == nil {
5707 t.Errorf("test-%d-%d did not panic", i, j)
5710 _ = StructOf(fields)
5715 rt := StructOf(fields)
5716 rv := New(rt).Elem()
5717 rv.Field(j).Set(table.val)
5719 if _, ok := rv.Interface().(Iface); ok != table.impl {
5721 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5723 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5732 v := rv.Interface().(Iface).Get()
5734 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5737 fct := rv.MethodByName("Get")
5738 out := fct.Call(nil)
5739 if !DeepEqual(out[0].Interface(), want) {
5740 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5745 // Test an embedded nil pointer with pointer methods.
5746 fields := []StructField{{
5749 Type: PointerTo(TypeOf(StructIPtr(want))),
5751 rt := StructOf(fields)
5752 rv := New(rt).Elem()
5753 // This should panic since the pointer is nil.
5754 shouldPanic("", func() {
5755 rv.Interface().(IfaceSet).Set(want)
5758 // Test an embedded nil pointer to a struct with pointer methods.
5760 fields = []StructField{{
5761 Name: "SettableStruct",
5763 Type: PointerTo(TypeOf(SettableStruct{})),
5765 rt = StructOf(fields)
5767 // This should panic since the pointer is nil.
5768 shouldPanic("", func() {
5769 rv.Interface().(IfaceSet).Set(want)
5772 // The behavior is different if there is a second field,
5773 // since now an interface value holds a pointer to the struct
5774 // rather than just holding a copy of the struct.
5775 fields = []StructField{
5777 Name: "SettableStruct",
5779 Type: PointerTo(TypeOf(SettableStruct{})),
5782 Name: "EmptyStruct",
5784 Type: StructOf(nil),
5787 // With the current implementation this is expected to panic.
5788 // Ideally it should work and we should be able to see a panic
5789 // if we call the Set method.
5790 shouldPanic("", func() {
5794 // Embed a field that can be stored directly in an interface,
5795 // with a second field.
5796 fields = []StructField{
5798 Name: "SettablePointer",
5800 Type: TypeOf(SettablePointer{}),
5803 Name: "EmptyStruct",
5805 Type: StructOf(nil),
5808 // With the current implementation this is expected to panic.
5809 // Ideally it should work and we should be able to call the
5810 // Set and Get methods.
5811 shouldPanic("", func() {
5816 func TestStructOfTooManyFields(t *testing.T) {
5817 // Bug Fix: #25402 - this should not panic
5818 tt := StructOf([]StructField{
5819 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5822 if _, present := tt.MethodByName("After"); !present {
5823 t.Errorf("Expected method `After` to be found")
5827 func TestStructOfDifferentPkgPath(t *testing.T) {
5828 fields := []StructField{
5832 Type: TypeOf(int(0)),
5837 Type: TypeOf(int(0)),
5840 shouldPanic("different PkgPath", func() {
5845 func TestChanOf(t *testing.T) {
5846 // check construction and use of type not in binary
5848 ct := ChanOf(BothDir, TypeOf(T("")))
5849 v := MakeChan(ct, 2)
5851 v.Send(ValueOf(T("hello")))
5853 v.Send(ValueOf(T("world")))
5860 if s1 != "hello" || s2 != "world" {
5861 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5864 // check that type already in binary is found
5866 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5868 // Check arrow token association in undefined chan types.
5869 var left chan<- chan T
5870 var right chan (<-chan T)
5871 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5872 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5873 if tLeft != TypeOf(left) {
5874 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5876 if tRight != TypeOf(right) {
5877 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5881 func TestChanOfDir(t *testing.T) {
5882 // check construction and use of type not in binary
5884 crt := ChanOf(RecvDir, TypeOf(T("")))
5885 cst := ChanOf(SendDir, TypeOf(T("")))
5887 // check that type already in binary is found
5889 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5890 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5892 // check String form of ChanDir
5893 if crt.ChanDir().String() != "<-chan" {
5894 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5896 if cst.ChanDir().String() != "chan<-" {
5897 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5901 func TestChanOfGC(t *testing.T) {
5902 done := make(chan bool, 1)
5906 case <-time.After(5 * time.Second):
5907 panic("deadlock in TestChanOfGC")
5916 tt := TypeOf(T(nil))
5917 ct := ChanOf(BothDir, tt)
5919 // NOTE: The garbage collector handles allocated channels specially,
5920 // so we have to save pointers to channels in x; the pointer code will
5921 // use the gc info in the newly constructed chan type.
5924 for i := 0; i < n; i++ {
5925 v := MakeChan(ct, n)
5926 for j := 0; j < n; j++ {
5928 *p = uintptr(i*n + j)
5929 v.Send(ValueOf(p).Convert(tt))
5933 x = append(x, pv.Interface())
5937 for i, xi := range x {
5938 v := ValueOf(xi).Elem()
5939 for j := 0; j < n; j++ {
5941 k := pv.Elem().Interface()
5942 if k != uintptr(i*n+j) {
5943 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5949 func TestMapOf(t *testing.T) {
5950 // check construction and use of type not in binary
5954 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5956 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5959 s := fmt.Sprint(v.Interface())
5962 t.Errorf("constructed map = %s, want %s", s, want)
5965 // check that type already in binary is found
5966 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5968 // check that invalid key type panics
5969 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5972 func TestMapOfGCKeys(t *testing.T) {
5974 tt := TypeOf(T(nil))
5975 mt := MapOf(tt, TypeOf(false))
5977 // NOTE: The garbage collector handles allocated maps specially,
5978 // so we have to save pointers to maps in x; the pointer code will
5979 // use the gc info in the newly constructed map type.
5982 for i := 0; i < n; i++ {
5984 for j := 0; j < n; j++ {
5986 *p = uintptr(i*n + j)
5987 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5991 x = append(x, pv.Interface())
5995 for i, xi := range x {
5996 v := ValueOf(xi).Elem()
5998 for _, kv := range v.MapKeys() {
5999 out = append(out, int(kv.Elem().Interface().(uintptr)))
6002 for j, k := range out {
6004 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6010 func TestMapOfGCValues(t *testing.T) {
6012 tt := TypeOf(T(nil))
6013 mt := MapOf(TypeOf(1), tt)
6015 // NOTE: The garbage collector handles allocated maps specially,
6016 // so we have to save pointers to maps in x; the pointer code will
6017 // use the gc info in the newly constructed map type.
6020 for i := 0; i < n; i++ {
6022 for j := 0; j < n; j++ {
6024 *p = uintptr(i*n + j)
6025 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6029 x = append(x, pv.Interface())
6033 for i, xi := range x {
6034 v := ValueOf(xi).Elem()
6035 for j := 0; j < n; j++ {
6036 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6037 if k != uintptr(i*n+j) {
6038 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6044 func TestTypelinksSorted(t *testing.T) {
6046 for i, n := range TypeLinks() {
6048 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6054 func TestFuncOf(t *testing.T) {
6055 // check construction and use of type not in binary
6059 fn := func(args []Value) []Value {
6061 t.Errorf("args == %v, want exactly one arg", args)
6062 } else if args[0].Type() != TypeOf(K("")) {
6063 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6064 } else if args[0].String() != "gopher" {
6065 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6067 return []Value{ValueOf(V(3.14))}
6069 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6071 outs := v.Call([]Value{ValueOf(K("gopher"))})
6073 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6074 } else if outs[0].Type() != TypeOf(V(0)) {
6075 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6077 f := outs[0].Float()
6079 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6082 // check that types already in binary are found
6084 testCases := []struct {
6089 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6090 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6091 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6092 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6093 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6095 for _, tt := range testCases {
6096 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6099 // check that variadic requires last element be a slice.
6100 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6101 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6102 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6111 func BenchmarkFieldByName1(b *testing.B) {
6113 b.RunParallel(func(pb *testing.PB) {
6120 func BenchmarkFieldByName2(b *testing.B) {
6122 b.RunParallel(func(pb *testing.PB) {
6199 func TestEmbed(t *testing.T) {
6201 f, ok := typ.FieldByName("X")
6203 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6207 func BenchmarkFieldByName3(b *testing.B) {
6209 b.RunParallel(func(pb *testing.PB) {
6221 func BenchmarkInterfaceBig(b *testing.B) {
6223 b.RunParallel(func(pb *testing.PB) {
6231 func TestAllocsInterfaceBig(t *testing.T) {
6232 if testing.Short() {
6233 t.Skip("skipping malloc count in short mode")
6236 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6237 t.Error("allocs:", allocs)
6241 func BenchmarkInterfaceSmall(b *testing.B) {
6242 v := ValueOf(int64(0))
6243 b.RunParallel(func(pb *testing.PB) {
6250 func TestAllocsInterfaceSmall(t *testing.T) {
6251 if testing.Short() {
6252 t.Skip("skipping malloc count in short mode")
6254 v := ValueOf(int64(0))
6255 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6256 t.Error("allocs:", allocs)
6260 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6261 // The basic usage is:
6264 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6267 // Each iteration of the loop returns a different set of results, until all
6268 // possible result sets have been explored. It is okay for different code paths
6269 // to make different method call sequences on x, but there must be no
6270 // other source of non-determinism in the call sequences.
6272 // When faced with a new decision, x chooses randomly. Future explorations
6273 // of that path will choose successive values for the result. Thus, stopping
6274 // the loop after a fixed number of iterations gives somewhat stochastic
6280 // v := make([]bool, x.Choose(4))
6281 // for i := range v {
6287 // prints (in some order):
6296 // [false false false]
6299 // [false false false false]
6301 // [true true true true]
6302 type exhaustive struct {
6308 type choice struct {
6314 func (x *exhaustive) Next() bool {
6316 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6323 for i := len(x.last) - 1; i >= 0; i-- {
6327 x.last = x.last[:i+1]
6334 func (x *exhaustive) Choose(max int) int {
6335 if x.pos >= len(x.last) {
6336 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6341 panic("inconsistent use of exhaustive tester")
6343 return (c.n + c.off) % max
6346 func (x *exhaustive) Maybe() bool {
6347 return x.Choose(2) == 1
6350 func GCFunc(args []Value) []Value {
6355 func TestReflectFuncTraceback(t *testing.T) {
6356 f := MakeFunc(TypeOf(func() {}), GCFunc)
6360 func TestReflectMethodTraceback(t *testing.T) {
6362 m := ValueOf(p).MethodByName("GCMethod")
6363 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6365 t.Errorf("Call returned %d; want 8", i)
6369 func TestSmallZero(t *testing.T) {
6372 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6373 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6377 func TestBigZero(t *testing.T) {
6378 const size = 1 << 10
6380 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6381 for i := 0; i < size; i++ {
6383 t.Fatalf("Zero object not all zero, index %d", i)
6388 func TestZeroSet(t *testing.T) {
6396 a: 0xaaaaaaaaaaaaaaaa,
6397 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6398 b: 0xbbbbbbbbbbbbbbbb,
6400 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6402 a: 0xaaaaaaaaaaaaaaaa,
6403 b: 0xbbbbbbbbbbbbbbbb,
6405 t.Fatalf("Setting a field to a Zero value didn't work")
6409 func TestFieldByIndexNil(t *testing.T) {
6418 v.FieldByName("P") // should be fine
6421 if err := recover(); err == nil {
6422 t.Fatalf("no error")
6423 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6424 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6427 v.FieldByName("F") // should panic
6429 t.Fatalf("did not panic")
6433 // type Outer struct {
6437 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6438 // The implementation is logically:
6439 // func (p *Outer) M() {
6442 // but since the only change here is the replacement of one pointer receiver with another,
6443 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6444 // then jumps to the M method expecting the *Inner receiver.
6446 // During reflect.Value.Call, we create an argument frame and the associated data structures
6447 // to describe it to the garbage collector, populate the frame, call reflect.call to
6448 // run a function call using that frame, and then copy the results back out of the frame.
6449 // The reflect.call function does a memmove of the frame structure onto the
6450 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6451 // the frame structure (to preserve the outputs).
6453 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6454 // were for the full stack frame. However, in the case where the called function was
6455 // one of these wrappers, the rewritten receiver is almost certainly a different type
6456 // than the original receiver. This is not a problem on the stack, where we use the
6457 // program counter to determine the type information and understand that
6458 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6459 // memory word is now an *Inner. But in the statically typed argument frame created
6460 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6461 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6462 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6463 // memory as if it were an *Outer. If the two have different memory layouts, the
6464 // collection will interpret the memory incorrectly.
6466 // One such possible incorrect interpretation is to treat two arbitrary memory words
6467 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6468 // an interface requires dereferencing the itab word, the misinterpretation will try to
6469 // deference Inner.P1, causing a crash during garbage collection.
6471 // This came up in a real program in issue 7725.
6484 func (pi *Inner) M() {
6485 // Clear references to pi so that the only way the
6486 // garbage collection will find the pointer is in the
6487 // argument frame, typed as a *Outer.
6490 // Set up an interface value that will cause a crash.
6491 // P1 = 1 is a non-zero, so the interface looks non-nil.
6492 // P2 = pi ensures that the data word points into the
6493 // allocated heap; if not the collection skips the interface
6494 // value as irrelevant, without dereferencing P1.
6496 pi.P2 = uintptr(unsafe.Pointer(pi))
6499 func TestCallMethodJump(t *testing.T) {
6500 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6501 // returns but before the args frame has been discarded.
6502 // This is a little clumsy but makes the failure repeatable.
6505 p := &Outer{Inner: new(Inner)}
6507 ValueOf(p).Method(0).Call(nil)
6509 // Stop garbage collecting during reflect.call.
6513 func TestCallArgLive(t *testing.T) {
6514 type T struct{ X, Y *string } // pointerful aggregate
6516 F := func(t T) { *t.X = "ok" }
6518 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6519 // between marshaling argument and the actual call.
6523 runtime.SetFinalizer(x, func(p *string) {
6525 t.Errorf("x dead prematurely")
6530 ValueOf(F).Call([]Value{ValueOf(v)})
6532 // Stop garbage collecting during reflect.call.
6536 func TestMakeFuncStackCopy(t *testing.T) {
6537 target := func(in []Value) []Value {
6540 return []Value{ValueOf(9)}
6543 var concrete func(*int, int) int
6544 fn := MakeFunc(ValueOf(concrete).Type(), target)
6545 ValueOf(&concrete).Elem().Set(fn)
6546 x := concrete(nil, 7)
6548 t.Errorf("have %#q want 9", x)
6552 // use about n KB of stack
6553 func useStack(n int) {
6557 var b [1024]byte // makes frame about 1KB
6558 useStack(n - 1 + int(b[99]))
6565 func TestValueString(t *testing.T) {
6566 rv := ValueOf(Impl{})
6567 if rv.String() != "<reflect_test.Impl Value>" {
6568 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6571 method := rv.Method(0)
6572 if method.String() != "<func() Value>" {
6573 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6577 func TestInvalid(t *testing.T) {
6578 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6579 type T struct{ v any }
6581 v := ValueOf(T{}).Field(0)
6582 if v.IsValid() != true || v.Kind() != Interface {
6583 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6586 if v.IsValid() != false || v.Kind() != Invalid {
6587 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6592 func TestLargeGCProg(t *testing.T) {
6593 fv := ValueOf(func([256]*byte) {})
6594 fv.Call([]Value{ValueOf([256]*byte{})})
6597 func fieldIndexRecover(t Type, i int) (recovered any) {
6599 recovered = recover()
6607 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6608 typ := TypeOf(struct{ X int }{10})
6609 testIndices := [...]struct {
6618 for i, tt := range testIndices {
6619 recoveredErr := fieldIndexRecover(typ, tt.i)
6621 if recoveredErr == nil {
6622 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6625 if recoveredErr != nil {
6626 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6633 func TestCallGC(t *testing.T) {
6634 f := func(a, b, c, d, e string) {
6636 g := func(in []Value) []Value {
6640 typ := ValueOf(f).Type()
6641 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6642 f2("four", "five5", "six666", "seven77", "eight888")
6645 // Issue 18635 (function version).
6646 func TestKeepFuncLive(t *testing.T) {
6647 // Test that we keep makeFuncImpl live as long as it is
6648 // referenced on the stack.
6649 typ := TypeOf(func(i int) {})
6650 var f, g func(in []Value) []Value
6651 f = func(in []Value) []Value {
6653 i := int(in[0].Int())
6655 // We can't use Value.Call here because
6656 // runtime.call* will keep the makeFuncImpl
6657 // alive. However, by converting it to an
6658 // interface value and calling that,
6659 // reflect.callReflect is the only thing that
6660 // can keep the makeFuncImpl live.
6662 // Alternate between f and g so that if we do
6663 // reuse the memory prematurely it's more
6664 // likely to get obviously corrupted.
6665 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6669 g = func(in []Value) []Value {
6671 i := int(in[0].Int())
6672 MakeFunc(typ, f).Interface().(func(i int))(i)
6675 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6678 type UnExportedFirst int
6680 func (i UnExportedFirst) ΦExported() {}
6681 func (i UnExportedFirst) unexported() {}
6684 func TestMethodByNameUnExportedFirst(t *testing.T) {
6686 if recover() != nil {
6687 t.Errorf("should not panic")
6690 typ := TypeOf(UnExportedFirst(0))
6691 m, _ := typ.MethodByName("ΦExported")
6692 if m.Name != "ΦExported" {
6693 t.Errorf("got %s, expected ΦExported", m.Name)
6697 // Issue 18635 (method version).
6698 type KeepMethodLive struct{}
6700 func (k KeepMethodLive) Method1(i int) {
6703 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6707 func (k KeepMethodLive) Method2(i int) {
6709 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6712 func TestKeepMethodLive(t *testing.T) {
6713 // Test that we keep methodValue live as long as it is
6714 // referenced on the stack.
6715 KeepMethodLive{}.Method1(10)
6718 // clobber tries to clobber unreachable memory.
6721 for i := 1; i < 32; i++ {
6722 for j := 0; j < 10; j++ {
6723 obj := make([]*byte, i)
6730 func TestFuncLayout(t *testing.T) {
6731 align := func(x uintptr) uintptr {
6732 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6735 if goarch.PtrSize == 4 {
6736 r = []byte{0, 0, 0, 1}
6748 size, argsize, retOffset uintptr
6749 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6750 intRegs, floatRegs int
6751 floatRegSize uintptr
6755 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6756 size: 6 * goarch.PtrSize,
6757 argsize: 4 * goarch.PtrSize,
6758 retOffset: 4 * goarch.PtrSize,
6759 stack: []byte{1, 0, 1, 0, 1},
6760 gc: []byte{1, 0, 1, 0, 1},
6763 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6764 size: align(align(3*4) + goarch.PtrSize + 2),
6765 argsize: align(3*4) + goarch.PtrSize + 2,
6766 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6771 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6772 size: 4 * goarch.PtrSize,
6773 argsize: 4 * goarch.PtrSize,
6774 retOffset: 4 * goarch.PtrSize,
6775 stack: []byte{1, 0, 1, 1},
6776 gc: []byte{1, 0, 1, 1},
6779 typ: ValueOf(func(a S) {}).Type(),
6780 size: 4 * goarch.PtrSize,
6781 argsize: 4 * goarch.PtrSize,
6782 retOffset: 4 * goarch.PtrSize,
6783 stack: []byte{0, 0, 1, 1},
6784 gc: []byte{0, 0, 1, 1},
6787 rcvr: ValueOf((*byte)(nil)).Type(),
6788 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6789 size: 3 * goarch.PtrSize,
6790 argsize: 3 * goarch.PtrSize,
6791 retOffset: 3 * goarch.PtrSize,
6792 stack: []byte{1, 0, 1},
6793 gc: []byte{1, 0, 1},
6796 typ: ValueOf(func(a uintptr) {}).Type(),
6797 size: goarch.PtrSize,
6798 argsize: goarch.PtrSize,
6799 retOffset: goarch.PtrSize,
6804 typ: ValueOf(func() uintptr { return 0 }).Type(),
6805 size: goarch.PtrSize,
6812 rcvr: ValueOf(uintptr(0)).Type(),
6813 typ: ValueOf(func(a uintptr) {}).Type(),
6814 size: 2 * goarch.PtrSize,
6815 argsize: 2 * goarch.PtrSize,
6816 retOffset: 2 * goarch.PtrSize,
6819 // Note: this one is tricky, as the receiver is not a pointer. But we
6820 // pass the receiver by reference to the autogenerated pointer-receiver
6821 // version of the function.
6823 // TODO(mknyszek): Add tests for non-zero register count.
6825 for _, lt := range tests {
6826 name := lt.typ.String()
6828 name = lt.rcvr.String() + "." + name
6830 t.Run(name, func(t *testing.T) {
6831 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6833 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6834 if typ.Size() != lt.size {
6835 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6837 if argsize != lt.argsize {
6838 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6840 if retOffset != lt.retOffset {
6841 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6843 if !bytes.Equal(stack, lt.stack) {
6844 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6846 if !bytes.Equal(gc, lt.gc) {
6847 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6849 if !bytes.Equal(inRegs, lt.inRegs) {
6850 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6852 if !bytes.Equal(outRegs, lt.outRegs) {
6853 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6855 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6856 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6862 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6863 heapBits := GCBits(New(typ).Interface())
6864 if !bytes.Equal(heapBits, bits) {
6865 _, _, line, _ := runtime.Caller(1)
6866 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6870 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6871 // Creating a slice causes the runtime to repeat a bitmap,
6872 // which exercises a different path from making the compiler
6873 // repeat a bitmap for a small array or executing a repeat in
6875 val := MakeSlice(typ, 0, cap)
6876 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
6877 heapBits := GCBits(data.Interface())
6878 // Repeat the bitmap for the slice size, trimming scalars in
6879 // the last element.
6880 bits = rep(cap, bits)
6881 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6882 bits = bits[:len(bits)-1]
6884 if !bytes.Equal(heapBits, bits) {
6885 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6889 func TestGCBits(t *testing.T) {
6890 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6892 // Building blocks for types seen by the compiler (like [2]Xscalar).
6893 // The compiler will create the type structures for the derived types,
6894 // including their GC metadata.
6895 type Xscalar struct{ x uintptr }
6896 type Xptr struct{ x *byte }
6897 type Xptrscalar struct {
6901 type Xscalarptr struct {
6905 type Xbigptrscalar struct {
6910 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6912 // Building blocks for types constructed by reflect.
6913 // This code is in a separate block so that code below
6914 // cannot accidentally refer to these.
6915 // The compiler must NOT see types derived from these
6916 // (for example, [2]Scalar must NOT appear in the program),
6917 // or else reflect will use it instead of having to construct one.
6918 // The goal is to test the construction.
6919 type Scalar struct{ x uintptr }
6920 type Ptr struct{ x *byte }
6921 type Ptrscalar struct {
6925 type Scalarptr struct {
6929 type Bigptrscalar struct {
6934 Tscalar = TypeOf(Scalar{})
6935 Tint64 = TypeOf(Int64(0))
6936 Tptr = TypeOf(Ptr{})
6937 Tscalarptr = TypeOf(Scalarptr{})
6938 Tptrscalar = TypeOf(Ptrscalar{})
6939 Tbigptrscalar = TypeOf(Bigptrscalar{})
6944 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6945 verifyGCBits(t, Tscalar, empty)
6946 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6947 verifyGCBits(t, Tptr, lit(1))
6948 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6949 verifyGCBits(t, Tscalarptr, lit(0, 1))
6950 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6951 verifyGCBits(t, Tptrscalar, lit(1))
6953 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6954 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6955 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6956 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6957 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6958 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6959 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6960 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6961 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6962 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6963 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6964 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6965 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6966 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6967 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6968 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6969 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6970 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6971 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6972 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6973 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6974 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6975 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6976 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6977 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6978 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6980 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6981 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6982 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6983 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6984 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6985 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6986 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6987 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6988 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6989 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6990 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6991 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6992 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6993 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6994 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6995 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6996 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6997 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6998 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6999 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
7000 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7001 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7002 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7003 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7004 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7005 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7007 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7008 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7010 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7011 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7013 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7014 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7016 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7017 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7019 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7020 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7022 hdr := make([]byte, 8/goarch.PtrSize)
7024 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7025 verifyGCBits(t, MapBucketOf(k, e), want)
7026 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7030 map[Xscalar]Xptr(nil),
7031 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7034 map[Xscalarptr]Xptr(nil),
7035 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7036 verifyMapBucket(t, Tint64, Tptr,
7037 map[int64]Xptr(nil),
7038 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7041 map[Xscalar]Xscalar(nil),
7044 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7045 map[[2]Xscalarptr][3]Xptrscalar(nil),
7046 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7048 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7049 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7050 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7052 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7053 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7054 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7056 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7057 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7058 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7060 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7061 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7062 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7065 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7066 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7067 func lit(x ...byte) []byte { return x }
7069 func TestTypeOfTypeOf(t *testing.T) {
7070 // Check that all the type constructors return concrete *rtype implementations.
7071 // It's difficult to test directly because the reflect package is only at arm's length.
7072 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7073 check := func(name string, typ Type) {
7074 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7075 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7079 type T struct{ int }
7080 check("TypeOf", TypeOf(T{}))
7082 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7083 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7084 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7085 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7086 check("PtrTo", PointerTo(TypeOf(T{})))
7087 check("SliceOf", SliceOf(TypeOf(T{})))
7090 type XM struct{ _ bool }
7092 func (*XM) String() string { return "" }
7094 func TestPtrToMethods(t *testing.T) {
7096 yp := New(TypeOf(y)).Interface()
7097 _, ok := yp.(fmt.Stringer)
7099 t.Fatal("does not implement Stringer, but should")
7103 func TestMapAlloc(t *testing.T) {
7104 m := ValueOf(make(map[int]int, 10))
7107 allocs := testing.AllocsPerRun(100, func() {
7111 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7116 val := ValueOf(&tmp).Elem()
7117 allocs = testing.AllocsPerRun(100, func() {
7118 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7119 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7120 for i := 0; i < size/2; i++ {
7121 val.SetInt(int64(i))
7122 mv.SetMapIndex(val, val)
7126 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7128 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7129 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7130 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7133 func TestChanAlloc(t *testing.T) {
7134 // Note: for a chan int, the return Value must be allocated, so we
7135 // use a chan *int instead.
7136 c := ValueOf(make(chan *int, 1))
7137 v := ValueOf(new(int))
7138 allocs := testing.AllocsPerRun(100, func() {
7142 if allocs < 0.5 || allocs > 1.5 {
7143 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7145 // Note: there is one allocation in reflect.recv which seems to be
7146 // a limitation of escape analysis. If that is ever fixed the
7147 // allocs < 0.5 condition will trigger and this test should be fixed.
7150 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7152 type nameTest struct {
7157 var nameTests = []nameTest{
7158 {(*int32)(nil), "int32"},
7161 {(*chan D1)(nil), ""},
7162 {(*func() D1)(nil), ""},
7163 {(*<-chan D1)(nil), ""},
7164 {(*chan<- D1)(nil), ""},
7169 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7172 func TestNames(t *testing.T) {
7173 for _, test := range nameTests {
7174 typ := TypeOf(test.v).Elem()
7175 if got := typ.Name(); got != test.want {
7176 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7181 func TestExported(t *testing.T) {
7182 type ΦExported struct{}
7183 type φUnexported struct{}
7190 type exportTest struct {
7194 exportTests := []exportTest{
7198 {(*big)(nil), false},
7199 {(BigP)(nil), true},
7200 {(*BigP)(nil), true},
7201 {ΦExported{}, true},
7202 {φUnexported{}, false},
7209 for i, test := range exportTests {
7210 typ := TypeOf(test.v)
7211 if got := IsExported(typ); got != test.want {
7212 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7217 func TestTypeStrings(t *testing.T) {
7218 type stringTest struct {
7222 stringTests := []stringTest{
7223 {TypeOf(func(int) {}), "func(int)"},
7224 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7225 {TypeOf(XM{}), "reflect_test.XM"},
7226 {TypeOf(new(XM)), "*reflect_test.XM"},
7227 {TypeOf(new(XM).String), "func() string"},
7228 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7229 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7230 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7231 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7232 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7235 for i, test := range stringTests {
7236 if got, want := test.typ.String(), test.want; got != want {
7237 t.Errorf("type %d String()=%q, want %q", i, got, want)
7242 func TestOffsetLock(t *testing.T) {
7243 var wg sync.WaitGroup
7244 for i := 0; i < 4; i++ {
7248 for j := 0; j < 50; j++ {
7249 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7257 func BenchmarkNew(b *testing.B) {
7259 b.RunParallel(func(pb *testing.PB) {
7266 func BenchmarkMap(b *testing.B) {
7268 value := ValueOf((V)(nil))
7269 stringKeys := []string{}
7270 mapOfStrings := map[string]V{}
7271 uint64Keys := []uint64{}
7272 mapOfUint64s := map[uint64]V{}
7273 for i := 0; i < 100; i++ {
7274 stringKey := fmt.Sprintf("key%d", i)
7275 stringKeys = append(stringKeys, stringKey)
7276 mapOfStrings[stringKey] = nil
7278 uint64Key := uint64(i)
7279 uint64Keys = append(uint64Keys, uint64Key)
7280 mapOfUint64s[uint64Key] = nil
7285 m, keys, value Value
7287 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7288 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7291 for _, tt := range tests {
7292 b.Run(tt.label, func(b *testing.B) {
7293 b.Run("MapIndex", func(b *testing.B) {
7295 for i := 0; i < b.N; i++ {
7296 for j := tt.keys.Len() - 1; j >= 0; j-- {
7297 tt.m.MapIndex(tt.keys.Index(j))
7301 b.Run("SetMapIndex", func(b *testing.B) {
7303 for i := 0; i < b.N; i++ {
7304 for j := tt.keys.Len() - 1; j >= 0; j-- {
7305 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7313 func TestSwapper(t *testing.T) {
7319 type pairPtr struct {
7331 in: []int{1, 20, 300},
7334 want: []int{300, 20, 1},
7337 in: []uintptr{1, 20, 300},
7340 want: []uintptr{300, 20, 1},
7343 in: []int16{1, 20, 300},
7346 want: []int16{300, 20, 1},
7349 in: []int8{1, 20, 100},
7352 want: []int8{100, 20, 1},
7355 in: []*I{&a, &b, &c},
7358 want: []*I{&c, &b, &a},
7361 in: []string{"eric", "sergey", "larry"},
7364 want: []string{"larry", "sergey", "eric"},
7367 in: []S{"eric", "sergey", "larry"},
7370 want: []S{"larry", "sergey", "eric"},
7373 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7376 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7379 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7382 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7386 for i, tt := range tests {
7387 inStr := fmt.Sprint(tt.in)
7388 Swapper(tt.in)(tt.i, tt.j)
7389 if !DeepEqual(tt.in, tt.want) {
7390 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7395 // TestUnaddressableField tests that the reflect package will not allow
7396 // a type from another package to be used as a named type with an
7397 // unexported field.
7399 // This ensures that unexported fields cannot be modified by other packages.
7400 func TestUnaddressableField(t *testing.T) {
7401 var b Buffer // type defined in reflect, a different package
7402 var localBuffer struct {
7405 lv := ValueOf(&localBuffer).Elem()
7407 shouldPanic("Set", func() {
7416 type Talias1 struct {
7424 type Talias2 struct {
7429 func TestAliasNames(t *testing.T) {
7430 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7431 out := fmt.Sprintf("%#v", t1)
7432 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7434 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7437 t2 := Talias2{Tint: 1, Tint2: 2}
7438 out = fmt.Sprintf("%#v", t2)
7439 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7441 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7445 func TestIssue22031(t *testing.T) {
7446 type s []struct{ C int }
7449 type t2 struct{ f s }
7452 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7453 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7456 for i, test := range tests {
7458 t.Errorf("%d: CanSet: got true, want false", i)
7463 type NonExportedFirst int
7465 func (i NonExportedFirst) ΦExported() {}
7466 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7468 func TestIssue22073(t *testing.T) {
7469 m := ValueOf(NonExportedFirst(0)).Method(0)
7471 if got := m.Type().NumOut(); got != 0 {
7472 t.Errorf("NumOut: got %v, want 0", got)
7479 func TestMapIterNonEmptyMap(t *testing.T) {
7480 m := map[string]int{"one": 1, "two": 2, "three": 3}
7481 iter := ValueOf(m).MapRange()
7482 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7483 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7487 func TestMapIterNilMap(t *testing.T) {
7488 var m map[string]int
7489 iter := ValueOf(m).MapRange()
7490 if got, want := iterateToString(iter), `[]`; got != want {
7491 t.Errorf("non-empty result iteratoring nil map: %s", got)
7495 func TestMapIterReset(t *testing.T) {
7496 iter := new(MapIter)
7498 // Use of zero iterator should panic.
7500 defer func() { recover() }()
7502 t.Error("Next did not panic")
7505 // Reset to new Map should work.
7506 m := map[string]int{"one": 1, "two": 2, "three": 3}
7507 iter.Reset(ValueOf(m))
7508 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7509 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7512 // Reset to Zero value should work, but iterating over it should panic.
7515 defer func() { recover() }()
7517 t.Error("Next did not panic")
7520 // Reset to a different Map with different types should work.
7521 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7522 iter.Reset(ValueOf(m2))
7523 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7524 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7527 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7528 m3 := map[uint64]uint64{
7533 kv := New(TypeOf(uint64(0))).Elem()
7534 for i := 0; i < 5; i++ {
7535 var seenk, seenv uint64
7536 iter.Reset(ValueOf(m3))
7540 kv.SetIterValue(iter)
7544 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7546 if seenv != 0b1110 {
7547 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7551 // Reset should not allocate.
7552 n := int(testing.AllocsPerRun(10, func() {
7553 iter.Reset(ValueOf(m2))
7557 t.Errorf("MapIter.Reset allocated %d times", n)
7561 func TestMapIterSafety(t *testing.T) {
7562 // Using a zero MapIter causes a panic, but not a crash.
7564 defer func() { recover() }()
7566 t.Fatal("Key did not panic")
7569 defer func() { recover() }()
7570 new(MapIter).Value()
7571 t.Fatal("Value did not panic")
7574 defer func() { recover() }()
7576 t.Fatal("Next did not panic")
7579 // Calling Key/Value on a MapIter before Next
7580 // causes a panic, but not a crash.
7581 var m map[string]int
7582 iter := ValueOf(m).MapRange()
7585 defer func() { recover() }()
7587 t.Fatal("Key did not panic")
7590 defer func() { recover() }()
7592 t.Fatal("Value did not panic")
7595 // Calling Next, Key, or Value on an exhausted iterator
7596 // causes a panic, but not a crash.
7597 iter.Next() // -> false
7599 defer func() { recover() }()
7601 t.Fatal("Key did not panic")
7604 defer func() { recover() }()
7606 t.Fatal("Value did not panic")
7609 defer func() { recover() }()
7611 t.Fatal("Next did not panic")
7615 func TestMapIterNext(t *testing.T) {
7616 // The first call to Next should reflect any
7617 // insertions to the map since the iterator was created.
7618 m := map[string]int{}
7619 iter := ValueOf(m).MapRange()
7621 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7622 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7626 func BenchmarkMapIterNext(b *testing.B) {
7627 m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3})
7629 for i := 0; i < b.N; i++ {
7636 func TestMapIterDelete0(t *testing.T) {
7637 // Delete all elements before first iteration.
7638 m := map[string]int{"one": 1, "two": 2, "three": 3}
7639 iter := ValueOf(m).MapRange()
7643 if got, want := iterateToString(iter), `[]`; got != want {
7644 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7648 func TestMapIterDelete1(t *testing.T) {
7649 // Delete all elements after first iteration.
7650 m := map[string]int{"one": 1, "two": 2, "three": 3}
7651 iter := ValueOf(m).MapRange()
7654 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7660 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7664 // iterateToString returns the set of elements
7665 // returned by an iterator in readable form.
7666 func iterateToString(it *MapIter) string {
7669 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7670 got = append(got, line)
7673 return "[" + strings.Join(got, ", ") + "]"
7676 func TestConvertibleTo(t *testing.T) {
7677 t1 := ValueOf(example1.MyStruct{}).Type()
7678 t2 := ValueOf(example2.MyStruct{}).Type()
7680 // Shouldn't raise stack overflow
7681 if t1.ConvertibleTo(t2) {
7682 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7685 t3 := ValueOf([]example1.MyStruct{}).Type()
7686 t4 := ValueOf([]example2.MyStruct{}).Type()
7688 if t3.ConvertibleTo(t4) {
7689 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7693 func TestSetIter(t *testing.T) {
7694 data := map[string]int{
7702 k := New(TypeOf("")).Elem()
7703 v := New(TypeOf(0)).Elem()
7704 shouldPanic("Value.SetIterKey called before Next", func() {
7707 shouldPanic("Value.SetIterValue called before Next", func() {
7710 data2 := map[string]int{}
7714 data2[k.Interface().(string)] = v.Interface().(int)
7716 if !DeepEqual(data, data2) {
7717 t.Errorf("maps not equal, got %v want %v", data2, data)
7719 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7722 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7728 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7729 ValueOf("").SetIterKey(i)
7731 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7732 ValueOf(0).SetIterValue(i)
7734 shouldPanic("value of type string is not assignable to type int", func() {
7735 New(TypeOf(0)).Elem().SetIterKey(i)
7737 shouldPanic("value of type int is not assignable to type string", func() {
7738 New(TypeOf("")).Elem().SetIterValue(i)
7741 // Make sure assignment conversion works.
7743 y := ValueOf(&x).Elem()
7745 if _, ok := data[x.(string)]; !ok {
7746 t.Errorf("got key %s which is not in map", x)
7749 if x.(int) < 1 || x.(int) > 3 {
7750 t.Errorf("got value %d which is not in map", x)
7753 // Try some key/value types which are direct interfaces.
7756 pp := map[*int]*int{
7759 i = ValueOf(pp).MapRange()
7762 if got := *y.Interface().(*int); got != a {
7763 t.Errorf("pointer incorrect: got %d want %d", got, a)
7766 if got := *y.Interface().(*int); got != b {
7767 t.Errorf("pointer incorrect: got %d want %d", got, b)
7772 type nih struct{ x int }
7774 var global_nih = nih{x: 7}
7776 func TestNotInHeapDeref(t *testing.T) {
7778 v := ValueOf((*nih)(nil))
7780 shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
7782 v = ValueOf(&global_nih)
7783 if got := v.Elem().Field(0).Int(); got != 7 {
7784 t.Fatalf("got %d, want 7", got)
7787 v = ValueOf((*nih)(unsafe.Pointer(new(int))))
7788 shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
7789 shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() })
7790 shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() })
7793 func TestMethodCallValueCodePtr(t *testing.T) {
7794 m := ValueOf(Point{}).Method(1)
7795 want := MethodValueCallCodePtr()
7796 if got := uintptr(m.UnsafePointer()); got != want {
7797 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7799 if got := m.Pointer(); got != want {
7800 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7805 type B[T any] struct{}
7807 func TestIssue50208(t *testing.T) {
7808 want1 := "B[reflect_test.A]"
7809 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7810 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7812 want2 := "B[reflect_test.B[reflect_test.A]]"
7813 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7814 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7818 func TestNegativeKindString(t *testing.T) {
7820 s := Kind(x).String()
7823 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)
7832 var sourceAll = struct {
7841 Bool: ValueOf(new(bool)).Elem(),
7842 String: ValueOf(new(string)).Elem(),
7843 Bytes: ValueOf(new([]byte)).Elem(),
7844 NamedBytes: ValueOf(new(namedBytes)).Elem(),
7845 BytesArray: ValueOf(new([32]byte)).Elem(),
7846 SliceAny: ValueOf(new([]any)).Elem(),
7847 MapStringAny: ValueOf(new(map[string]any)).Elem(),
7850 var sinkAll struct {
7857 func BenchmarkBool(b *testing.B) {
7858 for i := 0; i < b.N; i++ {
7859 sinkAll.RawBool = sourceAll.Bool.Bool()
7863 func BenchmarkString(b *testing.B) {
7864 for i := 0; i < b.N; i++ {
7865 sinkAll.RawString = sourceAll.String.String()
7869 func BenchmarkBytes(b *testing.B) {
7870 for i := 0; i < b.N; i++ {
7871 sinkAll.RawBytes = sourceAll.Bytes.Bytes()
7875 func BenchmarkNamedBytes(b *testing.B) {
7876 for i := 0; i < b.N; i++ {
7877 sinkAll.RawBytes = sourceAll.NamedBytes.Bytes()
7881 func BenchmarkBytesArray(b *testing.B) {
7882 for i := 0; i < b.N; i++ {
7883 sinkAll.RawBytes = sourceAll.BytesArray.Bytes()
7887 func BenchmarkSliceLen(b *testing.B) {
7888 for i := 0; i < b.N; i++ {
7889 sinkAll.RawInt = sourceAll.SliceAny.Len()
7893 func BenchmarkMapLen(b *testing.B) {
7894 for i := 0; i < b.N; i++ {
7895 sinkAll.RawInt = sourceAll.MapStringAny.Len()
7899 func BenchmarkStringLen(b *testing.B) {
7900 for i := 0; i < b.N; i++ {
7901 sinkAll.RawInt = sourceAll.String.Len()
7905 func BenchmarkArrayLen(b *testing.B) {
7906 for i := 0; i < b.N; i++ {
7907 sinkAll.RawInt = sourceAll.BytesArray.Len()
7911 func BenchmarkSliceCap(b *testing.B) {
7912 for i := 0; i < b.N; i++ {
7913 sinkAll.RawInt = sourceAll.SliceAny.Cap()
7917 func TestValue_Cap(t *testing.T) {
7918 a := &[3]int{1, 2, 3}
7920 if v.Cap() != cap(a) {
7921 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7926 if v.Cap() != cap(a) {
7927 t.Errorf("Cap = %d want %d", v.Cap(), cap(a))
7930 getError := func(f func()) (errorStr string) {
7933 if str, ok := e.(string); ok {
7940 e := getError(func() {
7944 wantStr := "reflect: call of reflect.Value.Cap on ptr to non-array Value"
7946 t.Errorf("error is %q, want %q", e, wantStr)
7950 func TestValue_Len(t *testing.T) {
7951 a := &[3]int{1, 2, 3}
7953 if v.Len() != len(a) {
7954 t.Errorf("Len = %d want %d", v.Len(), len(a))
7959 if v.Len() != len(a) {
7960 t.Errorf("Len = %d want %d", v.Len(), len(a))
7963 getError := func(f func()) (errorStr string) {
7966 if str, ok := e.(string); ok {
7973 e := getError(func() {
7977 wantStr := "reflect: call of reflect.Value.Len on ptr to non-array Value"
7979 t.Errorf("error is %q, want %q", e, wantStr)