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 got := int(testing.AllocsPerRun(10, func() {
374 // Calling MapRange should not allocate even though it returns a *MapIter.
375 // The function is inlineable, so if the local usage does not escape
376 // the *MapIter, it can remain stack allocated.
378 if strings.HasSuffix(testenv.Builder(), "-noopt") {
379 want = 1 // no inlining with the noopt builder
382 t.Errorf("wanted %d alloc, got %d", want, got)
386 func TestCanIntUintFloatComplex(t *testing.T) {
390 type complex complex128
392 var ops = [...]string{"CanInt", "CanUint", "CanFloat", "CanComplex"}
394 var testCases = []struct {
399 {132, [...]bool{true, false, false, false}},
400 {int8(8), [...]bool{true, false, false, false}},
401 {int16(16), [...]bool{true, false, false, false}},
402 {int32(32), [...]bool{true, false, false, false}},
403 {int64(64), [...]bool{true, false, false, false}},
405 {uint(132), [...]bool{false, true, false, false}},
406 {uint8(8), [...]bool{false, true, false, false}},
407 {uint16(16), [...]bool{false, true, false, false}},
408 {uint32(32), [...]bool{false, true, false, false}},
409 {uint64(64), [...]bool{false, true, false, false}},
410 {uintptr(0xABCD), [...]bool{false, true, false, false}},
412 {float32(256.25), [...]bool{false, false, true, false}},
413 {float64(512.125), [...]bool{false, false, true, false}},
415 {complex64(532.125 + 10i), [...]bool{false, false, false, true}},
416 {complex128(564.25 + 1i), [...]bool{false, false, false, true}},
418 {integer(-132), [...]bool{true, false, false, false}},
419 {uinteger(132), [...]bool{false, true, false, false}},
420 {float(256.25), [...]bool{false, false, true, false}},
421 {complex(532.125 + 10i), [...]bool{false, false, false, true}},
423 {"hello world", [...]bool{false, false, false, false}},
424 {new(int), [...]bool{false, false, false, false}},
425 {new(uint), [...]bool{false, false, false, false}},
426 {new(float64), [...]bool{false, false, false, false}},
427 {new(complex64), [...]bool{false, false, false, false}},
428 {new([5]int), [...]bool{false, false, false, false}},
429 {new(integer), [...]bool{false, false, false, false}},
430 {new(map[int]int), [...]bool{false, false, false, false}},
431 {new(chan<- int), [...]bool{false, false, false, false}},
432 {new(func(a int8)), [...]bool{false, false, false, false}},
433 {new(struct{ i int }), [...]bool{false, false, false, false}},
436 for i, tc := range testCases {
438 got := [...]bool{v.CanInt(), v.CanUint(), v.CanFloat(), v.CanComplex()}
440 for j := range tc.want {
441 if got[j] != tc.want[j] {
443 "#%d: v.%s() returned %t for type %T, want %t",
455 func TestCanSetField(t *testing.T) {
456 type embed struct{ x, X int }
457 type Embed struct{ x, X int }
475 type testCase struct {
476 // -1 means Addr().Elem() of current value
487 {[]int{0, -1}, false},
488 {[]int{0, 0}, false},
489 {[]int{0, 0, -1}, false},
490 {[]int{0, -1, 0}, false},
491 {[]int{0, -1, 0, -1}, false},
493 {[]int{0, 1, -1}, true},
494 {[]int{0, -1, 1}, true},
495 {[]int{0, -1, 1, -1}, true},
497 {[]int{1, -1}, false},
499 {[]int{2, -1}, true},
502 val: ValueOf(&S2{embed: &embed{}}),
505 {[]int{0, -1}, false},
506 {[]int{0, 0}, false},
507 {[]int{0, 0, -1}, false},
508 {[]int{0, -1, 0}, false},
509 {[]int{0, -1, 0, -1}, false},
511 {[]int{0, 1, -1}, true},
512 {[]int{0, -1, 1}, true},
513 {[]int{0, -1, 1, -1}, true},
521 {[]int{0, -1}, true},
522 {[]int{0, 0}, false},
523 {[]int{0, 0, -1}, false},
524 {[]int{0, -1, 0}, false},
525 {[]int{0, -1, 0, -1}, false},
527 {[]int{0, 1, -1}, true},
528 {[]int{0, -1, 1}, true},
529 {[]int{0, -1, 1, -1}, true},
534 val: ValueOf(&S4{Embed: &Embed{}}),
537 {[]int{0, -1}, true},
538 {[]int{0, 0}, false},
539 {[]int{0, 0, -1}, false},
540 {[]int{0, -1, 0}, false},
541 {[]int{0, -1, 0, -1}, false},
543 {[]int{0, 1, -1}, true},
544 {[]int{0, -1, 1}, true},
545 {[]int{0, -1, 1, -1}, true},
551 for _, tt := range tests {
552 t.Run(tt.val.Type().Name(), func(t *testing.T) {
553 for _, tc := range tt.cases {
555 for _, i := range tc.index {
556 if f.Kind() == Pointer {
565 if got := f.CanSet(); got != tc.canSet {
566 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
575 var valueToStringTests = []pair{
580 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
581 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
582 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
583 {&[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})"},
584 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 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(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
588 func TestValueToString(t *testing.T) {
589 for i, test := range valueToStringTests {
590 s := valueToString(ValueOf(test.i))
592 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
597 func TestArrayElemSet(t *testing.T) {
598 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
599 v.Index(4).SetInt(123)
600 s := valueToString(v)
601 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
603 t.Errorf("[10]int: have %#q want %#q", s, want)
606 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
607 v.Index(4).SetInt(123)
609 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
611 t.Errorf("[]int: have %#q want %#q", s, want1)
615 func TestPtrPointTo(t *testing.T) {
619 vi := ValueOf(&i).Elem()
620 vip.Elem().Set(vi.Addr())
622 t.Errorf("got %d, want 1234", *ip)
626 vp := ValueOf(&ip).Elem()
627 vp.Set(Zero(vp.Type()))
629 t.Errorf("got non-nil (%p), want nil", ip)
633 func TestPtrSetNil(t *testing.T) {
637 vip.Elem().Set(Zero(vip.Elem().Type()))
639 t.Errorf("got non-nil (%d), want nil", *ip)
643 func TestMapSetNil(t *testing.T) {
644 m := make(map[string]int)
646 vm.Elem().Set(Zero(vm.Elem().Type()))
648 t.Errorf("got non-nil (%p), want nil", m)
652 func TestAll(t *testing.T) {
653 testType(t, 1, TypeOf((int8)(0)), "int8")
654 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
656 typ := TypeOf((*struct {
660 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
662 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
665 testType(t, 5, f.Type, "chan *int32")
667 f, present := styp.FieldByName("d")
669 t.Errorf("FieldByName says present field is absent")
671 testType(t, 6, f.Type, "float32")
673 f, present = styp.FieldByName("absent")
675 t.Errorf("FieldByName says absent field is present")
678 typ = TypeOf([32]int32{})
679 testType(t, 7, typ, "[32]int32")
680 testType(t, 8, typ.Elem(), "int32")
682 typ = TypeOf((map[string]*int32)(nil))
683 testType(t, 9, typ, "map[string]*int32")
685 testType(t, 10, mtyp.Key(), "string")
686 testType(t, 11, mtyp.Elem(), "*int32")
688 typ = TypeOf((chan<- string)(nil))
689 testType(t, 12, typ, "chan<- string")
690 testType(t, 13, typ.Elem(), "string")
692 // make sure tag strings are not part of element type
693 typ = TypeOf(struct {
694 d []uint32 `reflect:"TAG"`
696 testType(t, 14, typ, "[]uint32")
699 func TestInterfaceGet(t *testing.T) {
704 v1 := ValueOf(&inter)
705 v2 := v1.Elem().Field(0)
706 assert(t, v2.Type().String(), "interface {}")
709 assert(t, v3.Type().String(), "float64")
712 func TestInterfaceValue(t *testing.T) {
717 v1 := ValueOf(&inter)
718 v2 := v1.Elem().Field(0)
719 assert(t, v2.Type().String(), "interface {}")
721 assert(t, v3.Type().String(), "float64")
724 if _, ok := i3.(float64); !ok {
725 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
729 func TestFunctionValue(t *testing.T) {
730 var x any = func() {}
732 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
733 t.Fatalf("TestFunction returned wrong pointer")
735 assert(t, v.Type().String(), "func()")
738 var appendTests = []struct {
741 {make([]int, 2, 4), []int{22}},
742 {make([]int, 2, 4), []int{22, 33, 44}},
745 func sameInts(x, y []int) bool {
746 if len(x) != len(y) {
749 for i, xx := range x {
757 func TestAppend(t *testing.T) {
758 for i, test := range appendTests {
759 origLen, extraLen := len(test.orig), len(test.extra)
760 want := append(test.orig, test.extra...)
761 // Convert extra from []int to []Value.
762 e0 := make([]Value, len(test.extra))
763 for j, e := range test.extra {
766 // Convert extra from []int to *SliceValue.
767 e1 := ValueOf(test.extra)
769 a0 := ValueOf(test.orig)
770 have0 := Append(a0, e0...).Interface().([]int)
771 if !sameInts(have0, want) {
772 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
774 // Check that the orig and extra slices were not modified.
775 if len(test.orig) != origLen {
776 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
778 if len(test.extra) != extraLen {
779 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
782 a1 := ValueOf(test.orig)
783 have1 := AppendSlice(a1, e1).Interface().([]int)
784 if !sameInts(have1, want) {
785 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
787 // Check that the orig and extra slices were not modified.
788 if len(test.orig) != origLen {
789 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
791 if len(test.extra) != extraLen {
792 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
797 func TestCopy(t *testing.T) {
798 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
799 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
800 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
801 for i := 0; i < len(b); i++ {
803 t.Fatalf("b != c before test")
808 aa := ValueOf(&a1).Elem()
809 ab := ValueOf(&b1).Elem()
810 for tocopy := 1; tocopy <= 7; tocopy++ {
814 for i := 0; i < tocopy; i++ {
816 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
817 tocopy, i, a[i], i, b[i])
820 for i := tocopy; i < len(b); i++ {
823 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
824 tocopy, i, a[i], i, b[i], i, c[i])
826 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
827 tocopy, i, b[i], i, c[i])
830 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
836 func TestCopyString(t *testing.T) {
837 t.Run("Slice", func(t *testing.T) {
838 s := bytes.Repeat([]byte{'_'}, 8)
841 n := Copy(val, ValueOf(""))
842 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
843 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
846 n = Copy(val, ValueOf("hello"))
847 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
848 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
851 n = Copy(val, ValueOf("helloworld"))
852 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
853 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
856 t.Run("Array", func(t *testing.T) {
857 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
858 val := ValueOf(&s).Elem()
860 n := Copy(val, ValueOf(""))
861 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
862 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
865 n = Copy(val, ValueOf("hello"))
866 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
867 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
870 n = Copy(val, ValueOf("helloworld"))
871 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
872 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
877 func TestCopyArray(t *testing.T) {
878 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
879 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
881 aa := ValueOf(&a).Elem()
882 ab := ValueOf(&b).Elem()
884 for i := 0; i < len(a); i++ {
886 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
889 for i := len(a); i < len(b); i++ {
891 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
893 t.Logf("elem %d is okay\n", i)
898 func TestBigUnnamedStruct(t *testing.T) {
899 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
901 b1 := v.Interface().(struct {
904 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
905 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
913 func TestBigStruct(t *testing.T) {
914 b := big{1, 2, 3, 4, 5}
916 b1 := v.Interface().(big)
917 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
918 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
929 type DeepEqualTest struct {
934 // Simple functions for DeepEqual tests.
938 fn3 = func() { fn1() } // Not nil.
946 var loop1, loop2 Loop
947 var loopy1, loopy2 Loopy
948 var cycleMap1, cycleMap2, cycleMap3 map[string]any
950 type structWithSelfPtr struct {
962 cycleMap1 = map[string]any{}
963 cycleMap1["cycle"] = cycleMap1
964 cycleMap2 = map[string]any{}
965 cycleMap2["cycle"] = cycleMap2
966 cycleMap3 = map[string]any{}
967 cycleMap3["different"] = cycleMap3
970 var deepEqualTests = []DeepEqualTest{
974 {int32(1), int32(1), true},
976 {float32(0.5), float32(0.5), true},
977 {"hello", "hello", true},
978 {make([]int, 10), make([]int, 10), true},
979 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
980 {Basic{1, 0.5}, Basic{1, 0.5}, true},
981 {error(nil), error(nil), true},
982 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
984 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
985 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
986 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
990 {int32(1), int32(2), false},
992 {float32(0.5), float32(0.6), false},
993 {"hello", "hey", false},
994 {make([]int, 10), make([]int, 11), false},
995 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
996 {Basic{1, 0.5}, Basic{1, 0.6}, false},
997 {Basic{1, 0}, Basic{2, 0}, false},
998 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
999 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
1000 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
1001 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
1006 {[][]int{{1}}, [][]int{{2}}, false},
1007 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
1009 // Fun with floating point.
1010 {math.NaN(), math.NaN(), false},
1011 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
1012 {&[1]float64{math.NaN()}, self{}, true},
1013 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
1014 {[]float64{math.NaN()}, self{}, true},
1015 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
1016 {map[float64]float64{math.NaN(): 1}, self{}, true},
1018 // Nil vs empty: not the same.
1019 {[]int{}, []int(nil), false},
1020 {[]int{}, []int{}, true},
1021 {[]int(nil), []int(nil), true},
1022 {map[int]int{}, map[int]int(nil), false},
1023 {map[int]int{}, map[int]int{}, true},
1024 {map[int]int(nil), map[int]int(nil), true},
1028 {int32(1), int64(1), false},
1029 {0.5, "hello", false},
1030 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
1031 {&[3]any{1, 2, 4}, &[3]any{1, 2, "s"}, false},
1032 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
1033 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
1034 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
1035 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1036 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
1039 {&loop1, &loop1, true},
1040 {&loop1, &loop2, true},
1041 {&loopy1, &loopy1, true},
1042 {&loopy1, &loopy2, true},
1043 {&cycleMap1, &cycleMap2, true},
1044 {&cycleMap1, &cycleMap3, false},
1047 func TestDeepEqual(t *testing.T) {
1048 for _, test := range deepEqualTests {
1049 if test.b == (self{}) {
1052 if r := DeepEqual(test.a, test.b); r != test.eq {
1053 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
1058 func TestTypeOf(t *testing.T) {
1059 // Special case for nil
1060 if typ := TypeOf(nil); typ != nil {
1061 t.Errorf("expected nil type for nil value; got %v", typ)
1063 for _, test := range deepEqualTests {
1064 v := ValueOf(test.a)
1068 typ := TypeOf(test.a)
1069 if typ != v.Type() {
1070 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
1075 type Recursive struct {
1080 func TestDeepEqualRecursiveStruct(t *testing.T) {
1081 a, b := new(Recursive), new(Recursive)
1082 *a = Recursive{12, a}
1083 *b = Recursive{12, b}
1084 if !DeepEqual(a, b) {
1085 t.Error("DeepEqual(recursive same) = false, want true")
1089 type _Complex struct {
1093 d map[float64]float64
1096 func TestDeepEqualComplexStruct(t *testing.T) {
1097 m := make(map[float64]float64)
1098 stra, strb := "hello", "hello"
1099 a, b := new(_Complex), new(_Complex)
1100 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1101 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1102 if !DeepEqual(a, b) {
1103 t.Error("DeepEqual(complex same) = false, want true")
1107 func TestDeepEqualComplexStructInequality(t *testing.T) {
1108 m := make(map[float64]float64)
1109 stra, strb := "hello", "helloo" // Difference is here
1110 a, b := new(_Complex), new(_Complex)
1111 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1112 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1113 if DeepEqual(a, b) {
1114 t.Error("DeepEqual(complex different) = true, want false")
1118 type UnexpT struct {
1122 func TestDeepEqualUnexportedMap(t *testing.T) {
1123 // Check that DeepEqual can look at unexported fields.
1124 x1 := UnexpT{map[int]int{1: 2}}
1125 x2 := UnexpT{map[int]int{1: 2}}
1126 if !DeepEqual(&x1, &x2) {
1127 t.Error("DeepEqual(x1, x2) = false, want true")
1130 y1 := UnexpT{map[int]int{2: 3}}
1131 if DeepEqual(&x1, &y1) {
1132 t.Error("DeepEqual(x1, y1) = true, want false")
1136 var deepEqualPerfTests = []struct {
1139 {x: int8(99), y: int8(99)},
1140 {x: []int8{99}, y: []int8{99}},
1141 {x: int16(99), y: int16(99)},
1142 {x: []int16{99}, y: []int16{99}},
1143 {x: int32(99), y: int32(99)},
1144 {x: []int32{99}, y: []int32{99}},
1145 {x: int64(99), y: int64(99)},
1146 {x: []int64{99}, y: []int64{99}},
1147 {x: int(999999), y: int(999999)},
1148 {x: []int{999999}, y: []int{999999}},
1150 {x: uint8(99), y: uint8(99)},
1151 {x: []uint8{99}, y: []uint8{99}},
1152 {x: uint16(99), y: uint16(99)},
1153 {x: []uint16{99}, y: []uint16{99}},
1154 {x: uint32(99), y: uint32(99)},
1155 {x: []uint32{99}, y: []uint32{99}},
1156 {x: uint64(99), y: uint64(99)},
1157 {x: []uint64{99}, y: []uint64{99}},
1158 {x: uint(999999), y: uint(999999)},
1159 {x: []uint{999999}, y: []uint{999999}},
1160 {x: uintptr(999999), y: uintptr(999999)},
1161 {x: []uintptr{999999}, y: []uintptr{999999}},
1163 {x: float32(1.414), y: float32(1.414)},
1164 {x: []float32{1.414}, y: []float32{1.414}},
1165 {x: float64(1.414), y: float64(1.414)},
1166 {x: []float64{1.414}, y: []float64{1.414}},
1168 {x: complex64(1.414), y: complex64(1.414)},
1169 {x: []complex64{1.414}, y: []complex64{1.414}},
1170 {x: complex128(1.414), y: complex128(1.414)},
1171 {x: []complex128{1.414}, y: []complex128{1.414}},
1174 {x: []bool{true}, y: []bool{true}},
1176 {x: "abcdef", y: "abcdef"},
1177 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1179 {x: []byte("abcdef"), y: []byte("abcdef")},
1180 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1182 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1183 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1186 func TestDeepEqualAllocs(t *testing.T) {
1187 for _, tt := range deepEqualPerfTests {
1188 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1189 got := testing.AllocsPerRun(100, func() {
1190 if !DeepEqual(tt.x, tt.y) {
1191 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1195 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1201 func BenchmarkDeepEqual(b *testing.B) {
1202 for _, bb := range deepEqualPerfTests {
1203 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1205 for i := 0; i < b.N; i++ {
1206 sink = DeepEqual(bb.x, bb.y)
1212 func check2ndField(x any, offs uintptr, t *testing.T) {
1214 f := s.Type().Field(1)
1215 if f.Offset != offs {
1216 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1220 // Check that structure alignment & offsets viewed through reflect agree with those
1221 // from the compiler itself.
1222 func TestAlignment(t *testing.T) {
1223 type T1inner struct {
1230 type T2inner struct {
1238 x := T1{T1inner{2}, 17}
1239 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1241 x1 := T2{T2inner{2, 3}, 17}
1242 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1245 func Nil(a any, t *testing.T) {
1246 n := ValueOf(a).Field(0)
1248 t.Errorf("%v should be nil", a)
1252 func NotNil(a any, t *testing.T) {
1253 n := ValueOf(a).Field(0)
1255 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1259 func TestIsNil(t *testing.T) {
1260 // These implement IsNil.
1261 // Wrap in extra struct to hide interface type.
1265 struct{ x map[string]int }{},
1266 struct{ x func() bool }{},
1267 struct{ x chan int }{},
1268 struct{ x []string }{},
1269 struct{ x unsafe.Pointer }{},
1271 for _, ts := range doNil {
1272 ty := TypeOf(ts).Field(0).Type
1274 v.IsNil() // panics if not okay to call
1277 // Check the implementations
1289 si.x = make([]int, 10)
1296 ci.x = make(chan int)
1303 mi.x = make(map[int]int)
1314 x func(t *testing.T)
1321 func TestIsZero(t *testing.T) {
1322 for i, tt := range []struct {
1351 {float32(1.2), false},
1353 {float64(1.2), false},
1354 {math.Copysign(0, -1), false},
1355 {complex64(0), true},
1356 {complex64(1.2), false},
1357 {complex128(0), true},
1358 {complex128(1.2), false},
1359 {complex(math.Copysign(0, -1), 0), false},
1360 {complex(0, math.Copysign(0, -1)), false},
1361 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1363 {uintptr(128), false},
1365 {Zero(TypeOf([5]string{})).Interface(), true},
1366 {[5]string{"", "", "", "", ""}, true},
1367 {[5]string{}, true},
1368 {[5]string{"", "", "", "a", ""}, false},
1370 {(chan string)(nil), true},
1371 {make(chan string), false},
1372 {time.After(1), false},
1374 {(func())(nil), true},
1377 {New(TypeOf(new(error)).Elem()).Elem(), true},
1378 {(io.Reader)(strings.NewReader("")), false},
1380 {(map[string]string)(nil), true},
1381 {map[string]string{}, false},
1382 {make(map[string]string), false},
1384 {(*func())(nil), true},
1385 {(*int)(nil), true},
1388 {[]string{}, false},
1389 {([]string)(nil), true},
1390 {make([]string, 0), false},
1393 {"not-zero", false},
1396 {T{123, 456.75, "hello", &_i}, false},
1398 {(unsafe.Pointer)(nil), true},
1399 {(unsafe.Pointer)(new(int)), false},
1402 if v, ok := tt.x.(Value); ok {
1410 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1413 if !Zero(TypeOf(tt.x)).IsZero() {
1414 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1420 if r := recover(); r == nil {
1421 t.Error("should panic for invalid value")
1428 func TestInterfaceExtraction(t *testing.T) {
1434 v := Indirect(ValueOf(&s)).Field(0).Interface()
1436 t.Error("Interface() on interface: ", v, s.W)
1440 func TestNilPtrValueSub(t *testing.T) {
1442 if pv := ValueOf(pi); pv.Elem().IsValid() {
1443 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1447 func TestMap(t *testing.T) {
1448 m := map[string]int{"a": 1, "b": 2}
1450 if n := mv.Len(); n != len(m) {
1451 t.Errorf("Len = %d, want %d", n, len(m))
1453 keys := mv.MapKeys()
1454 newmap := MakeMap(mv.Type())
1455 for k, v := range m {
1456 // Check that returned Keys match keys in range.
1457 // These aren't required to be in the same order.
1459 for _, kv := range keys {
1460 if kv.String() == k {
1466 t.Errorf("Missing key %q", k)
1469 // Check that value lookup is correct.
1470 vv := mv.MapIndex(ValueOf(k))
1471 if vi := vv.Int(); vi != int64(v) {
1472 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1475 // Copy into new map.
1476 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1478 vv := mv.MapIndex(ValueOf("not-present"))
1480 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1483 newm := newmap.Interface().(map[string]int)
1484 if len(newm) != len(m) {
1485 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1488 for k, v := range newm {
1491 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1495 newmap.SetMapIndex(ValueOf("a"), Value{})
1498 t.Errorf("newm[\"a\"] = %d after delete", v)
1501 mv = ValueOf(&m).Elem()
1502 mv.Set(Zero(mv.Type()))
1504 t.Errorf("mv.Set(nil) failed")
1508 func TestNilMap(t *testing.T) {
1509 var m map[string]int
1511 keys := mv.MapKeys()
1513 t.Errorf(">0 keys for nil map: %v", keys)
1516 // Check that value for missing key is zero.
1517 x := mv.MapIndex(ValueOf("hello"))
1518 if x.Kind() != Invalid {
1519 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1522 // Check big value too.
1523 var mbig map[string][10 << 20]byte
1524 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1525 if x.Kind() != Invalid {
1526 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1529 // Test that deletes from a nil map succeed.
1530 mv.SetMapIndex(ValueOf("hi"), Value{})
1533 func TestChan(t *testing.T) {
1534 for loop := 0; loop < 2; loop++ {
1538 // check both ways to allocate channels
1541 c = make(chan int, 1)
1544 cv = MakeChan(TypeOf(c), 1)
1545 c = cv.Interface().(chan int)
1550 if i := <-c; i != 2 {
1551 t.Errorf("reflect Send 2, native recv %d", i)
1556 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1557 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1561 val, ok := cv.TryRecv()
1562 if val.IsValid() || ok {
1563 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1568 val, ok = cv.TryRecv()
1570 t.Errorf("TryRecv on ready chan got nil")
1571 } else if i := val.Int(); i != 4 || !ok {
1572 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1577 ok = cv.TrySend(ValueOf(5))
1580 t.Errorf("TrySend on full chan succeeded: value %d", i)
1584 ok = cv.TrySend(ValueOf(6))
1586 t.Errorf("TrySend on empty chan failed")
1589 t.Errorf("TrySend failed but it did send %d", x)
1593 if i = <-c; i != 6 {
1594 t.Errorf("TrySend 6, recv %d", i)
1601 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1602 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1604 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1605 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1609 // check creation of unbuffered channel
1611 cv := MakeChan(TypeOf(c), 0)
1612 c = cv.Interface().(chan int)
1613 if cv.TrySend(ValueOf(7)) {
1614 t.Errorf("TrySend on sync chan succeeded")
1616 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1617 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1621 cv = MakeChan(TypeOf(c), 10)
1622 c = cv.Interface().(chan int)
1623 for i := 0; i < 3; i++ {
1626 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1627 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1631 // caseInfo describes a single case in a select test.
1632 type caseInfo struct {
1641 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1643 func TestSelect(t *testing.T) {
1644 selectWatch.once.Do(func() { go selectWatcher() })
1648 newop := func(n int, cap int) (ch, val Value) {
1651 c := make(chan int, cap)
1655 c := make(chan string, cap)
1657 val = ValueOf(fmt.Sprint(n))
1662 for n := 0; x.Next(); n++ {
1663 if testing.Short() && n >= 1000 {
1666 if n >= 100000 && !*allselect {
1669 if n%100000 == 0 && testing.Verbose() {
1670 println("TestSelect", n)
1672 var cases []SelectCase
1677 ch, val := newop(len(cases), 1)
1678 cases = append(cases, SelectCase{
1683 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1688 ch, val := newop(len(cases), 1)
1690 cases = append(cases, SelectCase{
1694 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1699 ch, val := newop(len(cases), 0)
1700 cases = append(cases, SelectCase{
1707 f := func() { ch.Recv() }
1708 info = append(info, caseInfo{desc: "blocking send", helper: f})
1710 info = append(info, caseInfo{desc: "blocking send"})
1716 ch, val := newop(len(cases), 0)
1717 cases = append(cases, SelectCase{
1723 f := func() { ch.Send(val) }
1724 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1726 info = append(info, caseInfo{desc: "blocking recv"})
1732 // Maybe include value to send.
1737 cases = append(cases, SelectCase{
1741 info = append(info, caseInfo{desc: "zero Chan send"})
1744 // Zero Chan receive.
1746 cases = append(cases, SelectCase{
1749 info = append(info, caseInfo{desc: "zero Chan recv"})
1754 cases = append(cases, SelectCase{
1756 Chan: ValueOf((chan int)(nil)),
1759 info = append(info, caseInfo{desc: "nil Chan send"})
1764 cases = append(cases, SelectCase{
1766 Chan: ValueOf((chan int)(nil)),
1768 info = append(info, caseInfo{desc: "nil Chan recv"})
1771 // closed Chan send.
1773 ch := make(chan int)
1775 cases = append(cases, SelectCase{
1780 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1783 // closed Chan recv.
1785 ch, val := newop(len(cases), 0)
1787 val = Zero(val.Type())
1788 cases = append(cases, SelectCase{
1792 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1795 var helper func() // goroutine to help the select complete
1797 // Add default? Must be last case here, but will permute.
1798 // Add the default if the select would otherwise
1799 // block forever, and maybe add it anyway.
1805 for i, c := range info {
1813 } else if c.helper != nil {
1815 helpers = append(helpers, i)
1818 if !canProceed || x.Maybe() {
1819 cases = append(cases, SelectCase{
1822 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1824 } else if canBlock {
1825 // Select needs to communicate with another goroutine.
1826 cas := &info[helpers[x.Choose(len(helpers))]]
1828 cas.canSelect = true
1832 // Permute cases and case info.
1833 // Doing too much here makes the exhaustive loop
1834 // too exhausting, so just do two swaps.
1835 for loop := 0; loop < 2; loop++ {
1836 i := x.Choose(len(cases))
1837 j := x.Choose(len(cases))
1838 cases[i], cases[j] = cases[j], cases[i]
1839 info[i], info[j] = info[j], info[i]
1843 // We wait before kicking off a goroutine to satisfy a blocked select.
1844 // The pause needs to be big enough to let the select block before
1845 // we run the helper, but if we lose that race once in a while it's okay: the
1846 // select will just proceed immediately. Not a big deal.
1847 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1848 pause := 10 * time.Microsecond
1849 if testing.Short() {
1850 pause = 100 * time.Microsecond
1852 time.AfterFunc(pause, helper)
1856 i, recv, recvOK, panicErr := runSelect(cases, info)
1857 if panicErr != nil && !canPanic {
1858 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1860 if panicErr == nil && canPanic && numCanSelect == 1 {
1861 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1863 if panicErr != nil {
1871 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1873 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1877 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1881 if cases[i].Dir == SelectRecv {
1882 if !recv.IsValid() {
1883 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1885 if !cas.recv.IsValid() {
1886 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1888 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1889 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1890 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1892 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1895 if recv.IsValid() || recvOK {
1896 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1902 func TestSelectMaxCases(t *testing.T) {
1903 var sCases []SelectCase
1904 channel := make(chan int)
1906 for i := 0; i < 65536; i++ {
1907 sCases = append(sCases, SelectCase{
1909 Chan: ValueOf(channel),
1913 _, _, _ = Select(sCases)
1914 sCases = append(sCases, SelectCase{
1916 Chan: ValueOf(channel),
1919 if err := recover(); err != nil {
1920 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1921 t.Fatalf("unexpected error from select call with greater than max supported cases")
1924 t.Fatalf("expected select call to panic with greater than max supported cases")
1928 _, _, _ = Select(sCases)
1931 func TestSelectNop(t *testing.T) {
1932 // "select { default: }" should always return the default case.
1933 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1935 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1939 func BenchmarkSelect(b *testing.B) {
1940 channel := make(chan int)
1942 var cases []SelectCase
1943 for i := 0; i < 8; i++ {
1944 cases = append(cases, SelectCase{
1946 Chan: ValueOf(channel),
1949 for _, numCases := range []int{1, 4, 8} {
1950 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1952 for i := 0; i < b.N; i++ {
1953 _, _, _ = Select(cases[:numCases])
1959 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1960 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1961 // an error describing the select and panics the entire test binary.
1962 var selectWatch struct {
1969 func selectWatcher() {
1971 time.Sleep(1 * time.Second)
1973 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1974 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1975 panic("select stuck")
1977 selectWatch.Unlock()
1981 // runSelect runs a single select test.
1982 // It returns the values returned by Select but also returns
1983 // a panic value if the Select panics.
1984 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr any) {
1986 panicErr = recover()
1989 selectWatch.info = nil
1990 selectWatch.Unlock()
1994 selectWatch.now = time.Now()
1995 selectWatch.info = info
1996 selectWatch.Unlock()
1998 chosen, recv, recvOK = Select(cases)
2002 // fmtSelect formats the information about a single select test.
2003 func fmtSelect(info []caseInfo) string {
2004 var buf bytes.Buffer
2005 fmt.Fprintf(&buf, "\nselect {\n")
2006 for i, cas := range info {
2007 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
2008 if cas.recv.IsValid() {
2009 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
2012 fmt.Fprintf(&buf, " canselect")
2015 fmt.Fprintf(&buf, " panic")
2017 fmt.Fprintf(&buf, "\n")
2019 fmt.Fprintf(&buf, "}")
2025 // Difficult test for function call because of
2026 // implicit padding between arguments.
2027 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) {
2028 return b, c, d, e, f, g, h
2031 func TestFunc(t *testing.T) {
2032 ret := ValueOf(dummy).Call([]Value{
2036 ValueOf(two{40, 50}),
2038 ValueOf(float32(70)),
2042 t.Fatalf("Call returned %d values, want 7", len(ret))
2045 i := byte(ret[0].Uint())
2046 j := int(ret[1].Int())
2047 k := byte(ret[2].Uint())
2048 l := ret[3].Interface().(two)
2049 m := byte(ret[4].Uint())
2050 n := float32(ret[5].Float())
2051 o := byte(ret[6].Uint())
2053 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2054 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)
2057 for i, v := range ret {
2059 t.Errorf("result %d is addressable", i)
2064 func TestCallConvert(t *testing.T) {
2065 v := ValueOf(new(io.ReadWriter)).Elem()
2066 f := ValueOf(func(r io.Reader) io.Reader { return r })
2067 out := f.Call([]Value{v})
2068 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
2069 t.Errorf("expected [nil], got %v", out)
2073 type emptyStruct struct{}
2075 type nonEmptyStruct struct {
2079 func returnEmpty() emptyStruct {
2080 return emptyStruct{}
2083 func takesEmpty(e emptyStruct) {
2086 func returnNonEmpty(i int) nonEmptyStruct {
2087 return nonEmptyStruct{member: i}
2090 func takesNonEmpty(n nonEmptyStruct) int {
2094 func TestCallWithStruct(t *testing.T) {
2095 r := ValueOf(returnEmpty).Call(nil)
2096 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2097 t.Errorf("returning empty struct returned %#v instead", r)
2099 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2101 t.Errorf("takesEmpty returned values: %#v", r)
2103 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2104 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2105 t.Errorf("returnNonEmpty returned %#v", r)
2107 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2108 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2109 t.Errorf("takesNonEmpty returned %#v", r)
2113 func TestCallReturnsEmpty(t *testing.T) {
2114 // Issue 21717: past-the-end pointer write in Call with
2115 // nonzero-sized frame and zero-sized return value.
2117 var finalized uint32
2118 f := func() (emptyStruct, *[2]int64) {
2119 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2120 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2121 return emptyStruct{}, i
2123 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2124 timeout := time.After(5 * time.Second)
2125 for atomic.LoadUint32(&finalized) == 0 {
2128 t.Fatal("finalizer did not run")
2134 runtime.KeepAlive(v)
2137 func BenchmarkCall(b *testing.B) {
2138 fv := ValueOf(func(a, b string) {})
2140 b.RunParallel(func(pb *testing.PB) {
2141 args := []Value{ValueOf("a"), ValueOf("b")}
2150 func (i *myint) inc() {
2154 func BenchmarkCallMethod(b *testing.B) {
2159 for i := 0; i < b.N; i++ {
2164 func BenchmarkCallArgCopy(b *testing.B) {
2165 byteArray := func(n int) Value {
2166 return Zero(ArrayOf(n, TypeOf(byte(0))))
2168 sizes := [...]struct {
2172 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2173 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2174 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2175 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2176 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2178 for _, size := range sizes {
2179 bench := func(b *testing.B) {
2180 args := []Value{size.arg}
2181 b.SetBytes(int64(size.arg.Len()))
2183 b.RunParallel(func(pb *testing.PB) {
2189 name := fmt.Sprintf("size=%v", size.arg.Len())
2194 func TestMakeFunc(t *testing.T) {
2196 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2197 ValueOf(&f).Elem().Set(fv)
2199 // Call g with small arguments so that there is
2200 // something predictable (and different from the
2201 // correct results) in those positions on the stack.
2203 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2205 // Call constructed function f.
2206 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2207 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2208 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)
2212 func TestMakeFuncInterface(t *testing.T) {
2213 fn := func(i int) int { return i }
2214 incr := func(in []Value) []Value {
2215 return []Value{ValueOf(int(in[0].Int() + 1))}
2217 fv := MakeFunc(TypeOf(fn), incr)
2218 ValueOf(&fn).Elem().Set(fv)
2219 if r := fn(2); r != 3 {
2220 t.Errorf("Call returned %d, want 3", r)
2222 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2223 t.Errorf("Call returned %d, want 15", r)
2225 if r := fv.Interface().(func(int) int)(26); r != 27 {
2226 t.Errorf("Call returned %d, want 27", r)
2230 func TestMakeFuncVariadic(t *testing.T) {
2231 // Test that variadic arguments are packed into a slice and passed as last arg
2232 fn := func(_ int, is ...int) []int { return nil }
2233 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2234 ValueOf(&fn).Elem().Set(fv)
2237 if r[0] != 2 || r[1] != 3 {
2238 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2241 r = fn(1, []int{2, 3}...)
2242 if r[0] != 2 || r[1] != 3 {
2243 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2246 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2247 if r[0] != 2 || r[1] != 3 {
2248 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2251 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2252 if r[0] != 2 || r[1] != 3 {
2253 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2256 f := fv.Interface().(func(int, ...int) []int)
2259 if r[0] != 2 || r[1] != 3 {
2260 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2262 r = f(1, []int{2, 3}...)
2263 if r[0] != 2 || r[1] != 3 {
2264 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2268 // Dummy type that implements io.WriteCloser
2272 func (w *WC) Write(p []byte) (n int, err error) {
2275 func (w *WC) Close() error {
2279 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2280 // reflect.Values returned from the wrapped function should be assignment-converted
2281 // to the types returned by the result of MakeFunc.
2283 // Concrete types should be promotable to interfaces they implement.
2285 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2286 return []Value{ValueOf(io.EOF)}
2287 }).Interface().(func() error)
2290 // Super-interfaces should be promotable to simpler interfaces.
2291 var g func() io.Writer
2292 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2293 var w io.WriteCloser = &WC{}
2294 return []Value{ValueOf(&w).Elem()}
2295 }).Interface().(func() io.Writer)
2298 // Channels should be promotable to directional channels.
2299 var h func() <-chan int
2300 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2301 return []Value{ValueOf(make(chan int))}
2302 }).Interface().(func() <-chan int)
2305 // Unnamed types should be promotable to named types.
2306 type T struct{ a, b, c int }
2308 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2309 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2310 }).Interface().(func() T)
2314 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2315 // Type doesn't implement the required interface.
2316 shouldPanic("", func() {
2318 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2319 return []Value{ValueOf(int(7))}
2320 }).Interface().(func() error)
2323 // Assigning to an interface with additional methods.
2324 shouldPanic("", func() {
2325 var f func() io.ReadWriteCloser
2326 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2327 var w io.WriteCloser = &WC{}
2328 return []Value{ValueOf(&w).Elem()}
2329 }).Interface().(func() io.ReadWriteCloser)
2332 // Directional channels can't be assigned to bidirectional ones.
2333 shouldPanic("", func() {
2334 var f func() chan int
2335 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2336 var c <-chan int = make(chan int)
2337 return []Value{ValueOf(c)}
2338 }).Interface().(func() chan int)
2341 // Two named types which are otherwise identical.
2342 shouldPanic("", func() {
2343 type T struct{ a, b, c int }
2344 type U struct{ a, b, c int }
2346 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2347 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2348 }).Interface().(func() T)
2357 // This will be index 0.
2358 func (p Point) AnotherMethod(scale int) int {
2362 // This will be index 1.
2363 func (p Point) Dist(scale int) int {
2364 //println("Point.Dist", p.x, p.y, scale)
2365 return p.x*p.x*scale + p.y*p.y*scale
2368 // This will be index 2.
2369 func (p Point) GCMethod(k int) int {
2374 // This will be index 3.
2375 func (p Point) NoArgs() {
2376 // Exercise no-argument/no-result paths.
2379 // This will be index 4.
2380 func (p Point) TotalDist(points ...Point) int {
2382 for _, q := range points {
2385 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2391 // This will be index 5.
2392 func (p *Point) Int64Method(x int64) int64 {
2396 // This will be index 6.
2397 func (p *Point) Int32Method(x int32) int32 {
2401 func TestMethod(t *testing.T) {
2402 // Non-curried method of type.
2404 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2406 t.Errorf("Type Method returned %d; want 250", i)
2409 m, ok := TypeOf(p).MethodByName("Dist")
2411 t.Fatalf("method by name failed")
2413 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2415 t.Errorf("Type MethodByName returned %d; want 275", i)
2418 m, ok = TypeOf(p).MethodByName("NoArgs")
2420 t.Fatalf("method by name failed")
2422 n := len(m.Func.Call([]Value{ValueOf(p)}))
2424 t.Errorf("NoArgs returned %d values; want 0", n)
2427 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2429 t.Errorf("Pointer Type Method returned %d; want 300", i)
2432 m, ok = TypeOf(&p).MethodByName("Dist")
2434 t.Fatalf("ptr method by name failed")
2436 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2438 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2441 m, ok = TypeOf(&p).MethodByName("NoArgs")
2443 t.Fatalf("method by name failed")
2445 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2447 t.Errorf("NoArgs returned %d values; want 0", n)
2450 // Curried method of value.
2451 tfunc := TypeOf((func(int) int)(nil))
2452 v := ValueOf(p).Method(1)
2453 if tt := v.Type(); tt != tfunc {
2454 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2456 i = v.Call([]Value{ValueOf(14)})[0].Int()
2458 t.Errorf("Value Method returned %d; want 350", i)
2460 v = ValueOf(p).MethodByName("Dist")
2461 if tt := v.Type(); tt != tfunc {
2462 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2464 i = v.Call([]Value{ValueOf(15)})[0].Int()
2466 t.Errorf("Value MethodByName returned %d; want 375", i)
2468 v = ValueOf(p).MethodByName("NoArgs")
2471 // Curried method of pointer.
2472 v = ValueOf(&p).Method(1)
2473 if tt := v.Type(); tt != tfunc {
2474 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2476 i = v.Call([]Value{ValueOf(16)})[0].Int()
2478 t.Errorf("Pointer Value Method returned %d; want 400", i)
2480 v = ValueOf(&p).MethodByName("Dist")
2481 if tt := v.Type(); tt != tfunc {
2482 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2484 i = v.Call([]Value{ValueOf(17)})[0].Int()
2486 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2488 v = ValueOf(&p).MethodByName("NoArgs")
2491 // Curried method of interface value.
2492 // Have to wrap interface value in a struct to get at it.
2493 // Passing it to ValueOf directly would
2494 // access the underlying Point, not the interface.
2498 pv := ValueOf(&x).Elem()
2500 if tt := v.Type(); tt != tfunc {
2501 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2503 i = v.Call([]Value{ValueOf(18)})[0].Int()
2505 t.Errorf("Interface Method returned %d; want 450", i)
2507 v = pv.MethodByName("Dist")
2508 if tt := v.Type(); tt != tfunc {
2509 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2511 i = v.Call([]Value{ValueOf(19)})[0].Int()
2513 t.Errorf("Interface MethodByName returned %d; want 475", i)
2517 func TestMethodValue(t *testing.T) {
2521 // Check that method value have the same underlying code pointers.
2522 if p1, p2 := ValueOf(Point{1, 1}).Method(1), ValueOf(Point{2, 2}).Method(1); p1.Pointer() != p2.Pointer() {
2523 t.Errorf("methodValueCall mismatched: %v - %v", p1, p2)
2526 // Curried method of value.
2527 tfunc := TypeOf((func(int) int)(nil))
2528 v := ValueOf(p).Method(1)
2529 if tt := v.Type(); tt != tfunc {
2530 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2532 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2534 t.Errorf("Value Method returned %d; want 250", i)
2536 v = ValueOf(p).MethodByName("Dist")
2537 if tt := v.Type(); tt != tfunc {
2538 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2540 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2542 t.Errorf("Value MethodByName returned %d; want 275", i)
2544 v = ValueOf(p).MethodByName("NoArgs")
2545 ValueOf(v.Interface()).Call(nil)
2546 v.Interface().(func())()
2548 // Curried method of pointer.
2549 v = ValueOf(&p).Method(1)
2550 if tt := v.Type(); tt != tfunc {
2551 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2553 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2555 t.Errorf("Pointer Value Method returned %d; want 300", i)
2557 v = ValueOf(&p).MethodByName("Dist")
2558 if tt := v.Type(); tt != tfunc {
2559 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2561 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2563 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2565 v = ValueOf(&p).MethodByName("NoArgs")
2566 ValueOf(v.Interface()).Call(nil)
2567 v.Interface().(func())()
2569 // Curried method of pointer to pointer.
2571 v = ValueOf(&pp).Elem().Method(1)
2572 if tt := v.Type(); tt != tfunc {
2573 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2575 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2577 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2579 v = ValueOf(&pp).Elem().MethodByName("Dist")
2580 if tt := v.Type(); tt != tfunc {
2581 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2583 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2585 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2588 // Curried method of interface value.
2589 // Have to wrap interface value in a struct to get at it.
2590 // Passing it to ValueOf directly would
2591 // access the underlying Point, not the interface.
2597 pv := ValueOf(s).Field(0)
2599 if tt := v.Type(); tt != tfunc {
2600 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2602 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2604 t.Errorf("Interface Method returned %d; want 400", i)
2606 v = pv.MethodByName("Dist")
2607 if tt := v.Type(); tt != tfunc {
2608 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2610 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2612 t.Errorf("Interface MethodByName returned %d; want 425", i)
2615 // For issue #33628: method args are not stored at the right offset
2617 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2618 if x := m64(123); x != 123 {
2619 t.Errorf("Int64Method returned %d; want 123", x)
2621 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2622 if x := m32(456); x != 456 {
2623 t.Errorf("Int32Method returned %d; want 456", x)
2627 func TestVariadicMethodValue(t *testing.T) {
2629 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2630 want := int64(p.TotalDist(points[0], points[1], points[2]))
2632 // Variadic method of type.
2633 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2634 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2635 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2638 // Curried method of value.
2639 tfunc = TypeOf((func(...Point) int)(nil))
2640 v := ValueOf(p).Method(4)
2641 if tt := v.Type(); tt != tfunc {
2642 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2644 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2646 t.Errorf("Variadic Method returned %d; want %d", i, want)
2648 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2650 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2653 f := v.Interface().(func(...Point) int)
2654 i = int64(f(points[0], points[1], points[2]))
2656 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2658 i = int64(f(points...))
2660 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2664 type DirectIfaceT struct {
2668 func (d DirectIfaceT) M() int { return *d.p }
2670 func TestDirectIfaceMethod(t *testing.T) {
2672 v := DirectIfaceT{&x}
2674 m, ok := typ.MethodByName("M")
2676 t.Fatalf("cannot find method M")
2678 in := []Value{ValueOf(v)}
2679 out := m.Func.Call(in)
2680 if got := out[0].Int(); got != 42 {
2681 t.Errorf("Call with value receiver got %d, want 42", got)
2686 m, ok = typ.MethodByName("M")
2688 t.Fatalf("cannot find method M")
2690 in = []Value{ValueOf(pv)}
2691 out = m.Func.Call(in)
2692 if got := out[0].Int(); got != 42 {
2693 t.Errorf("Call with pointer receiver got %d, want 42", got)
2697 // Reflect version of $GOROOT/test/method5.go
2699 // Concrete types implementing M method.
2700 // Smaller than a word, word-sized, larger than a word.
2701 // Value and pointer receivers.
2703 type Tinter interface {
2704 M(int, byte) (byte, int)
2709 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2713 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2717 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2721 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2723 type Tbigv [2]uintptr
2725 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2727 type Tbigp [2]uintptr
2729 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2731 type tinter interface {
2732 m(int, byte) (byte, int)
2735 // Embedding via pointer.
2752 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2754 func TestMethod5(t *testing.T) {
2755 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2757 if b != 99 || x != 1000+inc {
2758 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2762 CheckV := func(name string, i Value, inc int) {
2763 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2764 b := bx[0].Interface()
2765 x := bx[1].Interface()
2766 if b != byte(99) || x != 1000+inc {
2767 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2770 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2773 var TinterType = TypeOf(new(Tinter)).Elem()
2775 CheckI := func(name string, i any, inc int) {
2777 CheckV(name, v, inc)
2778 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2783 CheckI("&sv", &sv, 1)
2786 CheckI("&sp", &sp, 2)
2790 CheckI("&wv", &wv, 3)
2793 CheckI("&wp", &wp, 4)
2795 bv := Tbigv([2]uintptr{5, 6})
2796 CheckI("bv", bv, 11)
2797 CheckI("&bv", &bv, 11)
2799 bp := Tbigp([2]uintptr{7, 8})
2800 CheckI("&bp", &bp, 15)
2806 CheckI("t4", t4, 40)
2807 CheckI("&t4", &t4, 40)
2808 CheckI("t3", t3, 40)
2809 CheckI("&t3", &t3, 40)
2810 CheckI("t2", t2, 40)
2811 CheckI("&t2", &t2, 40)
2812 CheckI("t1", t1, 40)
2813 CheckI("&t1", &t1, 40)
2816 vnil := ValueOf(&tnil).Elem()
2817 shouldPanic("Method", func() { vnil.Method(0) })
2820 func TestInterfaceSet(t *testing.T) {
2829 sv := ValueOf(&s).Elem()
2830 sv.Field(0).Set(ValueOf(p))
2831 if q := s.I.(*Point); q != p {
2832 t.Errorf("i: have %p want %p", q, p)
2837 if q := s.P.(*Point); q != p {
2838 t.Errorf("i: have %p want %p", q, p)
2841 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2843 t.Errorf("Interface Method returned %d; want 250", i)
2852 func TestAnonymousFields(t *testing.T) {
2853 var field StructField
2857 if field, ok = type1.FieldByName("int"); !ok {
2858 t.Fatal("no field 'int'")
2860 if field.Index[0] != 1 {
2861 t.Error("field index should be 1; is", field.Index)
2915 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2937 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2956 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2970 var fieldTests = []FTest{
2971 {struct{}{}, "", nil, 0},
2972 {struct{}{}, "Foo", nil, 0},
2973 {S0{A: 'a'}, "A", []int{0}, 'a'},
2974 {S0{}, "D", nil, 0},
2975 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2976 {S1{B: 'b'}, "B", []int{0}, 'b'},
2977 {S1{}, "S0", []int{1}, 0},
2978 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2979 {S2{A: 'a'}, "A", []int{0}, 'a'},
2980 {S2{}, "S1", []int{1}, 0},
2981 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2982 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2983 {S2{}, "D", nil, 0},
2984 {S3{}, "S1", nil, 0},
2985 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2986 {S3{}, "B", nil, 0},
2987 {S3{D: 'd'}, "D", []int{2}, 0},
2988 {S3{E: 'e'}, "E", []int{3}, 'e'},
2989 {S4{A: 'a'}, "A", []int{1}, 'a'},
2990 {S4{}, "B", nil, 0},
2991 {S5{}, "X", nil, 0},
2992 {S5{}, "Y", []int{2, 0, 1}, 0},
2993 {S10{}, "X", nil, 0},
2994 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2995 {S14{}, "X", nil, 0},
2998 func TestFieldByIndex(t *testing.T) {
2999 for _, test := range fieldTests {
3001 f := s.FieldByIndex(test.index)
3003 if test.index != nil {
3004 if f.Name != test.name {
3005 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
3008 t.Errorf("%s.%s found", s.Name(), f.Name)
3010 } else if len(test.index) > 0 {
3011 t.Errorf("%s.%s not found", s.Name(), test.name)
3014 if test.value != 0 {
3015 v := ValueOf(test.s).FieldByIndex(test.index)
3017 if x, ok := v.Interface().(int); ok {
3018 if x != test.value {
3019 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
3022 t.Errorf("%s%v value not an int", s.Name(), test.index)
3025 t.Errorf("%s%v value not found", s.Name(), test.index)
3031 func TestFieldByName(t *testing.T) {
3032 for _, test := range fieldTests {
3034 f, found := s.FieldByName(test.name)
3036 if test.index != nil {
3037 // Verify field depth and index.
3038 if len(f.Index) != len(test.index) {
3039 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)
3041 for i, x := range f.Index {
3042 if x != test.index[i] {
3043 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
3048 t.Errorf("%s.%s found", s.Name(), f.Name)
3050 } else if len(test.index) > 0 {
3051 t.Errorf("%s.%s not found", s.Name(), test.name)
3054 if test.value != 0 {
3055 v := ValueOf(test.s).FieldByName(test.name)
3057 if x, ok := v.Interface().(int); ok {
3058 if x != test.value {
3059 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
3062 t.Errorf("%s.%s value not an int", s.Name(), test.name)
3065 t.Errorf("%s.%s value not found", s.Name(), test.name)
3071 func TestImportPath(t *testing.T) {
3076 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
3077 {TypeOf(int(0)), ""},
3078 {TypeOf(int8(0)), ""},
3079 {TypeOf(int16(0)), ""},
3080 {TypeOf(int32(0)), ""},
3081 {TypeOf(int64(0)), ""},
3082 {TypeOf(uint(0)), ""},
3083 {TypeOf(uint8(0)), ""},
3084 {TypeOf(uint16(0)), ""},
3085 {TypeOf(uint32(0)), ""},
3086 {TypeOf(uint64(0)), ""},
3087 {TypeOf(uintptr(0)), ""},
3088 {TypeOf(float32(0)), ""},
3089 {TypeOf(float64(0)), ""},
3090 {TypeOf(complex64(0)), ""},
3091 {TypeOf(complex128(0)), ""},
3092 {TypeOf(byte(0)), ""},
3093 {TypeOf(rune(0)), ""},
3094 {TypeOf([]byte(nil)), ""},
3095 {TypeOf([]rune(nil)), ""},
3096 {TypeOf(string("")), ""},
3097 {TypeOf((*any)(nil)).Elem(), ""},
3098 {TypeOf((*byte)(nil)), ""},
3099 {TypeOf((*rune)(nil)), ""},
3100 {TypeOf((*int64)(nil)), ""},
3101 {TypeOf(map[string]int{}), ""},
3102 {TypeOf((*error)(nil)).Elem(), ""},
3103 {TypeOf((*Point)(nil)), ""},
3104 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3106 for _, test := range tests {
3107 if path := test.t.PkgPath(); path != test.path {
3108 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3113 func TestFieldPkgPath(t *testing.T) {
3115 typ := TypeOf(struct {
3123 type pkgpathTest struct {
3130 checkPkgPath := func(name string, s []pkgpathTest) {
3131 for _, test := range s {
3132 f := typ.FieldByIndex(test.index)
3133 if got, want := f.PkgPath, test.pkgPath; got != want {
3134 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3136 if got, want := f.Anonymous, test.embedded; got != want {
3137 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3139 if got, want := f.IsExported(), test.exported; got != want {
3140 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3145 checkPkgPath("testStruct", []pkgpathTest{
3146 {[]int{0}, "", false, true}, // Exported
3147 {[]int{1}, "reflect_test", false, false}, // unexported
3148 {[]int{2}, "", true, true}, // OtherPkgFields
3149 {[]int{2, 0}, "", false, true}, // OtherExported
3150 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3151 {[]int{3}, "reflect_test", true, false}, // int
3152 {[]int{4}, "reflect_test", true, false}, // *x
3155 type localOtherPkgFields OtherPkgFields
3156 typ = TypeOf(localOtherPkgFields{})
3157 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3158 {[]int{0}, "", false, true}, // OtherExported
3159 {[]int{1}, "reflect", false, false}, // otherUnexported
3163 func TestMethodPkgPath(t *testing.T) {
3168 typ := TypeOf((*interface {
3181 {"x", "reflect_test", false},
3182 {"y", "reflect_test", false},
3185 for _, test := range tests {
3186 m, _ := typ.MethodByName(test.name)
3187 if got, want := m.PkgPath, test.pkgPath; got != want {
3188 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3190 if got, want := m.IsExported(), test.exported; got != want {
3191 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3196 func TestVariadicType(t *testing.T) {
3197 // Test example from Type documentation.
3198 var f func(x int, y ...float64)
3200 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3202 if sl.Kind() == Slice {
3203 if sl.Elem() == TypeOf(0.0) {
3211 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3212 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3213 for i := 0; i < typ.NumIn(); i++ {
3214 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3228 func (*inner) M() {}
3229 func (*outer) M() {}
3231 func TestNestedMethods(t *testing.T) {
3232 typ := TypeOf((*outer)(nil))
3233 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*outer).M).UnsafePointer() {
3234 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3235 for i := 0; i < typ.NumMethod(); i++ {
3237 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3244 func (*unexp) f() (int32, int8) { return 7, 7 }
3245 func (*unexp) g() (int64, int8) { return 8, 8 }
3247 type unexpI interface {
3251 var unexpi unexpI = new(unexp)
3253 func TestUnexportedMethods(t *testing.T) {
3254 typ := TypeOf(unexpi)
3256 if got := typ.NumMethod(); got != 0 {
3257 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3261 type InnerInt struct {
3265 type OuterInt struct {
3270 func (i *InnerInt) M() int {
3274 func TestEmbeddedMethods(t *testing.T) {
3275 typ := TypeOf((*OuterInt)(nil))
3276 if typ.NumMethod() != 1 || typ.Method(0).Func.UnsafePointer() != ValueOf((*OuterInt).M).UnsafePointer() {
3277 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3278 for i := 0; i < typ.NumMethod(); i++ {
3280 t.Errorf("\t%d: %s %p\n", i, m.Name, m.Func.UnsafePointer())
3285 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3286 t.Errorf("i.M() = %d, want 3", v)
3289 o := &OuterInt{1, InnerInt{2}}
3290 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3291 t.Errorf("i.M() = %d, want 2", v)
3295 if v := f(o); v != 2 {
3296 t.Errorf("f(o) = %d, want 2", v)
3300 type FuncDDD func(...any) error
3302 func (f FuncDDD) M() {}
3304 func TestNumMethodOnDDD(t *testing.T) {
3305 rv := ValueOf((FuncDDD)(nil))
3306 if n := rv.NumMethod(); n != 1 {
3307 t.Fatalf("NumMethod()=%d, want 1", n)
3311 func TestPtrTo(t *testing.T) {
3312 // This block of code means that the ptrToThis field of the
3313 // reflect data for *unsafe.Pointer is non zero, see
3314 // https://golang.org/issue/19003
3315 var x unsafe.Pointer
3322 for i = 0; i < 100; i++ {
3323 typ = PointerTo(typ)
3325 for i = 0; i < 100; i++ {
3328 if typ != TypeOf(z) {
3329 t.Errorf("after 100 PointerTo and Elem, have %s, want %s", typ, TypeOf(z))
3333 func TestPtrToGC(t *testing.T) {
3335 tt := TypeOf(T(nil))
3339 for i := 0; i < n; i++ {
3344 v.Elem().Set(ValueOf(p).Convert(pt))
3345 x = append(x, v.Interface())
3349 for i, xi := range x {
3350 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3351 if k != uintptr(i) {
3352 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3357 func BenchmarkPtrTo(b *testing.B) {
3358 // Construct a type with a zero ptrToThis.
3359 type T struct{ int }
3360 t := SliceOf(TypeOf(T{}))
3361 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3362 if !ptrToThis.IsValid() {
3363 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3365 if ptrToThis.Int() != 0 {
3366 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3370 // Now benchmark calling PointerTo on it: we'll have to hit the ptrMap cache on
3372 b.RunParallel(func(pb *testing.PB) {
3379 func TestAddr(t *testing.T) {
3391 t.Errorf("Addr.Elem.Set failed to set value")
3394 // Again but take address of the ValueOf value.
3395 // Exercises generation of PtrTypes not present in the binary.
3397 v = ValueOf(&q).Elem()
3406 t.Errorf("Addr.Elem.Set failed to set value")
3409 // Starting without pointer we should get changed value
3412 v = ValueOf(&qq).Elem()
3418 if p.X != 3 { // should be unchanged from last time
3419 t.Errorf("somehow value Set changed original p")
3421 p = v0.Interface().(struct {
3425 t.Errorf("Addr.Elem.Set valued to set value in top value")
3428 // Verify that taking the address of a type gives us a pointer
3429 // which we can convert back using the usual interface
3434 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3435 *(ps.(**bool)) = new(bool)
3437 t.Errorf("Addr.Interface direct assignment failed")
3441 func noAlloc(t *testing.T, n int, f func(int)) {
3442 if testing.Short() {
3443 t.Skip("skipping malloc count in short mode")
3445 if runtime.GOMAXPROCS(0) > 1 {
3446 t.Skip("skipping; GOMAXPROCS>1")
3449 allocs := testing.AllocsPerRun(n, func() {
3454 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3458 func TestAllocations(t *testing.T) {
3459 noAlloc(t, 100, func(j int) {
3463 // We can uncomment this when compiler escape analysis
3464 // is good enough to see that the integer assigned to i
3465 // does not escape and therefore need not be allocated.
3469 // if int(v.Int()) != 42+j {
3470 // panic("wrong int")
3473 i = func(j int) int { return j }
3475 if v.Interface().(func(int) int)(j) != j {
3476 panic("wrong result")
3481 func TestSmallNegativeInt(t *testing.T) {
3485 t.Errorf("int16(-1).Int() returned %v", v.Int())
3489 func TestIndex(t *testing.T) {
3490 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3491 v := ValueOf(xs).Index(3).Interface().(byte)
3493 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3495 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3496 v = ValueOf(xa).Index(2).Interface().(byte)
3498 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3501 v = ValueOf(s).Index(3).Interface().(byte)
3503 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3507 func TestSlice(t *testing.T) {
3508 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3509 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3511 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3514 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3516 if !DeepEqual(v[0:5], xs[3:]) {
3517 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3519 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3520 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3522 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3525 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3527 if !DeepEqual(v[0:6], xa[2:]) {
3528 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3531 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3533 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3536 rv := ValueOf(&xs).Elem()
3538 ptr2 := rv.UnsafePointer()
3540 ptr3 := rv.UnsafePointer()
3542 t.Errorf("xs.Slice(3,4).Slice3(5,5).UnsafePointer() = %p, want %p", ptr3, ptr2)
3546 func TestSlice3(t *testing.T) {
3547 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3548 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3550 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3553 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3555 if !DeepEqual(v[0:4], xs[3:7:7]) {
3556 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3558 rv := ValueOf(&xs).Elem()
3559 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3560 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3561 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3563 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3564 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3566 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3569 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3571 if !DeepEqual(v[0:4], xa[2:6:6]) {
3572 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3574 rv = ValueOf(&xa).Elem()
3575 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3576 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3577 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3580 rv = ValueOf(&s).Elem()
3581 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3583 rv = ValueOf(&xs).Elem()
3584 rv = rv.Slice3(3, 5, 7)
3585 ptr2 := rv.UnsafePointer()
3586 rv = rv.Slice3(4, 4, 4)
3587 ptr3 := rv.UnsafePointer()
3589 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).UnsafePointer() = %p, want %p", ptr3, ptr2)
3593 func TestSetLenCap(t *testing.T) {
3594 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3595 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3597 vs := ValueOf(&xs).Elem()
3598 shouldPanic("SetLen", func() { vs.SetLen(10) })
3599 shouldPanic("SetCap", func() { vs.SetCap(10) })
3600 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3601 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3602 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3604 if len(xs) != 5 || cap(xs) != 8 {
3605 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3608 if len(xs) != 5 || cap(xs) != 6 {
3609 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3612 if len(xs) != 5 || cap(xs) != 5 {
3613 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3615 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3616 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3618 va := ValueOf(&xa).Elem()
3619 shouldPanic("SetLen", func() { va.SetLen(8) })
3620 shouldPanic("SetCap", func() { va.SetCap(8) })
3623 func TestVariadic(t *testing.T) {
3628 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3629 if b.String() != "hello, 42 world" {
3630 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3634 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]any{"hello", 42})})
3635 if b.String() != "hello, 42 world" {
3636 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3640 func TestFuncArg(t *testing.T) {
3641 f1 := func(i int, f func(int) int) int { return f(i) }
3642 f2 := func(i int) int { return i + 1 }
3643 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3644 if r[0].Int() != 101 {
3645 t.Errorf("function returned %d, want 101", r[0].Int())
3649 func TestStructArg(t *testing.T) {
3650 type padded struct {
3657 wantA = padded{"3", 4}
3660 f := func(a padded, b uint32) {
3663 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3664 if gotA != wantA || gotB != wantB {
3665 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3669 var tagGetTests = []struct {
3674 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3675 {`protobuf:"PB(1,2)"`, `foo`, ``},
3676 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3677 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3678 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3679 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3680 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3683 func TestTagGet(t *testing.T) {
3684 for _, tt := range tagGetTests {
3685 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3686 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3691 func TestBytes(t *testing.T) {
3692 shouldPanic("on int Value", func() { ValueOf(0).Bytes() })
3693 shouldPanic("of non-byte slice", func() { ValueOf([]string{}).Bytes() })
3697 y := ValueOf(x).Bytes()
3698 if !bytes.Equal(x, y) {
3699 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3702 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3707 shouldPanic("unaddressable", func() { ValueOf(a).Bytes() })
3708 shouldPanic("on ptr Value", func() { ValueOf(&a).Bytes() })
3709 b := ValueOf(&a).Elem().Bytes()
3710 if !bytes.Equal(a[:], y) {
3711 t.Fatalf("ValueOf(%v).Bytes() = %v", a, b)
3714 t.Errorf("ValueOf(%p).Bytes() = %p", &a[0], &b[0])
3717 // Per issue #24746, it was decided that Bytes can be called on byte slices
3718 // that normally cannot be converted from per Go language semantics.
3722 ValueOf([]B{1, 2, 3, 4}).Bytes() // should not panic
3723 ValueOf(new([4]B)).Elem().Bytes() // should not panic
3724 ValueOf(SB{1, 2, 3, 4}).Bytes() // should not panic
3725 ValueOf(new(AB)).Elem().Bytes() // should not panic
3728 func TestSetBytes(t *testing.T) {
3731 y := []byte{1, 2, 3, 4}
3732 ValueOf(&x).Elem().SetBytes(y)
3733 if !bytes.Equal(x, y) {
3734 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3737 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3741 type Private struct {
3747 func (p *Private) m() {
3750 type private struct {
3758 func (p *private) P() {
3761 type Public struct {
3767 func (p *Public) M() {
3770 func TestUnexported(t *testing.T) {
3775 isValid(v.Elem().Field(0))
3776 isValid(v.Elem().Field(1))
3777 isValid(v.Elem().Field(2))
3778 isValid(v.Elem().FieldByName("X"))
3779 isValid(v.Elem().FieldByName("Y"))
3780 isValid(v.Elem().FieldByName("Z"))
3781 isValid(v.Type().Method(0).Func)
3782 m, _ := v.Type().MethodByName("M")
3784 m, _ = v.Type().MethodByName("P")
3786 isNonNil(v.Elem().Field(0).Interface())
3787 isNonNil(v.Elem().Field(1).Interface())
3788 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3789 isNonNil(v.Elem().FieldByName("X").Interface())
3790 isNonNil(v.Elem().FieldByName("Y").Interface())
3791 isNonNil(v.Elem().FieldByName("Z").Interface())
3792 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3793 isNonNil(v.Type().Method(0).Func.Interface())
3794 m, _ = v.Type().MethodByName("P")
3795 isNonNil(m.Func.Interface())
3799 isValid(v.Elem().Field(0))
3800 isValid(v.Elem().Field(1))
3801 isValid(v.Elem().FieldByName("x"))
3802 isValid(v.Elem().FieldByName("y"))
3803 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3804 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3805 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3806 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3807 shouldPanic("Method", func() { v.Type().Method(0) })
3810 func TestSetPanic(t *testing.T) {
3811 ok := func(f func()) { f() }
3812 bad := func(f func()) { shouldPanic("Set", f) }
3813 clear := func(v Value) { v.Set(Zero(v.Type())) }
3841 bad(func() { clear(v.Field(0)) }) // .X
3842 bad(func() { clear(v.Field(1)) }) // .t1
3843 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3844 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3845 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3846 bad(func() { clear(v.Field(2)) }) // .T2
3847 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3848 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3849 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3850 bad(func() { clear(v.Field(3)) }) // .NamedT1
3851 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3852 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3853 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3854 bad(func() { clear(v.Field(4)) }) // .NamedT2
3855 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3856 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3857 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3858 bad(func() { clear(v.Field(5)) }) // .namedT1
3859 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3860 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3861 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3862 bad(func() { clear(v.Field(6)) }) // .namedT2
3863 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3864 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3865 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3868 v = ValueOf(&T{}).Elem()
3869 ok(func() { clear(v.Field(0)) }) // .X
3870 bad(func() { clear(v.Field(1)) }) // .t1
3871 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3872 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3873 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3874 ok(func() { clear(v.Field(2)) }) // .T2
3875 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3876 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3877 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3878 ok(func() { clear(v.Field(3)) }) // .NamedT1
3879 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3880 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3881 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3882 ok(func() { clear(v.Field(4)) }) // .NamedT2
3883 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3884 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3885 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3886 bad(func() { clear(v.Field(5)) }) // .namedT1
3887 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3888 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3889 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3890 bad(func() { clear(v.Field(6)) }) // .namedT2
3891 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3892 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3893 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3898 func (t timp) W() {}
3899 func (t timp) Y() {}
3900 func (t timp) w() {}
3901 func (t timp) y() {}
3903 func TestCallPanic(t *testing.T) {
3928 ok := func(f func()) { f() }
3929 badCall := func(f func()) { shouldPanic("Call", f) }
3930 badMethod := func(f func()) { shouldPanic("Method", f) }
3931 call := func(v Value) { v.Call(nil) }
3934 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3935 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3936 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3937 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3938 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3939 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3940 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3941 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3942 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3944 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3945 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3946 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3947 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3949 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3950 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3951 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3952 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3954 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3955 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3956 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3957 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3959 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3960 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3961 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3962 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3964 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3965 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3966 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3967 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3969 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3970 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3971 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3972 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3975 func shouldPanic(expect string, f func()) {
3979 panic("did not panic")
3983 switch r := r.(type) {
3989 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3991 if !strings.HasPrefix(s, "reflect") {
3992 panic(`panic string does not start with "reflect": ` + s)
3994 if !strings.Contains(s, expect) {
3995 panic(`panic string does not contain "` + expect + `": ` + s)
4002 func isNonNil(x any) {
4004 panic("nil interface")
4008 func isValid(v Value) {
4014 func TestAlias(t *testing.T) {
4015 x := string("hello")
4016 v := ValueOf(&x).Elem()
4017 oldvalue := v.Interface()
4018 v.SetString("world")
4019 newvalue := v.Interface()
4021 if oldvalue != "hello" || newvalue != "world" {
4022 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
4028 func EmptyInterfaceV(x any) Value {
4029 return ValueOf(&x).Elem()
4032 func ReaderV(x io.Reader) Value {
4033 return ValueOf(&x).Elem()
4036 func ReadWriterV(x io.ReadWriter) Value {
4037 return ValueOf(&x).Elem()
4041 type MyStruct struct {
4044 type MyStruct1 struct {
4049 type MyStruct2 struct {
4054 type MyString string
4056 type MyBytesArrayPtr0 *[0]byte
4057 type MyBytesArrayPtr *[4]byte
4058 type MyBytesArray0 [0]byte
4059 type MyBytesArray [4]byte
4060 type MyRunes []int32
4064 type IntChan chan int
4065 type IntChanRecv <-chan int
4066 type IntChanSend chan<- int
4067 type BytesChan chan []byte
4068 type BytesChanRecv <-chan []byte
4069 type BytesChanSend chan<- []byte
4071 var convertTests = []struct {
4077 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
4083 var numbers = []string{
4084 "int8", "uint8", "int16", "uint16",
4085 "int32", "uint32", "int64", "uint64",
4086 "int", "uint", "uintptr",
4087 "float32", "float64",
4091 // all pairs but in an unusual order,
4092 // to emit all the int8, uint8 cases
4093 // before n grows too big.
4095 for i, f := range numbers {
4096 for _, g := range numbers[i:] {
4097 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
4100 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4107 {V(int8(1)), V(int8(1))},
4108 {V(int8(2)), V(uint8(2))},
4109 {V(uint8(3)), V(int8(3))},
4110 {V(int8(4)), V(int16(4))},
4111 {V(int16(5)), V(int8(5))},
4112 {V(int8(6)), V(uint16(6))},
4113 {V(uint16(7)), V(int8(7))},
4114 {V(int8(8)), V(int32(8))},
4115 {V(int32(9)), V(int8(9))},
4116 {V(int8(10)), V(uint32(10))},
4117 {V(uint32(11)), V(int8(11))},
4118 {V(int8(12)), V(int64(12))},
4119 {V(int64(13)), V(int8(13))},
4120 {V(int8(14)), V(uint64(14))},
4121 {V(uint64(15)), V(int8(15))},
4122 {V(int8(16)), V(int(16))},
4123 {V(int(17)), V(int8(17))},
4124 {V(int8(18)), V(uint(18))},
4125 {V(uint(19)), V(int8(19))},
4126 {V(int8(20)), V(uintptr(20))},
4127 {V(uintptr(21)), V(int8(21))},
4128 {V(int8(22)), V(float32(22))},
4129 {V(float32(23)), V(int8(23))},
4130 {V(int8(24)), V(float64(24))},
4131 {V(float64(25)), V(int8(25))},
4132 {V(uint8(26)), V(uint8(26))},
4133 {V(uint8(27)), V(int16(27))},
4134 {V(int16(28)), V(uint8(28))},
4135 {V(uint8(29)), V(uint16(29))},
4136 {V(uint16(30)), V(uint8(30))},
4137 {V(uint8(31)), V(int32(31))},
4138 {V(int32(32)), V(uint8(32))},
4139 {V(uint8(33)), V(uint32(33))},
4140 {V(uint32(34)), V(uint8(34))},
4141 {V(uint8(35)), V(int64(35))},
4142 {V(int64(36)), V(uint8(36))},
4143 {V(uint8(37)), V(uint64(37))},
4144 {V(uint64(38)), V(uint8(38))},
4145 {V(uint8(39)), V(int(39))},
4146 {V(int(40)), V(uint8(40))},
4147 {V(uint8(41)), V(uint(41))},
4148 {V(uint(42)), V(uint8(42))},
4149 {V(uint8(43)), V(uintptr(43))},
4150 {V(uintptr(44)), V(uint8(44))},
4151 {V(uint8(45)), V(float32(45))},
4152 {V(float32(46)), V(uint8(46))},
4153 {V(uint8(47)), V(float64(47))},
4154 {V(float64(48)), V(uint8(48))},
4155 {V(int16(49)), V(int16(49))},
4156 {V(int16(50)), V(uint16(50))},
4157 {V(uint16(51)), V(int16(51))},
4158 {V(int16(52)), V(int32(52))},
4159 {V(int32(53)), V(int16(53))},
4160 {V(int16(54)), V(uint32(54))},
4161 {V(uint32(55)), V(int16(55))},
4162 {V(int16(56)), V(int64(56))},
4163 {V(int64(57)), V(int16(57))},
4164 {V(int16(58)), V(uint64(58))},
4165 {V(uint64(59)), V(int16(59))},
4166 {V(int16(60)), V(int(60))},
4167 {V(int(61)), V(int16(61))},
4168 {V(int16(62)), V(uint(62))},
4169 {V(uint(63)), V(int16(63))},
4170 {V(int16(64)), V(uintptr(64))},
4171 {V(uintptr(65)), V(int16(65))},
4172 {V(int16(66)), V(float32(66))},
4173 {V(float32(67)), V(int16(67))},
4174 {V(int16(68)), V(float64(68))},
4175 {V(float64(69)), V(int16(69))},
4176 {V(uint16(70)), V(uint16(70))},
4177 {V(uint16(71)), V(int32(71))},
4178 {V(int32(72)), V(uint16(72))},
4179 {V(uint16(73)), V(uint32(73))},
4180 {V(uint32(74)), V(uint16(74))},
4181 {V(uint16(75)), V(int64(75))},
4182 {V(int64(76)), V(uint16(76))},
4183 {V(uint16(77)), V(uint64(77))},
4184 {V(uint64(78)), V(uint16(78))},
4185 {V(uint16(79)), V(int(79))},
4186 {V(int(80)), V(uint16(80))},
4187 {V(uint16(81)), V(uint(81))},
4188 {V(uint(82)), V(uint16(82))},
4189 {V(uint16(83)), V(uintptr(83))},
4190 {V(uintptr(84)), V(uint16(84))},
4191 {V(uint16(85)), V(float32(85))},
4192 {V(float32(86)), V(uint16(86))},
4193 {V(uint16(87)), V(float64(87))},
4194 {V(float64(88)), V(uint16(88))},
4195 {V(int32(89)), V(int32(89))},
4196 {V(int32(90)), V(uint32(90))},
4197 {V(uint32(91)), V(int32(91))},
4198 {V(int32(92)), V(int64(92))},
4199 {V(int64(93)), V(int32(93))},
4200 {V(int32(94)), V(uint64(94))},
4201 {V(uint64(95)), V(int32(95))},
4202 {V(int32(96)), V(int(96))},
4203 {V(int(97)), V(int32(97))},
4204 {V(int32(98)), V(uint(98))},
4205 {V(uint(99)), V(int32(99))},
4206 {V(int32(100)), V(uintptr(100))},
4207 {V(uintptr(101)), V(int32(101))},
4208 {V(int32(102)), V(float32(102))},
4209 {V(float32(103)), V(int32(103))},
4210 {V(int32(104)), V(float64(104))},
4211 {V(float64(105)), V(int32(105))},
4212 {V(uint32(106)), V(uint32(106))},
4213 {V(uint32(107)), V(int64(107))},
4214 {V(int64(108)), V(uint32(108))},
4215 {V(uint32(109)), V(uint64(109))},
4216 {V(uint64(110)), V(uint32(110))},
4217 {V(uint32(111)), V(int(111))},
4218 {V(int(112)), V(uint32(112))},
4219 {V(uint32(113)), V(uint(113))},
4220 {V(uint(114)), V(uint32(114))},
4221 {V(uint32(115)), V(uintptr(115))},
4222 {V(uintptr(116)), V(uint32(116))},
4223 {V(uint32(117)), V(float32(117))},
4224 {V(float32(118)), V(uint32(118))},
4225 {V(uint32(119)), V(float64(119))},
4226 {V(float64(120)), V(uint32(120))},
4227 {V(int64(121)), V(int64(121))},
4228 {V(int64(122)), V(uint64(122))},
4229 {V(uint64(123)), V(int64(123))},
4230 {V(int64(124)), V(int(124))},
4231 {V(int(125)), V(int64(125))},
4232 {V(int64(126)), V(uint(126))},
4233 {V(uint(127)), V(int64(127))},
4234 {V(int64(128)), V(uintptr(128))},
4235 {V(uintptr(129)), V(int64(129))},
4236 {V(int64(130)), V(float32(130))},
4237 {V(float32(131)), V(int64(131))},
4238 {V(int64(132)), V(float64(132))},
4239 {V(float64(133)), V(int64(133))},
4240 {V(uint64(134)), V(uint64(134))},
4241 {V(uint64(135)), V(int(135))},
4242 {V(int(136)), V(uint64(136))},
4243 {V(uint64(137)), V(uint(137))},
4244 {V(uint(138)), V(uint64(138))},
4245 {V(uint64(139)), V(uintptr(139))},
4246 {V(uintptr(140)), V(uint64(140))},
4247 {V(uint64(141)), V(float32(141))},
4248 {V(float32(142)), V(uint64(142))},
4249 {V(uint64(143)), V(float64(143))},
4250 {V(float64(144)), V(uint64(144))},
4251 {V(int(145)), V(int(145))},
4252 {V(int(146)), V(uint(146))},
4253 {V(uint(147)), V(int(147))},
4254 {V(int(148)), V(uintptr(148))},
4255 {V(uintptr(149)), V(int(149))},
4256 {V(int(150)), V(float32(150))},
4257 {V(float32(151)), V(int(151))},
4258 {V(int(152)), V(float64(152))},
4259 {V(float64(153)), V(int(153))},
4260 {V(uint(154)), V(uint(154))},
4261 {V(uint(155)), V(uintptr(155))},
4262 {V(uintptr(156)), V(uint(156))},
4263 {V(uint(157)), V(float32(157))},
4264 {V(float32(158)), V(uint(158))},
4265 {V(uint(159)), V(float64(159))},
4266 {V(float64(160)), V(uint(160))},
4267 {V(uintptr(161)), V(uintptr(161))},
4268 {V(uintptr(162)), V(float32(162))},
4269 {V(float32(163)), V(uintptr(163))},
4270 {V(uintptr(164)), V(float64(164))},
4271 {V(float64(165)), V(uintptr(165))},
4272 {V(float32(166)), V(float32(166))},
4273 {V(float32(167)), V(float64(167))},
4274 {V(float64(168)), V(float32(168))},
4275 {V(float64(169)), V(float64(169))},
4278 {V(float64(1.5)), V(int(1))},
4281 {V(complex64(1i)), V(complex64(1i))},
4282 {V(complex64(2i)), V(complex128(2i))},
4283 {V(complex128(3i)), V(complex64(3i))},
4284 {V(complex128(4i)), V(complex128(4i))},
4287 {V(string("hello")), V(string("hello"))},
4288 {V(string("bytes1")), V([]byte("bytes1"))},
4289 {V([]byte("bytes2")), V(string("bytes2"))},
4290 {V([]byte("bytes3")), V([]byte("bytes3"))},
4291 {V(string("runes♝")), V([]rune("runes♝"))},
4292 {V([]rune("runes♕")), V(string("runes♕"))},
4293 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4294 {V(int('a')), V(string("a"))},
4295 {V(int8('a')), V(string("a"))},
4296 {V(int16('a')), V(string("a"))},
4297 {V(int32('a')), V(string("a"))},
4298 {V(int64('a')), V(string("a"))},
4299 {V(uint('a')), V(string("a"))},
4300 {V(uint8('a')), V(string("a"))},
4301 {V(uint16('a')), V(string("a"))},
4302 {V(uint32('a')), V(string("a"))},
4303 {V(uint64('a')), V(string("a"))},
4304 {V(uintptr('a')), V(string("a"))},
4305 {V(int(-1)), V(string("\uFFFD"))},
4306 {V(int8(-2)), V(string("\uFFFD"))},
4307 {V(int16(-3)), V(string("\uFFFD"))},
4308 {V(int32(-4)), V(string("\uFFFD"))},
4309 {V(int64(-5)), V(string("\uFFFD"))},
4310 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4311 {V(int64(1 << 32)), V(string("\uFFFD"))},
4312 {V(uint(0x110001)), V(string("\uFFFD"))},
4313 {V(uint32(0x110002)), V(string("\uFFFD"))},
4314 {V(uint64(0x110003)), V(string("\uFFFD"))},
4315 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4316 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4319 {V(MyString("hello")), V(string("hello"))},
4320 {V(string("hello")), V(MyString("hello"))},
4321 {V(string("hello")), V(string("hello"))},
4322 {V(MyString("hello")), V(MyString("hello"))},
4323 {V(MyString("bytes1")), V([]byte("bytes1"))},
4324 {V([]byte("bytes2")), V(MyString("bytes2"))},
4325 {V([]byte("bytes3")), V([]byte("bytes3"))},
4326 {V(MyString("runes♝")), V([]rune("runes♝"))},
4327 {V([]rune("runes♕")), V(MyString("runes♕"))},
4328 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4329 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4330 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4331 {V(int('a')), V(MyString("a"))},
4332 {V(int8('a')), V(MyString("a"))},
4333 {V(int16('a')), V(MyString("a"))},
4334 {V(int32('a')), V(MyString("a"))},
4335 {V(int64('a')), V(MyString("a"))},
4336 {V(uint('a')), V(MyString("a"))},
4337 {V(uint8('a')), V(MyString("a"))},
4338 {V(uint16('a')), V(MyString("a"))},
4339 {V(uint32('a')), V(MyString("a"))},
4340 {V(uint64('a')), V(MyString("a"))},
4341 {V(uintptr('a')), V(MyString("a"))},
4342 {V(int(-1)), V(MyString("\uFFFD"))},
4343 {V(int8(-2)), V(MyString("\uFFFD"))},
4344 {V(int16(-3)), V(MyString("\uFFFD"))},
4345 {V(int32(-4)), V(MyString("\uFFFD"))},
4346 {V(int64(-5)), V(MyString("\uFFFD"))},
4347 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4348 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4349 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4350 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4353 {V(string("bytes1")), V(MyBytes("bytes1"))},
4354 {V(MyBytes("bytes2")), V(string("bytes2"))},
4355 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4356 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4357 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4360 {V(string("runes♝")), V(MyRunes("runes♝"))},
4361 {V(MyRunes("runes♕")), V(string("runes♕"))},
4362 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4363 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4364 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4366 // slice to array pointer
4367 {V([]byte(nil)), V((*[0]byte)(nil))},
4368 {V([]byte{}), V(new([0]byte))},
4369 {V([]byte{7}), V(&[1]byte{7})},
4370 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4371 {V(MyBytes([]byte{})), V(new([0]byte))},
4372 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4373 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4374 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4375 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4376 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4377 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4379 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4380 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4381 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4382 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4383 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4384 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4385 {V(new([0]byte)), V(new(MyBytesArray0))},
4386 {V(new(MyBytesArray0)), V(new([0]byte))},
4387 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4388 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4390 // named types and equal underlying types
4391 {V(new(int)), V(new(integer))},
4392 {V(new(integer)), V(new(int))},
4393 {V(Empty{}), V(struct{}{})},
4394 {V(new(Empty)), V(new(struct{}))},
4395 {V(struct{}{}), V(Empty{})},
4396 {V(new(struct{})), V(new(Empty))},
4397 {V(Empty{}), V(Empty{})},
4398 {V(MyBytes{}), V([]byte{})},
4399 {V([]byte{}), V(MyBytes{})},
4400 {V((func())(nil)), V(MyFunc(nil))},
4401 {V((MyFunc)(nil)), V((func())(nil))},
4403 // structs with different tags
4416 {V(MyStruct{}), V(struct {
4422 }{}), V(MyStruct{})},
4424 {V(MyStruct{}), V(struct {
4430 }{}), V(MyStruct{})},
4432 {V(MyStruct1{}), V(MyStruct2{})},
4433 {V(MyStruct2{}), V(MyStruct1{})},
4435 // can convert *byte and *MyByte
4436 {V((*byte)(nil)), V((*MyByte)(nil))},
4437 {V((*MyByte)(nil)), V((*byte)(nil))},
4439 // cannot convert mismatched array sizes
4440 {V([2]byte{}), V([2]byte{})},
4441 {V([3]byte{}), V([3]byte{})},
4443 // cannot convert other instances
4444 {V((**byte)(nil)), V((**byte)(nil))},
4445 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4446 {V((chan byte)(nil)), V((chan byte)(nil))},
4447 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4448 {V(([]byte)(nil)), V(([]byte)(nil))},
4449 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4450 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4451 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4452 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4453 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4454 {V([2]byte{}), V([2]byte{})},
4455 {V([2]MyByte{}), V([2]MyByte{})},
4458 {V((***int)(nil)), V((***int)(nil))},
4459 {V((***byte)(nil)), V((***byte)(nil))},
4460 {V((***int32)(nil)), V((***int32)(nil))},
4461 {V((***int64)(nil)), V((***int64)(nil))},
4462 {V((chan byte)(nil)), V((chan byte)(nil))},
4463 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4464 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4465 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4466 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4467 {V([]uint(nil)), V([]uint(nil))},
4468 {V([]int(nil)), V([]int(nil))},
4469 {V(new(any)), V(new(any))},
4470 {V(new(io.Reader)), V(new(io.Reader))},
4471 {V(new(io.Writer)), V(new(io.Writer))},
4474 {V(IntChan(nil)), V((chan<- int)(nil))},
4475 {V(IntChan(nil)), V((<-chan int)(nil))},
4476 {V((chan int)(nil)), V(IntChanRecv(nil))},
4477 {V((chan int)(nil)), V(IntChanSend(nil))},
4478 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4479 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4480 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4481 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4482 {V(IntChan(nil)), V((chan int)(nil))},
4483 {V((chan int)(nil)), V(IntChan(nil))},
4484 {V((chan int)(nil)), V((<-chan int)(nil))},
4485 {V((chan int)(nil)), V((chan<- int)(nil))},
4486 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4487 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4488 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4489 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4490 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4491 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4492 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4493 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4494 {V(BytesChan(nil)), V((chan []byte)(nil))},
4495 {V((chan []byte)(nil)), V(BytesChan(nil))},
4496 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4497 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4499 // cannot convert other instances (channels)
4500 {V(IntChan(nil)), V(IntChan(nil))},
4501 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4502 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4503 {V(BytesChan(nil)), V(BytesChan(nil))},
4504 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4505 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4508 {V(int(1)), EmptyInterfaceV(int(1))},
4509 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4510 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4511 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4512 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4515 func TestConvert(t *testing.T) {
4516 canConvert := map[[2]Type]bool{}
4517 all := map[Type]bool{}
4519 for _, tt := range convertTests {
4521 if !t1.ConvertibleTo(t1) {
4522 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4527 if !t1.ConvertibleTo(t2) {
4528 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4534 canConvert[[2]Type{t1, t2}] = true
4536 // vout1 represents the in value converted to the in type.
4538 if !v1.CanConvert(t1) {
4539 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4541 vout1 := v1.Convert(t1)
4542 out1 := vout1.Interface()
4543 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4544 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4547 // vout2 represents the in value converted to the out type.
4548 if !v1.CanConvert(t2) {
4549 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4551 vout2 := v1.Convert(t2)
4552 out2 := vout2.Interface()
4553 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4554 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4556 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4557 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4560 // vout3 represents a new value of the out type, set to vout2. This makes
4561 // sure the converted value vout2 is really usable as a regular value.
4562 vout3 := New(t2).Elem()
4564 out3 := vout3.Interface()
4565 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4566 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4570 t.Errorf("table entry %v is RO, should not be", v1)
4573 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4576 t.Errorf("conversion output %v is RO, should not be", vout2)
4579 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4581 if !IsRO(MakeRO(v1).Convert(t1)) {
4582 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4584 if !IsRO(MakeRO(v1).Convert(t2)) {
4585 t.Errorf("RO conversion output %v is not RO, should be", v1)
4589 // Assume that of all the types we saw during the tests,
4590 // if there wasn't an explicit entry for a conversion between
4591 // a pair of types, then it's not to be allowed. This checks for
4592 // things like 'int64' converting to '*int'.
4593 for t1 := range all {
4594 for t2 := range all {
4595 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4596 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4597 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4603 func TestConvertPanic(t *testing.T) {
4604 s := make([]byte, 4)
4608 if !v.Type().ConvertibleTo(pt) {
4609 t.Errorf("[]byte should be convertible to *[8]byte")
4611 if v.CanConvert(pt) {
4612 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4614 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4619 var gFloat32 float32
4621 const snan uint32 = 0x7f800001
4623 func TestConvertNaNs(t *testing.T) {
4624 // Test to see if a store followed by a load of a signaling NaN
4625 // maintains the signaling bit. (This used to fail on the 387 port.)
4626 gFloat32 = math.Float32frombits(snan)
4627 runtime.Gosched() // make sure we don't optimize the store/load away
4628 if got := math.Float32bits(gFloat32); got != snan {
4629 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4631 // Test reflect's conversion between float32s. See issue 36400.
4632 type myFloat32 float32
4633 x := V(myFloat32(math.Float32frombits(snan)))
4634 y := x.Convert(TypeOf(float32(0)))
4635 z := y.Interface().(float32)
4636 if got := math.Float32bits(z); got != snan {
4637 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4641 type ComparableStruct struct {
4645 type NonComparableStruct struct {
4650 var comparableTests = []struct {
4655 {TypeOf("hello"), true},
4656 {TypeOf(new(byte)), true},
4657 {TypeOf((func())(nil)), false},
4658 {TypeOf([]byte{}), false},
4659 {TypeOf(map[string]int{}), false},
4660 {TypeOf(make(chan int)), true},
4661 {TypeOf(1.5), true},
4662 {TypeOf(false), true},
4664 {TypeOf(ComparableStruct{}), true},
4665 {TypeOf(NonComparableStruct{}), false},
4666 {TypeOf([10]map[string]int{}), false},
4667 {TypeOf([10]string{}), true},
4668 {TypeOf(new(any)).Elem(), true},
4671 func TestComparable(t *testing.T) {
4672 for _, tt := range comparableTests {
4673 if ok := tt.typ.Comparable(); ok != tt.ok {
4674 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4679 func TestOverflow(t *testing.T) {
4680 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4681 t.Errorf("%v wrongly overflows float64", 1e300)
4684 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4685 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4686 t.Errorf("%v wrongly overflows float32", maxFloat32)
4688 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4689 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4690 t.Errorf("%v should overflow float32", ovfFloat32)
4692 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4693 t.Errorf("%v should overflow float32", -ovfFloat32)
4696 maxInt32 := int64(0x7fffffff)
4697 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4698 t.Errorf("%v wrongly overflows int32", maxInt32)
4700 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4701 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4703 ovfInt32 := int64(1 << 31)
4704 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4705 t.Errorf("%v should overflow int32", ovfInt32)
4708 maxUint32 := uint64(0xffffffff)
4709 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4710 t.Errorf("%v wrongly overflows uint32", maxUint32)
4712 ovfUint32 := uint64(1 << 32)
4713 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4714 t.Errorf("%v should overflow uint32", ovfUint32)
4718 func checkSameType(t *testing.T, x Type, y any) {
4719 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4720 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4724 func TestArrayOf(t *testing.T) {
4725 // check construction and use of type not in binary
4728 value func(i int) any
4734 value: func(i int) any { type Tint int; return Tint(i) },
4740 value: func(i int) any { type Tint int; return Tint(i) },
4742 want: "[0 1 2 3 4 5 6 7 8 9]",
4746 value: func(i int) any { type Tfloat float64; return Tfloat(i) },
4748 want: "[0 1 2 3 4 5 6 7 8 9]",
4752 value: func(i int) any { type Tstring string; return Tstring(strconv.Itoa(i)) },
4754 want: "[0 1 2 3 4 5 6 7 8 9]",
4758 value: func(i int) any { type Tstruct struct{ V int }; return Tstruct{i} },
4760 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4764 value: func(i int) any { type Tint int; return []Tint{Tint(i)} },
4766 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4770 value: func(i int) any { type Tint int; return [1]Tint{Tint(i)} },
4772 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4776 value: func(i int) any { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4778 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4782 value: func(i int) any { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4784 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4788 value: func(i int) any { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4790 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4794 value: func(i int) any {
4795 type TstructUV struct {
4799 return TstructUV{i, float64(i)}
4802 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4806 for _, table := range tests {
4807 at := ArrayOf(table.n, TypeOf(table.value(0)))
4809 vok := New(at).Elem()
4810 vnot := New(at).Elem()
4811 for i := 0; i < v.Len(); i++ {
4812 v.Index(i).Set(ValueOf(table.value(i)))
4813 vok.Index(i).Set(ValueOf(table.value(i)))
4818 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4820 s := fmt.Sprint(v.Interface())
4821 if s != table.want {
4822 t.Errorf("constructed array = %s, want %s", s, table.want)
4825 if table.comparable != at.Comparable() {
4826 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4828 if table.comparable {
4830 if DeepEqual(vnot.Interface(), v.Interface()) {
4832 "arrays (%#v) compare ok (but should not)",
4837 if !DeepEqual(vok.Interface(), v.Interface()) {
4839 "arrays (%#v) compare NOT-ok (but should)",
4846 // check that type already in binary is found
4848 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4851 func TestArrayOfGC(t *testing.T) {
4853 tt := TypeOf(T(nil))
4856 for i := 0; i < n; i++ {
4857 v := New(ArrayOf(n, tt)).Elem()
4858 for j := 0; j < v.Len(); j++ {
4860 *p = uintptr(i*n + j)
4861 v.Index(j).Set(ValueOf(p).Convert(tt))
4863 x = append(x, v.Interface())
4867 for i, xi := range x {
4869 for j := 0; j < v.Len(); j++ {
4870 k := v.Index(j).Elem().Interface()
4871 if k != uintptr(i*n+j) {
4872 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4878 func TestArrayOfAlg(t *testing.T) {
4879 at := ArrayOf(6, TypeOf(byte(0)))
4880 v1 := New(at).Elem()
4881 v2 := New(at).Elem()
4882 if v1.Interface() != v1.Interface() {
4883 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4885 v1.Index(5).Set(ValueOf(byte(1)))
4886 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4887 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4890 at = ArrayOf(6, TypeOf([]int(nil)))
4892 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4895 func TestArrayOfGenericAlg(t *testing.T) {
4896 at1 := ArrayOf(5, TypeOf(string("")))
4897 at := ArrayOf(6, at1)
4898 v1 := New(at).Elem()
4899 v2 := New(at).Elem()
4900 if v1.Interface() != v1.Interface() {
4901 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4904 v1.Index(0).Index(0).Set(ValueOf("abc"))
4905 v2.Index(0).Index(0).Set(ValueOf("efg"))
4906 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4907 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4910 v1.Index(0).Index(0).Set(ValueOf("abc"))
4911 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4912 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4913 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4917 m := MakeMap(MapOf(at, TypeOf(int(0))))
4918 m.SetMapIndex(v1, ValueOf(1))
4919 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4920 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4924 func TestArrayOfDirectIface(t *testing.T) {
4927 i1 := Zero(TypeOf(T{})).Interface()
4928 v1 := ValueOf(&i1).Elem()
4929 p1 := v1.InterfaceData()[1]
4931 i2 := Zero(ArrayOf(1, PointerTo(TypeOf(int8(0))))).Interface()
4932 v2 := ValueOf(&i2).Elem()
4933 p2 := v2.InterfaceData()[1]
4936 t.Errorf("got p1=%v. want=%v", p1, nil)
4940 t.Errorf("got p2=%v. want=%v", p2, nil)
4945 i1 := Zero(TypeOf(T{})).Interface()
4946 v1 := ValueOf(&i1).Elem()
4947 p1 := v1.InterfaceData()[1]
4949 i2 := Zero(ArrayOf(0, PointerTo(TypeOf(int8(0))))).Interface()
4950 v2 := ValueOf(&i2).Elem()
4951 p2 := v2.InterfaceData()[1]
4954 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4958 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4963 // Ensure passing in negative lengths panics.
4964 // See https://golang.org/issue/43603
4965 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4966 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4967 ArrayOf(-1, TypeOf(byte(0)))
4971 func TestSliceOf(t *testing.T) {
4972 // check construction and use of type not in binary
4974 st := SliceOf(TypeOf(T(1)))
4975 if got, want := st.String(), "[]reflect_test.T"; got != want {
4976 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4978 v := MakeSlice(st, 10, 10)
4980 for i := 0; i < v.Len(); i++ {
4981 v.Index(i).Set(ValueOf(T(i)))
4984 s := fmt.Sprint(v.Interface())
4985 want := "[0 1 2 3 4 5 6 7 8 9]"
4987 t.Errorf("constructed slice = %s, want %s", s, want)
4990 // check that type already in binary is found
4992 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4995 func TestSliceOverflow(t *testing.T) {
4996 // check that MakeSlice panics when size of slice overflows uint
4999 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
5001 t.Fatal("slice size does not overflow")
5004 st := SliceOf(TypeOf(x))
5008 t.Fatal("slice overflow does not panic")
5011 MakeSlice(st, int(l), int(l))
5014 func TestSliceOfGC(t *testing.T) {
5016 tt := TypeOf(T(nil))
5020 for i := 0; i < n; i++ {
5021 v := MakeSlice(st, n, n)
5022 for j := 0; j < v.Len(); j++ {
5024 *p = uintptr(i*n + j)
5025 v.Index(j).Set(ValueOf(p).Convert(tt))
5027 x = append(x, v.Interface())
5031 for i, xi := range x {
5033 for j := 0; j < v.Len(); j++ {
5034 k := v.Index(j).Elem().Interface()
5035 if k != uintptr(i*n+j) {
5036 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5042 func TestStructOfFieldName(t *testing.T) {
5043 // invalid field name "1nvalid"
5044 shouldPanic("has invalid name", func() {
5045 StructOf([]StructField{
5046 {Name: "Valid", Type: TypeOf("")},
5047 {Name: "1nvalid", Type: TypeOf("")},
5051 // invalid field name "+"
5052 shouldPanic("has invalid name", func() {
5053 StructOf([]StructField{
5054 {Name: "Val1d", Type: TypeOf("")},
5055 {Name: "+", Type: TypeOf("")},
5060 shouldPanic("has no name", func() {
5061 StructOf([]StructField{
5062 {Name: "", Type: TypeOf("")},
5066 // verify creation of a struct with valid struct fields
5067 validFields := []StructField{
5082 validStruct := StructOf(validFields)
5084 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
5085 if got, want := validStruct.String(), structStr; got != want {
5086 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
5090 func TestStructOf(t *testing.T) {
5091 // check construction and use of type not in binary
5092 fields := []StructField{
5101 Type: TypeOf(byte(0)),
5105 Type: TypeOf(uint64(0)),
5109 Type: TypeOf([3]uint16{}),
5113 st := StructOf(fields)
5116 v.FieldByName("X").Set(ValueOf(byte(2)))
5117 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5120 s := fmt.Sprint(v.Interface())
5121 want := `{ 1 0 [0 0 0]}`
5123 t.Errorf("constructed struct = %s, want %s", s, want)
5125 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5126 if got, want := st.String(), stStr; got != want {
5127 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5130 // check the size, alignment and field offsets
5131 stt := TypeOf(struct {
5137 if st.Size() != stt.Size() {
5138 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5140 if st.Align() != stt.Align() {
5141 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5143 if st.FieldAlign() != stt.FieldAlign() {
5144 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5146 for i := 0; i < st.NumField(); i++ {
5147 o1 := st.Field(i).Offset
5148 o2 := stt.Field(i).Offset
5150 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5154 // Check size and alignment with a trailing zero-sized field.
5155 st = StructOf([]StructField{
5158 Type: TypeOf(byte(0)),
5162 Type: TypeOf([0]*byte{}),
5165 stt = TypeOf(struct {
5169 if st.Size() != stt.Size() {
5170 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5172 if st.Align() != stt.Align() {
5173 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5175 if st.FieldAlign() != stt.FieldAlign() {
5176 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5178 for i := 0; i < st.NumField(); i++ {
5179 o1 := st.Field(i).Offset
5180 o2 := stt.Field(i).Offset
5182 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5186 // check duplicate names
5187 shouldPanic("duplicate field", func() {
5188 StructOf([]StructField{
5189 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5190 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5193 shouldPanic("has no name", func() {
5194 StructOf([]StructField{
5196 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5199 shouldPanic("has no name", func() {
5200 StructOf([]StructField{
5205 // check that type already in binary is found
5206 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5208 // gccgo used to fail this test.
5209 type structFieldType any
5211 StructOf([]StructField{
5214 Type: TypeOf((*structFieldType)(nil)).Elem(),
5217 struct{ F structFieldType }{})
5220 func TestStructOfExportRules(t *testing.T) {
5226 testPanic := func(i int, mustPanic bool, f func()) {
5229 if err == nil && mustPanic {
5230 t.Errorf("test-%d did not panic", i)
5232 if err != nil && !mustPanic {
5233 t.Errorf("test-%d panicked: %v\n", i, err)
5245 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5249 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5253 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5257 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5261 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5265 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5269 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5273 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5277 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5281 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5285 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5288 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5291 field: StructField{Name: "S", Type: TypeOf(S1{})},
5295 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5299 field: StructField{Name: "S", Type: TypeOf(s2{})},
5303 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5307 field: StructField{Name: "s", Type: TypeOf(S1{})},
5311 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5315 field: StructField{Name: "s", Type: TypeOf(s2{})},
5319 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5323 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5326 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5329 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5332 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5335 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5339 field: StructField{Name: "", Type: TypeOf(φType{})},
5343 field: StructField{Name: "Φ", Type: TypeOf(0)},
5347 field: StructField{Name: "φ", Type: TypeOf(0)},
5352 for i, test := range tests {
5353 testPanic(i, test.mustPanic, func() {
5354 typ := StructOf([]StructField{test.field})
5356 t.Errorf("test-%d: error creating struct type", i)
5359 field := typ.Field(0)
5362 panic("field.Name must not be empty")
5364 exported := token.IsExported(n)
5365 if exported != test.exported {
5366 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5368 if field.PkgPath != test.field.PkgPath {
5369 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5375 func TestStructOfGC(t *testing.T) {
5377 tt := TypeOf(T(nil))
5378 fields := []StructField{
5379 {Name: "X", Type: tt},
5380 {Name: "Y", Type: tt},
5382 st := StructOf(fields)
5386 for i := 0; i < n; i++ {
5388 for j := 0; j < v.NumField(); j++ {
5390 *p = uintptr(i*n + j)
5391 v.Field(j).Set(ValueOf(p).Convert(tt))
5393 x = append(x, v.Interface())
5397 for i, xi := range x {
5399 for j := 0; j < v.NumField(); j++ {
5400 k := v.Field(j).Elem().Interface()
5401 if k != uintptr(i*n+j) {
5402 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5408 func TestStructOfAlg(t *testing.T) {
5409 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5410 v1 := New(st).Elem()
5411 v2 := New(st).Elem()
5412 if !DeepEqual(v1.Interface(), v1.Interface()) {
5413 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5415 v1.FieldByName("X").Set(ValueOf(int(1)))
5416 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5417 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5420 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5422 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5425 func TestStructOfGenericAlg(t *testing.T) {
5426 st1 := StructOf([]StructField{
5427 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5428 {Name: "Y", Type: TypeOf(string(""))},
5430 st := StructOf([]StructField{
5431 {Name: "S0", Type: st1},
5432 {Name: "S1", Type: st1},
5450 {Name: "XX", Type: TypeOf([0]int{})},
5451 {Name: "YY", Type: TypeOf("")},
5459 {Name: "XX", Type: TypeOf([0]int{})},
5460 {Name: "YY", Type: TypeOf("")},
5461 {Name: "ZZ", Type: TypeOf([2]int{})},
5469 {Name: "XX", Type: TypeOf([1]int{})},
5470 {Name: "YY", Type: TypeOf("")},
5478 {Name: "XX", Type: TypeOf([1]int{})},
5479 {Name: "YY", Type: TypeOf("")},
5480 {Name: "ZZ", Type: TypeOf([1]int{})},
5488 {Name: "XX", Type: TypeOf([2]int{})},
5489 {Name: "YY", Type: TypeOf("")},
5490 {Name: "ZZ", Type: TypeOf([2]int{})},
5498 {Name: "XX", Type: TypeOf(int64(0))},
5499 {Name: "YY", Type: TypeOf(byte(0))},
5500 {Name: "ZZ", Type: TypeOf("")},
5508 {Name: "XX", Type: TypeOf(int64(0))},
5509 {Name: "YY", Type: TypeOf(int64(0))},
5510 {Name: "ZZ", Type: TypeOf("")},
5511 {Name: "AA", Type: TypeOf([1]int64{})},
5518 for _, table := range tests {
5519 v1 := New(table.rt).Elem()
5520 v2 := New(table.rt).Elem()
5522 if !DeepEqual(v1.Interface(), v1.Interface()) {
5523 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5526 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5527 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5528 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5529 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5533 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5534 val := "+" + abc + "-"
5535 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5536 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5537 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5541 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5542 m.SetMapIndex(v1, ValueOf(1))
5543 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5544 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5547 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5548 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5549 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5552 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5553 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5558 func TestStructOfDirectIface(t *testing.T) {
5560 type T struct{ X [1]*byte }
5561 i1 := Zero(TypeOf(T{})).Interface()
5562 v1 := ValueOf(&i1).Elem()
5563 p1 := v1.InterfaceData()[1]
5565 i2 := Zero(StructOf([]StructField{
5568 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5571 v2 := ValueOf(&i2).Elem()
5572 p2 := v2.InterfaceData()[1]
5575 t.Errorf("got p1=%v. want=%v", p1, nil)
5579 t.Errorf("got p2=%v. want=%v", p2, nil)
5583 type T struct{ X [0]*byte }
5584 i1 := Zero(TypeOf(T{})).Interface()
5585 v1 := ValueOf(&i1).Elem()
5586 p1 := v1.InterfaceData()[1]
5588 i2 := Zero(StructOf([]StructField{
5591 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5594 v2 := ValueOf(&i2).Elem()
5595 p2 := v2.InterfaceData()[1]
5598 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5602 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5609 func (i StructI) Get() int { return int(i) }
5613 func (i *StructIPtr) Get() int { return int(*i) }
5614 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5616 type SettableStruct struct {
5620 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5622 type SettablePointer struct {
5626 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5628 func TestStructOfWithInterface(t *testing.T) {
5630 type Iface interface {
5633 type IfaceSet interface {
5644 typ: TypeOf(StructI(want)),
5645 val: ValueOf(StructI(want)),
5650 typ: PointerTo(TypeOf(StructI(want))),
5651 val: ValueOf(func() any {
5659 typ: PointerTo(TypeOf(StructIPtr(want))),
5660 val: ValueOf(func() any {
5661 v := StructIPtr(want)
5668 typ: TypeOf(StructIPtr(want)),
5669 val: ValueOf(StructIPtr(want)),
5673 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5674 // val: ValueOf(StructI(want)),
5679 for i, table := range tests {
5680 for j := 0; j < 2; j++ {
5681 var fields []StructField
5683 fields = append(fields, StructField{
5686 Type: TypeOf(int(0)),
5689 fields = append(fields, StructField{
5696 // We currently do not correctly implement methods
5697 // for embedded fields other than the first.
5698 // Therefore, for now, we expect those methods
5699 // to not exist. See issues 15924 and 20824.
5700 // When those issues are fixed, this test of panic
5701 // should be removed.
5702 if j == 1 && table.impl {
5705 if err := recover(); err == nil {
5706 t.Errorf("test-%d-%d did not panic", i, j)
5709 _ = StructOf(fields)
5714 rt := StructOf(fields)
5715 rv := New(rt).Elem()
5716 rv.Field(j).Set(table.val)
5718 if _, ok := rv.Interface().(Iface); ok != table.impl {
5720 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5722 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5731 v := rv.Interface().(Iface).Get()
5733 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5736 fct := rv.MethodByName("Get")
5737 out := fct.Call(nil)
5738 if !DeepEqual(out[0].Interface(), want) {
5739 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5744 // Test an embedded nil pointer with pointer methods.
5745 fields := []StructField{{
5748 Type: PointerTo(TypeOf(StructIPtr(want))),
5750 rt := StructOf(fields)
5751 rv := New(rt).Elem()
5752 // This should panic since the pointer is nil.
5753 shouldPanic("", func() {
5754 rv.Interface().(IfaceSet).Set(want)
5757 // Test an embedded nil pointer to a struct with pointer methods.
5759 fields = []StructField{{
5760 Name: "SettableStruct",
5762 Type: PointerTo(TypeOf(SettableStruct{})),
5764 rt = StructOf(fields)
5766 // This should panic since the pointer is nil.
5767 shouldPanic("", func() {
5768 rv.Interface().(IfaceSet).Set(want)
5771 // The behavior is different if there is a second field,
5772 // since now an interface value holds a pointer to the struct
5773 // rather than just holding a copy of the struct.
5774 fields = []StructField{
5776 Name: "SettableStruct",
5778 Type: PointerTo(TypeOf(SettableStruct{})),
5781 Name: "EmptyStruct",
5783 Type: StructOf(nil),
5786 // With the current implementation this is expected to panic.
5787 // Ideally it should work and we should be able to see a panic
5788 // if we call the Set method.
5789 shouldPanic("", func() {
5793 // Embed a field that can be stored directly in an interface,
5794 // with a second field.
5795 fields = []StructField{
5797 Name: "SettablePointer",
5799 Type: TypeOf(SettablePointer{}),
5802 Name: "EmptyStruct",
5804 Type: StructOf(nil),
5807 // With the current implementation this is expected to panic.
5808 // Ideally it should work and we should be able to call the
5809 // Set and Get methods.
5810 shouldPanic("", func() {
5815 func TestStructOfTooManyFields(t *testing.T) {
5816 // Bug Fix: #25402 - this should not panic
5817 tt := StructOf([]StructField{
5818 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5821 if _, present := tt.MethodByName("After"); !present {
5822 t.Errorf("Expected method `After` to be found")
5826 func TestStructOfDifferentPkgPath(t *testing.T) {
5827 fields := []StructField{
5831 Type: TypeOf(int(0)),
5836 Type: TypeOf(int(0)),
5839 shouldPanic("different PkgPath", func() {
5844 func TestChanOf(t *testing.T) {
5845 // check construction and use of type not in binary
5847 ct := ChanOf(BothDir, TypeOf(T("")))
5848 v := MakeChan(ct, 2)
5850 v.Send(ValueOf(T("hello")))
5852 v.Send(ValueOf(T("world")))
5859 if s1 != "hello" || s2 != "world" {
5860 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5863 // check that type already in binary is found
5865 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5867 // Check arrow token association in undefined chan types.
5868 var left chan<- chan T
5869 var right chan (<-chan T)
5870 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5871 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5872 if tLeft != TypeOf(left) {
5873 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5875 if tRight != TypeOf(right) {
5876 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5880 func TestChanOfDir(t *testing.T) {
5881 // check construction and use of type not in binary
5883 crt := ChanOf(RecvDir, TypeOf(T("")))
5884 cst := ChanOf(SendDir, TypeOf(T("")))
5886 // check that type already in binary is found
5888 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5889 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5891 // check String form of ChanDir
5892 if crt.ChanDir().String() != "<-chan" {
5893 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5895 if cst.ChanDir().String() != "chan<-" {
5896 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5900 func TestChanOfGC(t *testing.T) {
5901 done := make(chan bool, 1)
5905 case <-time.After(5 * time.Second):
5906 panic("deadlock in TestChanOfGC")
5915 tt := TypeOf(T(nil))
5916 ct := ChanOf(BothDir, tt)
5918 // NOTE: The garbage collector handles allocated channels specially,
5919 // so we have to save pointers to channels in x; the pointer code will
5920 // use the gc info in the newly constructed chan type.
5923 for i := 0; i < n; i++ {
5924 v := MakeChan(ct, n)
5925 for j := 0; j < n; j++ {
5927 *p = uintptr(i*n + j)
5928 v.Send(ValueOf(p).Convert(tt))
5932 x = append(x, pv.Interface())
5936 for i, xi := range x {
5937 v := ValueOf(xi).Elem()
5938 for j := 0; j < n; j++ {
5940 k := pv.Elem().Interface()
5941 if k != uintptr(i*n+j) {
5942 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5948 func TestMapOf(t *testing.T) {
5949 // check construction and use of type not in binary
5953 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5955 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5958 s := fmt.Sprint(v.Interface())
5961 t.Errorf("constructed map = %s, want %s", s, want)
5964 // check that type already in binary is found
5965 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5967 // check that invalid key type panics
5968 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5971 func TestMapOfGCKeys(t *testing.T) {
5973 tt := TypeOf(T(nil))
5974 mt := MapOf(tt, TypeOf(false))
5976 // NOTE: The garbage collector handles allocated maps specially,
5977 // so we have to save pointers to maps in x; the pointer code will
5978 // use the gc info in the newly constructed map type.
5981 for i := 0; i < n; i++ {
5983 for j := 0; j < n; j++ {
5985 *p = uintptr(i*n + j)
5986 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5990 x = append(x, pv.Interface())
5994 for i, xi := range x {
5995 v := ValueOf(xi).Elem()
5997 for _, kv := range v.MapKeys() {
5998 out = append(out, int(kv.Elem().Interface().(uintptr)))
6001 for j, k := range out {
6003 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6009 func TestMapOfGCValues(t *testing.T) {
6011 tt := TypeOf(T(nil))
6012 mt := MapOf(TypeOf(1), tt)
6014 // NOTE: The garbage collector handles allocated maps specially,
6015 // so we have to save pointers to maps in x; the pointer code will
6016 // use the gc info in the newly constructed map type.
6019 for i := 0; i < n; i++ {
6021 for j := 0; j < n; j++ {
6023 *p = uintptr(i*n + j)
6024 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
6028 x = append(x, pv.Interface())
6032 for i, xi := range x {
6033 v := ValueOf(xi).Elem()
6034 for j := 0; j < n; j++ {
6035 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
6036 if k != uintptr(i*n+j) {
6037 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
6043 func TestTypelinksSorted(t *testing.T) {
6045 for i, n := range TypeLinks() {
6047 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
6053 func TestFuncOf(t *testing.T) {
6054 // check construction and use of type not in binary
6058 fn := func(args []Value) []Value {
6060 t.Errorf("args == %v, want exactly one arg", args)
6061 } else if args[0].Type() != TypeOf(K("")) {
6062 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
6063 } else if args[0].String() != "gopher" {
6064 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
6066 return []Value{ValueOf(V(3.14))}
6068 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
6070 outs := v.Call([]Value{ValueOf(K("gopher"))})
6072 t.Fatalf("v.Call returned %v, want exactly one result", outs)
6073 } else if outs[0].Type() != TypeOf(V(0)) {
6074 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
6076 f := outs[0].Float()
6078 t.Errorf("constructed func returned %f, want %f", f, 3.14)
6081 // check that types already in binary are found
6083 testCases := []struct {
6088 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
6089 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
6090 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
6091 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
6092 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
6094 for _, tt := range testCases {
6095 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
6098 // check that variadic requires last element be a slice.
6099 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
6100 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
6101 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6110 func BenchmarkFieldByName1(b *testing.B) {
6112 b.RunParallel(func(pb *testing.PB) {
6119 func BenchmarkFieldByName2(b *testing.B) {
6121 b.RunParallel(func(pb *testing.PB) {
6198 func TestEmbed(t *testing.T) {
6200 f, ok := typ.FieldByName("X")
6202 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6206 func BenchmarkFieldByName3(b *testing.B) {
6208 b.RunParallel(func(pb *testing.PB) {
6220 func BenchmarkInterfaceBig(b *testing.B) {
6222 b.RunParallel(func(pb *testing.PB) {
6230 func TestAllocsInterfaceBig(t *testing.T) {
6231 if testing.Short() {
6232 t.Skip("skipping malloc count in short mode")
6235 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6236 t.Error("allocs:", allocs)
6240 func BenchmarkInterfaceSmall(b *testing.B) {
6241 v := ValueOf(int64(0))
6242 b.RunParallel(func(pb *testing.PB) {
6249 func TestAllocsInterfaceSmall(t *testing.T) {
6250 if testing.Short() {
6251 t.Skip("skipping malloc count in short mode")
6253 v := ValueOf(int64(0))
6254 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6255 t.Error("allocs:", allocs)
6259 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6260 // The basic usage is:
6263 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6266 // Each iteration of the loop returns a different set of results, until all
6267 // possible result sets have been explored. It is okay for different code paths
6268 // to make different method call sequences on x, but there must be no
6269 // other source of non-determinism in the call sequences.
6271 // When faced with a new decision, x chooses randomly. Future explorations
6272 // of that path will choose successive values for the result. Thus, stopping
6273 // the loop after a fixed number of iterations gives somewhat stochastic
6279 // v := make([]bool, x.Choose(4))
6280 // for i := range v {
6286 // prints (in some order):
6295 // [false false false]
6298 // [false false false false]
6300 // [true true true true]
6301 type exhaustive struct {
6307 type choice struct {
6313 func (x *exhaustive) Next() bool {
6315 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6322 for i := len(x.last) - 1; i >= 0; i-- {
6326 x.last = x.last[:i+1]
6333 func (x *exhaustive) Choose(max int) int {
6334 if x.pos >= len(x.last) {
6335 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6340 panic("inconsistent use of exhaustive tester")
6342 return (c.n + c.off) % max
6345 func (x *exhaustive) Maybe() bool {
6346 return x.Choose(2) == 1
6349 func GCFunc(args []Value) []Value {
6354 func TestReflectFuncTraceback(t *testing.T) {
6355 f := MakeFunc(TypeOf(func() {}), GCFunc)
6359 func TestReflectMethodTraceback(t *testing.T) {
6361 m := ValueOf(p).MethodByName("GCMethod")
6362 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6364 t.Errorf("Call returned %d; want 8", i)
6368 func TestSmallZero(t *testing.T) {
6371 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6372 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6376 func TestBigZero(t *testing.T) {
6377 const size = 1 << 10
6379 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6380 for i := 0; i < size; i++ {
6382 t.Fatalf("Zero object not all zero, index %d", i)
6387 func TestZeroSet(t *testing.T) {
6395 a: 0xaaaaaaaaaaaaaaaa,
6396 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6397 b: 0xbbbbbbbbbbbbbbbb,
6399 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6401 a: 0xaaaaaaaaaaaaaaaa,
6402 b: 0xbbbbbbbbbbbbbbbb,
6404 t.Fatalf("Setting a field to a Zero value didn't work")
6408 func TestFieldByIndexNil(t *testing.T) {
6417 v.FieldByName("P") // should be fine
6420 if err := recover(); err == nil {
6421 t.Fatalf("no error")
6422 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6423 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6426 v.FieldByName("F") // should panic
6428 t.Fatalf("did not panic")
6432 // type Outer struct {
6436 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6437 // The implementation is logically:
6438 // func (p *Outer) M() {
6441 // but since the only change here is the replacement of one pointer receiver with another,
6442 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6443 // then jumps to the M method expecting the *Inner receiver.
6445 // During reflect.Value.Call, we create an argument frame and the associated data structures
6446 // to describe it to the garbage collector, populate the frame, call reflect.call to
6447 // run a function call using that frame, and then copy the results back out of the frame.
6448 // The reflect.call function does a memmove of the frame structure onto the
6449 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6450 // the frame structure (to preserve the outputs).
6452 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6453 // were for the full stack frame. However, in the case where the called function was
6454 // one of these wrappers, the rewritten receiver is almost certainly a different type
6455 // than the original receiver. This is not a problem on the stack, where we use the
6456 // program counter to determine the type information and understand that
6457 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6458 // memory word is now an *Inner. But in the statically typed argument frame created
6459 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6460 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6461 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6462 // memory as if it were an *Outer. If the two have different memory layouts, the
6463 // collection will interpret the memory incorrectly.
6465 // One such possible incorrect interpretation is to treat two arbitrary memory words
6466 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6467 // an interface requires dereferencing the itab word, the misinterpretation will try to
6468 // deference Inner.P1, causing a crash during garbage collection.
6470 // This came up in a real program in issue 7725.
6483 func (pi *Inner) M() {
6484 // Clear references to pi so that the only way the
6485 // garbage collection will find the pointer is in the
6486 // argument frame, typed as a *Outer.
6489 // Set up an interface value that will cause a crash.
6490 // P1 = 1 is a non-zero, so the interface looks non-nil.
6491 // P2 = pi ensures that the data word points into the
6492 // allocated heap; if not the collection skips the interface
6493 // value as irrelevant, without dereferencing P1.
6495 pi.P2 = uintptr(unsafe.Pointer(pi))
6498 func TestCallMethodJump(t *testing.T) {
6499 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6500 // returns but before the args frame has been discarded.
6501 // This is a little clumsy but makes the failure repeatable.
6504 p := &Outer{Inner: new(Inner)}
6506 ValueOf(p).Method(0).Call(nil)
6508 // Stop garbage collecting during reflect.call.
6512 func TestCallArgLive(t *testing.T) {
6513 type T struct{ X, Y *string } // pointerful aggregate
6515 F := func(t T) { *t.X = "ok" }
6517 // In reflect.Value.Call, trigger a garbage collection in reflect.call
6518 // between marshaling argument and the actual call.
6522 runtime.SetFinalizer(x, func(p *string) {
6524 t.Errorf("x dead prematurely")
6529 ValueOf(F).Call([]Value{ValueOf(v)})
6531 // Stop garbage collecting during reflect.call.
6535 func TestMakeFuncStackCopy(t *testing.T) {
6536 target := func(in []Value) []Value {
6539 return []Value{ValueOf(9)}
6542 var concrete func(*int, int) int
6543 fn := MakeFunc(ValueOf(concrete).Type(), target)
6544 ValueOf(&concrete).Elem().Set(fn)
6545 x := concrete(nil, 7)
6547 t.Errorf("have %#q want 9", x)
6551 // use about n KB of stack
6552 func useStack(n int) {
6556 var b [1024]byte // makes frame about 1KB
6557 useStack(n - 1 + int(b[99]))
6564 func TestValueString(t *testing.T) {
6565 rv := ValueOf(Impl{})
6566 if rv.String() != "<reflect_test.Impl Value>" {
6567 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6570 method := rv.Method(0)
6571 if method.String() != "<func() Value>" {
6572 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6576 func TestInvalid(t *testing.T) {
6577 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6578 type T struct{ v any }
6580 v := ValueOf(T{}).Field(0)
6581 if v.IsValid() != true || v.Kind() != Interface {
6582 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6585 if v.IsValid() != false || v.Kind() != Invalid {
6586 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6591 func TestLargeGCProg(t *testing.T) {
6592 fv := ValueOf(func([256]*byte) {})
6593 fv.Call([]Value{ValueOf([256]*byte{})})
6596 func fieldIndexRecover(t Type, i int) (recovered any) {
6598 recovered = recover()
6606 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6607 typ := TypeOf(struct{ X int }{10})
6608 testIndices := [...]struct {
6617 for i, tt := range testIndices {
6618 recoveredErr := fieldIndexRecover(typ, tt.i)
6620 if recoveredErr == nil {
6621 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6624 if recoveredErr != nil {
6625 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6632 func TestCallGC(t *testing.T) {
6633 f := func(a, b, c, d, e string) {
6635 g := func(in []Value) []Value {
6639 typ := ValueOf(f).Type()
6640 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6641 f2("four", "five5", "six666", "seven77", "eight888")
6644 // Issue 18635 (function version).
6645 func TestKeepFuncLive(t *testing.T) {
6646 // Test that we keep makeFuncImpl live as long as it is
6647 // referenced on the stack.
6648 typ := TypeOf(func(i int) {})
6649 var f, g func(in []Value) []Value
6650 f = func(in []Value) []Value {
6652 i := int(in[0].Int())
6654 // We can't use Value.Call here because
6655 // runtime.call* will keep the makeFuncImpl
6656 // alive. However, by converting it to an
6657 // interface value and calling that,
6658 // reflect.callReflect is the only thing that
6659 // can keep the makeFuncImpl live.
6661 // Alternate between f and g so that if we do
6662 // reuse the memory prematurely it's more
6663 // likely to get obviously corrupted.
6664 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6668 g = func(in []Value) []Value {
6670 i := int(in[0].Int())
6671 MakeFunc(typ, f).Interface().(func(i int))(i)
6674 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6677 type UnExportedFirst int
6679 func (i UnExportedFirst) ΦExported() {}
6680 func (i UnExportedFirst) unexported() {}
6683 func TestMethodByNameUnExportedFirst(t *testing.T) {
6685 if recover() != nil {
6686 t.Errorf("should not panic")
6689 typ := TypeOf(UnExportedFirst(0))
6690 m, _ := typ.MethodByName("ΦExported")
6691 if m.Name != "ΦExported" {
6692 t.Errorf("got %s, expected ΦExported", m.Name)
6696 // Issue 18635 (method version).
6697 type KeepMethodLive struct{}
6699 func (k KeepMethodLive) Method1(i int) {
6702 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6706 func (k KeepMethodLive) Method2(i int) {
6708 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6711 func TestKeepMethodLive(t *testing.T) {
6712 // Test that we keep methodValue live as long as it is
6713 // referenced on the stack.
6714 KeepMethodLive{}.Method1(10)
6717 // clobber tries to clobber unreachable memory.
6720 for i := 1; i < 32; i++ {
6721 for j := 0; j < 10; j++ {
6722 obj := make([]*byte, i)
6729 func TestFuncLayout(t *testing.T) {
6730 align := func(x uintptr) uintptr {
6731 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6734 if goarch.PtrSize == 4 {
6735 r = []byte{0, 0, 0, 1}
6747 size, argsize, retOffset uintptr
6748 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6749 intRegs, floatRegs int
6750 floatRegSize uintptr
6754 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6755 size: 6 * goarch.PtrSize,
6756 argsize: 4 * goarch.PtrSize,
6757 retOffset: 4 * goarch.PtrSize,
6758 stack: []byte{1, 0, 1, 0, 1},
6759 gc: []byte{1, 0, 1, 0, 1},
6762 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6763 size: align(align(3*4) + goarch.PtrSize + 2),
6764 argsize: align(3*4) + goarch.PtrSize + 2,
6765 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6770 typ: ValueOf(func(a map[int]int, b uintptr, c any) {}).Type(),
6771 size: 4 * goarch.PtrSize,
6772 argsize: 4 * goarch.PtrSize,
6773 retOffset: 4 * goarch.PtrSize,
6774 stack: []byte{1, 0, 1, 1},
6775 gc: []byte{1, 0, 1, 1},
6778 typ: ValueOf(func(a S) {}).Type(),
6779 size: 4 * goarch.PtrSize,
6780 argsize: 4 * goarch.PtrSize,
6781 retOffset: 4 * goarch.PtrSize,
6782 stack: []byte{0, 0, 1, 1},
6783 gc: []byte{0, 0, 1, 1},
6786 rcvr: ValueOf((*byte)(nil)).Type(),
6787 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6788 size: 3 * goarch.PtrSize,
6789 argsize: 3 * goarch.PtrSize,
6790 retOffset: 3 * goarch.PtrSize,
6791 stack: []byte{1, 0, 1},
6792 gc: []byte{1, 0, 1},
6795 typ: ValueOf(func(a uintptr) {}).Type(),
6796 size: goarch.PtrSize,
6797 argsize: goarch.PtrSize,
6798 retOffset: goarch.PtrSize,
6803 typ: ValueOf(func() uintptr { return 0 }).Type(),
6804 size: goarch.PtrSize,
6811 rcvr: ValueOf(uintptr(0)).Type(),
6812 typ: ValueOf(func(a uintptr) {}).Type(),
6813 size: 2 * goarch.PtrSize,
6814 argsize: 2 * goarch.PtrSize,
6815 retOffset: 2 * goarch.PtrSize,
6818 // Note: this one is tricky, as the receiver is not a pointer. But we
6819 // pass the receiver by reference to the autogenerated pointer-receiver
6820 // version of the function.
6822 // TODO(mknyszek): Add tests for non-zero register count.
6824 for _, lt := range tests {
6825 name := lt.typ.String()
6827 name = lt.rcvr.String() + "." + name
6829 t.Run(name, func(t *testing.T) {
6830 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6832 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6833 if typ.Size() != lt.size {
6834 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6836 if argsize != lt.argsize {
6837 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6839 if retOffset != lt.retOffset {
6840 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6842 if !bytes.Equal(stack, lt.stack) {
6843 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6845 if !bytes.Equal(gc, lt.gc) {
6846 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6848 if !bytes.Equal(inRegs, lt.inRegs) {
6849 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6851 if !bytes.Equal(outRegs, lt.outRegs) {
6852 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6854 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6855 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6861 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6862 heapBits := GCBits(New(typ).Interface())
6863 if !bytes.Equal(heapBits, bits) {
6864 _, _, line, _ := runtime.Caller(1)
6865 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6869 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6870 // Creating a slice causes the runtime to repeat a bitmap,
6871 // which exercises a different path from making the compiler
6872 // repeat a bitmap for a small array or executing a repeat in
6874 val := MakeSlice(typ, 0, cap)
6875 data := NewAt(ArrayOf(cap, typ), val.UnsafePointer())
6876 heapBits := GCBits(data.Interface())
6877 // Repeat the bitmap for the slice size, trimming scalars in
6878 // the last element.
6879 bits = rep(cap, bits)
6880 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6881 bits = bits[:len(bits)-1]
6883 if !bytes.Equal(heapBits, bits) {
6884 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6888 func TestGCBits(t *testing.T) {
6889 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6891 // Building blocks for types seen by the compiler (like [2]Xscalar).
6892 // The compiler will create the type structures for the derived types,
6893 // including their GC metadata.
6894 type Xscalar struct{ x uintptr }
6895 type Xptr struct{ x *byte }
6896 type Xptrscalar struct {
6900 type Xscalarptr struct {
6904 type Xbigptrscalar struct {
6909 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6911 // Building blocks for types constructed by reflect.
6912 // This code is in a separate block so that code below
6913 // cannot accidentally refer to these.
6914 // The compiler must NOT see types derived from these
6915 // (for example, [2]Scalar must NOT appear in the program),
6916 // or else reflect will use it instead of having to construct one.
6917 // The goal is to test the construction.
6918 type Scalar struct{ x uintptr }
6919 type Ptr struct{ x *byte }
6920 type Ptrscalar struct {
6924 type Scalarptr struct {
6928 type Bigptrscalar struct {
6933 Tscalar = TypeOf(Scalar{})
6934 Tint64 = TypeOf(Int64(0))
6935 Tptr = TypeOf(Ptr{})
6936 Tscalarptr = TypeOf(Scalarptr{})
6937 Tptrscalar = TypeOf(Ptrscalar{})
6938 Tbigptrscalar = TypeOf(Bigptrscalar{})
6943 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6944 verifyGCBits(t, Tscalar, empty)
6945 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6946 verifyGCBits(t, Tptr, lit(1))
6947 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6948 verifyGCBits(t, Tscalarptr, lit(0, 1))
6949 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6950 verifyGCBits(t, Tptrscalar, lit(1))
6952 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6953 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6954 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6955 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6956 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6957 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6958 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6959 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6960 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6961 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6962 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6963 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6964 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6965 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6966 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6967 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6968 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6969 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6970 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6971 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6972 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6973 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6974 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6975 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6976 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6977 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6979 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6980 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6981 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6982 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6983 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6984 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6985 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6986 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6987 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6988 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6989 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6990 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6991 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6992 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6993 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6994 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6995 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6996 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6997 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6998 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6999 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
7000 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
7001 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
7002 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
7003 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7004 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
7006 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
7007 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
7009 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
7010 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
7012 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
7013 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
7015 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
7016 verifyGCBits(t, PointerTo(ArrayOf(10000, Tscalar)), lit(1))
7018 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
7019 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
7021 hdr := make([]byte, 8/goarch.PtrSize)
7023 verifyMapBucket := func(t *testing.T, k, e Type, m any, want []byte) {
7024 verifyGCBits(t, MapBucketOf(k, e), want)
7025 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
7029 map[Xscalar]Xptr(nil),
7030 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
7033 map[Xscalarptr]Xptr(nil),
7034 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
7035 verifyMapBucket(t, Tint64, Tptr,
7036 map[int64]Xptr(nil),
7037 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
7040 map[Xscalar]Xscalar(nil),
7043 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
7044 map[[2]Xscalarptr][3]Xptrscalar(nil),
7045 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
7047 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7048 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7049 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7051 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
7052 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
7053 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
7055 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7056 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7057 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
7059 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
7060 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
7061 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
7064 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
7065 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
7066 func lit(x ...byte) []byte { return x }
7068 func TestTypeOfTypeOf(t *testing.T) {
7069 // Check that all the type constructors return concrete *rtype implementations.
7070 // It's difficult to test directly because the reflect package is only at arm's length.
7071 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
7072 check := func(name string, typ Type) {
7073 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
7074 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
7078 type T struct{ int }
7079 check("TypeOf", TypeOf(T{}))
7081 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
7082 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
7083 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
7084 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
7085 check("PtrTo", PointerTo(TypeOf(T{})))
7086 check("SliceOf", SliceOf(TypeOf(T{})))
7089 type XM struct{ _ bool }
7091 func (*XM) String() string { return "" }
7093 func TestPtrToMethods(t *testing.T) {
7095 yp := New(TypeOf(y)).Interface()
7096 _, ok := yp.(fmt.Stringer)
7098 t.Fatal("does not implement Stringer, but should")
7102 func TestMapAlloc(t *testing.T) {
7103 m := ValueOf(make(map[int]int, 10))
7106 allocs := testing.AllocsPerRun(100, func() {
7110 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
7115 val := ValueOf(&tmp).Elem()
7116 allocs = testing.AllocsPerRun(100, func() {
7117 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
7118 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
7119 for i := 0; i < size/2; i++ {
7120 val.SetInt(int64(i))
7121 mv.SetMapIndex(val, val)
7125 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
7127 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7128 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7129 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7132 func TestChanAlloc(t *testing.T) {
7133 // Note: for a chan int, the return Value must be allocated, so we
7134 // use a chan *int instead.
7135 c := ValueOf(make(chan *int, 1))
7136 v := ValueOf(new(int))
7137 allocs := testing.AllocsPerRun(100, func() {
7141 if allocs < 0.5 || allocs > 1.5 {
7142 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7144 // Note: there is one allocation in reflect.recv which seems to be
7145 // a limitation of escape analysis. If that is ever fixed the
7146 // allocs < 0.5 condition will trigger and this test should be fixed.
7149 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7151 type nameTest struct {
7156 var nameTests = []nameTest{
7157 {(*int32)(nil), "int32"},
7160 {(*chan D1)(nil), ""},
7161 {(*func() D1)(nil), ""},
7162 {(*<-chan D1)(nil), ""},
7163 {(*chan<- D1)(nil), ""},
7168 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7171 func TestNames(t *testing.T) {
7172 for _, test := range nameTests {
7173 typ := TypeOf(test.v).Elem()
7174 if got := typ.Name(); got != test.want {
7175 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7180 func TestExported(t *testing.T) {
7181 type ΦExported struct{}
7182 type φUnexported struct{}
7189 type exportTest struct {
7193 exportTests := []exportTest{
7197 {(*big)(nil), false},
7198 {(BigP)(nil), true},
7199 {(*BigP)(nil), true},
7200 {ΦExported{}, true},
7201 {φUnexported{}, false},
7208 for i, test := range exportTests {
7209 typ := TypeOf(test.v)
7210 if got := IsExported(typ); got != test.want {
7211 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7216 func TestTypeStrings(t *testing.T) {
7217 type stringTest struct {
7221 stringTests := []stringTest{
7222 {TypeOf(func(int) {}), "func(int)"},
7223 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7224 {TypeOf(XM{}), "reflect_test.XM"},
7225 {TypeOf(new(XM)), "*reflect_test.XM"},
7226 {TypeOf(new(XM).String), "func() string"},
7227 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7228 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7229 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7230 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7231 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7234 for i, test := range stringTests {
7235 if got, want := test.typ.String(), test.want; got != want {
7236 t.Errorf("type %d String()=%q, want %q", i, got, want)
7241 func TestOffsetLock(t *testing.T) {
7242 var wg sync.WaitGroup
7243 for i := 0; i < 4; i++ {
7247 for j := 0; j < 50; j++ {
7248 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7256 func BenchmarkNew(b *testing.B) {
7258 b.RunParallel(func(pb *testing.PB) {
7265 func BenchmarkMap(b *testing.B) {
7267 value := ValueOf((V)(nil))
7268 stringKeys := []string{}
7269 mapOfStrings := map[string]V{}
7270 uint64Keys := []uint64{}
7271 mapOfUint64s := map[uint64]V{}
7272 for i := 0; i < 100; i++ {
7273 stringKey := fmt.Sprintf("key%d", i)
7274 stringKeys = append(stringKeys, stringKey)
7275 mapOfStrings[stringKey] = nil
7277 uint64Key := uint64(i)
7278 uint64Keys = append(uint64Keys, uint64Key)
7279 mapOfUint64s[uint64Key] = nil
7284 m, keys, value Value
7286 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7287 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7290 for _, tt := range tests {
7291 b.Run(tt.label, func(b *testing.B) {
7292 b.Run("MapIndex", func(b *testing.B) {
7294 for i := 0; i < b.N; i++ {
7295 for j := tt.keys.Len() - 1; j >= 0; j-- {
7296 tt.m.MapIndex(tt.keys.Index(j))
7300 b.Run("SetMapIndex", func(b *testing.B) {
7302 for i := 0; i < b.N; i++ {
7303 for j := tt.keys.Len() - 1; j >= 0; j-- {
7304 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7312 func TestSwapper(t *testing.T) {
7318 type pairPtr struct {
7330 in: []int{1, 20, 300},
7333 want: []int{300, 20, 1},
7336 in: []uintptr{1, 20, 300},
7339 want: []uintptr{300, 20, 1},
7342 in: []int16{1, 20, 300},
7345 want: []int16{300, 20, 1},
7348 in: []int8{1, 20, 100},
7351 want: []int8{100, 20, 1},
7354 in: []*I{&a, &b, &c},
7357 want: []*I{&c, &b, &a},
7360 in: []string{"eric", "sergey", "larry"},
7363 want: []string{"larry", "sergey", "eric"},
7366 in: []S{"eric", "sergey", "larry"},
7369 want: []S{"larry", "sergey", "eric"},
7372 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7375 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7378 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7381 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7385 for i, tt := range tests {
7386 inStr := fmt.Sprint(tt.in)
7387 Swapper(tt.in)(tt.i, tt.j)
7388 if !DeepEqual(tt.in, tt.want) {
7389 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7394 // TestUnaddressableField tests that the reflect package will not allow
7395 // a type from another package to be used as a named type with an
7396 // unexported field.
7398 // This ensures that unexported fields cannot be modified by other packages.
7399 func TestUnaddressableField(t *testing.T) {
7400 var b Buffer // type defined in reflect, a different package
7401 var localBuffer struct {
7404 lv := ValueOf(&localBuffer).Elem()
7406 shouldPanic("Set", func() {
7415 type Talias1 struct {
7423 type Talias2 struct {
7428 func TestAliasNames(t *testing.T) {
7429 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7430 out := fmt.Sprintf("%#v", t1)
7431 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7433 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7436 t2 := Talias2{Tint: 1, Tint2: 2}
7437 out = fmt.Sprintf("%#v", t2)
7438 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7440 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7444 func TestIssue22031(t *testing.T) {
7445 type s []struct{ C int }
7448 type t2 struct{ f s }
7451 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7452 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7455 for i, test := range tests {
7457 t.Errorf("%d: CanSet: got true, want false", i)
7462 type NonExportedFirst int
7464 func (i NonExportedFirst) ΦExported() {}
7465 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7467 func TestIssue22073(t *testing.T) {
7468 m := ValueOf(NonExportedFirst(0)).Method(0)
7470 if got := m.Type().NumOut(); got != 0 {
7471 t.Errorf("NumOut: got %v, want 0", got)
7478 func TestMapIterNonEmptyMap(t *testing.T) {
7479 m := map[string]int{"one": 1, "two": 2, "three": 3}
7480 iter := ValueOf(m).MapRange()
7481 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7482 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7486 func TestMapIterNilMap(t *testing.T) {
7487 var m map[string]int
7488 iter := ValueOf(m).MapRange()
7489 if got, want := iterateToString(iter), `[]`; got != want {
7490 t.Errorf("non-empty result iteratoring nil map: %s", got)
7494 func TestMapIterReset(t *testing.T) {
7495 iter := new(MapIter)
7497 // Use of zero iterator should panic.
7499 defer func() { recover() }()
7501 t.Error("Next did not panic")
7504 // Reset to new Map should work.
7505 m := map[string]int{"one": 1, "two": 2, "three": 3}
7506 iter.Reset(ValueOf(m))
7507 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7508 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7511 // Reset to Zero value should work, but iterating over it should panic.
7514 defer func() { recover() }()
7516 t.Error("Next did not panic")
7519 // Reset to a different Map with different types should work.
7520 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7521 iter.Reset(ValueOf(m2))
7522 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7523 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7526 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7527 m3 := map[uint64]uint64{
7532 kv := New(TypeOf(uint64(0))).Elem()
7533 for i := 0; i < 5; i++ {
7534 var seenk, seenv uint64
7535 iter.Reset(ValueOf(m3))
7539 kv.SetIterValue(iter)
7543 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7545 if seenv != 0b1110 {
7546 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7550 // Reset should not allocate.
7551 n := int(testing.AllocsPerRun(10, func() {
7552 iter.Reset(ValueOf(m2))
7556 t.Errorf("MapIter.Reset allocated %d times", n)
7560 func TestMapIterSafety(t *testing.T) {
7561 // Using a zero MapIter causes a panic, but not a crash.
7563 defer func() { recover() }()
7565 t.Fatal("Key did not panic")
7568 defer func() { recover() }()
7569 new(MapIter).Value()
7570 t.Fatal("Value did not panic")
7573 defer func() { recover() }()
7575 t.Fatal("Next did not panic")
7578 // Calling Key/Value on a MapIter before Next
7579 // causes a panic, but not a crash.
7580 var m map[string]int
7581 iter := ValueOf(m).MapRange()
7584 defer func() { recover() }()
7586 t.Fatal("Key did not panic")
7589 defer func() { recover() }()
7591 t.Fatal("Value did not panic")
7594 // Calling Next, Key, or Value on an exhausted iterator
7595 // causes a panic, but not a crash.
7596 iter.Next() // -> false
7598 defer func() { recover() }()
7600 t.Fatal("Key did not panic")
7603 defer func() { recover() }()
7605 t.Fatal("Value did not panic")
7608 defer func() { recover() }()
7610 t.Fatal("Next did not panic")
7614 func TestMapIterNext(t *testing.T) {
7615 // The first call to Next should reflect any
7616 // insertions to the map since the iterator was created.
7617 m := map[string]int{}
7618 iter := ValueOf(m).MapRange()
7620 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7621 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7625 func BenchmarkMapIterNext(b *testing.B) {
7626 m := ValueOf(map[string]int{"a": 0, "b": 1, "c": 2, "d": 3})
7628 for i := 0; i < b.N; i++ {
7635 func TestMapIterDelete0(t *testing.T) {
7636 // Delete all elements before first iteration.
7637 m := map[string]int{"one": 1, "two": 2, "three": 3}
7638 iter := ValueOf(m).MapRange()
7642 if got, want := iterateToString(iter), `[]`; got != want {
7643 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7647 func TestMapIterDelete1(t *testing.T) {
7648 // Delete all elements after first iteration.
7649 m := map[string]int{"one": 1, "two": 2, "three": 3}
7650 iter := ValueOf(m).MapRange()
7653 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7659 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7663 // iterateToString returns the set of elements
7664 // returned by an iterator in readable form.
7665 func iterateToString(it *MapIter) string {
7668 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7669 got = append(got, line)
7672 return "[" + strings.Join(got, ", ") + "]"
7675 func TestConvertibleTo(t *testing.T) {
7676 t1 := ValueOf(example1.MyStruct{}).Type()
7677 t2 := ValueOf(example2.MyStruct{}).Type()
7679 // Shouldn't raise stack overflow
7680 if t1.ConvertibleTo(t2) {
7681 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7684 t3 := ValueOf([]example1.MyStruct{}).Type()
7685 t4 := ValueOf([]example2.MyStruct{}).Type()
7687 if t3.ConvertibleTo(t4) {
7688 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)
7692 func TestSetIter(t *testing.T) {
7693 data := map[string]int{
7701 k := New(TypeOf("")).Elem()
7702 v := New(TypeOf(0)).Elem()
7703 shouldPanic("Value.SetIterKey called before Next", func() {
7706 shouldPanic("Value.SetIterValue called before Next", func() {
7709 data2 := map[string]int{}
7713 data2[k.Interface().(string)] = v.Interface().(int)
7715 if !DeepEqual(data, data2) {
7716 t.Errorf("maps not equal, got %v want %v", data2, data)
7718 shouldPanic("Value.SetIterKey called on exhausted iterator", func() {
7721 shouldPanic("Value.SetIterValue called on exhausted iterator", func() {
7727 shouldPanic("Value.SetIterKey using unaddressable value", func() {
7728 ValueOf("").SetIterKey(i)
7730 shouldPanic("Value.SetIterValue using unaddressable value", func() {
7731 ValueOf(0).SetIterValue(i)
7733 shouldPanic("value of type string is not assignable to type int", func() {
7734 New(TypeOf(0)).Elem().SetIterKey(i)
7736 shouldPanic("value of type int is not assignable to type string", func() {
7737 New(TypeOf("")).Elem().SetIterValue(i)
7740 // Make sure assignment conversion works.
7742 y := ValueOf(&x).Elem()
7744 if _, ok := data[x.(string)]; !ok {
7745 t.Errorf("got key %s which is not in map", x)
7748 if x.(int) < 1 || x.(int) > 3 {
7749 t.Errorf("got value %d which is not in map", x)
7752 // Try some key/value types which are direct interfaces.
7755 pp := map[*int]*int{
7758 i = ValueOf(pp).MapRange()
7761 if got := *y.Interface().(*int); got != a {
7762 t.Errorf("pointer incorrect: got %d want %d", got, a)
7765 if got := *y.Interface().(*int); got != b {
7766 t.Errorf("pointer incorrect: got %d want %d", got, b)
7771 type nih struct{ x int }
7773 var global_nih = nih{x: 7}
7775 func TestNotInHeapDeref(t *testing.T) {
7777 v := ValueOf((*nih)(nil))
7779 shouldPanic("reflect: call of reflect.Value.Field on zero Value", func() { v.Elem().Field(0) })
7781 v = ValueOf(&global_nih)
7782 if got := v.Elem().Field(0).Int(); got != 7 {
7783 t.Fatalf("got %d, want 7", got)
7786 v = ValueOf((*nih)(unsafe.Pointer(new(int))))
7787 shouldPanic("reflect: reflect.Value.Elem on an invalid notinheap pointer", func() { v.Elem() })
7788 shouldPanic("reflect: reflect.Value.Pointer on an invalid notinheap pointer", func() { v.Pointer() })
7789 shouldPanic("reflect: reflect.Value.UnsafePointer on an invalid notinheap pointer", func() { v.UnsafePointer() })
7792 func TestMethodCallValueCodePtr(t *testing.T) {
7793 m := ValueOf(Point{}).Method(1)
7794 want := MethodValueCallCodePtr()
7795 if got := uintptr(m.UnsafePointer()); got != want {
7796 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7798 if got := m.Pointer(); got != want {
7799 t.Errorf("methodValueCall code pointer mismatched, want: %v, got: %v", want, got)
7804 type B[T any] struct{}
7806 func TestIssue50208(t *testing.T) {
7807 want1 := "B[reflect_test.A]"
7808 if got := TypeOf(new(B[A])).Elem().Name(); got != want1 {
7809 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want1, got)
7811 want2 := "B[reflect_test.B[reflect_test.A]]"
7812 if got := TypeOf(new(B[B[A]])).Elem().Name(); got != want2 {
7813 t.Errorf("name of type parameter mismatched, want:%s, got:%s", want2, got)
7817 func TestNegativeKindString(t *testing.T) {
7819 s := Kind(x).String()
7822 t.Fatalf("Kind(-1).String() = %q, want %q", s, want)