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.
19 "reflect/internal/example1"
20 "reflect/internal/example2"
34 func TestBool(t *testing.T) {
37 t.Fatal("ValueOf(true).Bool() = false")
54 func assert(t *testing.T, s, want string) {
56 t.Errorf("have %#q want %#q", s, want)
60 var typeTests = []pair{
61 {struct{ x int }{}, "int"},
62 {struct{ x int8 }{}, "int8"},
63 {struct{ x int16 }{}, "int16"},
64 {struct{ x int32 }{}, "int32"},
65 {struct{ x int64 }{}, "int64"},
66 {struct{ x uint }{}, "uint"},
67 {struct{ x uint8 }{}, "uint8"},
68 {struct{ x uint16 }{}, "uint16"},
69 {struct{ x uint32 }{}, "uint32"},
70 {struct{ x uint64 }{}, "uint64"},
71 {struct{ x float32 }{}, "float32"},
72 {struct{ x float64 }{}, "float64"},
73 {struct{ x int8 }{}, "int8"},
74 {struct{ x (**int8) }{}, "**int8"},
75 {struct{ x (**integer) }{}, "**reflect_test.integer"},
76 {struct{ x ([32]int32) }{}, "[32]int32"},
77 {struct{ x ([]int8) }{}, "[]int8"},
78 {struct{ x (map[string]int32) }{}, "map[string]int32"},
79 {struct{ x (chan<- string) }{}, "chan<- string"},
80 {struct{ x (chan<- chan string) }{}, "chan<- 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)"},
90 "struct { c chan *int32; d float32 }",
92 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
95 c func(chan *integer, *int8)
98 "struct { c func(chan *reflect_test.integer, *int8) }",
106 "struct { a int8; b int32 }",
115 "struct { a int8; b int8; c int32 }",
125 "struct { a int8; b int8; c int8; d int32 }",
136 "struct { a int8; b int8; c int8; d int8; e int32 }",
148 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
152 a int8 `reflect:"hi there"`
155 `struct { a int8 "reflect:\"hi there\"" }`,
159 a int8 `reflect:"hi \x00there\t\n\"\\"`
162 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
169 "struct { f func(...int) }",
173 a(func(func(int) int) func(func(int)) int)
177 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
185 "struct { int32; int64 }",
189 var valueTests = []pair{
200 {new(float32), "256.25"},
201 {new(float64), "512.125"},
202 {new(complex64), "532.125+10i"},
203 {new(complex128), "564.25+1i"},
204 {new(string), "stringy cheese"},
206 {new(*int8), "*int8(0)"},
207 {new(**int8), "**int8(0)"},
208 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
209 {new(**integer), "**reflect_test.integer(0)"},
210 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
211 {new(chan<- string), "chan<- string"},
212 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
217 "struct { c chan *int32; d float32 }{chan *int32, 0}",
219 {new(struct{ c func(chan *integer, *int8) }),
220 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
226 "struct { a int8; b int32 }{0, 0}",
233 "struct { a int8; b int8; c int32 }{0, 0, 0}",
237 func testType(t *testing.T, i int, typ Type, want string) {
240 t.Errorf("#%d: have %#q, want %#q", i, s, want)
244 func TestTypes(t *testing.T) {
245 for i, tt := range typeTests {
246 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
250 func TestSet(t *testing.T) {
251 for i, tt := range valueTests {
280 v.SetComplex(532.125 + 10i)
282 v.SetComplex(564.25 + 1i)
284 v.SetString("stringy cheese")
288 s := valueToString(v)
290 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
295 func TestSetValue(t *testing.T) {
296 for i, tt := range valueTests {
297 v := ValueOf(tt.i).Elem()
300 v.Set(ValueOf(int(132)))
302 v.Set(ValueOf(int8(8)))
304 v.Set(ValueOf(int16(16)))
306 v.Set(ValueOf(int32(32)))
308 v.Set(ValueOf(int64(64)))
310 v.Set(ValueOf(uint(132)))
312 v.Set(ValueOf(uint8(8)))
314 v.Set(ValueOf(uint16(16)))
316 v.Set(ValueOf(uint32(32)))
318 v.Set(ValueOf(uint64(64)))
320 v.Set(ValueOf(float32(256.25)))
322 v.Set(ValueOf(512.125))
324 v.Set(ValueOf(complex64(532.125 + 10i)))
326 v.Set(ValueOf(complex128(564.25 + 1i)))
328 v.Set(ValueOf("stringy cheese"))
332 s := valueToString(v)
334 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
339 func TestCanSetField(t *testing.T) {
340 type embed struct{ x, X int }
341 type Embed struct{ x, X int }
359 type testCase struct {
360 // -1 means Addr().Elem() of current value
371 {[]int{0, -1}, false},
372 {[]int{0, 0}, false},
373 {[]int{0, 0, -1}, false},
374 {[]int{0, -1, 0}, false},
375 {[]int{0, -1, 0, -1}, false},
377 {[]int{0, 1, -1}, true},
378 {[]int{0, -1, 1}, true},
379 {[]int{0, -1, 1, -1}, true},
381 {[]int{1, -1}, false},
383 {[]int{2, -1}, true},
386 val: ValueOf(&S2{embed: &embed{}}),
389 {[]int{0, -1}, false},
390 {[]int{0, 0}, false},
391 {[]int{0, 0, -1}, false},
392 {[]int{0, -1, 0}, false},
393 {[]int{0, -1, 0, -1}, false},
395 {[]int{0, 1, -1}, true},
396 {[]int{0, -1, 1}, true},
397 {[]int{0, -1, 1, -1}, true},
405 {[]int{0, -1}, true},
406 {[]int{0, 0}, false},
407 {[]int{0, 0, -1}, false},
408 {[]int{0, -1, 0}, false},
409 {[]int{0, -1, 0, -1}, false},
411 {[]int{0, 1, -1}, true},
412 {[]int{0, -1, 1}, true},
413 {[]int{0, -1, 1, -1}, true},
418 val: ValueOf(&S4{Embed: &Embed{}}),
421 {[]int{0, -1}, true},
422 {[]int{0, 0}, false},
423 {[]int{0, 0, -1}, false},
424 {[]int{0, -1, 0}, false},
425 {[]int{0, -1, 0, -1}, false},
427 {[]int{0, 1, -1}, true},
428 {[]int{0, -1, 1}, true},
429 {[]int{0, -1, 1, -1}, true},
435 for _, tt := range tests {
436 t.Run(tt.val.Type().Name(), func(t *testing.T) {
437 for _, tc := range tt.cases {
439 for _, i := range tc.index {
449 if got := f.CanSet(); got != tc.canSet {
450 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
459 var valueToStringTests = []pair{
464 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
465 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
466 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
467 {&[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})"},
468 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
469 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
472 func TestValueToString(t *testing.T) {
473 for i, test := range valueToStringTests {
474 s := valueToString(ValueOf(test.i))
476 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
481 func TestArrayElemSet(t *testing.T) {
482 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
483 v.Index(4).SetInt(123)
484 s := valueToString(v)
485 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
487 t.Errorf("[10]int: have %#q want %#q", s, want)
490 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
491 v.Index(4).SetInt(123)
493 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
495 t.Errorf("[]int: have %#q want %#q", s, want1)
499 func TestPtrPointTo(t *testing.T) {
503 vi := ValueOf(&i).Elem()
504 vip.Elem().Set(vi.Addr())
506 t.Errorf("got %d, want 1234", *ip)
510 vp := ValueOf(&ip).Elem()
511 vp.Set(Zero(vp.Type()))
513 t.Errorf("got non-nil (%p), want nil", ip)
517 func TestPtrSetNil(t *testing.T) {
521 vip.Elem().Set(Zero(vip.Elem().Type()))
523 t.Errorf("got non-nil (%d), want nil", *ip)
527 func TestMapSetNil(t *testing.T) {
528 m := make(map[string]int)
530 vm.Elem().Set(Zero(vm.Elem().Type()))
532 t.Errorf("got non-nil (%p), want nil", m)
536 func TestAll(t *testing.T) {
537 testType(t, 1, TypeOf((int8)(0)), "int8")
538 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
540 typ := TypeOf((*struct {
544 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
546 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
549 testType(t, 5, f.Type, "chan *int32")
551 f, present := styp.FieldByName("d")
553 t.Errorf("FieldByName says present field is absent")
555 testType(t, 6, f.Type, "float32")
557 f, present = styp.FieldByName("absent")
559 t.Errorf("FieldByName says absent field is present")
562 typ = TypeOf([32]int32{})
563 testType(t, 7, typ, "[32]int32")
564 testType(t, 8, typ.Elem(), "int32")
566 typ = TypeOf((map[string]*int32)(nil))
567 testType(t, 9, typ, "map[string]*int32")
569 testType(t, 10, mtyp.Key(), "string")
570 testType(t, 11, mtyp.Elem(), "*int32")
572 typ = TypeOf((chan<- string)(nil))
573 testType(t, 12, typ, "chan<- string")
574 testType(t, 13, typ.Elem(), "string")
576 // make sure tag strings are not part of element type
577 typ = TypeOf(struct {
578 d []uint32 `reflect:"TAG"`
580 testType(t, 14, typ, "[]uint32")
583 func TestInterfaceGet(t *testing.T) {
588 v1 := ValueOf(&inter)
589 v2 := v1.Elem().Field(0)
590 assert(t, v2.Type().String(), "interface {}")
593 assert(t, v3.Type().String(), "float64")
596 func TestInterfaceValue(t *testing.T) {
601 v1 := ValueOf(&inter)
602 v2 := v1.Elem().Field(0)
603 assert(t, v2.Type().String(), "interface {}")
605 assert(t, v3.Type().String(), "float64")
608 if _, ok := i3.(float64); !ok {
609 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
613 func TestFunctionValue(t *testing.T) {
614 var x interface{} = func() {}
616 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
617 t.Fatalf("TestFunction returned wrong pointer")
619 assert(t, v.Type().String(), "func()")
622 var appendTests = []struct {
625 {make([]int, 2, 4), []int{22}},
626 {make([]int, 2, 4), []int{22, 33, 44}},
629 func sameInts(x, y []int) bool {
630 if len(x) != len(y) {
633 for i, xx := range x {
641 func TestAppend(t *testing.T) {
642 for i, test := range appendTests {
643 origLen, extraLen := len(test.orig), len(test.extra)
644 want := append(test.orig, test.extra...)
645 // Convert extra from []int to []Value.
646 e0 := make([]Value, len(test.extra))
647 for j, e := range test.extra {
650 // Convert extra from []int to *SliceValue.
651 e1 := ValueOf(test.extra)
653 a0 := ValueOf(test.orig)
654 have0 := Append(a0, e0...).Interface().([]int)
655 if !sameInts(have0, want) {
656 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
658 // Check that the orig and extra slices were not modified.
659 if len(test.orig) != origLen {
660 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
662 if len(test.extra) != extraLen {
663 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
666 a1 := ValueOf(test.orig)
667 have1 := AppendSlice(a1, e1).Interface().([]int)
668 if !sameInts(have1, want) {
669 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
671 // Check that the orig and extra slices were not modified.
672 if len(test.orig) != origLen {
673 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
675 if len(test.extra) != extraLen {
676 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
681 func TestCopy(t *testing.T) {
682 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
683 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
684 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
685 for i := 0; i < len(b); i++ {
687 t.Fatalf("b != c before test")
692 aa := ValueOf(&a1).Elem()
693 ab := ValueOf(&b1).Elem()
694 for tocopy := 1; tocopy <= 7; tocopy++ {
698 for i := 0; i < tocopy; i++ {
700 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
701 tocopy, i, a[i], i, b[i])
704 for i := tocopy; i < len(b); i++ {
707 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
708 tocopy, i, a[i], i, b[i], i, c[i])
710 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
711 tocopy, i, b[i], i, c[i])
714 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
720 func TestCopyString(t *testing.T) {
721 t.Run("Slice", func(t *testing.T) {
722 s := bytes.Repeat([]byte{'_'}, 8)
725 n := Copy(val, ValueOf(""))
726 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
727 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
730 n = Copy(val, ValueOf("hello"))
731 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
732 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
735 n = Copy(val, ValueOf("helloworld"))
736 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
737 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
740 t.Run("Array", func(t *testing.T) {
741 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
742 val := ValueOf(&s).Elem()
744 n := Copy(val, ValueOf(""))
745 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
746 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
749 n = Copy(val, ValueOf("hello"))
750 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
751 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
754 n = Copy(val, ValueOf("helloworld"))
755 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
756 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
761 func TestCopyArray(t *testing.T) {
762 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
763 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
765 aa := ValueOf(&a).Elem()
766 ab := ValueOf(&b).Elem()
768 for i := 0; i < len(a); i++ {
770 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
773 for i := len(a); i < len(b); i++ {
775 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
777 t.Logf("elem %d is okay\n", i)
782 func TestBigUnnamedStruct(t *testing.T) {
783 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
785 b1 := v.Interface().(struct {
788 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
789 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
797 func TestBigStruct(t *testing.T) {
798 b := big{1, 2, 3, 4, 5}
800 b1 := v.Interface().(big)
801 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
802 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
813 type DeepEqualTest struct {
818 // Simple functions for DeepEqual tests.
822 fn3 = func() { fn1() } // Not nil.
828 type Loopy interface{}
830 var loop1, loop2 Loop
831 var loopy1, loopy2 Loopy
832 var cycleMap1, cycleMap2, cycleMap3 map[string]interface{}
834 type structWithSelfPtr struct {
846 cycleMap1 = map[string]interface{}{}
847 cycleMap1["cycle"] = cycleMap1
848 cycleMap2 = map[string]interface{}{}
849 cycleMap2["cycle"] = cycleMap2
850 cycleMap3 = map[string]interface{}{}
851 cycleMap3["different"] = cycleMap3
854 var deepEqualTests = []DeepEqualTest{
858 {int32(1), int32(1), true},
860 {float32(0.5), float32(0.5), true},
861 {"hello", "hello", true},
862 {make([]int, 10), make([]int, 10), true},
863 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
864 {Basic{1, 0.5}, Basic{1, 0.5}, true},
865 {error(nil), error(nil), true},
866 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
871 {int32(1), int32(2), false},
873 {float32(0.5), float32(0.6), false},
874 {"hello", "hey", false},
875 {make([]int, 10), make([]int, 11), false},
876 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
877 {Basic{1, 0.5}, Basic{1, 0.6}, false},
878 {Basic{1, 0}, Basic{2, 0}, false},
879 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
880 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
881 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
882 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
887 {[][]int{{1}}, [][]int{{2}}, false},
888 {math.NaN(), math.NaN(), false},
889 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
890 {&[1]float64{math.NaN()}, self{}, true},
891 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
892 {[]float64{math.NaN()}, self{}, true},
893 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
894 {map[float64]float64{math.NaN(): 1}, self{}, true},
895 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
897 // Nil vs empty: not the same.
898 {[]int{}, []int(nil), false},
899 {[]int{}, []int{}, true},
900 {[]int(nil), []int(nil), true},
901 {map[int]int{}, map[int]int(nil), false},
902 {map[int]int{}, map[int]int{}, true},
903 {map[int]int(nil), map[int]int(nil), true},
907 {int32(1), int64(1), false},
908 {0.5, "hello", false},
909 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
910 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
911 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
912 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
915 {&loop1, &loop1, true},
916 {&loop1, &loop2, true},
917 {&loopy1, &loopy1, true},
918 {&loopy1, &loopy2, true},
919 {&cycleMap1, &cycleMap2, true},
920 {&cycleMap1, &cycleMap3, false},
923 func TestDeepEqual(t *testing.T) {
924 for _, test := range deepEqualTests {
925 if test.b == (self{}) {
928 if r := DeepEqual(test.a, test.b); r != test.eq {
929 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
934 func TestTypeOf(t *testing.T) {
935 // Special case for nil
936 if typ := TypeOf(nil); typ != nil {
937 t.Errorf("expected nil type for nil value; got %v", typ)
939 for _, test := range deepEqualTests {
944 typ := TypeOf(test.a)
946 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
951 type Recursive struct {
956 func TestDeepEqualRecursiveStruct(t *testing.T) {
957 a, b := new(Recursive), new(Recursive)
958 *a = Recursive{12, a}
959 *b = Recursive{12, b}
960 if !DeepEqual(a, b) {
961 t.Error("DeepEqual(recursive same) = false, want true")
965 type _Complex struct {
969 d map[float64]float64
972 func TestDeepEqualComplexStruct(t *testing.T) {
973 m := make(map[float64]float64)
974 stra, strb := "hello", "hello"
975 a, b := new(_Complex), new(_Complex)
976 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
977 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
978 if !DeepEqual(a, b) {
979 t.Error("DeepEqual(complex same) = false, want true")
983 func TestDeepEqualComplexStructInequality(t *testing.T) {
984 m := make(map[float64]float64)
985 stra, strb := "hello", "helloo" // Difference is here
986 a, b := new(_Complex), new(_Complex)
987 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
988 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
990 t.Error("DeepEqual(complex different) = true, want false")
998 func TestDeepEqualUnexportedMap(t *testing.T) {
999 // Check that DeepEqual can look at unexported fields.
1000 x1 := UnexpT{map[int]int{1: 2}}
1001 x2 := UnexpT{map[int]int{1: 2}}
1002 if !DeepEqual(&x1, &x2) {
1003 t.Error("DeepEqual(x1, x2) = false, want true")
1006 y1 := UnexpT{map[int]int{2: 3}}
1007 if DeepEqual(&x1, &y1) {
1008 t.Error("DeepEqual(x1, y1) = true, want false")
1012 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
1014 f := s.Type().Field(1)
1015 if f.Offset != offs {
1016 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1020 // Check that structure alignment & offsets viewed through reflect agree with those
1021 // from the compiler itself.
1022 func TestAlignment(t *testing.T) {
1023 type T1inner struct {
1030 type T2inner struct {
1038 x := T1{T1inner{2}, 17}
1039 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1041 x1 := T2{T2inner{2, 3}, 17}
1042 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1045 func Nil(a interface{}, t *testing.T) {
1046 n := ValueOf(a).Field(0)
1048 t.Errorf("%v should be nil", a)
1052 func NotNil(a interface{}, t *testing.T) {
1053 n := ValueOf(a).Field(0)
1055 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1059 func TestIsNil(t *testing.T) {
1060 // These implement IsNil.
1061 // Wrap in extra struct to hide interface type.
1062 doNil := []interface{}{
1064 struct{ x interface{} }{},
1065 struct{ x map[string]int }{},
1066 struct{ x func() bool }{},
1067 struct{ x chan int }{},
1068 struct{ x []string }{},
1069 struct{ x unsafe.Pointer }{},
1071 for _, ts := range doNil {
1072 ty := TypeOf(ts).Field(0).Type
1074 v.IsNil() // panics if not okay to call
1077 // Check the implementations
1089 si.x = make([]int, 10)
1096 ci.x = make(chan int)
1103 mi.x = make(map[int]int)
1114 x func(t *testing.T)
1121 func TestIsZero(t *testing.T) {
1122 for i, tt := range []struct {
1151 {float32(1.2), false},
1153 {float64(1.2), false},
1154 {math.Copysign(0, -1), false},
1155 {complex64(0), true},
1156 {complex64(1.2), false},
1157 {complex128(0), true},
1158 {complex128(1.2), false},
1159 {complex(math.Copysign(0, -1), 0), false},
1160 {complex(0, math.Copysign(0, -1)), false},
1161 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1163 {uintptr(128), false},
1165 {Zero(TypeOf([5]string{})).Interface(), true},
1166 {[5]string{"", "", "", "", ""}, true},
1167 {[5]string{}, true},
1168 {[5]string{"", "", "", "a", ""}, false},
1170 {(chan string)(nil), true},
1171 {make(chan string), false},
1172 {time.After(1), false},
1174 {(func())(nil), true},
1177 {New(TypeOf(new(error)).Elem()).Elem(), true},
1178 {(io.Reader)(strings.NewReader("")), false},
1180 {(map[string]string)(nil), true},
1181 {map[string]string{}, false},
1182 {make(map[string]string), false},
1184 {(*func())(nil), true},
1185 {(*int)(nil), true},
1188 {[]string{}, false},
1189 {([]string)(nil), true},
1190 {make([]string, 0), false},
1193 {"not-zero", false},
1196 {T{123, 456.75, "hello", &_i}, false},
1198 {(unsafe.Pointer)(nil), true},
1199 {(unsafe.Pointer)(new(int)), false},
1202 if v, ok := tt.x.(Value); ok {
1210 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1213 if !Zero(TypeOf(tt.x)).IsZero() {
1214 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1220 if r := recover(); r == nil {
1221 t.Error("should panic for invalid value")
1228 func TestInterfaceExtraction(t *testing.T) {
1234 v := Indirect(ValueOf(&s)).Field(0).Interface()
1235 if v != s.W.(interface{}) {
1236 t.Error("Interface() on interface: ", v, s.W)
1240 func TestNilPtrValueSub(t *testing.T) {
1242 if pv := ValueOf(pi); pv.Elem().IsValid() {
1243 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1247 func TestMap(t *testing.T) {
1248 m := map[string]int{"a": 1, "b": 2}
1250 if n := mv.Len(); n != len(m) {
1251 t.Errorf("Len = %d, want %d", n, len(m))
1253 keys := mv.MapKeys()
1254 newmap := MakeMap(mv.Type())
1255 for k, v := range m {
1256 // Check that returned Keys match keys in range.
1257 // These aren't required to be in the same order.
1259 for _, kv := range keys {
1260 if kv.String() == k {
1266 t.Errorf("Missing key %q", k)
1269 // Check that value lookup is correct.
1270 vv := mv.MapIndex(ValueOf(k))
1271 if vi := vv.Int(); vi != int64(v) {
1272 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1275 // Copy into new map.
1276 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1278 vv := mv.MapIndex(ValueOf("not-present"))
1280 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1283 newm := newmap.Interface().(map[string]int)
1284 if len(newm) != len(m) {
1285 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1288 for k, v := range newm {
1291 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1295 newmap.SetMapIndex(ValueOf("a"), Value{})
1298 t.Errorf("newm[\"a\"] = %d after delete", v)
1301 mv = ValueOf(&m).Elem()
1302 mv.Set(Zero(mv.Type()))
1304 t.Errorf("mv.Set(nil) failed")
1308 func TestNilMap(t *testing.T) {
1309 var m map[string]int
1311 keys := mv.MapKeys()
1313 t.Errorf(">0 keys for nil map: %v", keys)
1316 // Check that value for missing key is zero.
1317 x := mv.MapIndex(ValueOf("hello"))
1318 if x.Kind() != Invalid {
1319 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1322 // Check big value too.
1323 var mbig map[string][10 << 20]byte
1324 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1325 if x.Kind() != Invalid {
1326 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1329 // Test that deletes from a nil map succeed.
1330 mv.SetMapIndex(ValueOf("hi"), Value{})
1333 func TestChan(t *testing.T) {
1334 for loop := 0; loop < 2; loop++ {
1338 // check both ways to allocate channels
1341 c = make(chan int, 1)
1344 cv = MakeChan(TypeOf(c), 1)
1345 c = cv.Interface().(chan int)
1350 if i := <-c; i != 2 {
1351 t.Errorf("reflect Send 2, native recv %d", i)
1356 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1357 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1361 val, ok := cv.TryRecv()
1362 if val.IsValid() || ok {
1363 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1368 val, ok = cv.TryRecv()
1370 t.Errorf("TryRecv on ready chan got nil")
1371 } else if i := val.Int(); i != 4 || !ok {
1372 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1377 ok = cv.TrySend(ValueOf(5))
1380 t.Errorf("TrySend on full chan succeeded: value %d", i)
1384 ok = cv.TrySend(ValueOf(6))
1386 t.Errorf("TrySend on empty chan failed")
1389 t.Errorf("TrySend failed but it did send %d", x)
1393 if i = <-c; i != 6 {
1394 t.Errorf("TrySend 6, recv %d", i)
1401 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1402 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1404 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1405 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1409 // check creation of unbuffered channel
1411 cv := MakeChan(TypeOf(c), 0)
1412 c = cv.Interface().(chan int)
1413 if cv.TrySend(ValueOf(7)) {
1414 t.Errorf("TrySend on sync chan succeeded")
1416 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1417 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1421 cv = MakeChan(TypeOf(c), 10)
1422 c = cv.Interface().(chan int)
1423 for i := 0; i < 3; i++ {
1426 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1427 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1431 // caseInfo describes a single case in a select test.
1432 type caseInfo struct {
1441 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1443 func TestSelect(t *testing.T) {
1444 selectWatch.once.Do(func() { go selectWatcher() })
1448 newop := func(n int, cap int) (ch, val Value) {
1451 c := make(chan int, cap)
1455 c := make(chan string, cap)
1457 val = ValueOf(fmt.Sprint(n))
1462 for n := 0; x.Next(); n++ {
1463 if testing.Short() && n >= 1000 {
1466 if n >= 100000 && !*allselect {
1469 if n%100000 == 0 && testing.Verbose() {
1470 println("TestSelect", n)
1472 var cases []SelectCase
1477 ch, val := newop(len(cases), 1)
1478 cases = append(cases, SelectCase{
1483 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1488 ch, val := newop(len(cases), 1)
1490 cases = append(cases, SelectCase{
1494 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1499 ch, val := newop(len(cases), 0)
1500 cases = append(cases, SelectCase{
1507 f := func() { ch.Recv() }
1508 info = append(info, caseInfo{desc: "blocking send", helper: f})
1510 info = append(info, caseInfo{desc: "blocking send"})
1516 ch, val := newop(len(cases), 0)
1517 cases = append(cases, SelectCase{
1523 f := func() { ch.Send(val) }
1524 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1526 info = append(info, caseInfo{desc: "blocking recv"})
1532 // Maybe include value to send.
1537 cases = append(cases, SelectCase{
1541 info = append(info, caseInfo{desc: "zero Chan send"})
1544 // Zero Chan receive.
1546 cases = append(cases, SelectCase{
1549 info = append(info, caseInfo{desc: "zero Chan recv"})
1554 cases = append(cases, SelectCase{
1556 Chan: ValueOf((chan int)(nil)),
1559 info = append(info, caseInfo{desc: "nil Chan send"})
1564 cases = append(cases, SelectCase{
1566 Chan: ValueOf((chan int)(nil)),
1568 info = append(info, caseInfo{desc: "nil Chan recv"})
1571 // closed Chan send.
1573 ch := make(chan int)
1575 cases = append(cases, SelectCase{
1580 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1583 // closed Chan recv.
1585 ch, val := newop(len(cases), 0)
1587 val = Zero(val.Type())
1588 cases = append(cases, SelectCase{
1592 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1595 var helper func() // goroutine to help the select complete
1597 // Add default? Must be last case here, but will permute.
1598 // Add the default if the select would otherwise
1599 // block forever, and maybe add it anyway.
1605 for i, c := range info {
1613 } else if c.helper != nil {
1615 helpers = append(helpers, i)
1618 if !canProceed || x.Maybe() {
1619 cases = append(cases, SelectCase{
1622 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1624 } else if canBlock {
1625 // Select needs to communicate with another goroutine.
1626 cas := &info[helpers[x.Choose(len(helpers))]]
1628 cas.canSelect = true
1632 // Permute cases and case info.
1633 // Doing too much here makes the exhaustive loop
1634 // too exhausting, so just do two swaps.
1635 for loop := 0; loop < 2; loop++ {
1636 i := x.Choose(len(cases))
1637 j := x.Choose(len(cases))
1638 cases[i], cases[j] = cases[j], cases[i]
1639 info[i], info[j] = info[j], info[i]
1643 // We wait before kicking off a goroutine to satisfy a blocked select.
1644 // The pause needs to be big enough to let the select block before
1645 // we run the helper, but if we lose that race once in a while it's okay: the
1646 // select will just proceed immediately. Not a big deal.
1647 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1648 pause := 10 * time.Microsecond
1649 if testing.Short() {
1650 pause = 100 * time.Microsecond
1652 time.AfterFunc(pause, helper)
1656 i, recv, recvOK, panicErr := runSelect(cases, info)
1657 if panicErr != nil && !canPanic {
1658 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1660 if panicErr == nil && canPanic && numCanSelect == 1 {
1661 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1663 if panicErr != nil {
1671 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1673 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1677 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1681 if cases[i].Dir == SelectRecv {
1682 if !recv.IsValid() {
1683 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1685 if !cas.recv.IsValid() {
1686 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1688 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1689 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1690 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1692 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1695 if recv.IsValid() || recvOK {
1696 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1702 func TestSelectMaxCases(t *testing.T) {
1703 var sCases []SelectCase
1704 channel := make(chan int)
1706 for i := 0; i < 65536; i++ {
1707 sCases = append(sCases, SelectCase{
1709 Chan: ValueOf(channel),
1713 _, _, _ = Select(sCases)
1714 sCases = append(sCases, SelectCase{
1716 Chan: ValueOf(channel),
1719 if err := recover(); err != nil {
1720 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1721 t.Fatalf("unexpected error from select call with greater than max supported cases")
1724 t.Fatalf("expected select call to panic with greater than max supported cases")
1728 _, _, _ = Select(sCases)
1731 func TestSelectNop(t *testing.T) {
1732 // "select { default: }" should always return the default case.
1733 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1735 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1739 func BenchmarkSelect(b *testing.B) {
1740 channel := make(chan int)
1742 var cases []SelectCase
1743 for i := 0; i < 8; i++ {
1744 cases = append(cases, SelectCase{
1746 Chan: ValueOf(channel),
1749 for _, numCases := range []int{1, 4, 8} {
1750 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1752 for i := 0; i < b.N; i++ {
1753 _, _, _ = Select(cases[:numCases])
1759 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1760 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1761 // an error describing the select and panics the entire test binary.
1762 var selectWatch struct {
1769 func selectWatcher() {
1771 time.Sleep(1 * time.Second)
1773 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1774 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1775 panic("select stuck")
1777 selectWatch.Unlock()
1781 // runSelect runs a single select test.
1782 // It returns the values returned by Select but also returns
1783 // a panic value if the Select panics.
1784 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1786 panicErr = recover()
1789 selectWatch.info = nil
1790 selectWatch.Unlock()
1794 selectWatch.now = time.Now()
1795 selectWatch.info = info
1796 selectWatch.Unlock()
1798 chosen, recv, recvOK = Select(cases)
1802 // fmtSelect formats the information about a single select test.
1803 func fmtSelect(info []caseInfo) string {
1804 var buf bytes.Buffer
1805 fmt.Fprintf(&buf, "\nselect {\n")
1806 for i, cas := range info {
1807 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1808 if cas.recv.IsValid() {
1809 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1812 fmt.Fprintf(&buf, " canselect")
1815 fmt.Fprintf(&buf, " panic")
1817 fmt.Fprintf(&buf, "\n")
1819 fmt.Fprintf(&buf, "}")
1825 // Difficult test for function call because of
1826 // implicit padding between arguments.
1827 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) {
1828 return b, c, d, e, f, g, h
1831 func TestFunc(t *testing.T) {
1832 ret := ValueOf(dummy).Call([]Value{
1836 ValueOf(two{40, 50}),
1838 ValueOf(float32(70)),
1842 t.Fatalf("Call returned %d values, want 7", len(ret))
1845 i := byte(ret[0].Uint())
1846 j := int(ret[1].Int())
1847 k := byte(ret[2].Uint())
1848 l := ret[3].Interface().(two)
1849 m := byte(ret[4].Uint())
1850 n := float32(ret[5].Float())
1851 o := byte(ret[6].Uint())
1853 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1854 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)
1857 for i, v := range ret {
1859 t.Errorf("result %d is addressable", i)
1864 func TestCallConvert(t *testing.T) {
1865 v := ValueOf(new(io.ReadWriter)).Elem()
1866 f := ValueOf(func(r io.Reader) io.Reader { return r })
1867 out := f.Call([]Value{v})
1868 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
1869 t.Errorf("expected [nil], got %v", out)
1873 type emptyStruct struct{}
1875 type nonEmptyStruct struct {
1879 func returnEmpty() emptyStruct {
1880 return emptyStruct{}
1883 func takesEmpty(e emptyStruct) {
1886 func returnNonEmpty(i int) nonEmptyStruct {
1887 return nonEmptyStruct{member: i}
1890 func takesNonEmpty(n nonEmptyStruct) int {
1894 func TestCallWithStruct(t *testing.T) {
1895 r := ValueOf(returnEmpty).Call(nil)
1896 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1897 t.Errorf("returning empty struct returned %#v instead", r)
1899 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1901 t.Errorf("takesEmpty returned values: %#v", r)
1903 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1904 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1905 t.Errorf("returnNonEmpty returned %#v", r)
1907 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1908 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1909 t.Errorf("takesNonEmpty returned %#v", r)
1913 func TestCallReturnsEmpty(t *testing.T) {
1914 // Issue 21717: past-the-end pointer write in Call with
1915 // nonzero-sized frame and zero-sized return value.
1917 var finalized uint32
1918 f := func() (emptyStruct, *[2]int64) {
1919 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
1920 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
1921 return emptyStruct{}, i
1923 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
1924 timeout := time.After(5 * time.Second)
1925 for atomic.LoadUint32(&finalized) == 0 {
1928 t.Fatal("finalizer did not run")
1934 runtime.KeepAlive(v)
1937 func BenchmarkCall(b *testing.B) {
1938 fv := ValueOf(func(a, b string) {})
1940 b.RunParallel(func(pb *testing.PB) {
1941 args := []Value{ValueOf("a"), ValueOf("b")}
1950 func (i *myint) inc() {
1954 func BenchmarkCallMethod(b *testing.B) {
1959 for i := 0; i < b.N; i++ {
1964 func BenchmarkCallArgCopy(b *testing.B) {
1965 byteArray := func(n int) Value {
1966 return Zero(ArrayOf(n, TypeOf(byte(0))))
1968 sizes := [...]struct {
1972 {ValueOf(func(a [128]byte) {}), byteArray(128)},
1973 {ValueOf(func(a [256]byte) {}), byteArray(256)},
1974 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
1975 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
1976 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
1978 for _, size := range sizes {
1979 bench := func(b *testing.B) {
1980 args := []Value{size.arg}
1981 b.SetBytes(int64(size.arg.Len()))
1983 b.RunParallel(func(pb *testing.PB) {
1989 name := fmt.Sprintf("size=%v", size.arg.Len())
1994 func TestMakeFunc(t *testing.T) {
1996 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1997 ValueOf(&f).Elem().Set(fv)
1999 // Call g with small arguments so that there is
2000 // something predictable (and different from the
2001 // correct results) in those positions on the stack.
2003 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2005 // Call constructed function f.
2006 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2007 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2008 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)
2012 func TestMakeFuncInterface(t *testing.T) {
2013 fn := func(i int) int { return i }
2014 incr := func(in []Value) []Value {
2015 return []Value{ValueOf(int(in[0].Int() + 1))}
2017 fv := MakeFunc(TypeOf(fn), incr)
2018 ValueOf(&fn).Elem().Set(fv)
2019 if r := fn(2); r != 3 {
2020 t.Errorf("Call returned %d, want 3", r)
2022 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2023 t.Errorf("Call returned %d, want 15", r)
2025 if r := fv.Interface().(func(int) int)(26); r != 27 {
2026 t.Errorf("Call returned %d, want 27", r)
2030 func TestMakeFuncVariadic(t *testing.T) {
2031 // Test that variadic arguments are packed into a slice and passed as last arg
2032 fn := func(_ int, is ...int) []int { return nil }
2033 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2034 ValueOf(&fn).Elem().Set(fv)
2037 if r[0] != 2 || r[1] != 3 {
2038 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2041 r = fn(1, []int{2, 3}...)
2042 if r[0] != 2 || r[1] != 3 {
2043 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2046 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2047 if r[0] != 2 || r[1] != 3 {
2048 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2051 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2052 if r[0] != 2 || r[1] != 3 {
2053 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2056 f := fv.Interface().(func(int, ...int) []int)
2059 if r[0] != 2 || r[1] != 3 {
2060 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2062 r = f(1, []int{2, 3}...)
2063 if r[0] != 2 || r[1] != 3 {
2064 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2068 // Dummy type that implements io.WriteCloser
2072 func (w *WC) Write(p []byte) (n int, err error) {
2075 func (w *WC) Close() error {
2079 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2080 // reflect.Values returned from the wrapped function should be assignment-converted
2081 // to the types returned by the result of MakeFunc.
2083 // Concrete types should be promotable to interfaces they implement.
2085 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2086 return []Value{ValueOf(io.EOF)}
2087 }).Interface().(func() error)
2090 // Super-interfaces should be promotable to simpler interfaces.
2091 var g func() io.Writer
2092 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2093 var w io.WriteCloser = &WC{}
2094 return []Value{ValueOf(&w).Elem()}
2095 }).Interface().(func() io.Writer)
2098 // Channels should be promotable to directional channels.
2099 var h func() <-chan int
2100 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2101 return []Value{ValueOf(make(chan int))}
2102 }).Interface().(func() <-chan int)
2105 // Unnamed types should be promotable to named types.
2106 type T struct{ a, b, c int }
2108 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2109 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2110 }).Interface().(func() T)
2114 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2115 // Type doesn't implement the required interface.
2116 shouldPanic("", func() {
2118 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2119 return []Value{ValueOf(int(7))}
2120 }).Interface().(func() error)
2123 // Assigning to an interface with additional methods.
2124 shouldPanic("", func() {
2125 var f func() io.ReadWriteCloser
2126 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2127 var w io.WriteCloser = &WC{}
2128 return []Value{ValueOf(&w).Elem()}
2129 }).Interface().(func() io.ReadWriteCloser)
2132 // Directional channels can't be assigned to bidirectional ones.
2133 shouldPanic("", func() {
2134 var f func() chan int
2135 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2136 var c <-chan int = make(chan int)
2137 return []Value{ValueOf(c)}
2138 }).Interface().(func() chan int)
2141 // Two named types which are otherwise identical.
2142 shouldPanic("", func() {
2143 type T struct{ a, b, c int }
2144 type U struct{ a, b, c int }
2146 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2147 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2148 }).Interface().(func() T)
2157 // This will be index 0.
2158 func (p Point) AnotherMethod(scale int) int {
2162 // This will be index 1.
2163 func (p Point) Dist(scale int) int {
2164 //println("Point.Dist", p.x, p.y, scale)
2165 return p.x*p.x*scale + p.y*p.y*scale
2168 // This will be index 2.
2169 func (p Point) GCMethod(k int) int {
2174 // This will be index 3.
2175 func (p Point) NoArgs() {
2176 // Exercise no-argument/no-result paths.
2179 // This will be index 4.
2180 func (p Point) TotalDist(points ...Point) int {
2182 for _, q := range points {
2185 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2191 // This will be index 5.
2192 func (p *Point) Int64Method(x int64) int64 {
2196 // This will be index 6.
2197 func (p *Point) Int32Method(x int32) int32 {
2201 func TestMethod(t *testing.T) {
2202 // Non-curried method of type.
2204 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2206 t.Errorf("Type Method returned %d; want 250", i)
2209 m, ok := TypeOf(p).MethodByName("Dist")
2211 t.Fatalf("method by name failed")
2213 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2215 t.Errorf("Type MethodByName returned %d; want 275", i)
2218 m, ok = TypeOf(p).MethodByName("NoArgs")
2220 t.Fatalf("method by name failed")
2222 n := len(m.Func.Call([]Value{ValueOf(p)}))
2224 t.Errorf("NoArgs returned %d values; want 0", n)
2227 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2229 t.Errorf("Pointer Type Method returned %d; want 300", i)
2232 m, ok = TypeOf(&p).MethodByName("Dist")
2234 t.Fatalf("ptr method by name failed")
2236 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2238 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2241 m, ok = TypeOf(&p).MethodByName("NoArgs")
2243 t.Fatalf("method by name failed")
2245 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2247 t.Errorf("NoArgs returned %d values; want 0", n)
2250 // Curried method of value.
2251 tfunc := TypeOf((func(int) int)(nil))
2252 v := ValueOf(p).Method(1)
2253 if tt := v.Type(); tt != tfunc {
2254 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2256 i = v.Call([]Value{ValueOf(14)})[0].Int()
2258 t.Errorf("Value Method returned %d; want 350", i)
2260 v = ValueOf(p).MethodByName("Dist")
2261 if tt := v.Type(); tt != tfunc {
2262 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2264 i = v.Call([]Value{ValueOf(15)})[0].Int()
2266 t.Errorf("Value MethodByName returned %d; want 375", i)
2268 v = ValueOf(p).MethodByName("NoArgs")
2271 // Curried method of pointer.
2272 v = ValueOf(&p).Method(1)
2273 if tt := v.Type(); tt != tfunc {
2274 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2276 i = v.Call([]Value{ValueOf(16)})[0].Int()
2278 t.Errorf("Pointer Value Method returned %d; want 400", i)
2280 v = ValueOf(&p).MethodByName("Dist")
2281 if tt := v.Type(); tt != tfunc {
2282 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2284 i = v.Call([]Value{ValueOf(17)})[0].Int()
2286 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2288 v = ValueOf(&p).MethodByName("NoArgs")
2291 // Curried method of interface value.
2292 // Have to wrap interface value in a struct to get at it.
2293 // Passing it to ValueOf directly would
2294 // access the underlying Point, not the interface.
2298 pv := ValueOf(&x).Elem()
2300 if tt := v.Type(); tt != tfunc {
2301 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2303 i = v.Call([]Value{ValueOf(18)})[0].Int()
2305 t.Errorf("Interface Method returned %d; want 450", i)
2307 v = pv.MethodByName("Dist")
2308 if tt := v.Type(); tt != tfunc {
2309 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2311 i = v.Call([]Value{ValueOf(19)})[0].Int()
2313 t.Errorf("Interface MethodByName returned %d; want 475", i)
2317 func TestMethodValue(t *testing.T) {
2321 // Curried method of value.
2322 tfunc := TypeOf((func(int) int)(nil))
2323 v := ValueOf(p).Method(1)
2324 if tt := v.Type(); tt != tfunc {
2325 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2327 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2329 t.Errorf("Value Method returned %d; want 250", i)
2331 v = ValueOf(p).MethodByName("Dist")
2332 if tt := v.Type(); tt != tfunc {
2333 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2335 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2337 t.Errorf("Value MethodByName returned %d; want 275", i)
2339 v = ValueOf(p).MethodByName("NoArgs")
2340 ValueOf(v.Interface()).Call(nil)
2341 v.Interface().(func())()
2343 // Curried method of pointer.
2344 v = ValueOf(&p).Method(1)
2345 if tt := v.Type(); tt != tfunc {
2346 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2348 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2350 t.Errorf("Pointer Value Method returned %d; want 300", i)
2352 v = ValueOf(&p).MethodByName("Dist")
2353 if tt := v.Type(); tt != tfunc {
2354 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2356 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2358 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2360 v = ValueOf(&p).MethodByName("NoArgs")
2361 ValueOf(v.Interface()).Call(nil)
2362 v.Interface().(func())()
2364 // Curried method of pointer to pointer.
2366 v = ValueOf(&pp).Elem().Method(1)
2367 if tt := v.Type(); tt != tfunc {
2368 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2370 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2372 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2374 v = ValueOf(&pp).Elem().MethodByName("Dist")
2375 if tt := v.Type(); tt != tfunc {
2376 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2378 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2380 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2383 // Curried method of interface value.
2384 // Have to wrap interface value in a struct to get at it.
2385 // Passing it to ValueOf directly would
2386 // access the underlying Point, not the interface.
2392 pv := ValueOf(s).Field(0)
2394 if tt := v.Type(); tt != tfunc {
2395 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2397 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2399 t.Errorf("Interface Method returned %d; want 400", i)
2401 v = pv.MethodByName("Dist")
2402 if tt := v.Type(); tt != tfunc {
2403 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2405 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2407 t.Errorf("Interface MethodByName returned %d; want 425", i)
2410 // For issue #33628: method args are not stored at the right offset
2412 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2413 if x := m64(123); x != 123 {
2414 t.Errorf("Int64Method returned %d; want 123", x)
2416 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2417 if x := m32(456); x != 456 {
2418 t.Errorf("Int32Method returned %d; want 456", x)
2422 func TestVariadicMethodValue(t *testing.T) {
2424 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2425 want := int64(p.TotalDist(points[0], points[1], points[2]))
2427 // Variadic method of type.
2428 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2429 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2430 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2433 // Curried method of value.
2434 tfunc = TypeOf((func(...Point) int)(nil))
2435 v := ValueOf(p).Method(4)
2436 if tt := v.Type(); tt != tfunc {
2437 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2439 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2441 t.Errorf("Variadic Method returned %d; want %d", i, want)
2443 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2445 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2448 f := v.Interface().(func(...Point) int)
2449 i = int64(f(points[0], points[1], points[2]))
2451 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2453 i = int64(f(points...))
2455 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2459 type DirectIfaceT struct {
2463 func (d DirectIfaceT) M() int { return *d.p }
2465 func TestDirectIfaceMethod(t *testing.T) {
2467 v := DirectIfaceT{&x}
2469 m, ok := typ.MethodByName("M")
2471 t.Fatalf("cannot find method M")
2473 in := []Value{ValueOf(v)}
2474 out := m.Func.Call(in)
2475 if got := out[0].Int(); got != 42 {
2476 t.Errorf("Call with value receiver got %d, want 42", got)
2481 m, ok = typ.MethodByName("M")
2483 t.Fatalf("cannot find method M")
2485 in = []Value{ValueOf(pv)}
2486 out = m.Func.Call(in)
2487 if got := out[0].Int(); got != 42 {
2488 t.Errorf("Call with pointer receiver got %d, want 42", got)
2492 // Reflect version of $GOROOT/test/method5.go
2494 // Concrete types implementing M method.
2495 // Smaller than a word, word-sized, larger than a word.
2496 // Value and pointer receivers.
2498 type Tinter interface {
2499 M(int, byte) (byte, int)
2504 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2508 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2512 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2516 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2518 type Tbigv [2]uintptr
2520 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2522 type Tbigp [2]uintptr
2524 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2526 type tinter interface {
2527 m(int, byte) (byte, int)
2530 // Embedding via pointer.
2547 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2549 func TestMethod5(t *testing.T) {
2550 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2552 if b != 99 || x != 1000+inc {
2553 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2557 CheckV := func(name string, i Value, inc int) {
2558 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2559 b := bx[0].Interface()
2560 x := bx[1].Interface()
2561 if b != byte(99) || x != 1000+inc {
2562 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2565 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2568 var TinterType = TypeOf(new(Tinter)).Elem()
2570 CheckI := func(name string, i interface{}, inc int) {
2572 CheckV(name, v, inc)
2573 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2578 CheckI("&sv", &sv, 1)
2581 CheckI("&sp", &sp, 2)
2585 CheckI("&wv", &wv, 3)
2588 CheckI("&wp", &wp, 4)
2590 bv := Tbigv([2]uintptr{5, 6})
2591 CheckI("bv", bv, 11)
2592 CheckI("&bv", &bv, 11)
2594 bp := Tbigp([2]uintptr{7, 8})
2595 CheckI("&bp", &bp, 15)
2601 CheckI("t4", t4, 40)
2602 CheckI("&t4", &t4, 40)
2603 CheckI("t3", t3, 40)
2604 CheckI("&t3", &t3, 40)
2605 CheckI("t2", t2, 40)
2606 CheckI("&t2", &t2, 40)
2607 CheckI("t1", t1, 40)
2608 CheckI("&t1", &t1, 40)
2611 vnil := ValueOf(&tnil).Elem()
2612 shouldPanic("Method", func() { vnil.Method(0) })
2615 func TestInterfaceSet(t *testing.T) {
2624 sv := ValueOf(&s).Elem()
2625 sv.Field(0).Set(ValueOf(p))
2626 if q := s.I.(*Point); q != p {
2627 t.Errorf("i: have %p want %p", q, p)
2632 if q := s.P.(*Point); q != p {
2633 t.Errorf("i: have %p want %p", q, p)
2636 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2638 t.Errorf("Interface Method returned %d; want 250", i)
2647 func TestAnonymousFields(t *testing.T) {
2648 var field StructField
2652 if field, ok = type1.FieldByName("int"); !ok {
2653 t.Fatal("no field 'int'")
2655 if field.Index[0] != 1 {
2656 t.Error("field index should be 1; is", field.Index)
2710 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2732 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2751 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2765 var fieldTests = []FTest{
2766 {struct{}{}, "", nil, 0},
2767 {struct{}{}, "Foo", nil, 0},
2768 {S0{A: 'a'}, "A", []int{0}, 'a'},
2769 {S0{}, "D", nil, 0},
2770 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2771 {S1{B: 'b'}, "B", []int{0}, 'b'},
2772 {S1{}, "S0", []int{1}, 0},
2773 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2774 {S2{A: 'a'}, "A", []int{0}, 'a'},
2775 {S2{}, "S1", []int{1}, 0},
2776 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2777 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2778 {S2{}, "D", nil, 0},
2779 {S3{}, "S1", nil, 0},
2780 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2781 {S3{}, "B", nil, 0},
2782 {S3{D: 'd'}, "D", []int{2}, 0},
2783 {S3{E: 'e'}, "E", []int{3}, 'e'},
2784 {S4{A: 'a'}, "A", []int{1}, 'a'},
2785 {S4{}, "B", nil, 0},
2786 {S5{}, "X", nil, 0},
2787 {S5{}, "Y", []int{2, 0, 1}, 0},
2788 {S10{}, "X", nil, 0},
2789 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2790 {S14{}, "X", nil, 0},
2793 func TestFieldByIndex(t *testing.T) {
2794 for _, test := range fieldTests {
2796 f := s.FieldByIndex(test.index)
2798 if test.index != nil {
2799 if f.Name != test.name {
2800 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2803 t.Errorf("%s.%s found", s.Name(), f.Name)
2805 } else if len(test.index) > 0 {
2806 t.Errorf("%s.%s not found", s.Name(), test.name)
2809 if test.value != 0 {
2810 v := ValueOf(test.s).FieldByIndex(test.index)
2812 if x, ok := v.Interface().(int); ok {
2813 if x != test.value {
2814 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2817 t.Errorf("%s%v value not an int", s.Name(), test.index)
2820 t.Errorf("%s%v value not found", s.Name(), test.index)
2826 func TestFieldByName(t *testing.T) {
2827 for _, test := range fieldTests {
2829 f, found := s.FieldByName(test.name)
2831 if test.index != nil {
2832 // Verify field depth and index.
2833 if len(f.Index) != len(test.index) {
2834 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)
2836 for i, x := range f.Index {
2837 if x != test.index[i] {
2838 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2843 t.Errorf("%s.%s found", s.Name(), f.Name)
2845 } else if len(test.index) > 0 {
2846 t.Errorf("%s.%s not found", s.Name(), test.name)
2849 if test.value != 0 {
2850 v := ValueOf(test.s).FieldByName(test.name)
2852 if x, ok := v.Interface().(int); ok {
2853 if x != test.value {
2854 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2857 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2860 t.Errorf("%s.%s value not found", s.Name(), test.name)
2866 func TestImportPath(t *testing.T) {
2871 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2872 {TypeOf(int(0)), ""},
2873 {TypeOf(int8(0)), ""},
2874 {TypeOf(int16(0)), ""},
2875 {TypeOf(int32(0)), ""},
2876 {TypeOf(int64(0)), ""},
2877 {TypeOf(uint(0)), ""},
2878 {TypeOf(uint8(0)), ""},
2879 {TypeOf(uint16(0)), ""},
2880 {TypeOf(uint32(0)), ""},
2881 {TypeOf(uint64(0)), ""},
2882 {TypeOf(uintptr(0)), ""},
2883 {TypeOf(float32(0)), ""},
2884 {TypeOf(float64(0)), ""},
2885 {TypeOf(complex64(0)), ""},
2886 {TypeOf(complex128(0)), ""},
2887 {TypeOf(byte(0)), ""},
2888 {TypeOf(rune(0)), ""},
2889 {TypeOf([]byte(nil)), ""},
2890 {TypeOf([]rune(nil)), ""},
2891 {TypeOf(string("")), ""},
2892 {TypeOf((*interface{})(nil)).Elem(), ""},
2893 {TypeOf((*byte)(nil)), ""},
2894 {TypeOf((*rune)(nil)), ""},
2895 {TypeOf((*int64)(nil)), ""},
2896 {TypeOf(map[string]int{}), ""},
2897 {TypeOf((*error)(nil)).Elem(), ""},
2898 {TypeOf((*Point)(nil)), ""},
2899 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
2901 for _, test := range tests {
2902 if path := test.t.PkgPath(); path != test.path {
2903 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2908 func TestFieldPkgPath(t *testing.T) {
2910 typ := TypeOf(struct {
2918 type pkgpathTest struct {
2925 checkPkgPath := func(name string, s []pkgpathTest) {
2926 for _, test := range s {
2927 f := typ.FieldByIndex(test.index)
2928 if got, want := f.PkgPath, test.pkgPath; got != want {
2929 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
2931 if got, want := f.Anonymous, test.embedded; got != want {
2932 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
2934 if got, want := f.IsExported(), test.exported; got != want {
2935 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
2940 checkPkgPath("testStruct", []pkgpathTest{
2941 {[]int{0}, "", false, true}, // Exported
2942 {[]int{1}, "reflect_test", false, false}, // unexported
2943 {[]int{2}, "", true, true}, // OtherPkgFields
2944 {[]int{2, 0}, "", false, true}, // OtherExported
2945 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
2946 {[]int{3}, "reflect_test", true, false}, // int
2947 {[]int{4}, "reflect_test", true, false}, // *x
2950 type localOtherPkgFields OtherPkgFields
2951 typ = TypeOf(localOtherPkgFields{})
2952 checkPkgPath("localOtherPkgFields", []pkgpathTest{
2953 {[]int{0}, "", false, true}, // OtherExported
2954 {[]int{1}, "reflect", false, false}, // otherUnexported
2958 func TestMethodPkgPath(t *testing.T) {
2963 typ := TypeOf((*interface {
2976 {"x", "reflect_test", false},
2977 {"y", "reflect_test", false},
2980 for _, test := range tests {
2981 m, _ := typ.MethodByName(test.name)
2982 if got, want := m.PkgPath, test.pkgPath; got != want {
2983 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
2985 if got, want := m.IsExported(), test.exported; got != want {
2986 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
2991 func TestVariadicType(t *testing.T) {
2992 // Test example from Type documentation.
2993 var f func(x int, y ...float64)
2995 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2997 if sl.Kind() == Slice {
2998 if sl.Elem() == TypeOf(0.0) {
3006 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3007 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3008 for i := 0; i < typ.NumIn(); i++ {
3009 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3023 func (*inner) M() {}
3024 func (*outer) M() {}
3026 func TestNestedMethods(t *testing.T) {
3027 typ := TypeOf((*outer)(nil))
3028 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
3029 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3030 for i := 0; i < typ.NumMethod(); i++ {
3032 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3039 func (*unexp) f() (int32, int8) { return 7, 7 }
3040 func (*unexp) g() (int64, int8) { return 8, 8 }
3042 type unexpI interface {
3046 var unexpi unexpI = new(unexp)
3048 func TestUnexportedMethods(t *testing.T) {
3049 typ := TypeOf(unexpi)
3051 if got := typ.NumMethod(); got != 0 {
3052 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3056 type InnerInt struct {
3060 type OuterInt struct {
3065 func (i *InnerInt) M() int {
3069 func TestEmbeddedMethods(t *testing.T) {
3070 typ := TypeOf((*OuterInt)(nil))
3071 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
3072 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3073 for i := 0; i < typ.NumMethod(); i++ {
3075 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3080 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3081 t.Errorf("i.M() = %d, want 3", v)
3084 o := &OuterInt{1, InnerInt{2}}
3085 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3086 t.Errorf("i.M() = %d, want 2", v)
3090 if v := f(o); v != 2 {
3091 t.Errorf("f(o) = %d, want 2", v)
3095 type FuncDDD func(...interface{}) error
3097 func (f FuncDDD) M() {}
3099 func TestNumMethodOnDDD(t *testing.T) {
3100 rv := ValueOf((FuncDDD)(nil))
3101 if n := rv.NumMethod(); n != 1 {
3102 t.Fatalf("NumMethod()=%d, want 1", n)
3106 func TestPtrTo(t *testing.T) {
3107 // This block of code means that the ptrToThis field of the
3108 // reflect data for *unsafe.Pointer is non zero, see
3109 // https://golang.org/issue/19003
3110 var x unsafe.Pointer
3117 for i = 0; i < 100; i++ {
3120 for i = 0; i < 100; i++ {
3123 if typ != TypeOf(z) {
3124 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
3128 func TestPtrToGC(t *testing.T) {
3130 tt := TypeOf(T(nil))
3134 for i := 0; i < n; i++ {
3139 v.Elem().Set(ValueOf(p).Convert(pt))
3140 x = append(x, v.Interface())
3144 for i, xi := range x {
3145 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3146 if k != uintptr(i) {
3147 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3152 func BenchmarkPtrTo(b *testing.B) {
3153 // Construct a type with a zero ptrToThis.
3154 type T struct{ int }
3155 t := SliceOf(TypeOf(T{}))
3156 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3157 if !ptrToThis.IsValid() {
3158 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3160 if ptrToThis.Int() != 0 {
3161 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3165 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
3167 b.RunParallel(func(pb *testing.PB) {
3174 func TestAddr(t *testing.T) {
3186 t.Errorf("Addr.Elem.Set failed to set value")
3189 // Again but take address of the ValueOf value.
3190 // Exercises generation of PtrTypes not present in the binary.
3192 v = ValueOf(&q).Elem()
3201 t.Errorf("Addr.Elem.Set failed to set value")
3204 // Starting without pointer we should get changed value
3207 v = ValueOf(&qq).Elem()
3213 if p.X != 3 { // should be unchanged from last time
3214 t.Errorf("somehow value Set changed original p")
3216 p = v0.Interface().(struct {
3220 t.Errorf("Addr.Elem.Set valued to set value in top value")
3223 // Verify that taking the address of a type gives us a pointer
3224 // which we can convert back using the usual interface
3229 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3230 *(ps.(**bool)) = new(bool)
3232 t.Errorf("Addr.Interface direct assignment failed")
3236 func noAlloc(t *testing.T, n int, f func(int)) {
3237 if testing.Short() {
3238 t.Skip("skipping malloc count in short mode")
3240 if runtime.GOMAXPROCS(0) > 1 {
3241 t.Skip("skipping; GOMAXPROCS>1")
3244 allocs := testing.AllocsPerRun(n, func() {
3249 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3253 func TestAllocations(t *testing.T) {
3254 noAlloc(t, 100, func(j int) {
3258 // We can uncomment this when compiler escape analysis
3259 // is good enough to see that the integer assigned to i
3260 // does not escape and therefore need not be allocated.
3264 // if int(v.Int()) != 42+j {
3265 // panic("wrong int")
3268 i = func(j int) int { return j }
3270 if v.Interface().(func(int) int)(j) != j {
3271 panic("wrong result")
3276 func TestSmallNegativeInt(t *testing.T) {
3280 t.Errorf("int16(-1).Int() returned %v", v.Int())
3284 func TestIndex(t *testing.T) {
3285 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3286 v := ValueOf(xs).Index(3).Interface().(byte)
3288 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3290 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3291 v = ValueOf(xa).Index(2).Interface().(byte)
3293 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3296 v = ValueOf(s).Index(3).Interface().(byte)
3298 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3302 func TestSlice(t *testing.T) {
3303 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3304 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3306 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3309 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3311 if !DeepEqual(v[0:5], xs[3:]) {
3312 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3314 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3315 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3317 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3320 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3322 if !DeepEqual(v[0:6], xa[2:]) {
3323 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3326 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3328 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3331 rv := ValueOf(&xs).Elem()
3333 ptr2 := rv.Pointer()
3335 ptr3 := rv.Pointer()
3337 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
3341 func TestSlice3(t *testing.T) {
3342 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3343 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3345 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3348 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3350 if !DeepEqual(v[0:4], xs[3:7:7]) {
3351 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3353 rv := ValueOf(&xs).Elem()
3354 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3355 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3356 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3358 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3359 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3361 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3364 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3366 if !DeepEqual(v[0:4], xa[2:6:6]) {
3367 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3369 rv = ValueOf(&xa).Elem()
3370 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3371 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3372 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3375 rv = ValueOf(&s).Elem()
3376 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3378 rv = ValueOf(&xs).Elem()
3379 rv = rv.Slice3(3, 5, 7)
3380 ptr2 := rv.Pointer()
3381 rv = rv.Slice3(4, 4, 4)
3382 ptr3 := rv.Pointer()
3384 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
3388 func TestSetLenCap(t *testing.T) {
3389 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3390 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3392 vs := ValueOf(&xs).Elem()
3393 shouldPanic("SetLen", func() { vs.SetLen(10) })
3394 shouldPanic("SetCap", func() { vs.SetCap(10) })
3395 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3396 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3397 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3399 if len(xs) != 5 || cap(xs) != 8 {
3400 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3403 if len(xs) != 5 || cap(xs) != 6 {
3404 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3407 if len(xs) != 5 || cap(xs) != 5 {
3408 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3410 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3411 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3413 va := ValueOf(&xa).Elem()
3414 shouldPanic("SetLen", func() { va.SetLen(8) })
3415 shouldPanic("SetCap", func() { va.SetCap(8) })
3418 func TestVariadic(t *testing.T) {
3423 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3424 if b.String() != "hello, 42 world" {
3425 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3429 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3430 if b.String() != "hello, 42 world" {
3431 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3435 func TestFuncArg(t *testing.T) {
3436 f1 := func(i int, f func(int) int) int { return f(i) }
3437 f2 := func(i int) int { return i + 1 }
3438 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3439 if r[0].Int() != 101 {
3440 t.Errorf("function returned %d, want 101", r[0].Int())
3444 func TestStructArg(t *testing.T) {
3445 type padded struct {
3452 wantA = padded{"3", 4}
3455 f := func(a padded, b uint32) {
3458 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3459 if gotA != wantA || gotB != wantB {
3460 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3464 var tagGetTests = []struct {
3469 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3470 {`protobuf:"PB(1,2)"`, `foo`, ``},
3471 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3472 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3473 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3474 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3475 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3478 func TestTagGet(t *testing.T) {
3479 for _, tt := range tagGetTests {
3480 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3481 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3486 func TestBytes(t *testing.T) {
3489 y := ValueOf(x).Bytes()
3490 if !bytes.Equal(x, y) {
3491 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3494 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3498 func TestSetBytes(t *testing.T) {
3501 y := []byte{1, 2, 3, 4}
3502 ValueOf(&x).Elem().SetBytes(y)
3503 if !bytes.Equal(x, y) {
3504 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3507 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3511 type Private struct {
3517 func (p *Private) m() {
3520 type private struct {
3528 func (p *private) P() {
3531 type Public struct {
3537 func (p *Public) M() {
3540 func TestUnexported(t *testing.T) {
3545 isValid(v.Elem().Field(0))
3546 isValid(v.Elem().Field(1))
3547 isValid(v.Elem().Field(2))
3548 isValid(v.Elem().FieldByName("X"))
3549 isValid(v.Elem().FieldByName("Y"))
3550 isValid(v.Elem().FieldByName("Z"))
3551 isValid(v.Type().Method(0).Func)
3552 m, _ := v.Type().MethodByName("M")
3554 m, _ = v.Type().MethodByName("P")
3556 isNonNil(v.Elem().Field(0).Interface())
3557 isNonNil(v.Elem().Field(1).Interface())
3558 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3559 isNonNil(v.Elem().FieldByName("X").Interface())
3560 isNonNil(v.Elem().FieldByName("Y").Interface())
3561 isNonNil(v.Elem().FieldByName("Z").Interface())
3562 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3563 isNonNil(v.Type().Method(0).Func.Interface())
3564 m, _ = v.Type().MethodByName("P")
3565 isNonNil(m.Func.Interface())
3569 isValid(v.Elem().Field(0))
3570 isValid(v.Elem().Field(1))
3571 isValid(v.Elem().FieldByName("x"))
3572 isValid(v.Elem().FieldByName("y"))
3573 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3574 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3575 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3576 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3577 shouldPanic("Method", func() { v.Type().Method(0) })
3580 func TestSetPanic(t *testing.T) {
3581 ok := func(f func()) { f() }
3582 bad := func(f func()) { shouldPanic("Set", f) }
3583 clear := func(v Value) { v.Set(Zero(v.Type())) }
3611 bad(func() { clear(v.Field(0)) }) // .X
3612 bad(func() { clear(v.Field(1)) }) // .t1
3613 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3614 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3615 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3616 bad(func() { clear(v.Field(2)) }) // .T2
3617 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3618 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3619 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3620 bad(func() { clear(v.Field(3)) }) // .NamedT1
3621 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3622 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3623 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3624 bad(func() { clear(v.Field(4)) }) // .NamedT2
3625 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3626 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3627 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3628 bad(func() { clear(v.Field(5)) }) // .namedT1
3629 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3630 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3631 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3632 bad(func() { clear(v.Field(6)) }) // .namedT2
3633 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3634 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3635 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3638 v = ValueOf(&T{}).Elem()
3639 ok(func() { clear(v.Field(0)) }) // .X
3640 bad(func() { clear(v.Field(1)) }) // .t1
3641 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3642 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3643 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3644 ok(func() { clear(v.Field(2)) }) // .T2
3645 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3646 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3647 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3648 ok(func() { clear(v.Field(3)) }) // .NamedT1
3649 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3650 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3651 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3652 ok(func() { clear(v.Field(4)) }) // .NamedT2
3653 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3654 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3655 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3656 bad(func() { clear(v.Field(5)) }) // .namedT1
3657 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3658 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3659 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3660 bad(func() { clear(v.Field(6)) }) // .namedT2
3661 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3662 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3663 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3668 func (t timp) W() {}
3669 func (t timp) Y() {}
3670 func (t timp) w() {}
3671 func (t timp) y() {}
3673 func TestCallPanic(t *testing.T) {
3698 ok := func(f func()) { f() }
3699 badCall := func(f func()) { shouldPanic("Call", f) }
3700 badMethod := func(f func()) { shouldPanic("Method", f) }
3701 call := func(v Value) { v.Call(nil) }
3704 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3705 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3706 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3707 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3708 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3709 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3710 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3711 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3712 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3714 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3715 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3716 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3717 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3719 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3720 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3721 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3722 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3724 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3725 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3726 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3727 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3729 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3730 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3731 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3732 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3734 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3735 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3736 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3737 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3739 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3740 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3741 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3742 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3745 func shouldPanic(expect string, f func()) {
3749 panic("did not panic")
3753 switch r := r.(type) {
3759 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3761 if !strings.HasPrefix(s, "reflect") {
3762 panic(`panic string does not start with "reflect": ` + s)
3764 if !strings.Contains(s, expect) {
3765 panic(`panic string does not contain "` + expect + `": ` + s)
3772 func isNonNil(x interface{}) {
3774 panic("nil interface")
3778 func isValid(v Value) {
3784 func TestAlias(t *testing.T) {
3785 x := string("hello")
3786 v := ValueOf(&x).Elem()
3787 oldvalue := v.Interface()
3788 v.SetString("world")
3789 newvalue := v.Interface()
3791 if oldvalue != "hello" || newvalue != "world" {
3792 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3798 func EmptyInterfaceV(x interface{}) Value {
3799 return ValueOf(&x).Elem()
3802 func ReaderV(x io.Reader) Value {
3803 return ValueOf(&x).Elem()
3806 func ReadWriterV(x io.ReadWriter) Value {
3807 return ValueOf(&x).Elem()
3811 type MyStruct struct {
3814 type MyStruct1 struct {
3819 type MyStruct2 struct {
3824 type MyString string
3826 type MyBytesArrayPtr0 *[0]byte
3827 type MyBytesArrayPtr *[4]byte
3828 type MyBytesArray0 [0]byte
3829 type MyBytesArray [4]byte
3830 type MyRunes []int32
3834 type IntChan chan int
3835 type IntChanRecv <-chan int
3836 type IntChanSend chan<- int
3837 type BytesChan chan []byte
3838 type BytesChanRecv <-chan []byte
3839 type BytesChanSend chan<- []byte
3841 var convertTests = []struct {
3847 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3853 var numbers = []string{
3854 "int8", "uint8", "int16", "uint16",
3855 "int32", "uint32", "int64", "uint64",
3856 "int", "uint", "uintptr",
3857 "float32", "float64",
3861 // all pairs but in an unusual order,
3862 // to emit all the int8, uint8 cases
3863 // before n grows too big.
3865 for i, f := range numbers {
3866 for _, g := range numbers[i:] {
3867 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3870 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3877 {V(int8(1)), V(int8(1))},
3878 {V(int8(2)), V(uint8(2))},
3879 {V(uint8(3)), V(int8(3))},
3880 {V(int8(4)), V(int16(4))},
3881 {V(int16(5)), V(int8(5))},
3882 {V(int8(6)), V(uint16(6))},
3883 {V(uint16(7)), V(int8(7))},
3884 {V(int8(8)), V(int32(8))},
3885 {V(int32(9)), V(int8(9))},
3886 {V(int8(10)), V(uint32(10))},
3887 {V(uint32(11)), V(int8(11))},
3888 {V(int8(12)), V(int64(12))},
3889 {V(int64(13)), V(int8(13))},
3890 {V(int8(14)), V(uint64(14))},
3891 {V(uint64(15)), V(int8(15))},
3892 {V(int8(16)), V(int(16))},
3893 {V(int(17)), V(int8(17))},
3894 {V(int8(18)), V(uint(18))},
3895 {V(uint(19)), V(int8(19))},
3896 {V(int8(20)), V(uintptr(20))},
3897 {V(uintptr(21)), V(int8(21))},
3898 {V(int8(22)), V(float32(22))},
3899 {V(float32(23)), V(int8(23))},
3900 {V(int8(24)), V(float64(24))},
3901 {V(float64(25)), V(int8(25))},
3902 {V(uint8(26)), V(uint8(26))},
3903 {V(uint8(27)), V(int16(27))},
3904 {V(int16(28)), V(uint8(28))},
3905 {V(uint8(29)), V(uint16(29))},
3906 {V(uint16(30)), V(uint8(30))},
3907 {V(uint8(31)), V(int32(31))},
3908 {V(int32(32)), V(uint8(32))},
3909 {V(uint8(33)), V(uint32(33))},
3910 {V(uint32(34)), V(uint8(34))},
3911 {V(uint8(35)), V(int64(35))},
3912 {V(int64(36)), V(uint8(36))},
3913 {V(uint8(37)), V(uint64(37))},
3914 {V(uint64(38)), V(uint8(38))},
3915 {V(uint8(39)), V(int(39))},
3916 {V(int(40)), V(uint8(40))},
3917 {V(uint8(41)), V(uint(41))},
3918 {V(uint(42)), V(uint8(42))},
3919 {V(uint8(43)), V(uintptr(43))},
3920 {V(uintptr(44)), V(uint8(44))},
3921 {V(uint8(45)), V(float32(45))},
3922 {V(float32(46)), V(uint8(46))},
3923 {V(uint8(47)), V(float64(47))},
3924 {V(float64(48)), V(uint8(48))},
3925 {V(int16(49)), V(int16(49))},
3926 {V(int16(50)), V(uint16(50))},
3927 {V(uint16(51)), V(int16(51))},
3928 {V(int16(52)), V(int32(52))},
3929 {V(int32(53)), V(int16(53))},
3930 {V(int16(54)), V(uint32(54))},
3931 {V(uint32(55)), V(int16(55))},
3932 {V(int16(56)), V(int64(56))},
3933 {V(int64(57)), V(int16(57))},
3934 {V(int16(58)), V(uint64(58))},
3935 {V(uint64(59)), V(int16(59))},
3936 {V(int16(60)), V(int(60))},
3937 {V(int(61)), V(int16(61))},
3938 {V(int16(62)), V(uint(62))},
3939 {V(uint(63)), V(int16(63))},
3940 {V(int16(64)), V(uintptr(64))},
3941 {V(uintptr(65)), V(int16(65))},
3942 {V(int16(66)), V(float32(66))},
3943 {V(float32(67)), V(int16(67))},
3944 {V(int16(68)), V(float64(68))},
3945 {V(float64(69)), V(int16(69))},
3946 {V(uint16(70)), V(uint16(70))},
3947 {V(uint16(71)), V(int32(71))},
3948 {V(int32(72)), V(uint16(72))},
3949 {V(uint16(73)), V(uint32(73))},
3950 {V(uint32(74)), V(uint16(74))},
3951 {V(uint16(75)), V(int64(75))},
3952 {V(int64(76)), V(uint16(76))},
3953 {V(uint16(77)), V(uint64(77))},
3954 {V(uint64(78)), V(uint16(78))},
3955 {V(uint16(79)), V(int(79))},
3956 {V(int(80)), V(uint16(80))},
3957 {V(uint16(81)), V(uint(81))},
3958 {V(uint(82)), V(uint16(82))},
3959 {V(uint16(83)), V(uintptr(83))},
3960 {V(uintptr(84)), V(uint16(84))},
3961 {V(uint16(85)), V(float32(85))},
3962 {V(float32(86)), V(uint16(86))},
3963 {V(uint16(87)), V(float64(87))},
3964 {V(float64(88)), V(uint16(88))},
3965 {V(int32(89)), V(int32(89))},
3966 {V(int32(90)), V(uint32(90))},
3967 {V(uint32(91)), V(int32(91))},
3968 {V(int32(92)), V(int64(92))},
3969 {V(int64(93)), V(int32(93))},
3970 {V(int32(94)), V(uint64(94))},
3971 {V(uint64(95)), V(int32(95))},
3972 {V(int32(96)), V(int(96))},
3973 {V(int(97)), V(int32(97))},
3974 {V(int32(98)), V(uint(98))},
3975 {V(uint(99)), V(int32(99))},
3976 {V(int32(100)), V(uintptr(100))},
3977 {V(uintptr(101)), V(int32(101))},
3978 {V(int32(102)), V(float32(102))},
3979 {V(float32(103)), V(int32(103))},
3980 {V(int32(104)), V(float64(104))},
3981 {V(float64(105)), V(int32(105))},
3982 {V(uint32(106)), V(uint32(106))},
3983 {V(uint32(107)), V(int64(107))},
3984 {V(int64(108)), V(uint32(108))},
3985 {V(uint32(109)), V(uint64(109))},
3986 {V(uint64(110)), V(uint32(110))},
3987 {V(uint32(111)), V(int(111))},
3988 {V(int(112)), V(uint32(112))},
3989 {V(uint32(113)), V(uint(113))},
3990 {V(uint(114)), V(uint32(114))},
3991 {V(uint32(115)), V(uintptr(115))},
3992 {V(uintptr(116)), V(uint32(116))},
3993 {V(uint32(117)), V(float32(117))},
3994 {V(float32(118)), V(uint32(118))},
3995 {V(uint32(119)), V(float64(119))},
3996 {V(float64(120)), V(uint32(120))},
3997 {V(int64(121)), V(int64(121))},
3998 {V(int64(122)), V(uint64(122))},
3999 {V(uint64(123)), V(int64(123))},
4000 {V(int64(124)), V(int(124))},
4001 {V(int(125)), V(int64(125))},
4002 {V(int64(126)), V(uint(126))},
4003 {V(uint(127)), V(int64(127))},
4004 {V(int64(128)), V(uintptr(128))},
4005 {V(uintptr(129)), V(int64(129))},
4006 {V(int64(130)), V(float32(130))},
4007 {V(float32(131)), V(int64(131))},
4008 {V(int64(132)), V(float64(132))},
4009 {V(float64(133)), V(int64(133))},
4010 {V(uint64(134)), V(uint64(134))},
4011 {V(uint64(135)), V(int(135))},
4012 {V(int(136)), V(uint64(136))},
4013 {V(uint64(137)), V(uint(137))},
4014 {V(uint(138)), V(uint64(138))},
4015 {V(uint64(139)), V(uintptr(139))},
4016 {V(uintptr(140)), V(uint64(140))},
4017 {V(uint64(141)), V(float32(141))},
4018 {V(float32(142)), V(uint64(142))},
4019 {V(uint64(143)), V(float64(143))},
4020 {V(float64(144)), V(uint64(144))},
4021 {V(int(145)), V(int(145))},
4022 {V(int(146)), V(uint(146))},
4023 {V(uint(147)), V(int(147))},
4024 {V(int(148)), V(uintptr(148))},
4025 {V(uintptr(149)), V(int(149))},
4026 {V(int(150)), V(float32(150))},
4027 {V(float32(151)), V(int(151))},
4028 {V(int(152)), V(float64(152))},
4029 {V(float64(153)), V(int(153))},
4030 {V(uint(154)), V(uint(154))},
4031 {V(uint(155)), V(uintptr(155))},
4032 {V(uintptr(156)), V(uint(156))},
4033 {V(uint(157)), V(float32(157))},
4034 {V(float32(158)), V(uint(158))},
4035 {V(uint(159)), V(float64(159))},
4036 {V(float64(160)), V(uint(160))},
4037 {V(uintptr(161)), V(uintptr(161))},
4038 {V(uintptr(162)), V(float32(162))},
4039 {V(float32(163)), V(uintptr(163))},
4040 {V(uintptr(164)), V(float64(164))},
4041 {V(float64(165)), V(uintptr(165))},
4042 {V(float32(166)), V(float32(166))},
4043 {V(float32(167)), V(float64(167))},
4044 {V(float64(168)), V(float32(168))},
4045 {V(float64(169)), V(float64(169))},
4048 {V(float64(1.5)), V(int(1))},
4051 {V(complex64(1i)), V(complex64(1i))},
4052 {V(complex64(2i)), V(complex128(2i))},
4053 {V(complex128(3i)), V(complex64(3i))},
4054 {V(complex128(4i)), V(complex128(4i))},
4057 {V(string("hello")), V(string("hello"))},
4058 {V(string("bytes1")), V([]byte("bytes1"))},
4059 {V([]byte("bytes2")), V(string("bytes2"))},
4060 {V([]byte("bytes3")), V([]byte("bytes3"))},
4061 {V(string("runes♝")), V([]rune("runes♝"))},
4062 {V([]rune("runes♕")), V(string("runes♕"))},
4063 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4064 {V(int('a')), V(string("a"))},
4065 {V(int8('a')), V(string("a"))},
4066 {V(int16('a')), V(string("a"))},
4067 {V(int32('a')), V(string("a"))},
4068 {V(int64('a')), V(string("a"))},
4069 {V(uint('a')), V(string("a"))},
4070 {V(uint8('a')), V(string("a"))},
4071 {V(uint16('a')), V(string("a"))},
4072 {V(uint32('a')), V(string("a"))},
4073 {V(uint64('a')), V(string("a"))},
4074 {V(uintptr('a')), V(string("a"))},
4075 {V(int(-1)), V(string("\uFFFD"))},
4076 {V(int8(-2)), V(string("\uFFFD"))},
4077 {V(int16(-3)), V(string("\uFFFD"))},
4078 {V(int32(-4)), V(string("\uFFFD"))},
4079 {V(int64(-5)), V(string("\uFFFD"))},
4080 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4081 {V(int64(1 << 32)), V(string("\uFFFD"))},
4082 {V(uint(0x110001)), V(string("\uFFFD"))},
4083 {V(uint32(0x110002)), V(string("\uFFFD"))},
4084 {V(uint64(0x110003)), V(string("\uFFFD"))},
4085 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4086 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4089 {V(MyString("hello")), V(string("hello"))},
4090 {V(string("hello")), V(MyString("hello"))},
4091 {V(string("hello")), V(string("hello"))},
4092 {V(MyString("hello")), V(MyString("hello"))},
4093 {V(MyString("bytes1")), V([]byte("bytes1"))},
4094 {V([]byte("bytes2")), V(MyString("bytes2"))},
4095 {V([]byte("bytes3")), V([]byte("bytes3"))},
4096 {V(MyString("runes♝")), V([]rune("runes♝"))},
4097 {V([]rune("runes♕")), V(MyString("runes♕"))},
4098 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4099 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4100 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4101 {V(int('a')), V(MyString("a"))},
4102 {V(int8('a')), V(MyString("a"))},
4103 {V(int16('a')), V(MyString("a"))},
4104 {V(int32('a')), V(MyString("a"))},
4105 {V(int64('a')), V(MyString("a"))},
4106 {V(uint('a')), V(MyString("a"))},
4107 {V(uint8('a')), V(MyString("a"))},
4108 {V(uint16('a')), V(MyString("a"))},
4109 {V(uint32('a')), V(MyString("a"))},
4110 {V(uint64('a')), V(MyString("a"))},
4111 {V(uintptr('a')), V(MyString("a"))},
4112 {V(int(-1)), V(MyString("\uFFFD"))},
4113 {V(int8(-2)), V(MyString("\uFFFD"))},
4114 {V(int16(-3)), V(MyString("\uFFFD"))},
4115 {V(int32(-4)), V(MyString("\uFFFD"))},
4116 {V(int64(-5)), V(MyString("\uFFFD"))},
4117 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4118 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4119 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4120 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4123 {V(string("bytes1")), V(MyBytes("bytes1"))},
4124 {V(MyBytes("bytes2")), V(string("bytes2"))},
4125 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4126 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4127 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4130 {V(string("runes♝")), V(MyRunes("runes♝"))},
4131 {V(MyRunes("runes♕")), V(string("runes♕"))},
4132 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4133 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4134 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4136 // slice to array pointer
4137 {V([]byte(nil)), V((*[0]byte)(nil))},
4138 {V([]byte{}), V(new([0]byte))},
4139 {V([]byte{7}), V(&[1]byte{7})},
4140 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4141 {V(MyBytes([]byte{})), V(new([0]byte))},
4142 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4143 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4144 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4145 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4146 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4147 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4149 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4150 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4151 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4152 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4153 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4154 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4155 {V(new([0]byte)), V(new(MyBytesArray0))},
4156 {V(new(MyBytesArray0)), V(new([0]byte))},
4157 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4158 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4160 // named types and equal underlying types
4161 {V(new(int)), V(new(integer))},
4162 {V(new(integer)), V(new(int))},
4163 {V(Empty{}), V(struct{}{})},
4164 {V(new(Empty)), V(new(struct{}))},
4165 {V(struct{}{}), V(Empty{})},
4166 {V(new(struct{})), V(new(Empty))},
4167 {V(Empty{}), V(Empty{})},
4168 {V(MyBytes{}), V([]byte{})},
4169 {V([]byte{}), V(MyBytes{})},
4170 {V((func())(nil)), V(MyFunc(nil))},
4171 {V((MyFunc)(nil)), V((func())(nil))},
4173 // structs with different tags
4186 {V(MyStruct{}), V(struct {
4192 }{}), V(MyStruct{})},
4194 {V(MyStruct{}), V(struct {
4200 }{}), V(MyStruct{})},
4202 {V(MyStruct1{}), V(MyStruct2{})},
4203 {V(MyStruct2{}), V(MyStruct1{})},
4205 // can convert *byte and *MyByte
4206 {V((*byte)(nil)), V((*MyByte)(nil))},
4207 {V((*MyByte)(nil)), V((*byte)(nil))},
4209 // cannot convert mismatched array sizes
4210 {V([2]byte{}), V([2]byte{})},
4211 {V([3]byte{}), V([3]byte{})},
4213 // cannot convert other instances
4214 {V((**byte)(nil)), V((**byte)(nil))},
4215 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4216 {V((chan byte)(nil)), V((chan byte)(nil))},
4217 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4218 {V(([]byte)(nil)), V(([]byte)(nil))},
4219 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4220 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4221 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4222 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4223 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4224 {V([2]byte{}), V([2]byte{})},
4225 {V([2]MyByte{}), V([2]MyByte{})},
4228 {V((***int)(nil)), V((***int)(nil))},
4229 {V((***byte)(nil)), V((***byte)(nil))},
4230 {V((***int32)(nil)), V((***int32)(nil))},
4231 {V((***int64)(nil)), V((***int64)(nil))},
4232 {V((chan byte)(nil)), V((chan byte)(nil))},
4233 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4234 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4235 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4236 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4237 {V([]uint(nil)), V([]uint(nil))},
4238 {V([]int(nil)), V([]int(nil))},
4239 {V(new(interface{})), V(new(interface{}))},
4240 {V(new(io.Reader)), V(new(io.Reader))},
4241 {V(new(io.Writer)), V(new(io.Writer))},
4244 {V(IntChan(nil)), V((chan<- int)(nil))},
4245 {V(IntChan(nil)), V((<-chan int)(nil))},
4246 {V((chan int)(nil)), V(IntChanRecv(nil))},
4247 {V((chan int)(nil)), V(IntChanSend(nil))},
4248 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4249 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4250 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4251 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4252 {V(IntChan(nil)), V((chan int)(nil))},
4253 {V((chan int)(nil)), V(IntChan(nil))},
4254 {V((chan int)(nil)), V((<-chan int)(nil))},
4255 {V((chan int)(nil)), V((chan<- int)(nil))},
4256 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4257 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4258 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4259 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4260 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4261 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4262 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4263 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4264 {V(BytesChan(nil)), V((chan []byte)(nil))},
4265 {V((chan []byte)(nil)), V(BytesChan(nil))},
4266 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4267 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4269 // cannot convert other instances (channels)
4270 {V(IntChan(nil)), V(IntChan(nil))},
4271 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4272 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4273 {V(BytesChan(nil)), V(BytesChan(nil))},
4274 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4275 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4278 {V(int(1)), EmptyInterfaceV(int(1))},
4279 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4280 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4281 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4282 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4285 func TestConvert(t *testing.T) {
4286 canConvert := map[[2]Type]bool{}
4287 all := map[Type]bool{}
4289 for _, tt := range convertTests {
4291 if !t1.ConvertibleTo(t1) {
4292 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4297 if !t1.ConvertibleTo(t2) {
4298 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4304 canConvert[[2]Type{t1, t2}] = true
4306 // vout1 represents the in value converted to the in type.
4308 vout1 := v1.Convert(t1)
4309 out1 := vout1.Interface()
4310 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4311 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4314 // vout2 represents the in value converted to the out type.
4315 vout2 := v1.Convert(t2)
4316 out2 := vout2.Interface()
4317 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4318 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4320 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4321 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4324 // vout3 represents a new value of the out type, set to vout2. This makes
4325 // sure the converted value vout2 is really usable as a regular value.
4326 vout3 := New(t2).Elem()
4328 out3 := vout3.Interface()
4329 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4330 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4334 t.Errorf("table entry %v is RO, should not be", v1)
4337 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4340 t.Errorf("conversion output %v is RO, should not be", vout2)
4343 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4345 if !IsRO(MakeRO(v1).Convert(t1)) {
4346 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4348 if !IsRO(MakeRO(v1).Convert(t2)) {
4349 t.Errorf("RO conversion output %v is not RO, should be", v1)
4353 // Assume that of all the types we saw during the tests,
4354 // if there wasn't an explicit entry for a conversion between
4355 // a pair of types, then it's not to be allowed. This checks for
4356 // things like 'int64' converting to '*int'.
4357 for t1 := range all {
4358 for t2 := range all {
4359 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4360 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4361 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4367 func TestConvertPanic(t *testing.T) {
4368 s := make([]byte, 4)
4372 if !v.Type().ConvertibleTo(pt) {
4373 t.Errorf("[]byte should be convertible to *[8]byte")
4375 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4380 var gFloat32 float32
4382 func TestConvertNaNs(t *testing.T) {
4383 const snan uint32 = 0x7f800001
4384 type myFloat32 float32
4385 x := V(myFloat32(math.Float32frombits(snan)))
4386 y := x.Convert(TypeOf(float32(0)))
4387 z := y.Interface().(float32)
4388 if got := math.Float32bits(z); got != snan {
4389 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4393 type ComparableStruct struct {
4397 type NonComparableStruct struct {
4402 var comparableTests = []struct {
4407 {TypeOf("hello"), true},
4408 {TypeOf(new(byte)), true},
4409 {TypeOf((func())(nil)), false},
4410 {TypeOf([]byte{}), false},
4411 {TypeOf(map[string]int{}), false},
4412 {TypeOf(make(chan int)), true},
4413 {TypeOf(1.5), true},
4414 {TypeOf(false), true},
4416 {TypeOf(ComparableStruct{}), true},
4417 {TypeOf(NonComparableStruct{}), false},
4418 {TypeOf([10]map[string]int{}), false},
4419 {TypeOf([10]string{}), true},
4420 {TypeOf(new(interface{})).Elem(), true},
4423 func TestComparable(t *testing.T) {
4424 for _, tt := range comparableTests {
4425 if ok := tt.typ.Comparable(); ok != tt.ok {
4426 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4431 func TestOverflow(t *testing.T) {
4432 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4433 t.Errorf("%v wrongly overflows float64", 1e300)
4436 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4437 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4438 t.Errorf("%v wrongly overflows float32", maxFloat32)
4440 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4441 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4442 t.Errorf("%v should overflow float32", ovfFloat32)
4444 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4445 t.Errorf("%v should overflow float32", -ovfFloat32)
4448 maxInt32 := int64(0x7fffffff)
4449 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4450 t.Errorf("%v wrongly overflows int32", maxInt32)
4452 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4453 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4455 ovfInt32 := int64(1 << 31)
4456 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4457 t.Errorf("%v should overflow int32", ovfInt32)
4460 maxUint32 := uint64(0xffffffff)
4461 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4462 t.Errorf("%v wrongly overflows uint32", maxUint32)
4464 ovfUint32 := uint64(1 << 32)
4465 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4466 t.Errorf("%v should overflow uint32", ovfUint32)
4470 func checkSameType(t *testing.T, x Type, y interface{}) {
4471 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4472 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4476 func TestArrayOf(t *testing.T) {
4477 // check construction and use of type not in binary
4480 value func(i int) interface{}
4486 value: func(i int) interface{} { type Tint int; return Tint(i) },
4492 value: func(i int) interface{} { type Tint int; return Tint(i) },
4494 want: "[0 1 2 3 4 5 6 7 8 9]",
4498 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
4500 want: "[0 1 2 3 4 5 6 7 8 9]",
4504 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
4506 want: "[0 1 2 3 4 5 6 7 8 9]",
4510 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
4512 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4516 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
4518 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4522 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
4524 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4528 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4530 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4534 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4536 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4540 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4542 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4546 value: func(i int) interface{} {
4547 type TstructUV struct {
4551 return TstructUV{i, float64(i)}
4554 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4558 for _, table := range tests {
4559 at := ArrayOf(table.n, TypeOf(table.value(0)))
4561 vok := New(at).Elem()
4562 vnot := New(at).Elem()
4563 for i := 0; i < v.Len(); i++ {
4564 v.Index(i).Set(ValueOf(table.value(i)))
4565 vok.Index(i).Set(ValueOf(table.value(i)))
4570 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4572 s := fmt.Sprint(v.Interface())
4573 if s != table.want {
4574 t.Errorf("constructed array = %s, want %s", s, table.want)
4577 if table.comparable != at.Comparable() {
4578 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4580 if table.comparable {
4582 if DeepEqual(vnot.Interface(), v.Interface()) {
4584 "arrays (%#v) compare ok (but should not)",
4589 if !DeepEqual(vok.Interface(), v.Interface()) {
4591 "arrays (%#v) compare NOT-ok (but should)",
4598 // check that type already in binary is found
4600 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4603 func TestArrayOfGC(t *testing.T) {
4605 tt := TypeOf(T(nil))
4608 for i := 0; i < n; i++ {
4609 v := New(ArrayOf(n, tt)).Elem()
4610 for j := 0; j < v.Len(); j++ {
4612 *p = uintptr(i*n + j)
4613 v.Index(j).Set(ValueOf(p).Convert(tt))
4615 x = append(x, v.Interface())
4619 for i, xi := range x {
4621 for j := 0; j < v.Len(); j++ {
4622 k := v.Index(j).Elem().Interface()
4623 if k != uintptr(i*n+j) {
4624 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4630 func TestArrayOfAlg(t *testing.T) {
4631 at := ArrayOf(6, TypeOf(byte(0)))
4632 v1 := New(at).Elem()
4633 v2 := New(at).Elem()
4634 if v1.Interface() != v1.Interface() {
4635 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4637 v1.Index(5).Set(ValueOf(byte(1)))
4638 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4639 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4642 at = ArrayOf(6, TypeOf([]int(nil)))
4644 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4647 func TestArrayOfGenericAlg(t *testing.T) {
4648 at1 := ArrayOf(5, TypeOf(string("")))
4649 at := ArrayOf(6, at1)
4650 v1 := New(at).Elem()
4651 v2 := New(at).Elem()
4652 if v1.Interface() != v1.Interface() {
4653 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4656 v1.Index(0).Index(0).Set(ValueOf("abc"))
4657 v2.Index(0).Index(0).Set(ValueOf("efg"))
4658 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4659 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4662 v1.Index(0).Index(0).Set(ValueOf("abc"))
4663 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4664 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4665 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4669 m := MakeMap(MapOf(at, TypeOf(int(0))))
4670 m.SetMapIndex(v1, ValueOf(1))
4671 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4672 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4676 func TestArrayOfDirectIface(t *testing.T) {
4679 i1 := Zero(TypeOf(T{})).Interface()
4680 v1 := ValueOf(&i1).Elem()
4681 p1 := v1.InterfaceData()[1]
4683 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4684 v2 := ValueOf(&i2).Elem()
4685 p2 := v2.InterfaceData()[1]
4688 t.Errorf("got p1=%v. want=%v", p1, nil)
4692 t.Errorf("got p2=%v. want=%v", p2, nil)
4697 i1 := Zero(TypeOf(T{})).Interface()
4698 v1 := ValueOf(&i1).Elem()
4699 p1 := v1.InterfaceData()[1]
4701 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4702 v2 := ValueOf(&i2).Elem()
4703 p2 := v2.InterfaceData()[1]
4706 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4710 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4715 // Ensure passing in negative lengths panics.
4716 // See https://golang.org/issue/43603
4717 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4718 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4719 ArrayOf(-1, TypeOf(byte(0)))
4723 func TestSliceOf(t *testing.T) {
4724 // check construction and use of type not in binary
4726 st := SliceOf(TypeOf(T(1)))
4727 if got, want := st.String(), "[]reflect_test.T"; got != want {
4728 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4730 v := MakeSlice(st, 10, 10)
4732 for i := 0; i < v.Len(); i++ {
4733 v.Index(i).Set(ValueOf(T(i)))
4736 s := fmt.Sprint(v.Interface())
4737 want := "[0 1 2 3 4 5 6 7 8 9]"
4739 t.Errorf("constructed slice = %s, want %s", s, want)
4742 // check that type already in binary is found
4744 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4747 func TestSliceOverflow(t *testing.T) {
4748 // check that MakeSlice panics when size of slice overflows uint
4751 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4753 t.Fatal("slice size does not overflow")
4756 st := SliceOf(TypeOf(x))
4760 t.Fatal("slice overflow does not panic")
4763 MakeSlice(st, int(l), int(l))
4766 func TestSliceOfGC(t *testing.T) {
4768 tt := TypeOf(T(nil))
4772 for i := 0; i < n; i++ {
4773 v := MakeSlice(st, n, n)
4774 for j := 0; j < v.Len(); j++ {
4776 *p = uintptr(i*n + j)
4777 v.Index(j).Set(ValueOf(p).Convert(tt))
4779 x = append(x, v.Interface())
4783 for i, xi := range x {
4785 for j := 0; j < v.Len(); j++ {
4786 k := v.Index(j).Elem().Interface()
4787 if k != uintptr(i*n+j) {
4788 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4794 func TestStructOfFieldName(t *testing.T) {
4795 // invalid field name "1nvalid"
4796 shouldPanic("has invalid name", func() {
4797 StructOf([]StructField{
4798 {Name: "Valid", Type: TypeOf("")},
4799 {Name: "1nvalid", Type: TypeOf("")},
4803 // invalid field name "+"
4804 shouldPanic("has invalid name", func() {
4805 StructOf([]StructField{
4806 {Name: "Val1d", Type: TypeOf("")},
4807 {Name: "+", Type: TypeOf("")},
4812 shouldPanic("has no name", func() {
4813 StructOf([]StructField{
4814 {Name: "", Type: TypeOf("")},
4818 // verify creation of a struct with valid struct fields
4819 validFields := []StructField{
4834 validStruct := StructOf(validFields)
4836 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
4837 if got, want := validStruct.String(), structStr; got != want {
4838 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
4842 func TestStructOf(t *testing.T) {
4843 // check construction and use of type not in binary
4844 fields := []StructField{
4853 Type: TypeOf(byte(0)),
4857 Type: TypeOf(uint64(0)),
4861 Type: TypeOf([3]uint16{}),
4865 st := StructOf(fields)
4868 v.FieldByName("X").Set(ValueOf(byte(2)))
4869 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
4872 s := fmt.Sprint(v.Interface())
4873 want := `{ 1 0 [0 0 0]}`
4875 t.Errorf("constructed struct = %s, want %s", s, want)
4877 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
4878 if got, want := st.String(), stStr; got != want {
4879 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
4882 // check the size, alignment and field offsets
4883 stt := TypeOf(struct {
4889 if st.Size() != stt.Size() {
4890 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
4892 if st.Align() != stt.Align() {
4893 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
4895 if st.FieldAlign() != stt.FieldAlign() {
4896 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4898 for i := 0; i < st.NumField(); i++ {
4899 o1 := st.Field(i).Offset
4900 o2 := stt.Field(i).Offset
4902 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
4906 // Check size and alignment with a trailing zero-sized field.
4907 st = StructOf([]StructField{
4910 Type: TypeOf(byte(0)),
4914 Type: TypeOf([0]*byte{}),
4917 stt = TypeOf(struct {
4921 if st.Size() != stt.Size() {
4922 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
4924 if st.Align() != stt.Align() {
4925 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
4927 if st.FieldAlign() != stt.FieldAlign() {
4928 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4930 for i := 0; i < st.NumField(); i++ {
4931 o1 := st.Field(i).Offset
4932 o2 := stt.Field(i).Offset
4934 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
4938 // check duplicate names
4939 shouldPanic("duplicate field", func() {
4940 StructOf([]StructField{
4941 {Name: "string", PkgPath: "p", Type: TypeOf("")},
4942 {Name: "string", PkgPath: "p", Type: TypeOf("")},
4945 shouldPanic("has no name", func() {
4946 StructOf([]StructField{
4948 {Name: "string", PkgPath: "p", Type: TypeOf("")},
4951 shouldPanic("has no name", func() {
4952 StructOf([]StructField{
4957 // check that type already in binary is found
4958 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
4960 // gccgo used to fail this test.
4961 type structFieldType interface{}
4963 StructOf([]StructField{
4966 Type: TypeOf((*structFieldType)(nil)).Elem(),
4969 struct{ F structFieldType }{})
4972 func TestStructOfExportRules(t *testing.T) {
4978 testPanic := func(i int, mustPanic bool, f func()) {
4981 if err == nil && mustPanic {
4982 t.Errorf("test-%d did not panic", i)
4984 if err != nil && !mustPanic {
4985 t.Errorf("test-%d panicked: %v\n", i, err)
4997 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5001 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5005 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5009 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5013 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5017 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5021 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5025 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5029 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5033 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5037 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5040 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5043 field: StructField{Name: "S", Type: TypeOf(S1{})},
5047 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5051 field: StructField{Name: "S", Type: TypeOf(s2{})},
5055 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5059 field: StructField{Name: "s", Type: TypeOf(S1{})},
5063 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5067 field: StructField{Name: "s", Type: TypeOf(s2{})},
5071 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5075 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5078 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5081 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5084 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5087 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5091 field: StructField{Name: "", Type: TypeOf(φType{})},
5095 field: StructField{Name: "Φ", Type: TypeOf(0)},
5099 field: StructField{Name: "φ", Type: TypeOf(0)},
5104 for i, test := range tests {
5105 testPanic(i, test.mustPanic, func() {
5106 typ := StructOf([]StructField{test.field})
5108 t.Errorf("test-%d: error creating struct type", i)
5111 field := typ.Field(0)
5114 panic("field.Name must not be empty")
5116 exported := token.IsExported(n)
5117 if exported != test.exported {
5118 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5120 if field.PkgPath != test.field.PkgPath {
5121 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5127 func TestStructOfGC(t *testing.T) {
5129 tt := TypeOf(T(nil))
5130 fields := []StructField{
5131 {Name: "X", Type: tt},
5132 {Name: "Y", Type: tt},
5134 st := StructOf(fields)
5138 for i := 0; i < n; i++ {
5140 for j := 0; j < v.NumField(); j++ {
5142 *p = uintptr(i*n + j)
5143 v.Field(j).Set(ValueOf(p).Convert(tt))
5145 x = append(x, v.Interface())
5149 for i, xi := range x {
5151 for j := 0; j < v.NumField(); j++ {
5152 k := v.Field(j).Elem().Interface()
5153 if k != uintptr(i*n+j) {
5154 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5160 func TestStructOfAlg(t *testing.T) {
5161 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5162 v1 := New(st).Elem()
5163 v2 := New(st).Elem()
5164 if !DeepEqual(v1.Interface(), v1.Interface()) {
5165 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5167 v1.FieldByName("X").Set(ValueOf(int(1)))
5168 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5169 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5172 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5174 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5177 func TestStructOfGenericAlg(t *testing.T) {
5178 st1 := StructOf([]StructField{
5179 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5180 {Name: "Y", Type: TypeOf(string(""))},
5182 st := StructOf([]StructField{
5183 {Name: "S0", Type: st1},
5184 {Name: "S1", Type: st1},
5202 {Name: "XX", Type: TypeOf([0]int{})},
5203 {Name: "YY", Type: TypeOf("")},
5211 {Name: "XX", Type: TypeOf([0]int{})},
5212 {Name: "YY", Type: TypeOf("")},
5213 {Name: "ZZ", Type: TypeOf([2]int{})},
5221 {Name: "XX", Type: TypeOf([1]int{})},
5222 {Name: "YY", Type: TypeOf("")},
5230 {Name: "XX", Type: TypeOf([1]int{})},
5231 {Name: "YY", Type: TypeOf("")},
5232 {Name: "ZZ", Type: TypeOf([1]int{})},
5240 {Name: "XX", Type: TypeOf([2]int{})},
5241 {Name: "YY", Type: TypeOf("")},
5242 {Name: "ZZ", Type: TypeOf([2]int{})},
5250 {Name: "XX", Type: TypeOf(int64(0))},
5251 {Name: "YY", Type: TypeOf(byte(0))},
5252 {Name: "ZZ", Type: TypeOf("")},
5260 {Name: "XX", Type: TypeOf(int64(0))},
5261 {Name: "YY", Type: TypeOf(int64(0))},
5262 {Name: "ZZ", Type: TypeOf("")},
5263 {Name: "AA", Type: TypeOf([1]int64{})},
5270 for _, table := range tests {
5271 v1 := New(table.rt).Elem()
5272 v2 := New(table.rt).Elem()
5274 if !DeepEqual(v1.Interface(), v1.Interface()) {
5275 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5278 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5279 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5280 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5281 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5285 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5286 val := "+" + abc + "-"
5287 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5288 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5289 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5293 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5294 m.SetMapIndex(v1, ValueOf(1))
5295 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5296 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5299 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5300 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5301 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5304 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5305 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5310 func TestStructOfDirectIface(t *testing.T) {
5312 type T struct{ X [1]*byte }
5313 i1 := Zero(TypeOf(T{})).Interface()
5314 v1 := ValueOf(&i1).Elem()
5315 p1 := v1.InterfaceData()[1]
5317 i2 := Zero(StructOf([]StructField{
5320 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5323 v2 := ValueOf(&i2).Elem()
5324 p2 := v2.InterfaceData()[1]
5327 t.Errorf("got p1=%v. want=%v", p1, nil)
5331 t.Errorf("got p2=%v. want=%v", p2, nil)
5335 type T struct{ X [0]*byte }
5336 i1 := Zero(TypeOf(T{})).Interface()
5337 v1 := ValueOf(&i1).Elem()
5338 p1 := v1.InterfaceData()[1]
5340 i2 := Zero(StructOf([]StructField{
5343 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5346 v2 := ValueOf(&i2).Elem()
5347 p2 := v2.InterfaceData()[1]
5350 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5354 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5361 func (i StructI) Get() int { return int(i) }
5365 func (i *StructIPtr) Get() int { return int(*i) }
5366 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5368 type SettableStruct struct {
5372 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5374 type SettablePointer struct {
5378 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5380 func TestStructOfWithInterface(t *testing.T) {
5382 type Iface interface {
5385 type IfaceSet interface {
5396 typ: TypeOf(StructI(want)),
5397 val: ValueOf(StructI(want)),
5402 typ: PtrTo(TypeOf(StructI(want))),
5403 val: ValueOf(func() interface{} {
5411 typ: PtrTo(TypeOf(StructIPtr(want))),
5412 val: ValueOf(func() interface{} {
5413 v := StructIPtr(want)
5420 typ: TypeOf(StructIPtr(want)),
5421 val: ValueOf(StructIPtr(want)),
5425 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5426 // val: ValueOf(StructI(want)),
5431 for i, table := range tests {
5432 for j := 0; j < 2; j++ {
5433 var fields []StructField
5435 fields = append(fields, StructField{
5438 Type: TypeOf(int(0)),
5441 fields = append(fields, StructField{
5448 // We currently do not correctly implement methods
5449 // for embedded fields other than the first.
5450 // Therefore, for now, we expect those methods
5451 // to not exist. See issues 15924 and 20824.
5452 // When those issues are fixed, this test of panic
5453 // should be removed.
5454 if j == 1 && table.impl {
5457 if err := recover(); err == nil {
5458 t.Errorf("test-%d-%d did not panic", i, j)
5461 _ = StructOf(fields)
5466 rt := StructOf(fields)
5467 rv := New(rt).Elem()
5468 rv.Field(j).Set(table.val)
5470 if _, ok := rv.Interface().(Iface); ok != table.impl {
5472 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5474 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5483 v := rv.Interface().(Iface).Get()
5485 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5488 fct := rv.MethodByName("Get")
5489 out := fct.Call(nil)
5490 if !DeepEqual(out[0].Interface(), want) {
5491 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5496 // Test an embedded nil pointer with pointer methods.
5497 fields := []StructField{{
5500 Type: PtrTo(TypeOf(StructIPtr(want))),
5502 rt := StructOf(fields)
5503 rv := New(rt).Elem()
5504 // This should panic since the pointer is nil.
5505 shouldPanic("", func() {
5506 rv.Interface().(IfaceSet).Set(want)
5509 // Test an embedded nil pointer to a struct with pointer methods.
5511 fields = []StructField{{
5512 Name: "SettableStruct",
5514 Type: PtrTo(TypeOf(SettableStruct{})),
5516 rt = StructOf(fields)
5518 // This should panic since the pointer is nil.
5519 shouldPanic("", func() {
5520 rv.Interface().(IfaceSet).Set(want)
5523 // The behavior is different if there is a second field,
5524 // since now an interface value holds a pointer to the struct
5525 // rather than just holding a copy of the struct.
5526 fields = []StructField{
5528 Name: "SettableStruct",
5530 Type: PtrTo(TypeOf(SettableStruct{})),
5533 Name: "EmptyStruct",
5535 Type: StructOf(nil),
5538 // With the current implementation this is expected to panic.
5539 // Ideally it should work and we should be able to see a panic
5540 // if we call the Set method.
5541 shouldPanic("", func() {
5545 // Embed a field that can be stored directly in an interface,
5546 // with a second field.
5547 fields = []StructField{
5549 Name: "SettablePointer",
5551 Type: TypeOf(SettablePointer{}),
5554 Name: "EmptyStruct",
5556 Type: StructOf(nil),
5559 // With the current implementation this is expected to panic.
5560 // Ideally it should work and we should be able to call the
5561 // Set and Get methods.
5562 shouldPanic("", func() {
5567 func TestStructOfTooManyFields(t *testing.T) {
5568 // Bug Fix: #25402 - this should not panic
5569 tt := StructOf([]StructField{
5570 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5573 if _, present := tt.MethodByName("After"); !present {
5574 t.Errorf("Expected method `After` to be found")
5578 func TestStructOfDifferentPkgPath(t *testing.T) {
5579 fields := []StructField{
5583 Type: TypeOf(int(0)),
5588 Type: TypeOf(int(0)),
5591 shouldPanic("different PkgPath", func() {
5596 func TestChanOf(t *testing.T) {
5597 // check construction and use of type not in binary
5599 ct := ChanOf(BothDir, TypeOf(T("")))
5600 v := MakeChan(ct, 2)
5602 v.Send(ValueOf(T("hello")))
5604 v.Send(ValueOf(T("world")))
5611 if s1 != "hello" || s2 != "world" {
5612 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5615 // check that type already in binary is found
5617 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5619 // Check arrow token association in undefined chan types.
5620 var left chan<- chan T
5621 var right chan (<-chan T)
5622 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5623 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5624 if tLeft != TypeOf(left) {
5625 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5627 if tRight != TypeOf(right) {
5628 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5632 func TestChanOfDir(t *testing.T) {
5633 // check construction and use of type not in binary
5635 crt := ChanOf(RecvDir, TypeOf(T("")))
5636 cst := ChanOf(SendDir, TypeOf(T("")))
5638 // check that type already in binary is found
5640 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5641 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5643 // check String form of ChanDir
5644 if crt.ChanDir().String() != "<-chan" {
5645 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5647 if cst.ChanDir().String() != "chan<-" {
5648 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5652 func TestChanOfGC(t *testing.T) {
5653 done := make(chan bool, 1)
5657 case <-time.After(5 * time.Second):
5658 panic("deadlock in TestChanOfGC")
5667 tt := TypeOf(T(nil))
5668 ct := ChanOf(BothDir, tt)
5670 // NOTE: The garbage collector handles allocated channels specially,
5671 // so we have to save pointers to channels in x; the pointer code will
5672 // use the gc info in the newly constructed chan type.
5675 for i := 0; i < n; i++ {
5676 v := MakeChan(ct, n)
5677 for j := 0; j < n; j++ {
5679 *p = uintptr(i*n + j)
5680 v.Send(ValueOf(p).Convert(tt))
5684 x = append(x, pv.Interface())
5688 for i, xi := range x {
5689 v := ValueOf(xi).Elem()
5690 for j := 0; j < n; j++ {
5692 k := pv.Elem().Interface()
5693 if k != uintptr(i*n+j) {
5694 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5700 func TestMapOf(t *testing.T) {
5701 // check construction and use of type not in binary
5705 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5707 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5710 s := fmt.Sprint(v.Interface())
5713 t.Errorf("constructed map = %s, want %s", s, want)
5716 // check that type already in binary is found
5717 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5719 // check that invalid key type panics
5720 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5723 func TestMapOfGCKeys(t *testing.T) {
5725 tt := TypeOf(T(nil))
5726 mt := MapOf(tt, TypeOf(false))
5728 // NOTE: The garbage collector handles allocated maps specially,
5729 // so we have to save pointers to maps in x; the pointer code will
5730 // use the gc info in the newly constructed map type.
5733 for i := 0; i < n; i++ {
5735 for j := 0; j < n; j++ {
5737 *p = uintptr(i*n + j)
5738 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5742 x = append(x, pv.Interface())
5746 for i, xi := range x {
5747 v := ValueOf(xi).Elem()
5749 for _, kv := range v.MapKeys() {
5750 out = append(out, int(kv.Elem().Interface().(uintptr)))
5753 for j, k := range out {
5755 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5761 func TestMapOfGCValues(t *testing.T) {
5763 tt := TypeOf(T(nil))
5764 mt := MapOf(TypeOf(1), tt)
5766 // NOTE: The garbage collector handles allocated maps specially,
5767 // so we have to save pointers to maps in x; the pointer code will
5768 // use the gc info in the newly constructed map type.
5771 for i := 0; i < n; i++ {
5773 for j := 0; j < n; j++ {
5775 *p = uintptr(i*n + j)
5776 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5780 x = append(x, pv.Interface())
5784 for i, xi := range x {
5785 v := ValueOf(xi).Elem()
5786 for j := 0; j < n; j++ {
5787 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
5788 if k != uintptr(i*n+j) {
5789 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5795 func TestTypelinksSorted(t *testing.T) {
5797 for i, n := range TypeLinks() {
5799 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
5805 func TestFuncOf(t *testing.T) {
5806 // check construction and use of type not in binary
5810 fn := func(args []Value) []Value {
5812 t.Errorf("args == %v, want exactly one arg", args)
5813 } else if args[0].Type() != TypeOf(K("")) {
5814 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
5815 } else if args[0].String() != "gopher" {
5816 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
5818 return []Value{ValueOf(V(3.14))}
5820 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
5822 outs := v.Call([]Value{ValueOf(K("gopher"))})
5824 t.Fatalf("v.Call returned %v, want exactly one result", outs)
5825 } else if outs[0].Type() != TypeOf(V(0)) {
5826 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
5828 f := outs[0].Float()
5830 t.Errorf("constructed func returned %f, want %f", f, 3.14)
5833 // check that types already in binary are found
5835 testCases := []struct {
5840 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
5841 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
5842 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
5843 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
5844 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
5846 for _, tt := range testCases {
5847 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
5850 // check that variadic requires last element be a slice.
5851 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5852 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5853 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
5862 func BenchmarkFieldByName1(b *testing.B) {
5864 b.RunParallel(func(pb *testing.PB) {
5871 func BenchmarkFieldByName2(b *testing.B) {
5873 b.RunParallel(func(pb *testing.PB) {
5950 func TestEmbed(t *testing.T) {
5952 f, ok := typ.FieldByName("X")
5954 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
5958 func BenchmarkFieldByName3(b *testing.B) {
5960 b.RunParallel(func(pb *testing.PB) {
5972 func BenchmarkInterfaceBig(b *testing.B) {
5974 b.RunParallel(func(pb *testing.PB) {
5982 func TestAllocsInterfaceBig(t *testing.T) {
5983 if testing.Short() {
5984 t.Skip("skipping malloc count in short mode")
5987 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
5988 t.Error("allocs:", allocs)
5992 func BenchmarkInterfaceSmall(b *testing.B) {
5993 v := ValueOf(int64(0))
5994 b.RunParallel(func(pb *testing.PB) {
6001 func TestAllocsInterfaceSmall(t *testing.T) {
6002 if testing.Short() {
6003 t.Skip("skipping malloc count in short mode")
6005 v := ValueOf(int64(0))
6006 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6007 t.Error("allocs:", allocs)
6011 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6012 // The basic usage is:
6015 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6018 // Each iteration of the loop returns a different set of results, until all
6019 // possible result sets have been explored. It is okay for different code paths
6020 // to make different method call sequences on x, but there must be no
6021 // other source of non-determinism in the call sequences.
6023 // When faced with a new decision, x chooses randomly. Future explorations
6024 // of that path will choose successive values for the result. Thus, stopping
6025 // the loop after a fixed number of iterations gives somewhat stochastic
6031 // v := make([]bool, x.Choose(4))
6032 // for i := range v {
6038 // prints (in some order):
6047 // [false false false]
6050 // [false false false false]
6052 // [true true true true]
6054 type exhaustive struct {
6060 type choice struct {
6066 func (x *exhaustive) Next() bool {
6068 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6075 for i := len(x.last) - 1; i >= 0; i-- {
6079 x.last = x.last[:i+1]
6086 func (x *exhaustive) Choose(max int) int {
6087 if x.pos >= len(x.last) {
6088 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6093 panic("inconsistent use of exhaustive tester")
6095 return (c.n + c.off) % max
6098 func (x *exhaustive) Maybe() bool {
6099 return x.Choose(2) == 1
6102 func GCFunc(args []Value) []Value {
6107 func TestReflectFuncTraceback(t *testing.T) {
6108 f := MakeFunc(TypeOf(func() {}), GCFunc)
6112 func TestReflectMethodTraceback(t *testing.T) {
6114 m := ValueOf(p).MethodByName("GCMethod")
6115 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6117 t.Errorf("Call returned %d; want 8", i)
6121 func TestSmallZero(t *testing.T) {
6124 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6125 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6129 func TestBigZero(t *testing.T) {
6130 const size = 1 << 10
6132 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6133 for i := 0; i < size; i++ {
6135 t.Fatalf("Zero object not all zero, index %d", i)
6140 func TestZeroSet(t *testing.T) {
6148 a: 0xaaaaaaaaaaaaaaaa,
6149 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6150 b: 0xbbbbbbbbbbbbbbbb,
6152 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6154 a: 0xaaaaaaaaaaaaaaaa,
6155 b: 0xbbbbbbbbbbbbbbbb,
6157 t.Fatalf("Setting a field to a Zero value didn't work")
6161 func TestFieldByIndexNil(t *testing.T) {
6170 v.FieldByName("P") // should be fine
6173 if err := recover(); err == nil {
6174 t.Fatalf("no error")
6175 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6176 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6179 v.FieldByName("F") // should panic
6181 t.Fatalf("did not panic")
6185 // type Outer struct {
6189 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6190 // The implementation is logically:
6191 // func (p *Outer) M() {
6194 // but since the only change here is the replacement of one pointer receiver with another,
6195 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6196 // then jumps to the M method expecting the *Inner receiver.
6198 // During reflect.Value.Call, we create an argument frame and the associated data structures
6199 // to describe it to the garbage collector, populate the frame, call reflect.call to
6200 // run a function call using that frame, and then copy the results back out of the frame.
6201 // The reflect.call function does a memmove of the frame structure onto the
6202 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6203 // the frame structure (to preserve the outputs).
6205 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6206 // were for the full stack frame. However, in the case where the called function was
6207 // one of these wrappers, the rewritten receiver is almost certainly a different type
6208 // than the original receiver. This is not a problem on the stack, where we use the
6209 // program counter to determine the type information and understand that
6210 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6211 // memory word is now an *Inner. But in the statically typed argument frame created
6212 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6213 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6214 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6215 // memory as if it were an *Outer. If the two have different memory layouts, the
6216 // collection will interpret the memory incorrectly.
6218 // One such possible incorrect interpretation is to treat two arbitrary memory words
6219 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6220 // an interface requires dereferencing the itab word, the misinterpretation will try to
6221 // deference Inner.P1, causing a crash during garbage collection.
6223 // This came up in a real program in issue 7725.
6236 func (pi *Inner) M() {
6237 // Clear references to pi so that the only way the
6238 // garbage collection will find the pointer is in the
6239 // argument frame, typed as a *Outer.
6242 // Set up an interface value that will cause a crash.
6243 // P1 = 1 is a non-zero, so the interface looks non-nil.
6244 // P2 = pi ensures that the data word points into the
6245 // allocated heap; if not the collection skips the interface
6246 // value as irrelevant, without dereferencing P1.
6248 pi.P2 = uintptr(unsafe.Pointer(pi))
6251 func TestCallMethodJump(t *testing.T) {
6252 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6253 // returns but before the args frame has been discarded.
6254 // This is a little clumsy but makes the failure repeatable.
6257 p := &Outer{Inner: new(Inner)}
6259 ValueOf(p).Method(0).Call(nil)
6261 // Stop garbage collecting during reflect.call.
6265 func TestMakeFuncStackCopy(t *testing.T) {
6266 target := func(in []Value) []Value {
6269 return []Value{ValueOf(9)}
6272 var concrete func(*int, int) int
6273 fn := MakeFunc(ValueOf(concrete).Type(), target)
6274 ValueOf(&concrete).Elem().Set(fn)
6275 x := concrete(nil, 7)
6277 t.Errorf("have %#q want 9", x)
6281 // use about n KB of stack
6282 func useStack(n int) {
6286 var b [1024]byte // makes frame about 1KB
6287 useStack(n - 1 + int(b[99]))
6294 func TestValueString(t *testing.T) {
6295 rv := ValueOf(Impl{})
6296 if rv.String() != "<reflect_test.Impl Value>" {
6297 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6300 method := rv.Method(0)
6301 if method.String() != "<func() Value>" {
6302 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6306 func TestInvalid(t *testing.T) {
6307 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6308 type T struct{ v interface{} }
6310 v := ValueOf(T{}).Field(0)
6311 if v.IsValid() != true || v.Kind() != Interface {
6312 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6315 if v.IsValid() != false || v.Kind() != Invalid {
6316 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6321 func TestLargeGCProg(t *testing.T) {
6322 fv := ValueOf(func([256]*byte) {})
6323 fv.Call([]Value{ValueOf([256]*byte{})})
6326 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
6328 recovered = recover()
6336 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6337 typ := TypeOf(struct{ X int }{10})
6338 testIndices := [...]struct {
6347 for i, tt := range testIndices {
6348 recoveredErr := fieldIndexRecover(typ, tt.i)
6350 if recoveredErr == nil {
6351 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6354 if recoveredErr != nil {
6355 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6362 func TestCallGC(t *testing.T) {
6363 f := func(a, b, c, d, e string) {
6365 g := func(in []Value) []Value {
6369 typ := ValueOf(f).Type()
6370 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6371 f2("four", "five5", "six666", "seven77", "eight888")
6374 // Issue 18635 (function version).
6375 func TestKeepFuncLive(t *testing.T) {
6376 // Test that we keep makeFuncImpl live as long as it is
6377 // referenced on the stack.
6378 typ := TypeOf(func(i int) {})
6379 var f, g func(in []Value) []Value
6380 f = func(in []Value) []Value {
6382 i := int(in[0].Int())
6384 // We can't use Value.Call here because
6385 // runtime.call* will keep the makeFuncImpl
6386 // alive. However, by converting it to an
6387 // interface value and calling that,
6388 // reflect.callReflect is the only thing that
6389 // can keep the makeFuncImpl live.
6391 // Alternate between f and g so that if we do
6392 // reuse the memory prematurely it's more
6393 // likely to get obviously corrupted.
6394 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6398 g = func(in []Value) []Value {
6400 i := int(in[0].Int())
6401 MakeFunc(typ, f).Interface().(func(i int))(i)
6404 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6407 type UnExportedFirst int
6409 func (i UnExportedFirst) ΦExported() {}
6410 func (i UnExportedFirst) unexported() {}
6413 func TestMethodByNameUnExportedFirst(t *testing.T) {
6415 if recover() != nil {
6416 t.Errorf("should not panic")
6419 typ := TypeOf(UnExportedFirst(0))
6420 m, _ := typ.MethodByName("ΦExported")
6421 if m.Name != "ΦExported" {
6422 t.Errorf("got %s, expected ΦExported", m.Name)
6426 // Issue 18635 (method version).
6427 type KeepMethodLive struct{}
6429 func (k KeepMethodLive) Method1(i int) {
6432 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6436 func (k KeepMethodLive) Method2(i int) {
6438 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6441 func TestKeepMethodLive(t *testing.T) {
6442 // Test that we keep methodValue live as long as it is
6443 // referenced on the stack.
6444 KeepMethodLive{}.Method1(10)
6447 // clobber tries to clobber unreachable memory.
6450 for i := 1; i < 32; i++ {
6451 for j := 0; j < 10; j++ {
6452 obj := make([]*byte, i)
6459 func TestFuncLayout(t *testing.T) {
6460 align := func(x uintptr) uintptr {
6461 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6464 if goarch.PtrSize == 4 {
6465 r = []byte{0, 0, 0, 1}
6477 size, argsize, retOffset uintptr
6478 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6479 intRegs, floatRegs int
6480 floatRegSize uintptr
6484 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6485 size: 6 * goarch.PtrSize,
6486 argsize: 4 * goarch.PtrSize,
6487 retOffset: 4 * goarch.PtrSize,
6488 stack: []byte{1, 0, 1, 0, 1},
6489 gc: []byte{1, 0, 1, 0, 1},
6492 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6493 size: align(align(3*4) + goarch.PtrSize + 2),
6494 argsize: align(3*4) + goarch.PtrSize + 2,
6495 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6500 typ: ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
6501 size: 4 * goarch.PtrSize,
6502 argsize: 4 * goarch.PtrSize,
6503 retOffset: 4 * goarch.PtrSize,
6504 stack: []byte{1, 0, 1, 1},
6505 gc: []byte{1, 0, 1, 1},
6508 typ: ValueOf(func(a S) {}).Type(),
6509 size: 4 * goarch.PtrSize,
6510 argsize: 4 * goarch.PtrSize,
6511 retOffset: 4 * goarch.PtrSize,
6512 stack: []byte{0, 0, 1, 1},
6513 gc: []byte{0, 0, 1, 1},
6516 rcvr: ValueOf((*byte)(nil)).Type(),
6517 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6518 size: 3 * goarch.PtrSize,
6519 argsize: 3 * goarch.PtrSize,
6520 retOffset: 3 * goarch.PtrSize,
6521 stack: []byte{1, 0, 1},
6522 gc: []byte{1, 0, 1},
6525 typ: ValueOf(func(a uintptr) {}).Type(),
6526 size: goarch.PtrSize,
6527 argsize: goarch.PtrSize,
6528 retOffset: goarch.PtrSize,
6533 typ: ValueOf(func() uintptr { return 0 }).Type(),
6534 size: goarch.PtrSize,
6541 rcvr: ValueOf(uintptr(0)).Type(),
6542 typ: ValueOf(func(a uintptr) {}).Type(),
6543 size: 2 * goarch.PtrSize,
6544 argsize: 2 * goarch.PtrSize,
6545 retOffset: 2 * goarch.PtrSize,
6548 // Note: this one is tricky, as the receiver is not a pointer. But we
6549 // pass the receiver by reference to the autogenerated pointer-receiver
6550 // version of the function.
6552 // TODO(mknyszek): Add tests for non-zero register count.
6554 for _, lt := range tests {
6555 name := lt.typ.String()
6557 name = lt.rcvr.String() + "." + name
6559 t.Run(name, func(t *testing.T) {
6560 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6562 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6563 if typ.Size() != lt.size {
6564 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6566 if argsize != lt.argsize {
6567 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6569 if retOffset != lt.retOffset {
6570 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6572 if !bytes.Equal(stack, lt.stack) {
6573 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6575 if !bytes.Equal(gc, lt.gc) {
6576 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6578 if !bytes.Equal(inRegs, lt.inRegs) {
6579 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6581 if !bytes.Equal(outRegs, lt.outRegs) {
6582 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6584 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6585 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6591 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6592 heapBits := GCBits(New(typ).Interface())
6593 if !bytes.Equal(heapBits, bits) {
6594 _, _, line, _ := runtime.Caller(1)
6595 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6599 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6600 // Creating a slice causes the runtime to repeat a bitmap,
6601 // which exercises a different path from making the compiler
6602 // repeat a bitmap for a small array or executing a repeat in
6604 val := MakeSlice(typ, 0, cap)
6605 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
6606 heapBits := GCBits(data.Interface())
6607 // Repeat the bitmap for the slice size, trimming scalars in
6608 // the last element.
6609 bits = rep(cap, bits)
6610 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6611 bits = bits[:len(bits)-1]
6613 if !bytes.Equal(heapBits, bits) {
6614 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6618 func TestGCBits(t *testing.T) {
6619 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6621 // Building blocks for types seen by the compiler (like [2]Xscalar).
6622 // The compiler will create the type structures for the derived types,
6623 // including their GC metadata.
6624 type Xscalar struct{ x uintptr }
6625 type Xptr struct{ x *byte }
6626 type Xptrscalar struct {
6630 type Xscalarptr struct {
6634 type Xbigptrscalar struct {
6639 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6641 // Building blocks for types constructed by reflect.
6642 // This code is in a separate block so that code below
6643 // cannot accidentally refer to these.
6644 // The compiler must NOT see types derived from these
6645 // (for example, [2]Scalar must NOT appear in the program),
6646 // or else reflect will use it instead of having to construct one.
6647 // The goal is to test the construction.
6648 type Scalar struct{ x uintptr }
6649 type Ptr struct{ x *byte }
6650 type Ptrscalar struct {
6654 type Scalarptr struct {
6658 type Bigptrscalar struct {
6663 Tscalar = TypeOf(Scalar{})
6664 Tint64 = TypeOf(Int64(0))
6665 Tptr = TypeOf(Ptr{})
6666 Tscalarptr = TypeOf(Scalarptr{})
6667 Tptrscalar = TypeOf(Ptrscalar{})
6668 Tbigptrscalar = TypeOf(Bigptrscalar{})
6673 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6674 verifyGCBits(t, Tscalar, empty)
6675 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6676 verifyGCBits(t, Tptr, lit(1))
6677 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6678 verifyGCBits(t, Tscalarptr, lit(0, 1))
6679 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6680 verifyGCBits(t, Tptrscalar, lit(1))
6682 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6683 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6684 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6685 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6686 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6687 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6688 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6689 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6690 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6691 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6692 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6693 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6694 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6695 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6696 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6697 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6698 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6699 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6700 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6701 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6702 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6703 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6704 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6705 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6706 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6707 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6709 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6710 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6711 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6712 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6713 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6714 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6715 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6716 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6717 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6718 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6719 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6720 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6721 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6722 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6723 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6724 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6725 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6726 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6727 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6728 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6729 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6730 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6731 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6732 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6733 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6734 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6736 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6737 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6739 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6740 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6742 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6743 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6745 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6746 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6748 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6749 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6751 hdr := make([]byte, 8/goarch.PtrSize)
6753 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6754 verifyGCBits(t, MapBucketOf(k, e), want)
6755 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6759 map[Xscalar]Xptr(nil),
6760 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6763 map[Xscalarptr]Xptr(nil),
6764 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6765 verifyMapBucket(t, Tint64, Tptr,
6766 map[int64]Xptr(nil),
6767 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
6770 map[Xscalar]Xscalar(nil),
6773 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6774 map[[2]Xscalarptr][3]Xptrscalar(nil),
6775 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6777 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6778 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6779 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6781 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6782 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6783 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6785 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6786 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6787 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
6789 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6790 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6791 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6794 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
6795 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
6796 func lit(x ...byte) []byte { return x }
6798 func TestTypeOfTypeOf(t *testing.T) {
6799 // Check that all the type constructors return concrete *rtype implementations.
6800 // It's difficult to test directly because the reflect package is only at arm's length.
6801 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6802 check := func(name string, typ Type) {
6803 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
6804 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
6808 type T struct{ int }
6809 check("TypeOf", TypeOf(T{}))
6811 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
6812 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
6813 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
6814 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
6815 check("PtrTo", PtrTo(TypeOf(T{})))
6816 check("SliceOf", SliceOf(TypeOf(T{})))
6819 type XM struct{ _ bool }
6821 func (*XM) String() string { return "" }
6823 func TestPtrToMethods(t *testing.T) {
6825 yp := New(TypeOf(y)).Interface()
6826 _, ok := yp.(fmt.Stringer)
6828 t.Fatal("does not implement Stringer, but should")
6832 func TestMapAlloc(t *testing.T) {
6833 m := ValueOf(make(map[int]int, 10))
6836 allocs := testing.AllocsPerRun(100, func() {
6840 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
6845 val := ValueOf(&tmp).Elem()
6846 allocs = testing.AllocsPerRun(100, func() {
6847 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
6848 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6849 for i := 0; i < size/2; i++ {
6850 val.SetInt(int64(i))
6851 mv.SetMapIndex(val, val)
6855 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
6857 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
6858 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
6859 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
6862 func TestChanAlloc(t *testing.T) {
6863 // Note: for a chan int, the return Value must be allocated, so we
6864 // use a chan *int instead.
6865 c := ValueOf(make(chan *int, 1))
6866 v := ValueOf(new(int))
6867 allocs := testing.AllocsPerRun(100, func() {
6871 if allocs < 0.5 || allocs > 1.5 {
6872 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
6874 // Note: there is one allocation in reflect.recv which seems to be
6875 // a limitation of escape analysis. If that is ever fixed the
6876 // allocs < 0.5 condition will trigger and this test should be fixed.
6879 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
6881 type nameTest struct {
6886 var nameTests = []nameTest{
6887 {(*int32)(nil), "int32"},
6890 {(*chan D1)(nil), ""},
6891 {(*func() D1)(nil), ""},
6892 {(*<-chan D1)(nil), ""},
6893 {(*chan<- D1)(nil), ""},
6894 {(*interface{})(nil), ""},
6898 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
6901 func TestNames(t *testing.T) {
6902 for _, test := range nameTests {
6903 typ := TypeOf(test.v).Elem()
6904 if got := typ.Name(); got != test.want {
6905 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
6910 func TestExported(t *testing.T) {
6911 type ΦExported struct{}
6912 type φUnexported struct{}
6919 type exportTest struct {
6923 exportTests := []exportTest{
6927 {(*big)(nil), false},
6928 {(BigP)(nil), true},
6929 {(*BigP)(nil), true},
6930 {ΦExported{}, true},
6931 {φUnexported{}, false},
6938 for i, test := range exportTests {
6939 typ := TypeOf(test.v)
6940 if got := IsExported(typ); got != test.want {
6941 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
6946 func TestTypeStrings(t *testing.T) {
6947 type stringTest struct {
6951 stringTests := []stringTest{
6952 {TypeOf(func(int) {}), "func(int)"},
6953 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
6954 {TypeOf(XM{}), "reflect_test.XM"},
6955 {TypeOf(new(XM)), "*reflect_test.XM"},
6956 {TypeOf(new(XM).String), "func() string"},
6957 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
6958 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
6959 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
6960 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
6961 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
6964 for i, test := range stringTests {
6965 if got, want := test.typ.String(), test.want; got != want {
6966 t.Errorf("type %d String()=%q, want %q", i, got, want)
6971 func TestOffsetLock(t *testing.T) {
6972 var wg sync.WaitGroup
6973 for i := 0; i < 4; i++ {
6977 for j := 0; j < 50; j++ {
6978 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
6986 func BenchmarkNew(b *testing.B) {
6988 b.RunParallel(func(pb *testing.PB) {
6995 func TestSwapper(t *testing.T) {
7001 type pairPtr struct {
7013 in: []int{1, 20, 300},
7016 want: []int{300, 20, 1},
7019 in: []uintptr{1, 20, 300},
7022 want: []uintptr{300, 20, 1},
7025 in: []int16{1, 20, 300},
7028 want: []int16{300, 20, 1},
7031 in: []int8{1, 20, 100},
7034 want: []int8{100, 20, 1},
7037 in: []*I{&a, &b, &c},
7040 want: []*I{&c, &b, &a},
7043 in: []string{"eric", "sergey", "larry"},
7046 want: []string{"larry", "sergey", "eric"},
7049 in: []S{"eric", "sergey", "larry"},
7052 want: []S{"larry", "sergey", "eric"},
7055 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7058 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7061 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7064 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7068 for i, tt := range tests {
7069 inStr := fmt.Sprint(tt.in)
7070 Swapper(tt.in)(tt.i, tt.j)
7071 if !DeepEqual(tt.in, tt.want) {
7072 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7077 // TestUnaddressableField tests that the reflect package will not allow
7078 // a type from another package to be used as a named type with an
7079 // unexported field.
7081 // This ensures that unexported fields cannot be modified by other packages.
7082 func TestUnaddressableField(t *testing.T) {
7083 var b Buffer // type defined in reflect, a different package
7084 var localBuffer struct {
7087 lv := ValueOf(&localBuffer).Elem()
7089 shouldPanic("Set", func() {
7098 type Talias1 struct {
7106 type Talias2 struct {
7111 func TestAliasNames(t *testing.T) {
7112 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7113 out := fmt.Sprintf("%#v", t1)
7114 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7116 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7119 t2 := Talias2{Tint: 1, Tint2: 2}
7120 out = fmt.Sprintf("%#v", t2)
7121 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7123 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7127 func TestIssue22031(t *testing.T) {
7128 type s []struct{ C int }
7131 type t2 struct{ f s }
7134 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7135 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7138 for i, test := range tests {
7140 t.Errorf("%d: CanSet: got true, want false", i)
7145 type NonExportedFirst int
7147 func (i NonExportedFirst) ΦExported() {}
7148 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7150 func TestIssue22073(t *testing.T) {
7151 m := ValueOf(NonExportedFirst(0)).Method(0)
7153 if got := m.Type().NumOut(); got != 0 {
7154 t.Errorf("NumOut: got %v, want 0", got)
7161 func TestMapIterNonEmptyMap(t *testing.T) {
7162 m := map[string]int{"one": 1, "two": 2, "three": 3}
7163 iter := ValueOf(m).MapRange()
7164 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7165 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7169 func TestMapIterNilMap(t *testing.T) {
7170 var m map[string]int
7171 iter := ValueOf(m).MapRange()
7172 if got, want := iterateToString(iter), `[]`; got != want {
7173 t.Errorf("non-empty result iteratoring nil map: %s", got)
7177 func TestMapIterSafety(t *testing.T) {
7178 // Using a zero MapIter causes a panic, but not a crash.
7180 defer func() { recover() }()
7182 t.Fatal("Key did not panic")
7185 defer func() { recover() }()
7186 new(MapIter).Value()
7187 t.Fatal("Value did not panic")
7190 defer func() { recover() }()
7192 t.Fatal("Next did not panic")
7195 // Calling Key/Value on a MapIter before Next
7196 // causes a panic, but not a crash.
7197 var m map[string]int
7198 iter := ValueOf(m).MapRange()
7201 defer func() { recover() }()
7203 t.Fatal("Key did not panic")
7206 defer func() { recover() }()
7208 t.Fatal("Value did not panic")
7211 // Calling Next, Key, or Value on an exhausted iterator
7212 // causes a panic, but not a crash.
7213 iter.Next() // -> false
7215 defer func() { recover() }()
7217 t.Fatal("Key did not panic")
7220 defer func() { recover() }()
7222 t.Fatal("Value did not panic")
7225 defer func() { recover() }()
7227 t.Fatal("Next did not panic")
7231 func TestMapIterNext(t *testing.T) {
7232 // The first call to Next should reflect any
7233 // insertions to the map since the iterator was created.
7234 m := map[string]int{}
7235 iter := ValueOf(m).MapRange()
7237 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7238 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7242 func TestMapIterDelete0(t *testing.T) {
7243 // Delete all elements before first iteration.
7244 m := map[string]int{"one": 1, "two": 2, "three": 3}
7245 iter := ValueOf(m).MapRange()
7249 if got, want := iterateToString(iter), `[]`; got != want {
7250 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7254 func TestMapIterDelete1(t *testing.T) {
7255 // Delete all elements after first iteration.
7256 m := map[string]int{"one": 1, "two": 2, "three": 3}
7257 iter := ValueOf(m).MapRange()
7260 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7266 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7270 // iterateToString returns the set of elements
7271 // returned by an iterator in readable form.
7272 func iterateToString(it *MapIter) string {
7275 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7276 got = append(got, line)
7279 return "[" + strings.Join(got, ", ") + "]"
7282 func TestConvertibleTo(t *testing.T) {
7283 t1 := ValueOf(example1.MyStruct{}).Type()
7284 t2 := ValueOf(example2.MyStruct{}).Type()
7286 // Shouldn't raise stack overflow
7287 if t1.ConvertibleTo(t2) {
7288 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)