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.
18 "reflect/internal/example1"
19 "reflect/internal/example2"
33 func TestBool(t *testing.T) {
36 t.Fatal("ValueOf(true).Bool() = false")
53 func assert(t *testing.T, s, want string) {
55 t.Errorf("have %#q want %#q", s, want)
59 var typeTests = []pair{
60 {struct{ x int }{}, "int"},
61 {struct{ x int8 }{}, "int8"},
62 {struct{ x int16 }{}, "int16"},
63 {struct{ x int32 }{}, "int32"},
64 {struct{ x int64 }{}, "int64"},
65 {struct{ x uint }{}, "uint"},
66 {struct{ x uint8 }{}, "uint8"},
67 {struct{ x uint16 }{}, "uint16"},
68 {struct{ x uint32 }{}, "uint32"},
69 {struct{ x uint64 }{}, "uint64"},
70 {struct{ x float32 }{}, "float32"},
71 {struct{ x float64 }{}, "float64"},
72 {struct{ x int8 }{}, "int8"},
73 {struct{ x (**int8) }{}, "**int8"},
74 {struct{ x (**integer) }{}, "**reflect_test.integer"},
75 {struct{ x ([32]int32) }{}, "[32]int32"},
76 {struct{ x ([]int8) }{}, "[]int8"},
77 {struct{ x (map[string]int32) }{}, "map[string]int32"},
78 {struct{ x (chan<- string) }{}, "chan<- string"},
79 {struct{ x (chan<- chan string) }{}, "chan<- 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)"},
89 "struct { c chan *int32; d float32 }",
91 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
94 c func(chan *integer, *int8)
97 "struct { c func(chan *reflect_test.integer, *int8) }",
105 "struct { a int8; b int32 }",
114 "struct { a int8; b int8; c int32 }",
124 "struct { a int8; b int8; c int8; d int32 }",
135 "struct { a int8; b int8; c int8; d int8; e int32 }",
147 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
151 a int8 `reflect:"hi there"`
154 `struct { a int8 "reflect:\"hi there\"" }`,
158 a int8 `reflect:"hi \x00there\t\n\"\\"`
161 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
168 "struct { f func(...int) }",
172 a(func(func(int) int) func(func(int)) int)
176 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
184 "struct { int32; int64 }",
188 var valueTests = []pair{
199 {new(float32), "256.25"},
200 {new(float64), "512.125"},
201 {new(complex64), "532.125+10i"},
202 {new(complex128), "564.25+1i"},
203 {new(string), "stringy cheese"},
205 {new(*int8), "*int8(0)"},
206 {new(**int8), "**int8(0)"},
207 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
208 {new(**integer), "**reflect_test.integer(0)"},
209 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
210 {new(chan<- string), "chan<- string"},
211 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
216 "struct { c chan *int32; d float32 }{chan *int32, 0}",
218 {new(struct{ c func(chan *integer, *int8) }),
219 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
225 "struct { a int8; b int32 }{0, 0}",
232 "struct { a int8; b int8; c int32 }{0, 0, 0}",
236 func testType(t *testing.T, i int, typ Type, want string) {
239 t.Errorf("#%d: have %#q, want %#q", i, s, want)
243 func TestTypes(t *testing.T) {
244 for i, tt := range typeTests {
245 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
249 func TestSet(t *testing.T) {
250 for i, tt := range valueTests {
279 v.SetComplex(532.125 + 10i)
281 v.SetComplex(564.25 + 1i)
283 v.SetString("stringy cheese")
287 s := valueToString(v)
289 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
294 func TestSetValue(t *testing.T) {
295 for i, tt := range valueTests {
296 v := ValueOf(tt.i).Elem()
299 v.Set(ValueOf(int(132)))
301 v.Set(ValueOf(int8(8)))
303 v.Set(ValueOf(int16(16)))
305 v.Set(ValueOf(int32(32)))
307 v.Set(ValueOf(int64(64)))
309 v.Set(ValueOf(uint(132)))
311 v.Set(ValueOf(uint8(8)))
313 v.Set(ValueOf(uint16(16)))
315 v.Set(ValueOf(uint32(32)))
317 v.Set(ValueOf(uint64(64)))
319 v.Set(ValueOf(float32(256.25)))
321 v.Set(ValueOf(512.125))
323 v.Set(ValueOf(complex64(532.125 + 10i)))
325 v.Set(ValueOf(complex128(564.25 + 1i)))
327 v.Set(ValueOf("stringy cheese"))
331 s := valueToString(v)
333 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
338 func TestCanSetField(t *testing.T) {
339 type embed struct{ x, X int }
340 type Embed struct{ x, X int }
358 type testCase struct {
359 // -1 means Addr().Elem() of current value
370 {[]int{0, -1}, false},
371 {[]int{0, 0}, false},
372 {[]int{0, 0, -1}, false},
373 {[]int{0, -1, 0}, false},
374 {[]int{0, -1, 0, -1}, false},
376 {[]int{0, 1, -1}, true},
377 {[]int{0, -1, 1}, true},
378 {[]int{0, -1, 1, -1}, true},
380 {[]int{1, -1}, false},
382 {[]int{2, -1}, true},
385 val: ValueOf(&S2{embed: &embed{}}),
388 {[]int{0, -1}, false},
389 {[]int{0, 0}, false},
390 {[]int{0, 0, -1}, false},
391 {[]int{0, -1, 0}, false},
392 {[]int{0, -1, 0, -1}, false},
394 {[]int{0, 1, -1}, true},
395 {[]int{0, -1, 1}, true},
396 {[]int{0, -1, 1, -1}, true},
404 {[]int{0, -1}, true},
405 {[]int{0, 0}, false},
406 {[]int{0, 0, -1}, false},
407 {[]int{0, -1, 0}, false},
408 {[]int{0, -1, 0, -1}, false},
410 {[]int{0, 1, -1}, true},
411 {[]int{0, -1, 1}, true},
412 {[]int{0, -1, 1, -1}, true},
417 val: ValueOf(&S4{Embed: &Embed{}}),
420 {[]int{0, -1}, true},
421 {[]int{0, 0}, false},
422 {[]int{0, 0, -1}, false},
423 {[]int{0, -1, 0}, false},
424 {[]int{0, -1, 0, -1}, false},
426 {[]int{0, 1, -1}, true},
427 {[]int{0, -1, 1}, true},
428 {[]int{0, -1, 1, -1}, true},
434 for _, tt := range tests {
435 t.Run(tt.val.Type().Name(), func(t *testing.T) {
436 for _, tc := range tt.cases {
438 for _, i := range tc.index {
448 if got := f.CanSet(); got != tc.canSet {
449 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
458 var valueToStringTests = []pair{
463 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
464 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
465 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
466 {&[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})"},
467 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 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(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
471 func TestValueToString(t *testing.T) {
472 for i, test := range valueToStringTests {
473 s := valueToString(ValueOf(test.i))
475 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
480 func TestArrayElemSet(t *testing.T) {
481 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
482 v.Index(4).SetInt(123)
483 s := valueToString(v)
484 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
486 t.Errorf("[10]int: have %#q want %#q", s, want)
489 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
490 v.Index(4).SetInt(123)
492 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
494 t.Errorf("[]int: have %#q want %#q", s, want1)
498 func TestPtrPointTo(t *testing.T) {
502 vi := ValueOf(&i).Elem()
503 vip.Elem().Set(vi.Addr())
505 t.Errorf("got %d, want 1234", *ip)
509 vp := ValueOf(&ip).Elem()
510 vp.Set(Zero(vp.Type()))
512 t.Errorf("got non-nil (%p), want nil", ip)
516 func TestPtrSetNil(t *testing.T) {
520 vip.Elem().Set(Zero(vip.Elem().Type()))
522 t.Errorf("got non-nil (%d), want nil", *ip)
526 func TestMapSetNil(t *testing.T) {
527 m := make(map[string]int)
529 vm.Elem().Set(Zero(vm.Elem().Type()))
531 t.Errorf("got non-nil (%p), want nil", m)
535 func TestAll(t *testing.T) {
536 testType(t, 1, TypeOf((int8)(0)), "int8")
537 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
539 typ := TypeOf((*struct {
543 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
545 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
548 testType(t, 5, f.Type, "chan *int32")
550 f, present := styp.FieldByName("d")
552 t.Errorf("FieldByName says present field is absent")
554 testType(t, 6, f.Type, "float32")
556 f, present = styp.FieldByName("absent")
558 t.Errorf("FieldByName says absent field is present")
561 typ = TypeOf([32]int32{})
562 testType(t, 7, typ, "[32]int32")
563 testType(t, 8, typ.Elem(), "int32")
565 typ = TypeOf((map[string]*int32)(nil))
566 testType(t, 9, typ, "map[string]*int32")
568 testType(t, 10, mtyp.Key(), "string")
569 testType(t, 11, mtyp.Elem(), "*int32")
571 typ = TypeOf((chan<- string)(nil))
572 testType(t, 12, typ, "chan<- string")
573 testType(t, 13, typ.Elem(), "string")
575 // make sure tag strings are not part of element type
576 typ = TypeOf(struct {
577 d []uint32 `reflect:"TAG"`
579 testType(t, 14, typ, "[]uint32")
582 func TestInterfaceGet(t *testing.T) {
587 v1 := ValueOf(&inter)
588 v2 := v1.Elem().Field(0)
589 assert(t, v2.Type().String(), "interface {}")
592 assert(t, v3.Type().String(), "float64")
595 func TestInterfaceValue(t *testing.T) {
600 v1 := ValueOf(&inter)
601 v2 := v1.Elem().Field(0)
602 assert(t, v2.Type().String(), "interface {}")
604 assert(t, v3.Type().String(), "float64")
607 if _, ok := i3.(float64); !ok {
608 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
612 func TestFunctionValue(t *testing.T) {
613 var x interface{} = func() {}
615 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
616 t.Fatalf("TestFunction returned wrong pointer")
618 assert(t, v.Type().String(), "func()")
621 var appendTests = []struct {
624 {make([]int, 2, 4), []int{22}},
625 {make([]int, 2, 4), []int{22, 33, 44}},
628 func sameInts(x, y []int) bool {
629 if len(x) != len(y) {
632 for i, xx := range x {
640 func TestAppend(t *testing.T) {
641 for i, test := range appendTests {
642 origLen, extraLen := len(test.orig), len(test.extra)
643 want := append(test.orig, test.extra...)
644 // Convert extra from []int to []Value.
645 e0 := make([]Value, len(test.extra))
646 for j, e := range test.extra {
649 // Convert extra from []int to *SliceValue.
650 e1 := ValueOf(test.extra)
652 a0 := ValueOf(test.orig)
653 have0 := Append(a0, e0...).Interface().([]int)
654 if !sameInts(have0, want) {
655 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
657 // Check that the orig and extra slices were not modified.
658 if len(test.orig) != origLen {
659 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
661 if len(test.extra) != extraLen {
662 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
665 a1 := ValueOf(test.orig)
666 have1 := AppendSlice(a1, e1).Interface().([]int)
667 if !sameInts(have1, want) {
668 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
670 // Check that the orig and extra slices were not modified.
671 if len(test.orig) != origLen {
672 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
674 if len(test.extra) != extraLen {
675 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
680 func TestCopy(t *testing.T) {
681 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
682 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
683 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
684 for i := 0; i < len(b); i++ {
686 t.Fatalf("b != c before test")
691 aa := ValueOf(&a1).Elem()
692 ab := ValueOf(&b1).Elem()
693 for tocopy := 1; tocopy <= 7; tocopy++ {
697 for i := 0; i < tocopy; i++ {
699 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
700 tocopy, i, a[i], i, b[i])
703 for i := tocopy; i < len(b); i++ {
706 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
707 tocopy, i, a[i], i, b[i], i, c[i])
709 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
710 tocopy, i, b[i], i, c[i])
713 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
719 func TestCopyString(t *testing.T) {
720 t.Run("Slice", func(t *testing.T) {
721 s := bytes.Repeat([]byte{'_'}, 8)
724 n := Copy(val, ValueOf(""))
725 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
726 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
729 n = Copy(val, ValueOf("hello"))
730 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
731 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
734 n = Copy(val, ValueOf("helloworld"))
735 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
736 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
739 t.Run("Array", func(t *testing.T) {
740 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
741 val := ValueOf(&s).Elem()
743 n := Copy(val, ValueOf(""))
744 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
745 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
748 n = Copy(val, ValueOf("hello"))
749 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
750 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
753 n = Copy(val, ValueOf("helloworld"))
754 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
755 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
760 func TestCopyArray(t *testing.T) {
761 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
762 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
764 aa := ValueOf(&a).Elem()
765 ab := ValueOf(&b).Elem()
767 for i := 0; i < len(a); i++ {
769 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
772 for i := len(a); i < len(b); i++ {
774 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
776 t.Logf("elem %d is okay\n", i)
781 func TestBigUnnamedStruct(t *testing.T) {
782 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
784 b1 := v.Interface().(struct {
787 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
788 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
796 func TestBigStruct(t *testing.T) {
797 b := big{1, 2, 3, 4, 5}
799 b1 := v.Interface().(big)
800 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
801 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
812 type DeepEqualTest struct {
817 // Simple functions for DeepEqual tests.
821 fn3 = func() { fn1() } // Not nil.
827 type Loopy interface{}
829 var loop1, loop2 Loop
830 var loopy1, loopy2 Loopy
831 var cycleMap1, cycleMap2, cycleMap3 map[string]interface{}
833 type structWithSelfPtr struct {
845 cycleMap1 = map[string]interface{}{}
846 cycleMap1["cycle"] = cycleMap1
847 cycleMap2 = map[string]interface{}{}
848 cycleMap2["cycle"] = cycleMap2
849 cycleMap3 = map[string]interface{}{}
850 cycleMap3["different"] = cycleMap3
853 var deepEqualTests = []DeepEqualTest{
857 {int32(1), int32(1), true},
859 {float32(0.5), float32(0.5), true},
860 {"hello", "hello", true},
861 {make([]int, 10), make([]int, 10), true},
862 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
863 {Basic{1, 0.5}, Basic{1, 0.5}, true},
864 {error(nil), error(nil), true},
865 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
870 {int32(1), int32(2), false},
872 {float32(0.5), float32(0.6), false},
873 {"hello", "hey", false},
874 {make([]int, 10), make([]int, 11), false},
875 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
876 {Basic{1, 0.5}, Basic{1, 0.6}, false},
877 {Basic{1, 0}, Basic{2, 0}, false},
878 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
879 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
880 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
881 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
886 {[][]int{{1}}, [][]int{{2}}, false},
887 {math.NaN(), math.NaN(), false},
888 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
889 {&[1]float64{math.NaN()}, self{}, true},
890 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
891 {[]float64{math.NaN()}, self{}, true},
892 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
893 {map[float64]float64{math.NaN(): 1}, self{}, true},
894 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
896 // Nil vs empty: not the same.
897 {[]int{}, []int(nil), false},
898 {[]int{}, []int{}, true},
899 {[]int(nil), []int(nil), true},
900 {map[int]int{}, map[int]int(nil), false},
901 {map[int]int{}, map[int]int{}, true},
902 {map[int]int(nil), map[int]int(nil), true},
906 {int32(1), int64(1), false},
907 {0.5, "hello", false},
908 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
909 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
910 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
911 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
914 {&loop1, &loop1, true},
915 {&loop1, &loop2, true},
916 {&loopy1, &loopy1, true},
917 {&loopy1, &loopy2, true},
918 {&cycleMap1, &cycleMap2, true},
919 {&cycleMap1, &cycleMap3, false},
922 func TestDeepEqual(t *testing.T) {
923 for _, test := range deepEqualTests {
924 if test.b == (self{}) {
927 if r := DeepEqual(test.a, test.b); r != test.eq {
928 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
933 func TestTypeOf(t *testing.T) {
934 // Special case for nil
935 if typ := TypeOf(nil); typ != nil {
936 t.Errorf("expected nil type for nil value; got %v", typ)
938 for _, test := range deepEqualTests {
943 typ := TypeOf(test.a)
945 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
950 type Recursive struct {
955 func TestDeepEqualRecursiveStruct(t *testing.T) {
956 a, b := new(Recursive), new(Recursive)
957 *a = Recursive{12, a}
958 *b = Recursive{12, b}
959 if !DeepEqual(a, b) {
960 t.Error("DeepEqual(recursive same) = false, want true")
964 type _Complex struct {
968 d map[float64]float64
971 func TestDeepEqualComplexStruct(t *testing.T) {
972 m := make(map[float64]float64)
973 stra, strb := "hello", "hello"
974 a, b := new(_Complex), new(_Complex)
975 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
976 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
977 if !DeepEqual(a, b) {
978 t.Error("DeepEqual(complex same) = false, want true")
982 func TestDeepEqualComplexStructInequality(t *testing.T) {
983 m := make(map[float64]float64)
984 stra, strb := "hello", "helloo" // Difference is here
985 a, b := new(_Complex), new(_Complex)
986 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
987 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
989 t.Error("DeepEqual(complex different) = true, want false")
997 func TestDeepEqualUnexportedMap(t *testing.T) {
998 // Check that DeepEqual can look at unexported fields.
999 x1 := UnexpT{map[int]int{1: 2}}
1000 x2 := UnexpT{map[int]int{1: 2}}
1001 if !DeepEqual(&x1, &x2) {
1002 t.Error("DeepEqual(x1, x2) = false, want true")
1005 y1 := UnexpT{map[int]int{2: 3}}
1006 if DeepEqual(&x1, &y1) {
1007 t.Error("DeepEqual(x1, y1) = true, want false")
1011 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
1013 f := s.Type().Field(1)
1014 if f.Offset != offs {
1015 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1019 // Check that structure alignment & offsets viewed through reflect agree with those
1020 // from the compiler itself.
1021 func TestAlignment(t *testing.T) {
1022 type T1inner struct {
1029 type T2inner struct {
1037 x := T1{T1inner{2}, 17}
1038 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1040 x1 := T2{T2inner{2, 3}, 17}
1041 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1044 func Nil(a interface{}, t *testing.T) {
1045 n := ValueOf(a).Field(0)
1047 t.Errorf("%v should be nil", a)
1051 func NotNil(a interface{}, t *testing.T) {
1052 n := ValueOf(a).Field(0)
1054 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1058 func TestIsNil(t *testing.T) {
1059 // These implement IsNil.
1060 // Wrap in extra struct to hide interface type.
1061 doNil := []interface{}{
1063 struct{ x interface{} }{},
1064 struct{ x map[string]int }{},
1065 struct{ x func() bool }{},
1066 struct{ x chan int }{},
1067 struct{ x []string }{},
1068 struct{ x unsafe.Pointer }{},
1070 for _, ts := range doNil {
1071 ty := TypeOf(ts).Field(0).Type
1073 v.IsNil() // panics if not okay to call
1076 // Check the implementations
1088 si.x = make([]int, 10)
1095 ci.x = make(chan int)
1102 mi.x = make(map[int]int)
1113 x func(t *testing.T)
1120 func TestIsZero(t *testing.T) {
1121 for i, tt := range []struct {
1150 {float32(1.2), false},
1152 {float64(1.2), false},
1153 {math.Copysign(0, -1), false},
1154 {complex64(0), true},
1155 {complex64(1.2), false},
1156 {complex128(0), true},
1157 {complex128(1.2), false},
1158 {complex(math.Copysign(0, -1), 0), false},
1159 {complex(0, math.Copysign(0, -1)), false},
1160 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1162 {uintptr(128), false},
1164 {Zero(TypeOf([5]string{})).Interface(), true},
1165 {[5]string{"", "", "", "", ""}, true},
1166 {[5]string{}, true},
1167 {[5]string{"", "", "", "a", ""}, false},
1169 {(chan string)(nil), true},
1170 {make(chan string), false},
1171 {time.After(1), false},
1173 {(func())(nil), true},
1176 {New(TypeOf(new(error)).Elem()).Elem(), true},
1177 {(io.Reader)(strings.NewReader("")), false},
1179 {(map[string]string)(nil), true},
1180 {map[string]string{}, false},
1181 {make(map[string]string), false},
1183 {(*func())(nil), true},
1184 {(*int)(nil), true},
1187 {[]string{}, false},
1188 {([]string)(nil), true},
1189 {make([]string, 0), false},
1192 {"not-zero", false},
1195 {T{123, 456.75, "hello", &_i}, false},
1197 {(unsafe.Pointer)(nil), true},
1198 {(unsafe.Pointer)(new(int)), false},
1201 if v, ok := tt.x.(Value); ok {
1209 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1212 if !Zero(TypeOf(tt.x)).IsZero() {
1213 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1219 if r := recover(); r == nil {
1220 t.Error("should panic for invalid value")
1227 func TestInterfaceExtraction(t *testing.T) {
1233 v := Indirect(ValueOf(&s)).Field(0).Interface()
1234 if v != s.W.(interface{}) {
1235 t.Error("Interface() on interface: ", v, s.W)
1239 func TestNilPtrValueSub(t *testing.T) {
1241 if pv := ValueOf(pi); pv.Elem().IsValid() {
1242 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1246 func TestMap(t *testing.T) {
1247 m := map[string]int{"a": 1, "b": 2}
1249 if n := mv.Len(); n != len(m) {
1250 t.Errorf("Len = %d, want %d", n, len(m))
1252 keys := mv.MapKeys()
1253 newmap := MakeMap(mv.Type())
1254 for k, v := range m {
1255 // Check that returned Keys match keys in range.
1256 // These aren't required to be in the same order.
1258 for _, kv := range keys {
1259 if kv.String() == k {
1265 t.Errorf("Missing key %q", k)
1268 // Check that value lookup is correct.
1269 vv := mv.MapIndex(ValueOf(k))
1270 if vi := vv.Int(); vi != int64(v) {
1271 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1274 // Copy into new map.
1275 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1277 vv := mv.MapIndex(ValueOf("not-present"))
1279 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1282 newm := newmap.Interface().(map[string]int)
1283 if len(newm) != len(m) {
1284 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1287 for k, v := range newm {
1290 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1294 newmap.SetMapIndex(ValueOf("a"), Value{})
1297 t.Errorf("newm[\"a\"] = %d after delete", v)
1300 mv = ValueOf(&m).Elem()
1301 mv.Set(Zero(mv.Type()))
1303 t.Errorf("mv.Set(nil) failed")
1307 func TestNilMap(t *testing.T) {
1308 var m map[string]int
1310 keys := mv.MapKeys()
1312 t.Errorf(">0 keys for nil map: %v", keys)
1315 // Check that value for missing key is zero.
1316 x := mv.MapIndex(ValueOf("hello"))
1317 if x.Kind() != Invalid {
1318 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1321 // Check big value too.
1322 var mbig map[string][10 << 20]byte
1323 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1324 if x.Kind() != Invalid {
1325 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1328 // Test that deletes from a nil map succeed.
1329 mv.SetMapIndex(ValueOf("hi"), Value{})
1332 func TestChan(t *testing.T) {
1333 for loop := 0; loop < 2; loop++ {
1337 // check both ways to allocate channels
1340 c = make(chan int, 1)
1343 cv = MakeChan(TypeOf(c), 1)
1344 c = cv.Interface().(chan int)
1349 if i := <-c; i != 2 {
1350 t.Errorf("reflect Send 2, native recv %d", i)
1355 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1356 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1360 val, ok := cv.TryRecv()
1361 if val.IsValid() || ok {
1362 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1367 val, ok = cv.TryRecv()
1369 t.Errorf("TryRecv on ready chan got nil")
1370 } else if i := val.Int(); i != 4 || !ok {
1371 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1376 ok = cv.TrySend(ValueOf(5))
1379 t.Errorf("TrySend on full chan succeeded: value %d", i)
1383 ok = cv.TrySend(ValueOf(6))
1385 t.Errorf("TrySend on empty chan failed")
1388 t.Errorf("TrySend failed but it did send %d", x)
1392 if i = <-c; i != 6 {
1393 t.Errorf("TrySend 6, recv %d", i)
1400 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1401 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1403 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1404 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1408 // check creation of unbuffered channel
1410 cv := MakeChan(TypeOf(c), 0)
1411 c = cv.Interface().(chan int)
1412 if cv.TrySend(ValueOf(7)) {
1413 t.Errorf("TrySend on sync chan succeeded")
1415 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1416 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1420 cv = MakeChan(TypeOf(c), 10)
1421 c = cv.Interface().(chan int)
1422 for i := 0; i < 3; i++ {
1425 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1426 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1430 // caseInfo describes a single case in a select test.
1431 type caseInfo struct {
1440 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1442 func TestSelect(t *testing.T) {
1443 selectWatch.once.Do(func() { go selectWatcher() })
1447 newop := func(n int, cap int) (ch, val Value) {
1450 c := make(chan int, cap)
1454 c := make(chan string, cap)
1456 val = ValueOf(fmt.Sprint(n))
1461 for n := 0; x.Next(); n++ {
1462 if testing.Short() && n >= 1000 {
1465 if n >= 100000 && !*allselect {
1468 if n%100000 == 0 && testing.Verbose() {
1469 println("TestSelect", n)
1471 var cases []SelectCase
1476 ch, val := newop(len(cases), 1)
1477 cases = append(cases, SelectCase{
1482 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1487 ch, val := newop(len(cases), 1)
1489 cases = append(cases, SelectCase{
1493 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1498 ch, val := newop(len(cases), 0)
1499 cases = append(cases, SelectCase{
1506 f := func() { ch.Recv() }
1507 info = append(info, caseInfo{desc: "blocking send", helper: f})
1509 info = append(info, caseInfo{desc: "blocking send"})
1515 ch, val := newop(len(cases), 0)
1516 cases = append(cases, SelectCase{
1522 f := func() { ch.Send(val) }
1523 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1525 info = append(info, caseInfo{desc: "blocking recv"})
1531 // Maybe include value to send.
1536 cases = append(cases, SelectCase{
1540 info = append(info, caseInfo{desc: "zero Chan send"})
1543 // Zero Chan receive.
1545 cases = append(cases, SelectCase{
1548 info = append(info, caseInfo{desc: "zero Chan recv"})
1553 cases = append(cases, SelectCase{
1555 Chan: ValueOf((chan int)(nil)),
1558 info = append(info, caseInfo{desc: "nil Chan send"})
1563 cases = append(cases, SelectCase{
1565 Chan: ValueOf((chan int)(nil)),
1567 info = append(info, caseInfo{desc: "nil Chan recv"})
1570 // closed Chan send.
1572 ch := make(chan int)
1574 cases = append(cases, SelectCase{
1579 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1582 // closed Chan recv.
1584 ch, val := newop(len(cases), 0)
1586 val = Zero(val.Type())
1587 cases = append(cases, SelectCase{
1591 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1594 var helper func() // goroutine to help the select complete
1596 // Add default? Must be last case here, but will permute.
1597 // Add the default if the select would otherwise
1598 // block forever, and maybe add it anyway.
1604 for i, c := range info {
1612 } else if c.helper != nil {
1614 helpers = append(helpers, i)
1617 if !canProceed || x.Maybe() {
1618 cases = append(cases, SelectCase{
1621 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1623 } else if canBlock {
1624 // Select needs to communicate with another goroutine.
1625 cas := &info[helpers[x.Choose(len(helpers))]]
1627 cas.canSelect = true
1631 // Permute cases and case info.
1632 // Doing too much here makes the exhaustive loop
1633 // too exhausting, so just do two swaps.
1634 for loop := 0; loop < 2; loop++ {
1635 i := x.Choose(len(cases))
1636 j := x.Choose(len(cases))
1637 cases[i], cases[j] = cases[j], cases[i]
1638 info[i], info[j] = info[j], info[i]
1642 // We wait before kicking off a goroutine to satisfy a blocked select.
1643 // The pause needs to be big enough to let the select block before
1644 // we run the helper, but if we lose that race once in a while it's okay: the
1645 // select will just proceed immediately. Not a big deal.
1646 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1647 pause := 10 * time.Microsecond
1648 if testing.Short() {
1649 pause = 100 * time.Microsecond
1651 time.AfterFunc(pause, helper)
1655 i, recv, recvOK, panicErr := runSelect(cases, info)
1656 if panicErr != nil && !canPanic {
1657 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1659 if panicErr == nil && canPanic && numCanSelect == 1 {
1660 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1662 if panicErr != nil {
1670 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1672 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1676 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1680 if cases[i].Dir == SelectRecv {
1681 if !recv.IsValid() {
1682 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1684 if !cas.recv.IsValid() {
1685 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1687 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1688 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1689 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1691 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1694 if recv.IsValid() || recvOK {
1695 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1701 func TestSelectMaxCases(t *testing.T) {
1702 var sCases []SelectCase
1703 channel := make(chan int)
1705 for i := 0; i < 65536; i++ {
1706 sCases = append(sCases, SelectCase{
1708 Chan: ValueOf(channel),
1712 _, _, _ = Select(sCases)
1713 sCases = append(sCases, SelectCase{
1715 Chan: ValueOf(channel),
1718 if err := recover(); err != nil {
1719 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1720 t.Fatalf("unexpected error from select call with greater than max supported cases")
1723 t.Fatalf("expected select call to panic with greater than max supported cases")
1727 _, _, _ = Select(sCases)
1730 func TestSelectNop(t *testing.T) {
1731 // "select { default: }" should always return the default case.
1732 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1734 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1738 func BenchmarkSelect(b *testing.B) {
1739 channel := make(chan int)
1741 var cases []SelectCase
1742 for i := 0; i < 8; i++ {
1743 cases = append(cases, SelectCase{
1745 Chan: ValueOf(channel),
1748 for _, numCases := range []int{1, 4, 8} {
1749 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1751 for i := 0; i < b.N; i++ {
1752 _, _, _ = Select(cases[:numCases])
1758 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1759 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1760 // an error describing the select and panics the entire test binary.
1761 var selectWatch struct {
1768 func selectWatcher() {
1770 time.Sleep(1 * time.Second)
1772 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1773 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1774 panic("select stuck")
1776 selectWatch.Unlock()
1780 // runSelect runs a single select test.
1781 // It returns the values returned by Select but also returns
1782 // a panic value if the Select panics.
1783 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1785 panicErr = recover()
1788 selectWatch.info = nil
1789 selectWatch.Unlock()
1793 selectWatch.now = time.Now()
1794 selectWatch.info = info
1795 selectWatch.Unlock()
1797 chosen, recv, recvOK = Select(cases)
1801 // fmtSelect formats the information about a single select test.
1802 func fmtSelect(info []caseInfo) string {
1803 var buf bytes.Buffer
1804 fmt.Fprintf(&buf, "\nselect {\n")
1805 for i, cas := range info {
1806 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1807 if cas.recv.IsValid() {
1808 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1811 fmt.Fprintf(&buf, " canselect")
1814 fmt.Fprintf(&buf, " panic")
1816 fmt.Fprintf(&buf, "\n")
1818 fmt.Fprintf(&buf, "}")
1824 // Difficult test for function call because of
1825 // implicit padding between arguments.
1826 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) {
1827 return b, c, d, e, f, g, h
1830 func TestFunc(t *testing.T) {
1831 ret := ValueOf(dummy).Call([]Value{
1835 ValueOf(two{40, 50}),
1837 ValueOf(float32(70)),
1841 t.Fatalf("Call returned %d values, want 7", len(ret))
1844 i := byte(ret[0].Uint())
1845 j := int(ret[1].Int())
1846 k := byte(ret[2].Uint())
1847 l := ret[3].Interface().(two)
1848 m := byte(ret[4].Uint())
1849 n := float32(ret[5].Float())
1850 o := byte(ret[6].Uint())
1852 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1853 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)
1856 for i, v := range ret {
1858 t.Errorf("result %d is addressable", i)
1863 func TestCallConvert(t *testing.T) {
1864 v := ValueOf(new(io.ReadWriter)).Elem()
1865 f := ValueOf(func(r io.Reader) io.Reader { return r })
1866 out := f.Call([]Value{v})
1867 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
1868 t.Errorf("expected [nil], got %v", out)
1872 type emptyStruct struct{}
1874 type nonEmptyStruct struct {
1878 func returnEmpty() emptyStruct {
1879 return emptyStruct{}
1882 func takesEmpty(e emptyStruct) {
1885 func returnNonEmpty(i int) nonEmptyStruct {
1886 return nonEmptyStruct{member: i}
1889 func takesNonEmpty(n nonEmptyStruct) int {
1893 func TestCallWithStruct(t *testing.T) {
1894 r := ValueOf(returnEmpty).Call(nil)
1895 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1896 t.Errorf("returning empty struct returned %#v instead", r)
1898 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1900 t.Errorf("takesEmpty returned values: %#v", r)
1902 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1903 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1904 t.Errorf("returnNonEmpty returned %#v", r)
1906 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1907 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1908 t.Errorf("takesNonEmpty returned %#v", r)
1912 func TestCallReturnsEmpty(t *testing.T) {
1913 // Issue 21717: past-the-end pointer write in Call with
1914 // nonzero-sized frame and zero-sized return value.
1916 var finalized uint32
1917 f := func() (emptyStruct, *[2]int64) {
1918 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
1919 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
1920 return emptyStruct{}, i
1922 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
1923 timeout := time.After(5 * time.Second)
1924 for atomic.LoadUint32(&finalized) == 0 {
1927 t.Fatal("finalizer did not run")
1933 runtime.KeepAlive(v)
1936 func BenchmarkCall(b *testing.B) {
1937 fv := ValueOf(func(a, b string) {})
1939 b.RunParallel(func(pb *testing.PB) {
1940 args := []Value{ValueOf("a"), ValueOf("b")}
1949 func (i *myint) inc() {
1953 func BenchmarkCallMethod(b *testing.B) {
1958 for i := 0; i < b.N; i++ {
1963 func BenchmarkCallArgCopy(b *testing.B) {
1964 byteArray := func(n int) Value {
1965 return Zero(ArrayOf(n, TypeOf(byte(0))))
1967 sizes := [...]struct {
1971 {ValueOf(func(a [128]byte) {}), byteArray(128)},
1972 {ValueOf(func(a [256]byte) {}), byteArray(256)},
1973 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
1974 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
1975 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
1977 for _, size := range sizes {
1978 bench := func(b *testing.B) {
1979 args := []Value{size.arg}
1980 b.SetBytes(int64(size.arg.Len()))
1982 b.RunParallel(func(pb *testing.PB) {
1988 name := fmt.Sprintf("size=%v", size.arg.Len())
1993 func TestMakeFunc(t *testing.T) {
1995 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1996 ValueOf(&f).Elem().Set(fv)
1998 // Call g with small arguments so that there is
1999 // something predictable (and different from the
2000 // correct results) in those positions on the stack.
2002 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2004 // Call constructed function f.
2005 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2006 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2007 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)
2011 func TestMakeFuncInterface(t *testing.T) {
2012 fn := func(i int) int { return i }
2013 incr := func(in []Value) []Value {
2014 return []Value{ValueOf(int(in[0].Int() + 1))}
2016 fv := MakeFunc(TypeOf(fn), incr)
2017 ValueOf(&fn).Elem().Set(fv)
2018 if r := fn(2); r != 3 {
2019 t.Errorf("Call returned %d, want 3", r)
2021 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2022 t.Errorf("Call returned %d, want 15", r)
2024 if r := fv.Interface().(func(int) int)(26); r != 27 {
2025 t.Errorf("Call returned %d, want 27", r)
2029 func TestMakeFuncVariadic(t *testing.T) {
2030 // Test that variadic arguments are packed into a slice and passed as last arg
2031 fn := func(_ int, is ...int) []int { return nil }
2032 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2033 ValueOf(&fn).Elem().Set(fv)
2036 if r[0] != 2 || r[1] != 3 {
2037 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2040 r = fn(1, []int{2, 3}...)
2041 if r[0] != 2 || r[1] != 3 {
2042 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2045 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2046 if r[0] != 2 || r[1] != 3 {
2047 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2050 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2051 if r[0] != 2 || r[1] != 3 {
2052 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2055 f := fv.Interface().(func(int, ...int) []int)
2058 if r[0] != 2 || r[1] != 3 {
2059 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2061 r = f(1, []int{2, 3}...)
2062 if r[0] != 2 || r[1] != 3 {
2063 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2067 // Dummy type that implements io.WriteCloser
2071 func (w *WC) Write(p []byte) (n int, err error) {
2074 func (w *WC) Close() error {
2078 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2079 // reflect.Values returned from the wrapped function should be assignment-converted
2080 // to the types returned by the result of MakeFunc.
2082 // Concrete types should be promotable to interfaces they implement.
2084 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2085 return []Value{ValueOf(io.EOF)}
2086 }).Interface().(func() error)
2089 // Super-interfaces should be promotable to simpler interfaces.
2090 var g func() io.Writer
2091 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2092 var w io.WriteCloser = &WC{}
2093 return []Value{ValueOf(&w).Elem()}
2094 }).Interface().(func() io.Writer)
2097 // Channels should be promotable to directional channels.
2098 var h func() <-chan int
2099 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2100 return []Value{ValueOf(make(chan int))}
2101 }).Interface().(func() <-chan int)
2104 // Unnamed types should be promotable to named types.
2105 type T struct{ a, b, c int }
2107 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2108 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2109 }).Interface().(func() T)
2113 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2114 // Type doesn't implement the required interface.
2115 shouldPanic("", func() {
2117 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2118 return []Value{ValueOf(int(7))}
2119 }).Interface().(func() error)
2122 // Assigning to an interface with additional methods.
2123 shouldPanic("", func() {
2124 var f func() io.ReadWriteCloser
2125 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2126 var w io.WriteCloser = &WC{}
2127 return []Value{ValueOf(&w).Elem()}
2128 }).Interface().(func() io.ReadWriteCloser)
2131 // Directional channels can't be assigned to bidirectional ones.
2132 shouldPanic("", func() {
2133 var f func() chan int
2134 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2135 var c <-chan int = make(chan int)
2136 return []Value{ValueOf(c)}
2137 }).Interface().(func() chan int)
2140 // Two named types which are otherwise identical.
2141 shouldPanic("", func() {
2142 type T struct{ a, b, c int }
2143 type U struct{ a, b, c int }
2145 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2146 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2147 }).Interface().(func() T)
2156 // This will be index 0.
2157 func (p Point) AnotherMethod(scale int) int {
2161 // This will be index 1.
2162 func (p Point) Dist(scale int) int {
2163 //println("Point.Dist", p.x, p.y, scale)
2164 return p.x*p.x*scale + p.y*p.y*scale
2167 // This will be index 2.
2168 func (p Point) GCMethod(k int) int {
2173 // This will be index 3.
2174 func (p Point) NoArgs() {
2175 // Exercise no-argument/no-result paths.
2178 // This will be index 4.
2179 func (p Point) TotalDist(points ...Point) int {
2181 for _, q := range points {
2184 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2190 // This will be index 5.
2191 func (p *Point) Int64Method(x int64) int64 {
2195 // This will be index 6.
2196 func (p *Point) Int32Method(x int32) int32 {
2200 func TestMethod(t *testing.T) {
2201 // Non-curried method of type.
2203 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2205 t.Errorf("Type Method returned %d; want 250", i)
2208 m, ok := TypeOf(p).MethodByName("Dist")
2210 t.Fatalf("method by name failed")
2212 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2214 t.Errorf("Type MethodByName returned %d; want 275", i)
2217 m, ok = TypeOf(p).MethodByName("NoArgs")
2219 t.Fatalf("method by name failed")
2221 n := len(m.Func.Call([]Value{ValueOf(p)}))
2223 t.Errorf("NoArgs returned %d values; want 0", n)
2226 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2228 t.Errorf("Pointer Type Method returned %d; want 300", i)
2231 m, ok = TypeOf(&p).MethodByName("Dist")
2233 t.Fatalf("ptr method by name failed")
2235 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2237 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2240 m, ok = TypeOf(&p).MethodByName("NoArgs")
2242 t.Fatalf("method by name failed")
2244 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2246 t.Errorf("NoArgs returned %d values; want 0", n)
2249 // Curried method of value.
2250 tfunc := TypeOf((func(int) int)(nil))
2251 v := ValueOf(p).Method(1)
2252 if tt := v.Type(); tt != tfunc {
2253 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2255 i = v.Call([]Value{ValueOf(14)})[0].Int()
2257 t.Errorf("Value Method returned %d; want 350", i)
2259 v = ValueOf(p).MethodByName("Dist")
2260 if tt := v.Type(); tt != tfunc {
2261 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2263 i = v.Call([]Value{ValueOf(15)})[0].Int()
2265 t.Errorf("Value MethodByName returned %d; want 375", i)
2267 v = ValueOf(p).MethodByName("NoArgs")
2270 // Curried method of pointer.
2271 v = ValueOf(&p).Method(1)
2272 if tt := v.Type(); tt != tfunc {
2273 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2275 i = v.Call([]Value{ValueOf(16)})[0].Int()
2277 t.Errorf("Pointer Value Method returned %d; want 400", i)
2279 v = ValueOf(&p).MethodByName("Dist")
2280 if tt := v.Type(); tt != tfunc {
2281 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2283 i = v.Call([]Value{ValueOf(17)})[0].Int()
2285 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2287 v = ValueOf(&p).MethodByName("NoArgs")
2290 // Curried method of interface value.
2291 // Have to wrap interface value in a struct to get at it.
2292 // Passing it to ValueOf directly would
2293 // access the underlying Point, not the interface.
2297 pv := ValueOf(&x).Elem()
2299 if tt := v.Type(); tt != tfunc {
2300 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2302 i = v.Call([]Value{ValueOf(18)})[0].Int()
2304 t.Errorf("Interface Method returned %d; want 450", i)
2306 v = pv.MethodByName("Dist")
2307 if tt := v.Type(); tt != tfunc {
2308 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2310 i = v.Call([]Value{ValueOf(19)})[0].Int()
2312 t.Errorf("Interface MethodByName returned %d; want 475", i)
2316 func TestMethodValue(t *testing.T) {
2320 // Curried method of value.
2321 tfunc := TypeOf((func(int) int)(nil))
2322 v := ValueOf(p).Method(1)
2323 if tt := v.Type(); tt != tfunc {
2324 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2326 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2328 t.Errorf("Value Method returned %d; want 250", i)
2330 v = ValueOf(p).MethodByName("Dist")
2331 if tt := v.Type(); tt != tfunc {
2332 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2334 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2336 t.Errorf("Value MethodByName returned %d; want 275", i)
2338 v = ValueOf(p).MethodByName("NoArgs")
2339 ValueOf(v.Interface()).Call(nil)
2340 v.Interface().(func())()
2342 // Curried method of pointer.
2343 v = ValueOf(&p).Method(1)
2344 if tt := v.Type(); tt != tfunc {
2345 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2347 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2349 t.Errorf("Pointer Value Method returned %d; want 300", i)
2351 v = ValueOf(&p).MethodByName("Dist")
2352 if tt := v.Type(); tt != tfunc {
2353 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2355 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2357 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2359 v = ValueOf(&p).MethodByName("NoArgs")
2360 ValueOf(v.Interface()).Call(nil)
2361 v.Interface().(func())()
2363 // Curried method of pointer to pointer.
2365 v = ValueOf(&pp).Elem().Method(1)
2366 if tt := v.Type(); tt != tfunc {
2367 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2369 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2371 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2373 v = ValueOf(&pp).Elem().MethodByName("Dist")
2374 if tt := v.Type(); tt != tfunc {
2375 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2377 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2379 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2382 // Curried method of interface value.
2383 // Have to wrap interface value in a struct to get at it.
2384 // Passing it to ValueOf directly would
2385 // access the underlying Point, not the interface.
2391 pv := ValueOf(s).Field(0)
2393 if tt := v.Type(); tt != tfunc {
2394 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2396 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2398 t.Errorf("Interface Method returned %d; want 400", i)
2400 v = pv.MethodByName("Dist")
2401 if tt := v.Type(); tt != tfunc {
2402 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2404 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2406 t.Errorf("Interface MethodByName returned %d; want 425", i)
2409 // For issue #33628: method args are not stored at the right offset
2411 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2412 if x := m64(123); x != 123 {
2413 t.Errorf("Int64Method returned %d; want 123", x)
2415 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2416 if x := m32(456); x != 456 {
2417 t.Errorf("Int32Method returned %d; want 456", x)
2421 func TestVariadicMethodValue(t *testing.T) {
2423 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2424 want := int64(p.TotalDist(points[0], points[1], points[2]))
2426 // Variadic method of type.
2427 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2428 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2429 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2432 // Curried method of value.
2433 tfunc = TypeOf((func(...Point) int)(nil))
2434 v := ValueOf(p).Method(4)
2435 if tt := v.Type(); tt != tfunc {
2436 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2438 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2440 t.Errorf("Variadic Method returned %d; want %d", i, want)
2442 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2444 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2447 f := v.Interface().(func(...Point) int)
2448 i = int64(f(points[0], points[1], points[2]))
2450 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2452 i = int64(f(points...))
2454 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2458 type DirectIfaceT struct {
2462 func (d DirectIfaceT) M() int { return *d.p }
2464 func TestDirectIfaceMethod(t *testing.T) {
2466 v := DirectIfaceT{&x}
2468 m, ok := typ.MethodByName("M")
2470 t.Fatalf("cannot find method M")
2472 in := []Value{ValueOf(v)}
2473 out := m.Func.Call(in)
2474 if got := out[0].Int(); got != 42 {
2475 t.Errorf("Call with value receiver got %d, want 42", got)
2480 m, ok = typ.MethodByName("M")
2482 t.Fatalf("cannot find method M")
2484 in = []Value{ValueOf(pv)}
2485 out = m.Func.Call(in)
2486 if got := out[0].Int(); got != 42 {
2487 t.Errorf("Call with pointer receiver got %d, want 42", got)
2491 // Reflect version of $GOROOT/test/method5.go
2493 // Concrete types implementing M method.
2494 // Smaller than a word, word-sized, larger than a word.
2495 // Value and pointer receivers.
2497 type Tinter interface {
2498 M(int, byte) (byte, int)
2503 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2507 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2511 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2515 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2517 type Tbigv [2]uintptr
2519 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2521 type Tbigp [2]uintptr
2523 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2525 type tinter interface {
2526 m(int, byte) (byte, int)
2529 // Embedding via pointer.
2546 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2548 func TestMethod5(t *testing.T) {
2549 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2551 if b != 99 || x != 1000+inc {
2552 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2556 CheckV := func(name string, i Value, inc int) {
2557 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2558 b := bx[0].Interface()
2559 x := bx[1].Interface()
2560 if b != byte(99) || x != 1000+inc {
2561 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2564 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2567 var TinterType = TypeOf(new(Tinter)).Elem()
2569 CheckI := func(name string, i interface{}, inc int) {
2571 CheckV(name, v, inc)
2572 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2577 CheckI("&sv", &sv, 1)
2580 CheckI("&sp", &sp, 2)
2584 CheckI("&wv", &wv, 3)
2587 CheckI("&wp", &wp, 4)
2589 bv := Tbigv([2]uintptr{5, 6})
2590 CheckI("bv", bv, 11)
2591 CheckI("&bv", &bv, 11)
2593 bp := Tbigp([2]uintptr{7, 8})
2594 CheckI("&bp", &bp, 15)
2600 CheckI("t4", t4, 40)
2601 CheckI("&t4", &t4, 40)
2602 CheckI("t3", t3, 40)
2603 CheckI("&t3", &t3, 40)
2604 CheckI("t2", t2, 40)
2605 CheckI("&t2", &t2, 40)
2606 CheckI("t1", t1, 40)
2607 CheckI("&t1", &t1, 40)
2610 vnil := ValueOf(&tnil).Elem()
2611 shouldPanic("Method", func() { vnil.Method(0) })
2614 func TestInterfaceSet(t *testing.T) {
2623 sv := ValueOf(&s).Elem()
2624 sv.Field(0).Set(ValueOf(p))
2625 if q := s.I.(*Point); q != p {
2626 t.Errorf("i: have %p want %p", q, p)
2631 if q := s.P.(*Point); q != p {
2632 t.Errorf("i: have %p want %p", q, p)
2635 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2637 t.Errorf("Interface Method returned %d; want 250", i)
2646 func TestAnonymousFields(t *testing.T) {
2647 var field StructField
2651 if field, ok = type1.FieldByName("int"); !ok {
2652 t.Fatal("no field 'int'")
2654 if field.Index[0] != 1 {
2655 t.Error("field index should be 1; is", field.Index)
2709 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2731 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2750 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2764 var fieldTests = []FTest{
2765 {struct{}{}, "", nil, 0},
2766 {struct{}{}, "Foo", nil, 0},
2767 {S0{A: 'a'}, "A", []int{0}, 'a'},
2768 {S0{}, "D", nil, 0},
2769 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2770 {S1{B: 'b'}, "B", []int{0}, 'b'},
2771 {S1{}, "S0", []int{1}, 0},
2772 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2773 {S2{A: 'a'}, "A", []int{0}, 'a'},
2774 {S2{}, "S1", []int{1}, 0},
2775 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2776 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2777 {S2{}, "D", nil, 0},
2778 {S3{}, "S1", nil, 0},
2779 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2780 {S3{}, "B", nil, 0},
2781 {S3{D: 'd'}, "D", []int{2}, 0},
2782 {S3{E: 'e'}, "E", []int{3}, 'e'},
2783 {S4{A: 'a'}, "A", []int{1}, 'a'},
2784 {S4{}, "B", nil, 0},
2785 {S5{}, "X", nil, 0},
2786 {S5{}, "Y", []int{2, 0, 1}, 0},
2787 {S10{}, "X", nil, 0},
2788 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2789 {S14{}, "X", nil, 0},
2792 func TestFieldByIndex(t *testing.T) {
2793 for _, test := range fieldTests {
2795 f := s.FieldByIndex(test.index)
2797 if test.index != nil {
2798 if f.Name != test.name {
2799 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2802 t.Errorf("%s.%s found", s.Name(), f.Name)
2804 } else if len(test.index) > 0 {
2805 t.Errorf("%s.%s not found", s.Name(), test.name)
2808 if test.value != 0 {
2809 v := ValueOf(test.s).FieldByIndex(test.index)
2811 if x, ok := v.Interface().(int); ok {
2812 if x != test.value {
2813 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2816 t.Errorf("%s%v value not an int", s.Name(), test.index)
2819 t.Errorf("%s%v value not found", s.Name(), test.index)
2825 func TestFieldByName(t *testing.T) {
2826 for _, test := range fieldTests {
2828 f, found := s.FieldByName(test.name)
2830 if test.index != nil {
2831 // Verify field depth and index.
2832 if len(f.Index) != len(test.index) {
2833 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)
2835 for i, x := range f.Index {
2836 if x != test.index[i] {
2837 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2842 t.Errorf("%s.%s found", s.Name(), f.Name)
2844 } else if len(test.index) > 0 {
2845 t.Errorf("%s.%s not found", s.Name(), test.name)
2848 if test.value != 0 {
2849 v := ValueOf(test.s).FieldByName(test.name)
2851 if x, ok := v.Interface().(int); ok {
2852 if x != test.value {
2853 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2856 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2859 t.Errorf("%s.%s value not found", s.Name(), test.name)
2865 func TestImportPath(t *testing.T) {
2870 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2871 {TypeOf(int(0)), ""},
2872 {TypeOf(int8(0)), ""},
2873 {TypeOf(int16(0)), ""},
2874 {TypeOf(int32(0)), ""},
2875 {TypeOf(int64(0)), ""},
2876 {TypeOf(uint(0)), ""},
2877 {TypeOf(uint8(0)), ""},
2878 {TypeOf(uint16(0)), ""},
2879 {TypeOf(uint32(0)), ""},
2880 {TypeOf(uint64(0)), ""},
2881 {TypeOf(uintptr(0)), ""},
2882 {TypeOf(float32(0)), ""},
2883 {TypeOf(float64(0)), ""},
2884 {TypeOf(complex64(0)), ""},
2885 {TypeOf(complex128(0)), ""},
2886 {TypeOf(byte(0)), ""},
2887 {TypeOf(rune(0)), ""},
2888 {TypeOf([]byte(nil)), ""},
2889 {TypeOf([]rune(nil)), ""},
2890 {TypeOf(string("")), ""},
2891 {TypeOf((*interface{})(nil)).Elem(), ""},
2892 {TypeOf((*byte)(nil)), ""},
2893 {TypeOf((*rune)(nil)), ""},
2894 {TypeOf((*int64)(nil)), ""},
2895 {TypeOf(map[string]int{}), ""},
2896 {TypeOf((*error)(nil)).Elem(), ""},
2897 {TypeOf((*Point)(nil)), ""},
2898 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
2900 for _, test := range tests {
2901 if path := test.t.PkgPath(); path != test.path {
2902 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2907 func TestFieldPkgPath(t *testing.T) {
2909 typ := TypeOf(struct {
2917 type pkgpathTest struct {
2924 checkPkgPath := func(name string, s []pkgpathTest) {
2925 for _, test := range s {
2926 f := typ.FieldByIndex(test.index)
2927 if got, want := f.PkgPath, test.pkgPath; got != want {
2928 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
2930 if got, want := f.Anonymous, test.embedded; got != want {
2931 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
2933 if got, want := f.IsExported(), test.exported; got != want {
2934 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
2939 checkPkgPath("testStruct", []pkgpathTest{
2940 {[]int{0}, "", false, true}, // Exported
2941 {[]int{1}, "reflect_test", false, false}, // unexported
2942 {[]int{2}, "", true, true}, // OtherPkgFields
2943 {[]int{2, 0}, "", false, true}, // OtherExported
2944 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
2945 {[]int{3}, "reflect_test", true, false}, // int
2946 {[]int{4}, "reflect_test", true, false}, // *x
2949 type localOtherPkgFields OtherPkgFields
2950 typ = TypeOf(localOtherPkgFields{})
2951 checkPkgPath("localOtherPkgFields", []pkgpathTest{
2952 {[]int{0}, "", false, true}, // OtherExported
2953 {[]int{1}, "reflect", false, false}, // otherUnexported
2957 func TestMethodPkgPath(t *testing.T) {
2962 typ := TypeOf((*interface {
2975 {"x", "reflect_test", false},
2976 {"y", "reflect_test", false},
2979 for _, test := range tests {
2980 m, _ := typ.MethodByName(test.name)
2981 if got, want := m.PkgPath, test.pkgPath; got != want {
2982 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
2984 if got, want := m.IsExported(), test.exported; got != want {
2985 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
2990 func TestVariadicType(t *testing.T) {
2991 // Test example from Type documentation.
2992 var f func(x int, y ...float64)
2994 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2996 if sl.Kind() == Slice {
2997 if sl.Elem() == TypeOf(0.0) {
3005 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3006 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3007 for i := 0; i < typ.NumIn(); i++ {
3008 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3022 func (*inner) M() {}
3023 func (*outer) M() {}
3025 func TestNestedMethods(t *testing.T) {
3026 typ := TypeOf((*outer)(nil))
3027 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
3028 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3029 for i := 0; i < typ.NumMethod(); i++ {
3031 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3038 func (*unexp) f() (int32, int8) { return 7, 7 }
3039 func (*unexp) g() (int64, int8) { return 8, 8 }
3041 type unexpI interface {
3045 var unexpi unexpI = new(unexp)
3047 func TestUnexportedMethods(t *testing.T) {
3048 typ := TypeOf(unexpi)
3050 if got := typ.NumMethod(); got != 0 {
3051 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3055 type InnerInt struct {
3059 type OuterInt struct {
3064 func (i *InnerInt) M() int {
3068 func TestEmbeddedMethods(t *testing.T) {
3069 typ := TypeOf((*OuterInt)(nil))
3070 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
3071 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3072 for i := 0; i < typ.NumMethod(); i++ {
3074 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3079 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3080 t.Errorf("i.M() = %d, want 3", v)
3083 o := &OuterInt{1, InnerInt{2}}
3084 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3085 t.Errorf("i.M() = %d, want 2", v)
3089 if v := f(o); v != 2 {
3090 t.Errorf("f(o) = %d, want 2", v)
3094 type FuncDDD func(...interface{}) error
3096 func (f FuncDDD) M() {}
3098 func TestNumMethodOnDDD(t *testing.T) {
3099 rv := ValueOf((FuncDDD)(nil))
3100 if n := rv.NumMethod(); n != 1 {
3101 t.Fatalf("NumMethod()=%d, want 1", n)
3105 func TestPtrTo(t *testing.T) {
3106 // This block of code means that the ptrToThis field of the
3107 // reflect data for *unsafe.Pointer is non zero, see
3108 // https://golang.org/issue/19003
3109 var x unsafe.Pointer
3116 for i = 0; i < 100; i++ {
3119 for i = 0; i < 100; i++ {
3122 if typ != TypeOf(z) {
3123 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
3127 func TestPtrToGC(t *testing.T) {
3129 tt := TypeOf(T(nil))
3133 for i := 0; i < n; i++ {
3138 v.Elem().Set(ValueOf(p).Convert(pt))
3139 x = append(x, v.Interface())
3143 for i, xi := range x {
3144 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3145 if k != uintptr(i) {
3146 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3151 func BenchmarkPtrTo(b *testing.B) {
3152 // Construct a type with a zero ptrToThis.
3153 type T struct{ int }
3154 t := SliceOf(TypeOf(T{}))
3155 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3156 if !ptrToThis.IsValid() {
3157 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3159 if ptrToThis.Int() != 0 {
3160 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3164 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
3166 b.RunParallel(func(pb *testing.PB) {
3173 func TestAddr(t *testing.T) {
3185 t.Errorf("Addr.Elem.Set failed to set value")
3188 // Again but take address of the ValueOf value.
3189 // Exercises generation of PtrTypes not present in the binary.
3191 v = ValueOf(&q).Elem()
3200 t.Errorf("Addr.Elem.Set failed to set value")
3203 // Starting without pointer we should get changed value
3206 v = ValueOf(&qq).Elem()
3212 if p.X != 3 { // should be unchanged from last time
3213 t.Errorf("somehow value Set changed original p")
3215 p = v0.Interface().(struct {
3219 t.Errorf("Addr.Elem.Set valued to set value in top value")
3222 // Verify that taking the address of a type gives us a pointer
3223 // which we can convert back using the usual interface
3228 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3229 *(ps.(**bool)) = new(bool)
3231 t.Errorf("Addr.Interface direct assignment failed")
3235 func noAlloc(t *testing.T, n int, f func(int)) {
3236 if testing.Short() {
3237 t.Skip("skipping malloc count in short mode")
3239 if runtime.GOMAXPROCS(0) > 1 {
3240 t.Skip("skipping; GOMAXPROCS>1")
3243 allocs := testing.AllocsPerRun(n, func() {
3248 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3252 func TestAllocations(t *testing.T) {
3253 noAlloc(t, 100, func(j int) {
3257 // We can uncomment this when compiler escape analysis
3258 // is good enough to see that the integer assigned to i
3259 // does not escape and therefore need not be allocated.
3263 // if int(v.Int()) != 42+j {
3264 // panic("wrong int")
3267 i = func(j int) int { return j }
3269 if v.Interface().(func(int) int)(j) != j {
3270 panic("wrong result")
3275 func TestSmallNegativeInt(t *testing.T) {
3279 t.Errorf("int16(-1).Int() returned %v", v.Int())
3283 func TestIndex(t *testing.T) {
3284 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3285 v := ValueOf(xs).Index(3).Interface().(byte)
3287 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3289 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3290 v = ValueOf(xa).Index(2).Interface().(byte)
3292 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3295 v = ValueOf(s).Index(3).Interface().(byte)
3297 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3301 func TestSlice(t *testing.T) {
3302 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3303 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3305 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3308 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3310 if !DeepEqual(v[0:5], xs[3:]) {
3311 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3313 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3314 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3316 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3319 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3321 if !DeepEqual(v[0:6], xa[2:]) {
3322 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3325 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3327 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3330 rv := ValueOf(&xs).Elem()
3332 ptr2 := rv.Pointer()
3334 ptr3 := rv.Pointer()
3336 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
3340 func TestSlice3(t *testing.T) {
3341 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3342 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3344 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3347 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3349 if !DeepEqual(v[0:4], xs[3:7:7]) {
3350 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3352 rv := ValueOf(&xs).Elem()
3353 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3354 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3355 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3357 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3358 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3360 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3363 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3365 if !DeepEqual(v[0:4], xa[2:6:6]) {
3366 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3368 rv = ValueOf(&xa).Elem()
3369 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3370 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3371 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3374 rv = ValueOf(&s).Elem()
3375 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3377 rv = ValueOf(&xs).Elem()
3378 rv = rv.Slice3(3, 5, 7)
3379 ptr2 := rv.Pointer()
3380 rv = rv.Slice3(4, 4, 4)
3381 ptr3 := rv.Pointer()
3383 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
3387 func TestSetLenCap(t *testing.T) {
3388 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3389 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3391 vs := ValueOf(&xs).Elem()
3392 shouldPanic("SetLen", func() { vs.SetLen(10) })
3393 shouldPanic("SetCap", func() { vs.SetCap(10) })
3394 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3395 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3396 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3398 if len(xs) != 5 || cap(xs) != 8 {
3399 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3402 if len(xs) != 5 || cap(xs) != 6 {
3403 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3406 if len(xs) != 5 || cap(xs) != 5 {
3407 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3409 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3410 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3412 va := ValueOf(&xa).Elem()
3413 shouldPanic("SetLen", func() { va.SetLen(8) })
3414 shouldPanic("SetCap", func() { va.SetCap(8) })
3417 func TestVariadic(t *testing.T) {
3422 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3423 if b.String() != "hello, 42 world" {
3424 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3428 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3429 if b.String() != "hello, 42 world" {
3430 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3434 func TestFuncArg(t *testing.T) {
3435 f1 := func(i int, f func(int) int) int { return f(i) }
3436 f2 := func(i int) int { return i + 1 }
3437 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3438 if r[0].Int() != 101 {
3439 t.Errorf("function returned %d, want 101", r[0].Int())
3443 func TestStructArg(t *testing.T) {
3444 type padded struct {
3451 wantA = padded{"3", 4}
3454 f := func(a padded, b uint32) {
3457 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3458 if gotA != wantA || gotB != wantB {
3459 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3463 var tagGetTests = []struct {
3468 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3469 {`protobuf:"PB(1,2)"`, `foo`, ``},
3470 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3471 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3472 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3473 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3474 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3477 func TestTagGet(t *testing.T) {
3478 for _, tt := range tagGetTests {
3479 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3480 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3485 func TestBytes(t *testing.T) {
3488 y := ValueOf(x).Bytes()
3489 if !bytes.Equal(x, y) {
3490 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3493 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3497 func TestSetBytes(t *testing.T) {
3500 y := []byte{1, 2, 3, 4}
3501 ValueOf(&x).Elem().SetBytes(y)
3502 if !bytes.Equal(x, y) {
3503 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3506 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3510 type Private struct {
3516 func (p *Private) m() {
3519 type private struct {
3527 func (p *private) P() {
3530 type Public struct {
3536 func (p *Public) M() {
3539 func TestUnexported(t *testing.T) {
3544 isValid(v.Elem().Field(0))
3545 isValid(v.Elem().Field(1))
3546 isValid(v.Elem().Field(2))
3547 isValid(v.Elem().FieldByName("X"))
3548 isValid(v.Elem().FieldByName("Y"))
3549 isValid(v.Elem().FieldByName("Z"))
3550 isValid(v.Type().Method(0).Func)
3551 m, _ := v.Type().MethodByName("M")
3553 m, _ = v.Type().MethodByName("P")
3555 isNonNil(v.Elem().Field(0).Interface())
3556 isNonNil(v.Elem().Field(1).Interface())
3557 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3558 isNonNil(v.Elem().FieldByName("X").Interface())
3559 isNonNil(v.Elem().FieldByName("Y").Interface())
3560 isNonNil(v.Elem().FieldByName("Z").Interface())
3561 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3562 isNonNil(v.Type().Method(0).Func.Interface())
3563 m, _ = v.Type().MethodByName("P")
3564 isNonNil(m.Func.Interface())
3568 isValid(v.Elem().Field(0))
3569 isValid(v.Elem().Field(1))
3570 isValid(v.Elem().FieldByName("x"))
3571 isValid(v.Elem().FieldByName("y"))
3572 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3573 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3574 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3575 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3576 shouldPanic("Method", func() { v.Type().Method(0) })
3579 func TestSetPanic(t *testing.T) {
3580 ok := func(f func()) { f() }
3581 bad := func(f func()) { shouldPanic("Set", f) }
3582 clear := func(v Value) { v.Set(Zero(v.Type())) }
3610 bad(func() { clear(v.Field(0)) }) // .X
3611 bad(func() { clear(v.Field(1)) }) // .t1
3612 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3613 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3614 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3615 bad(func() { clear(v.Field(2)) }) // .T2
3616 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3617 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3618 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3619 bad(func() { clear(v.Field(3)) }) // .NamedT1
3620 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3621 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3622 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3623 bad(func() { clear(v.Field(4)) }) // .NamedT2
3624 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3625 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3626 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3627 bad(func() { clear(v.Field(5)) }) // .namedT1
3628 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3629 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3630 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3631 bad(func() { clear(v.Field(6)) }) // .namedT2
3632 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3633 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3634 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3637 v = ValueOf(&T{}).Elem()
3638 ok(func() { clear(v.Field(0)) }) // .X
3639 bad(func() { clear(v.Field(1)) }) // .t1
3640 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3641 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3642 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3643 ok(func() { clear(v.Field(2)) }) // .T2
3644 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3645 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3646 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3647 ok(func() { clear(v.Field(3)) }) // .NamedT1
3648 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3649 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3650 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3651 ok(func() { clear(v.Field(4)) }) // .NamedT2
3652 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3653 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3654 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3655 bad(func() { clear(v.Field(5)) }) // .namedT1
3656 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3657 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3658 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3659 bad(func() { clear(v.Field(6)) }) // .namedT2
3660 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3661 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3662 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3667 func (t timp) W() {}
3668 func (t timp) Y() {}
3669 func (t timp) w() {}
3670 func (t timp) y() {}
3672 func TestCallPanic(t *testing.T) {
3697 ok := func(f func()) { f() }
3698 badCall := func(f func()) { shouldPanic("Call", f) }
3699 badMethod := func(f func()) { shouldPanic("Method", f) }
3700 call := func(v Value) { v.Call(nil) }
3703 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3704 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3705 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3706 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3707 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3708 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3709 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3710 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3711 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3713 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3714 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3715 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3716 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3718 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3719 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3720 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3721 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3723 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3724 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3725 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3726 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3728 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3729 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3730 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3731 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3733 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3734 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3735 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3736 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3738 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3739 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3740 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3741 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3744 func shouldPanic(expect string, f func()) {
3748 panic("did not panic")
3752 switch r := r.(type) {
3758 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3760 if !strings.HasPrefix(s, "reflect") {
3761 panic(`panic string does not start with "reflect": ` + s)
3763 if !strings.Contains(s, expect) {
3764 panic(`panic string does not contain "` + expect + `": ` + s)
3771 func isNonNil(x interface{}) {
3773 panic("nil interface")
3777 func isValid(v Value) {
3783 func TestAlias(t *testing.T) {
3784 x := string("hello")
3785 v := ValueOf(&x).Elem()
3786 oldvalue := v.Interface()
3787 v.SetString("world")
3788 newvalue := v.Interface()
3790 if oldvalue != "hello" || newvalue != "world" {
3791 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3797 func EmptyInterfaceV(x interface{}) Value {
3798 return ValueOf(&x).Elem()
3801 func ReaderV(x io.Reader) Value {
3802 return ValueOf(&x).Elem()
3805 func ReadWriterV(x io.ReadWriter) Value {
3806 return ValueOf(&x).Elem()
3810 type MyStruct struct {
3813 type MyStruct1 struct {
3818 type MyStruct2 struct {
3823 type MyString string
3825 type MyBytesArrayPtr0 *[0]byte
3826 type MyBytesArrayPtr *[4]byte
3827 type MyBytesArray0 [0]byte
3828 type MyBytesArray [4]byte
3829 type MyRunes []int32
3833 type IntChan chan int
3834 type IntChanRecv <-chan int
3835 type IntChanSend chan<- int
3836 type BytesChan chan []byte
3837 type BytesChanRecv <-chan []byte
3838 type BytesChanSend chan<- []byte
3840 var convertTests = []struct {
3846 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3852 var numbers = []string{
3853 "int8", "uint8", "int16", "uint16",
3854 "int32", "uint32", "int64", "uint64",
3855 "int", "uint", "uintptr",
3856 "float32", "float64",
3860 // all pairs but in an unusual order,
3861 // to emit all the int8, uint8 cases
3862 // before n grows too big.
3864 for i, f := range numbers {
3865 for _, g := range numbers[i:] {
3866 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3869 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3876 {V(int8(1)), V(int8(1))},
3877 {V(int8(2)), V(uint8(2))},
3878 {V(uint8(3)), V(int8(3))},
3879 {V(int8(4)), V(int16(4))},
3880 {V(int16(5)), V(int8(5))},
3881 {V(int8(6)), V(uint16(6))},
3882 {V(uint16(7)), V(int8(7))},
3883 {V(int8(8)), V(int32(8))},
3884 {V(int32(9)), V(int8(9))},
3885 {V(int8(10)), V(uint32(10))},
3886 {V(uint32(11)), V(int8(11))},
3887 {V(int8(12)), V(int64(12))},
3888 {V(int64(13)), V(int8(13))},
3889 {V(int8(14)), V(uint64(14))},
3890 {V(uint64(15)), V(int8(15))},
3891 {V(int8(16)), V(int(16))},
3892 {V(int(17)), V(int8(17))},
3893 {V(int8(18)), V(uint(18))},
3894 {V(uint(19)), V(int8(19))},
3895 {V(int8(20)), V(uintptr(20))},
3896 {V(uintptr(21)), V(int8(21))},
3897 {V(int8(22)), V(float32(22))},
3898 {V(float32(23)), V(int8(23))},
3899 {V(int8(24)), V(float64(24))},
3900 {V(float64(25)), V(int8(25))},
3901 {V(uint8(26)), V(uint8(26))},
3902 {V(uint8(27)), V(int16(27))},
3903 {V(int16(28)), V(uint8(28))},
3904 {V(uint8(29)), V(uint16(29))},
3905 {V(uint16(30)), V(uint8(30))},
3906 {V(uint8(31)), V(int32(31))},
3907 {V(int32(32)), V(uint8(32))},
3908 {V(uint8(33)), V(uint32(33))},
3909 {V(uint32(34)), V(uint8(34))},
3910 {V(uint8(35)), V(int64(35))},
3911 {V(int64(36)), V(uint8(36))},
3912 {V(uint8(37)), V(uint64(37))},
3913 {V(uint64(38)), V(uint8(38))},
3914 {V(uint8(39)), V(int(39))},
3915 {V(int(40)), V(uint8(40))},
3916 {V(uint8(41)), V(uint(41))},
3917 {V(uint(42)), V(uint8(42))},
3918 {V(uint8(43)), V(uintptr(43))},
3919 {V(uintptr(44)), V(uint8(44))},
3920 {V(uint8(45)), V(float32(45))},
3921 {V(float32(46)), V(uint8(46))},
3922 {V(uint8(47)), V(float64(47))},
3923 {V(float64(48)), V(uint8(48))},
3924 {V(int16(49)), V(int16(49))},
3925 {V(int16(50)), V(uint16(50))},
3926 {V(uint16(51)), V(int16(51))},
3927 {V(int16(52)), V(int32(52))},
3928 {V(int32(53)), V(int16(53))},
3929 {V(int16(54)), V(uint32(54))},
3930 {V(uint32(55)), V(int16(55))},
3931 {V(int16(56)), V(int64(56))},
3932 {V(int64(57)), V(int16(57))},
3933 {V(int16(58)), V(uint64(58))},
3934 {V(uint64(59)), V(int16(59))},
3935 {V(int16(60)), V(int(60))},
3936 {V(int(61)), V(int16(61))},
3937 {V(int16(62)), V(uint(62))},
3938 {V(uint(63)), V(int16(63))},
3939 {V(int16(64)), V(uintptr(64))},
3940 {V(uintptr(65)), V(int16(65))},
3941 {V(int16(66)), V(float32(66))},
3942 {V(float32(67)), V(int16(67))},
3943 {V(int16(68)), V(float64(68))},
3944 {V(float64(69)), V(int16(69))},
3945 {V(uint16(70)), V(uint16(70))},
3946 {V(uint16(71)), V(int32(71))},
3947 {V(int32(72)), V(uint16(72))},
3948 {V(uint16(73)), V(uint32(73))},
3949 {V(uint32(74)), V(uint16(74))},
3950 {V(uint16(75)), V(int64(75))},
3951 {V(int64(76)), V(uint16(76))},
3952 {V(uint16(77)), V(uint64(77))},
3953 {V(uint64(78)), V(uint16(78))},
3954 {V(uint16(79)), V(int(79))},
3955 {V(int(80)), V(uint16(80))},
3956 {V(uint16(81)), V(uint(81))},
3957 {V(uint(82)), V(uint16(82))},
3958 {V(uint16(83)), V(uintptr(83))},
3959 {V(uintptr(84)), V(uint16(84))},
3960 {V(uint16(85)), V(float32(85))},
3961 {V(float32(86)), V(uint16(86))},
3962 {V(uint16(87)), V(float64(87))},
3963 {V(float64(88)), V(uint16(88))},
3964 {V(int32(89)), V(int32(89))},
3965 {V(int32(90)), V(uint32(90))},
3966 {V(uint32(91)), V(int32(91))},
3967 {V(int32(92)), V(int64(92))},
3968 {V(int64(93)), V(int32(93))},
3969 {V(int32(94)), V(uint64(94))},
3970 {V(uint64(95)), V(int32(95))},
3971 {V(int32(96)), V(int(96))},
3972 {V(int(97)), V(int32(97))},
3973 {V(int32(98)), V(uint(98))},
3974 {V(uint(99)), V(int32(99))},
3975 {V(int32(100)), V(uintptr(100))},
3976 {V(uintptr(101)), V(int32(101))},
3977 {V(int32(102)), V(float32(102))},
3978 {V(float32(103)), V(int32(103))},
3979 {V(int32(104)), V(float64(104))},
3980 {V(float64(105)), V(int32(105))},
3981 {V(uint32(106)), V(uint32(106))},
3982 {V(uint32(107)), V(int64(107))},
3983 {V(int64(108)), V(uint32(108))},
3984 {V(uint32(109)), V(uint64(109))},
3985 {V(uint64(110)), V(uint32(110))},
3986 {V(uint32(111)), V(int(111))},
3987 {V(int(112)), V(uint32(112))},
3988 {V(uint32(113)), V(uint(113))},
3989 {V(uint(114)), V(uint32(114))},
3990 {V(uint32(115)), V(uintptr(115))},
3991 {V(uintptr(116)), V(uint32(116))},
3992 {V(uint32(117)), V(float32(117))},
3993 {V(float32(118)), V(uint32(118))},
3994 {V(uint32(119)), V(float64(119))},
3995 {V(float64(120)), V(uint32(120))},
3996 {V(int64(121)), V(int64(121))},
3997 {V(int64(122)), V(uint64(122))},
3998 {V(uint64(123)), V(int64(123))},
3999 {V(int64(124)), V(int(124))},
4000 {V(int(125)), V(int64(125))},
4001 {V(int64(126)), V(uint(126))},
4002 {V(uint(127)), V(int64(127))},
4003 {V(int64(128)), V(uintptr(128))},
4004 {V(uintptr(129)), V(int64(129))},
4005 {V(int64(130)), V(float32(130))},
4006 {V(float32(131)), V(int64(131))},
4007 {V(int64(132)), V(float64(132))},
4008 {V(float64(133)), V(int64(133))},
4009 {V(uint64(134)), V(uint64(134))},
4010 {V(uint64(135)), V(int(135))},
4011 {V(int(136)), V(uint64(136))},
4012 {V(uint64(137)), V(uint(137))},
4013 {V(uint(138)), V(uint64(138))},
4014 {V(uint64(139)), V(uintptr(139))},
4015 {V(uintptr(140)), V(uint64(140))},
4016 {V(uint64(141)), V(float32(141))},
4017 {V(float32(142)), V(uint64(142))},
4018 {V(uint64(143)), V(float64(143))},
4019 {V(float64(144)), V(uint64(144))},
4020 {V(int(145)), V(int(145))},
4021 {V(int(146)), V(uint(146))},
4022 {V(uint(147)), V(int(147))},
4023 {V(int(148)), V(uintptr(148))},
4024 {V(uintptr(149)), V(int(149))},
4025 {V(int(150)), V(float32(150))},
4026 {V(float32(151)), V(int(151))},
4027 {V(int(152)), V(float64(152))},
4028 {V(float64(153)), V(int(153))},
4029 {V(uint(154)), V(uint(154))},
4030 {V(uint(155)), V(uintptr(155))},
4031 {V(uintptr(156)), V(uint(156))},
4032 {V(uint(157)), V(float32(157))},
4033 {V(float32(158)), V(uint(158))},
4034 {V(uint(159)), V(float64(159))},
4035 {V(float64(160)), V(uint(160))},
4036 {V(uintptr(161)), V(uintptr(161))},
4037 {V(uintptr(162)), V(float32(162))},
4038 {V(float32(163)), V(uintptr(163))},
4039 {V(uintptr(164)), V(float64(164))},
4040 {V(float64(165)), V(uintptr(165))},
4041 {V(float32(166)), V(float32(166))},
4042 {V(float32(167)), V(float64(167))},
4043 {V(float64(168)), V(float32(168))},
4044 {V(float64(169)), V(float64(169))},
4047 {V(float64(1.5)), V(int(1))},
4050 {V(complex64(1i)), V(complex64(1i))},
4051 {V(complex64(2i)), V(complex128(2i))},
4052 {V(complex128(3i)), V(complex64(3i))},
4053 {V(complex128(4i)), V(complex128(4i))},
4056 {V(string("hello")), V(string("hello"))},
4057 {V(string("bytes1")), V([]byte("bytes1"))},
4058 {V([]byte("bytes2")), V(string("bytes2"))},
4059 {V([]byte("bytes3")), V([]byte("bytes3"))},
4060 {V(string("runes♝")), V([]rune("runes♝"))},
4061 {V([]rune("runes♕")), V(string("runes♕"))},
4062 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4063 {V(int('a')), V(string("a"))},
4064 {V(int8('a')), V(string("a"))},
4065 {V(int16('a')), V(string("a"))},
4066 {V(int32('a')), V(string("a"))},
4067 {V(int64('a')), V(string("a"))},
4068 {V(uint('a')), V(string("a"))},
4069 {V(uint8('a')), V(string("a"))},
4070 {V(uint16('a')), V(string("a"))},
4071 {V(uint32('a')), V(string("a"))},
4072 {V(uint64('a')), V(string("a"))},
4073 {V(uintptr('a')), V(string("a"))},
4074 {V(int(-1)), V(string("\uFFFD"))},
4075 {V(int8(-2)), V(string("\uFFFD"))},
4076 {V(int16(-3)), V(string("\uFFFD"))},
4077 {V(int32(-4)), V(string("\uFFFD"))},
4078 {V(int64(-5)), V(string("\uFFFD"))},
4079 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4080 {V(int64(1 << 32)), V(string("\uFFFD"))},
4081 {V(uint(0x110001)), V(string("\uFFFD"))},
4082 {V(uint32(0x110002)), V(string("\uFFFD"))},
4083 {V(uint64(0x110003)), V(string("\uFFFD"))},
4084 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4085 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4088 {V(MyString("hello")), V(string("hello"))},
4089 {V(string("hello")), V(MyString("hello"))},
4090 {V(string("hello")), V(string("hello"))},
4091 {V(MyString("hello")), V(MyString("hello"))},
4092 {V(MyString("bytes1")), V([]byte("bytes1"))},
4093 {V([]byte("bytes2")), V(MyString("bytes2"))},
4094 {V([]byte("bytes3")), V([]byte("bytes3"))},
4095 {V(MyString("runes♝")), V([]rune("runes♝"))},
4096 {V([]rune("runes♕")), V(MyString("runes♕"))},
4097 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4098 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4099 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4100 {V(int('a')), V(MyString("a"))},
4101 {V(int8('a')), V(MyString("a"))},
4102 {V(int16('a')), V(MyString("a"))},
4103 {V(int32('a')), V(MyString("a"))},
4104 {V(int64('a')), V(MyString("a"))},
4105 {V(uint('a')), V(MyString("a"))},
4106 {V(uint8('a')), V(MyString("a"))},
4107 {V(uint16('a')), V(MyString("a"))},
4108 {V(uint32('a')), V(MyString("a"))},
4109 {V(uint64('a')), V(MyString("a"))},
4110 {V(uintptr('a')), V(MyString("a"))},
4111 {V(int(-1)), V(MyString("\uFFFD"))},
4112 {V(int8(-2)), V(MyString("\uFFFD"))},
4113 {V(int16(-3)), V(MyString("\uFFFD"))},
4114 {V(int32(-4)), V(MyString("\uFFFD"))},
4115 {V(int64(-5)), V(MyString("\uFFFD"))},
4116 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4117 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4118 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4119 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4122 {V(string("bytes1")), V(MyBytes("bytes1"))},
4123 {V(MyBytes("bytes2")), V(string("bytes2"))},
4124 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4125 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4126 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4129 {V(string("runes♝")), V(MyRunes("runes♝"))},
4130 {V(MyRunes("runes♕")), V(string("runes♕"))},
4131 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4132 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4133 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4135 // slice to array pointer
4136 {V([]byte(nil)), V((*[0]byte)(nil))},
4137 {V([]byte{}), V(new([0]byte))},
4138 {V([]byte{7}), V(&[1]byte{7})},
4139 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4140 {V(MyBytes([]byte{})), V(new([0]byte))},
4141 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4142 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4143 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4144 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4145 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4146 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4148 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4149 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4150 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4151 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4152 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4153 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4154 {V(new([0]byte)), V(new(MyBytesArray0))},
4155 {V(new(MyBytesArray0)), V(new([0]byte))},
4156 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4157 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4159 // named types and equal underlying types
4160 {V(new(int)), V(new(integer))},
4161 {V(new(integer)), V(new(int))},
4162 {V(Empty{}), V(struct{}{})},
4163 {V(new(Empty)), V(new(struct{}))},
4164 {V(struct{}{}), V(Empty{})},
4165 {V(new(struct{})), V(new(Empty))},
4166 {V(Empty{}), V(Empty{})},
4167 {V(MyBytes{}), V([]byte{})},
4168 {V([]byte{}), V(MyBytes{})},
4169 {V((func())(nil)), V(MyFunc(nil))},
4170 {V((MyFunc)(nil)), V((func())(nil))},
4172 // structs with different tags
4185 {V(MyStruct{}), V(struct {
4191 }{}), V(MyStruct{})},
4193 {V(MyStruct{}), V(struct {
4199 }{}), V(MyStruct{})},
4201 {V(MyStruct1{}), V(MyStruct2{})},
4202 {V(MyStruct2{}), V(MyStruct1{})},
4204 // can convert *byte and *MyByte
4205 {V((*byte)(nil)), V((*MyByte)(nil))},
4206 {V((*MyByte)(nil)), V((*byte)(nil))},
4208 // cannot convert mismatched array sizes
4209 {V([2]byte{}), V([2]byte{})},
4210 {V([3]byte{}), V([3]byte{})},
4212 // cannot convert other instances
4213 {V((**byte)(nil)), V((**byte)(nil))},
4214 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4215 {V((chan byte)(nil)), V((chan byte)(nil))},
4216 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4217 {V(([]byte)(nil)), V(([]byte)(nil))},
4218 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4219 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4220 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4221 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4222 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4223 {V([2]byte{}), V([2]byte{})},
4224 {V([2]MyByte{}), V([2]MyByte{})},
4227 {V((***int)(nil)), V((***int)(nil))},
4228 {V((***byte)(nil)), V((***byte)(nil))},
4229 {V((***int32)(nil)), V((***int32)(nil))},
4230 {V((***int64)(nil)), V((***int64)(nil))},
4231 {V((chan byte)(nil)), V((chan byte)(nil))},
4232 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4233 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4234 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4235 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4236 {V([]uint(nil)), V([]uint(nil))},
4237 {V([]int(nil)), V([]int(nil))},
4238 {V(new(interface{})), V(new(interface{}))},
4239 {V(new(io.Reader)), V(new(io.Reader))},
4240 {V(new(io.Writer)), V(new(io.Writer))},
4243 {V(IntChan(nil)), V((chan<- int)(nil))},
4244 {V(IntChan(nil)), V((<-chan int)(nil))},
4245 {V((chan int)(nil)), V(IntChanRecv(nil))},
4246 {V((chan int)(nil)), V(IntChanSend(nil))},
4247 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4248 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4249 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4250 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4251 {V(IntChan(nil)), V((chan int)(nil))},
4252 {V((chan int)(nil)), V(IntChan(nil))},
4253 {V((chan int)(nil)), V((<-chan int)(nil))},
4254 {V((chan int)(nil)), V((chan<- int)(nil))},
4255 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4256 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4257 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4258 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4259 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4260 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4261 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4262 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4263 {V(BytesChan(nil)), V((chan []byte)(nil))},
4264 {V((chan []byte)(nil)), V(BytesChan(nil))},
4265 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4266 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4268 // cannot convert other instances (channels)
4269 {V(IntChan(nil)), V(IntChan(nil))},
4270 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4271 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4272 {V(BytesChan(nil)), V(BytesChan(nil))},
4273 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4274 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4277 {V(int(1)), EmptyInterfaceV(int(1))},
4278 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4279 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4280 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4281 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4284 func TestConvert(t *testing.T) {
4285 canConvert := map[[2]Type]bool{}
4286 all := map[Type]bool{}
4288 for _, tt := range convertTests {
4290 if !t1.ConvertibleTo(t1) {
4291 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4296 if !t1.ConvertibleTo(t2) {
4297 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4303 canConvert[[2]Type{t1, t2}] = true
4305 // vout1 represents the in value converted to the in type.
4307 if !v1.CanConvert(t1) {
4308 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4310 vout1 := v1.Convert(t1)
4311 out1 := vout1.Interface()
4312 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4313 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4316 // vout2 represents the in value converted to the out type.
4317 if !v1.CanConvert(t2) {
4318 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4320 vout2 := v1.Convert(t2)
4321 out2 := vout2.Interface()
4322 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4323 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4325 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4326 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4329 // vout3 represents a new value of the out type, set to vout2. This makes
4330 // sure the converted value vout2 is really usable as a regular value.
4331 vout3 := New(t2).Elem()
4333 out3 := vout3.Interface()
4334 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4335 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4339 t.Errorf("table entry %v is RO, should not be", v1)
4342 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4345 t.Errorf("conversion output %v is RO, should not be", vout2)
4348 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4350 if !IsRO(MakeRO(v1).Convert(t1)) {
4351 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4353 if !IsRO(MakeRO(v1).Convert(t2)) {
4354 t.Errorf("RO conversion output %v is not RO, should be", v1)
4358 // Assume that of all the types we saw during the tests,
4359 // if there wasn't an explicit entry for a conversion between
4360 // a pair of types, then it's not to be allowed. This checks for
4361 // things like 'int64' converting to '*int'.
4362 for t1 := range all {
4363 for t2 := range all {
4364 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4365 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4366 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4372 func TestConvertPanic(t *testing.T) {
4373 s := make([]byte, 4)
4377 if !v.Type().ConvertibleTo(pt) {
4378 t.Errorf("[]byte should be convertible to *[8]byte")
4380 if v.CanConvert(pt) {
4381 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4383 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4388 var gFloat32 float32
4390 func TestConvertNaNs(t *testing.T) {
4391 const snan uint32 = 0x7f800001
4392 type myFloat32 float32
4393 x := V(myFloat32(math.Float32frombits(snan)))
4394 y := x.Convert(TypeOf(float32(0)))
4395 z := y.Interface().(float32)
4396 if got := math.Float32bits(z); got != snan {
4397 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4401 type ComparableStruct struct {
4405 type NonComparableStruct struct {
4410 var comparableTests = []struct {
4415 {TypeOf("hello"), true},
4416 {TypeOf(new(byte)), true},
4417 {TypeOf((func())(nil)), false},
4418 {TypeOf([]byte{}), false},
4419 {TypeOf(map[string]int{}), false},
4420 {TypeOf(make(chan int)), true},
4421 {TypeOf(1.5), true},
4422 {TypeOf(false), true},
4424 {TypeOf(ComparableStruct{}), true},
4425 {TypeOf(NonComparableStruct{}), false},
4426 {TypeOf([10]map[string]int{}), false},
4427 {TypeOf([10]string{}), true},
4428 {TypeOf(new(interface{})).Elem(), true},
4431 func TestComparable(t *testing.T) {
4432 for _, tt := range comparableTests {
4433 if ok := tt.typ.Comparable(); ok != tt.ok {
4434 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4439 func TestOverflow(t *testing.T) {
4440 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4441 t.Errorf("%v wrongly overflows float64", 1e300)
4444 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4445 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4446 t.Errorf("%v wrongly overflows float32", maxFloat32)
4448 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4449 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4450 t.Errorf("%v should overflow float32", ovfFloat32)
4452 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4453 t.Errorf("%v should overflow float32", -ovfFloat32)
4456 maxInt32 := int64(0x7fffffff)
4457 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4458 t.Errorf("%v wrongly overflows int32", maxInt32)
4460 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4461 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4463 ovfInt32 := int64(1 << 31)
4464 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4465 t.Errorf("%v should overflow int32", ovfInt32)
4468 maxUint32 := uint64(0xffffffff)
4469 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4470 t.Errorf("%v wrongly overflows uint32", maxUint32)
4472 ovfUint32 := uint64(1 << 32)
4473 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4474 t.Errorf("%v should overflow uint32", ovfUint32)
4478 func checkSameType(t *testing.T, x Type, y interface{}) {
4479 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4480 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4484 func TestArrayOf(t *testing.T) {
4485 // check construction and use of type not in binary
4488 value func(i int) interface{}
4494 value: func(i int) interface{} { type Tint int; return Tint(i) },
4500 value: func(i int) interface{} { type Tint int; return Tint(i) },
4502 want: "[0 1 2 3 4 5 6 7 8 9]",
4506 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
4508 want: "[0 1 2 3 4 5 6 7 8 9]",
4512 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
4514 want: "[0 1 2 3 4 5 6 7 8 9]",
4518 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
4520 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4524 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
4526 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4530 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
4532 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4536 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4538 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4542 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4544 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4548 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4550 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4554 value: func(i int) interface{} {
4555 type TstructUV struct {
4559 return TstructUV{i, float64(i)}
4562 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4566 for _, table := range tests {
4567 at := ArrayOf(table.n, TypeOf(table.value(0)))
4569 vok := New(at).Elem()
4570 vnot := New(at).Elem()
4571 for i := 0; i < v.Len(); i++ {
4572 v.Index(i).Set(ValueOf(table.value(i)))
4573 vok.Index(i).Set(ValueOf(table.value(i)))
4578 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4580 s := fmt.Sprint(v.Interface())
4581 if s != table.want {
4582 t.Errorf("constructed array = %s, want %s", s, table.want)
4585 if table.comparable != at.Comparable() {
4586 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4588 if table.comparable {
4590 if DeepEqual(vnot.Interface(), v.Interface()) {
4592 "arrays (%#v) compare ok (but should not)",
4597 if !DeepEqual(vok.Interface(), v.Interface()) {
4599 "arrays (%#v) compare NOT-ok (but should)",
4606 // check that type already in binary is found
4608 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4611 func TestArrayOfGC(t *testing.T) {
4613 tt := TypeOf(T(nil))
4616 for i := 0; i < n; i++ {
4617 v := New(ArrayOf(n, tt)).Elem()
4618 for j := 0; j < v.Len(); j++ {
4620 *p = uintptr(i*n + j)
4621 v.Index(j).Set(ValueOf(p).Convert(tt))
4623 x = append(x, v.Interface())
4627 for i, xi := range x {
4629 for j := 0; j < v.Len(); j++ {
4630 k := v.Index(j).Elem().Interface()
4631 if k != uintptr(i*n+j) {
4632 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4638 func TestArrayOfAlg(t *testing.T) {
4639 at := ArrayOf(6, TypeOf(byte(0)))
4640 v1 := New(at).Elem()
4641 v2 := New(at).Elem()
4642 if v1.Interface() != v1.Interface() {
4643 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4645 v1.Index(5).Set(ValueOf(byte(1)))
4646 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4647 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4650 at = ArrayOf(6, TypeOf([]int(nil)))
4652 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4655 func TestArrayOfGenericAlg(t *testing.T) {
4656 at1 := ArrayOf(5, TypeOf(string("")))
4657 at := ArrayOf(6, at1)
4658 v1 := New(at).Elem()
4659 v2 := New(at).Elem()
4660 if v1.Interface() != v1.Interface() {
4661 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4664 v1.Index(0).Index(0).Set(ValueOf("abc"))
4665 v2.Index(0).Index(0).Set(ValueOf("efg"))
4666 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4667 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4670 v1.Index(0).Index(0).Set(ValueOf("abc"))
4671 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4672 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4673 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4677 m := MakeMap(MapOf(at, TypeOf(int(0))))
4678 m.SetMapIndex(v1, ValueOf(1))
4679 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4680 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4684 func TestArrayOfDirectIface(t *testing.T) {
4687 i1 := Zero(TypeOf(T{})).Interface()
4688 v1 := ValueOf(&i1).Elem()
4689 p1 := v1.InterfaceData()[1]
4691 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4692 v2 := ValueOf(&i2).Elem()
4693 p2 := v2.InterfaceData()[1]
4696 t.Errorf("got p1=%v. want=%v", p1, nil)
4700 t.Errorf("got p2=%v. want=%v", p2, nil)
4705 i1 := Zero(TypeOf(T{})).Interface()
4706 v1 := ValueOf(&i1).Elem()
4707 p1 := v1.InterfaceData()[1]
4709 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4710 v2 := ValueOf(&i2).Elem()
4711 p2 := v2.InterfaceData()[1]
4714 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4718 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4723 // Ensure passing in negative lengths panics.
4724 // See https://golang.org/issue/43603
4725 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4726 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4727 ArrayOf(-1, TypeOf(byte(0)))
4731 func TestSliceOf(t *testing.T) {
4732 // check construction and use of type not in binary
4734 st := SliceOf(TypeOf(T(1)))
4735 if got, want := st.String(), "[]reflect_test.T"; got != want {
4736 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4738 v := MakeSlice(st, 10, 10)
4740 for i := 0; i < v.Len(); i++ {
4741 v.Index(i).Set(ValueOf(T(i)))
4744 s := fmt.Sprint(v.Interface())
4745 want := "[0 1 2 3 4 5 6 7 8 9]"
4747 t.Errorf("constructed slice = %s, want %s", s, want)
4750 // check that type already in binary is found
4752 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4755 func TestSliceOverflow(t *testing.T) {
4756 // check that MakeSlice panics when size of slice overflows uint
4759 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4761 t.Fatal("slice size does not overflow")
4764 st := SliceOf(TypeOf(x))
4768 t.Fatal("slice overflow does not panic")
4771 MakeSlice(st, int(l), int(l))
4774 func TestSliceOfGC(t *testing.T) {
4776 tt := TypeOf(T(nil))
4780 for i := 0; i < n; i++ {
4781 v := MakeSlice(st, n, n)
4782 for j := 0; j < v.Len(); j++ {
4784 *p = uintptr(i*n + j)
4785 v.Index(j).Set(ValueOf(p).Convert(tt))
4787 x = append(x, v.Interface())
4791 for i, xi := range x {
4793 for j := 0; j < v.Len(); j++ {
4794 k := v.Index(j).Elem().Interface()
4795 if k != uintptr(i*n+j) {
4796 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4802 func TestStructOfFieldName(t *testing.T) {
4803 // invalid field name "1nvalid"
4804 shouldPanic("has invalid name", func() {
4805 StructOf([]StructField{
4806 {Name: "Valid", Type: TypeOf("")},
4807 {Name: "1nvalid", Type: TypeOf("")},
4811 // invalid field name "+"
4812 shouldPanic("has invalid name", func() {
4813 StructOf([]StructField{
4814 {Name: "Val1d", Type: TypeOf("")},
4815 {Name: "+", Type: TypeOf("")},
4820 shouldPanic("has no name", func() {
4821 StructOf([]StructField{
4822 {Name: "", Type: TypeOf("")},
4826 // verify creation of a struct with valid struct fields
4827 validFields := []StructField{
4842 validStruct := StructOf(validFields)
4844 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
4845 if got, want := validStruct.String(), structStr; got != want {
4846 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
4850 func TestStructOf(t *testing.T) {
4851 // check construction and use of type not in binary
4852 fields := []StructField{
4861 Type: TypeOf(byte(0)),
4865 Type: TypeOf(uint64(0)),
4869 Type: TypeOf([3]uint16{}),
4873 st := StructOf(fields)
4876 v.FieldByName("X").Set(ValueOf(byte(2)))
4877 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
4880 s := fmt.Sprint(v.Interface())
4881 want := `{ 1 0 [0 0 0]}`
4883 t.Errorf("constructed struct = %s, want %s", s, want)
4885 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
4886 if got, want := st.String(), stStr; got != want {
4887 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
4890 // check the size, alignment and field offsets
4891 stt := TypeOf(struct {
4897 if st.Size() != stt.Size() {
4898 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
4900 if st.Align() != stt.Align() {
4901 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
4903 if st.FieldAlign() != stt.FieldAlign() {
4904 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4906 for i := 0; i < st.NumField(); i++ {
4907 o1 := st.Field(i).Offset
4908 o2 := stt.Field(i).Offset
4910 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
4914 // Check size and alignment with a trailing zero-sized field.
4915 st = StructOf([]StructField{
4918 Type: TypeOf(byte(0)),
4922 Type: TypeOf([0]*byte{}),
4925 stt = TypeOf(struct {
4929 if st.Size() != stt.Size() {
4930 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
4932 if st.Align() != stt.Align() {
4933 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
4935 if st.FieldAlign() != stt.FieldAlign() {
4936 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4938 for i := 0; i < st.NumField(); i++ {
4939 o1 := st.Field(i).Offset
4940 o2 := stt.Field(i).Offset
4942 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
4946 // check duplicate names
4947 shouldPanic("duplicate field", func() {
4948 StructOf([]StructField{
4949 {Name: "string", PkgPath: "p", Type: TypeOf("")},
4950 {Name: "string", PkgPath: "p", Type: TypeOf("")},
4953 shouldPanic("has no name", func() {
4954 StructOf([]StructField{
4956 {Name: "string", PkgPath: "p", Type: TypeOf("")},
4959 shouldPanic("has no name", func() {
4960 StructOf([]StructField{
4965 // check that type already in binary is found
4966 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
4968 // gccgo used to fail this test.
4969 type structFieldType interface{}
4971 StructOf([]StructField{
4974 Type: TypeOf((*structFieldType)(nil)).Elem(),
4977 struct{ F structFieldType }{})
4980 func TestStructOfExportRules(t *testing.T) {
4986 testPanic := func(i int, mustPanic bool, f func()) {
4989 if err == nil && mustPanic {
4990 t.Errorf("test-%d did not panic", i)
4992 if err != nil && !mustPanic {
4993 t.Errorf("test-%d panicked: %v\n", i, err)
5005 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5009 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5013 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5017 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5021 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5025 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5029 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5033 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5037 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5041 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5045 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5048 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5051 field: StructField{Name: "S", Type: TypeOf(S1{})},
5055 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5059 field: StructField{Name: "S", Type: TypeOf(s2{})},
5063 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5067 field: StructField{Name: "s", Type: TypeOf(S1{})},
5071 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5075 field: StructField{Name: "s", Type: TypeOf(s2{})},
5079 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5083 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5086 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5089 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5092 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5095 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5099 field: StructField{Name: "", Type: TypeOf(φType{})},
5103 field: StructField{Name: "Φ", Type: TypeOf(0)},
5107 field: StructField{Name: "φ", Type: TypeOf(0)},
5112 for i, test := range tests {
5113 testPanic(i, test.mustPanic, func() {
5114 typ := StructOf([]StructField{test.field})
5116 t.Errorf("test-%d: error creating struct type", i)
5119 field := typ.Field(0)
5122 panic("field.Name must not be empty")
5124 exported := token.IsExported(n)
5125 if exported != test.exported {
5126 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5128 if field.PkgPath != test.field.PkgPath {
5129 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5135 func TestStructOfGC(t *testing.T) {
5137 tt := TypeOf(T(nil))
5138 fields := []StructField{
5139 {Name: "X", Type: tt},
5140 {Name: "Y", Type: tt},
5142 st := StructOf(fields)
5146 for i := 0; i < n; i++ {
5148 for j := 0; j < v.NumField(); j++ {
5150 *p = uintptr(i*n + j)
5151 v.Field(j).Set(ValueOf(p).Convert(tt))
5153 x = append(x, v.Interface())
5157 for i, xi := range x {
5159 for j := 0; j < v.NumField(); j++ {
5160 k := v.Field(j).Elem().Interface()
5161 if k != uintptr(i*n+j) {
5162 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5168 func TestStructOfAlg(t *testing.T) {
5169 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5170 v1 := New(st).Elem()
5171 v2 := New(st).Elem()
5172 if !DeepEqual(v1.Interface(), v1.Interface()) {
5173 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5175 v1.FieldByName("X").Set(ValueOf(int(1)))
5176 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5177 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5180 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5182 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5185 func TestStructOfGenericAlg(t *testing.T) {
5186 st1 := StructOf([]StructField{
5187 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5188 {Name: "Y", Type: TypeOf(string(""))},
5190 st := StructOf([]StructField{
5191 {Name: "S0", Type: st1},
5192 {Name: "S1", Type: st1},
5210 {Name: "XX", Type: TypeOf([0]int{})},
5211 {Name: "YY", Type: TypeOf("")},
5219 {Name: "XX", Type: TypeOf([0]int{})},
5220 {Name: "YY", Type: TypeOf("")},
5221 {Name: "ZZ", Type: TypeOf([2]int{})},
5229 {Name: "XX", Type: TypeOf([1]int{})},
5230 {Name: "YY", Type: TypeOf("")},
5238 {Name: "XX", Type: TypeOf([1]int{})},
5239 {Name: "YY", Type: TypeOf("")},
5240 {Name: "ZZ", Type: TypeOf([1]int{})},
5248 {Name: "XX", Type: TypeOf([2]int{})},
5249 {Name: "YY", Type: TypeOf("")},
5250 {Name: "ZZ", Type: TypeOf([2]int{})},
5258 {Name: "XX", Type: TypeOf(int64(0))},
5259 {Name: "YY", Type: TypeOf(byte(0))},
5260 {Name: "ZZ", Type: TypeOf("")},
5268 {Name: "XX", Type: TypeOf(int64(0))},
5269 {Name: "YY", Type: TypeOf(int64(0))},
5270 {Name: "ZZ", Type: TypeOf("")},
5271 {Name: "AA", Type: TypeOf([1]int64{})},
5278 for _, table := range tests {
5279 v1 := New(table.rt).Elem()
5280 v2 := New(table.rt).Elem()
5282 if !DeepEqual(v1.Interface(), v1.Interface()) {
5283 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5286 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5287 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5288 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5289 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5293 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5294 val := "+" + abc + "-"
5295 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5296 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5297 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5301 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5302 m.SetMapIndex(v1, ValueOf(1))
5303 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5304 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5307 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5308 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5309 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5312 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5313 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5318 func TestStructOfDirectIface(t *testing.T) {
5320 type T struct{ X [1]*byte }
5321 i1 := Zero(TypeOf(T{})).Interface()
5322 v1 := ValueOf(&i1).Elem()
5323 p1 := v1.InterfaceData()[1]
5325 i2 := Zero(StructOf([]StructField{
5328 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5331 v2 := ValueOf(&i2).Elem()
5332 p2 := v2.InterfaceData()[1]
5335 t.Errorf("got p1=%v. want=%v", p1, nil)
5339 t.Errorf("got p2=%v. want=%v", p2, nil)
5343 type T struct{ X [0]*byte }
5344 i1 := Zero(TypeOf(T{})).Interface()
5345 v1 := ValueOf(&i1).Elem()
5346 p1 := v1.InterfaceData()[1]
5348 i2 := Zero(StructOf([]StructField{
5351 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5354 v2 := ValueOf(&i2).Elem()
5355 p2 := v2.InterfaceData()[1]
5358 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5362 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5369 func (i StructI) Get() int { return int(i) }
5373 func (i *StructIPtr) Get() int { return int(*i) }
5374 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5376 type SettableStruct struct {
5380 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5382 type SettablePointer struct {
5386 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5388 func TestStructOfWithInterface(t *testing.T) {
5390 type Iface interface {
5393 type IfaceSet interface {
5404 typ: TypeOf(StructI(want)),
5405 val: ValueOf(StructI(want)),
5410 typ: PtrTo(TypeOf(StructI(want))),
5411 val: ValueOf(func() interface{} {
5419 typ: PtrTo(TypeOf(StructIPtr(want))),
5420 val: ValueOf(func() interface{} {
5421 v := StructIPtr(want)
5428 typ: TypeOf(StructIPtr(want)),
5429 val: ValueOf(StructIPtr(want)),
5433 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5434 // val: ValueOf(StructI(want)),
5439 for i, table := range tests {
5440 for j := 0; j < 2; j++ {
5441 var fields []StructField
5443 fields = append(fields, StructField{
5446 Type: TypeOf(int(0)),
5449 fields = append(fields, StructField{
5456 // We currently do not correctly implement methods
5457 // for embedded fields other than the first.
5458 // Therefore, for now, we expect those methods
5459 // to not exist. See issues 15924 and 20824.
5460 // When those issues are fixed, this test of panic
5461 // should be removed.
5462 if j == 1 && table.impl {
5465 if err := recover(); err == nil {
5466 t.Errorf("test-%d-%d did not panic", i, j)
5469 _ = StructOf(fields)
5474 rt := StructOf(fields)
5475 rv := New(rt).Elem()
5476 rv.Field(j).Set(table.val)
5478 if _, ok := rv.Interface().(Iface); ok != table.impl {
5480 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5482 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5491 v := rv.Interface().(Iface).Get()
5493 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5496 fct := rv.MethodByName("Get")
5497 out := fct.Call(nil)
5498 if !DeepEqual(out[0].Interface(), want) {
5499 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5504 // Test an embedded nil pointer with pointer methods.
5505 fields := []StructField{{
5508 Type: PtrTo(TypeOf(StructIPtr(want))),
5510 rt := StructOf(fields)
5511 rv := New(rt).Elem()
5512 // This should panic since the pointer is nil.
5513 shouldPanic("", func() {
5514 rv.Interface().(IfaceSet).Set(want)
5517 // Test an embedded nil pointer to a struct with pointer methods.
5519 fields = []StructField{{
5520 Name: "SettableStruct",
5522 Type: PtrTo(TypeOf(SettableStruct{})),
5524 rt = StructOf(fields)
5526 // This should panic since the pointer is nil.
5527 shouldPanic("", func() {
5528 rv.Interface().(IfaceSet).Set(want)
5531 // The behavior is different if there is a second field,
5532 // since now an interface value holds a pointer to the struct
5533 // rather than just holding a copy of the struct.
5534 fields = []StructField{
5536 Name: "SettableStruct",
5538 Type: PtrTo(TypeOf(SettableStruct{})),
5541 Name: "EmptyStruct",
5543 Type: StructOf(nil),
5546 // With the current implementation this is expected to panic.
5547 // Ideally it should work and we should be able to see a panic
5548 // if we call the Set method.
5549 shouldPanic("", func() {
5553 // Embed a field that can be stored directly in an interface,
5554 // with a second field.
5555 fields = []StructField{
5557 Name: "SettablePointer",
5559 Type: TypeOf(SettablePointer{}),
5562 Name: "EmptyStruct",
5564 Type: StructOf(nil),
5567 // With the current implementation this is expected to panic.
5568 // Ideally it should work and we should be able to call the
5569 // Set and Get methods.
5570 shouldPanic("", func() {
5575 func TestStructOfTooManyFields(t *testing.T) {
5576 // Bug Fix: #25402 - this should not panic
5577 tt := StructOf([]StructField{
5578 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5581 if _, present := tt.MethodByName("After"); !present {
5582 t.Errorf("Expected method `After` to be found")
5586 func TestStructOfDifferentPkgPath(t *testing.T) {
5587 fields := []StructField{
5591 Type: TypeOf(int(0)),
5596 Type: TypeOf(int(0)),
5599 shouldPanic("different PkgPath", func() {
5604 func TestChanOf(t *testing.T) {
5605 // check construction and use of type not in binary
5607 ct := ChanOf(BothDir, TypeOf(T("")))
5608 v := MakeChan(ct, 2)
5610 v.Send(ValueOf(T("hello")))
5612 v.Send(ValueOf(T("world")))
5619 if s1 != "hello" || s2 != "world" {
5620 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5623 // check that type already in binary is found
5625 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5627 // Check arrow token association in undefined chan types.
5628 var left chan<- chan T
5629 var right chan (<-chan T)
5630 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5631 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5632 if tLeft != TypeOf(left) {
5633 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5635 if tRight != TypeOf(right) {
5636 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5640 func TestChanOfDir(t *testing.T) {
5641 // check construction and use of type not in binary
5643 crt := ChanOf(RecvDir, TypeOf(T("")))
5644 cst := ChanOf(SendDir, TypeOf(T("")))
5646 // check that type already in binary is found
5648 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5649 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5651 // check String form of ChanDir
5652 if crt.ChanDir().String() != "<-chan" {
5653 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5655 if cst.ChanDir().String() != "chan<-" {
5656 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5660 func TestChanOfGC(t *testing.T) {
5661 done := make(chan bool, 1)
5665 case <-time.After(5 * time.Second):
5666 panic("deadlock in TestChanOfGC")
5675 tt := TypeOf(T(nil))
5676 ct := ChanOf(BothDir, tt)
5678 // NOTE: The garbage collector handles allocated channels specially,
5679 // so we have to save pointers to channels in x; the pointer code will
5680 // use the gc info in the newly constructed chan type.
5683 for i := 0; i < n; i++ {
5684 v := MakeChan(ct, n)
5685 for j := 0; j < n; j++ {
5687 *p = uintptr(i*n + j)
5688 v.Send(ValueOf(p).Convert(tt))
5692 x = append(x, pv.Interface())
5696 for i, xi := range x {
5697 v := ValueOf(xi).Elem()
5698 for j := 0; j < n; j++ {
5700 k := pv.Elem().Interface()
5701 if k != uintptr(i*n+j) {
5702 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5708 func TestMapOf(t *testing.T) {
5709 // check construction and use of type not in binary
5713 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5715 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5718 s := fmt.Sprint(v.Interface())
5721 t.Errorf("constructed map = %s, want %s", s, want)
5724 // check that type already in binary is found
5725 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5727 // check that invalid key type panics
5728 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5731 func TestMapOfGCKeys(t *testing.T) {
5733 tt := TypeOf(T(nil))
5734 mt := MapOf(tt, TypeOf(false))
5736 // NOTE: The garbage collector handles allocated maps specially,
5737 // so we have to save pointers to maps in x; the pointer code will
5738 // use the gc info in the newly constructed map type.
5741 for i := 0; i < n; i++ {
5743 for j := 0; j < n; j++ {
5745 *p = uintptr(i*n + j)
5746 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5750 x = append(x, pv.Interface())
5754 for i, xi := range x {
5755 v := ValueOf(xi).Elem()
5757 for _, kv := range v.MapKeys() {
5758 out = append(out, int(kv.Elem().Interface().(uintptr)))
5761 for j, k := range out {
5763 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5769 func TestMapOfGCValues(t *testing.T) {
5771 tt := TypeOf(T(nil))
5772 mt := MapOf(TypeOf(1), tt)
5774 // NOTE: The garbage collector handles allocated maps specially,
5775 // so we have to save pointers to maps in x; the pointer code will
5776 // use the gc info in the newly constructed map type.
5779 for i := 0; i < n; i++ {
5781 for j := 0; j < n; j++ {
5783 *p = uintptr(i*n + j)
5784 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5788 x = append(x, pv.Interface())
5792 for i, xi := range x {
5793 v := ValueOf(xi).Elem()
5794 for j := 0; j < n; j++ {
5795 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
5796 if k != uintptr(i*n+j) {
5797 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5803 func TestTypelinksSorted(t *testing.T) {
5805 for i, n := range TypeLinks() {
5807 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
5813 func TestFuncOf(t *testing.T) {
5814 // check construction and use of type not in binary
5818 fn := func(args []Value) []Value {
5820 t.Errorf("args == %v, want exactly one arg", args)
5821 } else if args[0].Type() != TypeOf(K("")) {
5822 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
5823 } else if args[0].String() != "gopher" {
5824 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
5826 return []Value{ValueOf(V(3.14))}
5828 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
5830 outs := v.Call([]Value{ValueOf(K("gopher"))})
5832 t.Fatalf("v.Call returned %v, want exactly one result", outs)
5833 } else if outs[0].Type() != TypeOf(V(0)) {
5834 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
5836 f := outs[0].Float()
5838 t.Errorf("constructed func returned %f, want %f", f, 3.14)
5841 // check that types already in binary are found
5843 testCases := []struct {
5848 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
5849 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
5850 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
5851 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
5852 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
5854 for _, tt := range testCases {
5855 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
5858 // check that variadic requires last element be a slice.
5859 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5860 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5861 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
5870 func BenchmarkFieldByName1(b *testing.B) {
5872 b.RunParallel(func(pb *testing.PB) {
5879 func BenchmarkFieldByName2(b *testing.B) {
5881 b.RunParallel(func(pb *testing.PB) {
5958 func TestEmbed(t *testing.T) {
5960 f, ok := typ.FieldByName("X")
5962 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
5966 func BenchmarkFieldByName3(b *testing.B) {
5968 b.RunParallel(func(pb *testing.PB) {
5980 func BenchmarkInterfaceBig(b *testing.B) {
5982 b.RunParallel(func(pb *testing.PB) {
5990 func TestAllocsInterfaceBig(t *testing.T) {
5991 if testing.Short() {
5992 t.Skip("skipping malloc count in short mode")
5995 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
5996 t.Error("allocs:", allocs)
6000 func BenchmarkInterfaceSmall(b *testing.B) {
6001 v := ValueOf(int64(0))
6002 b.RunParallel(func(pb *testing.PB) {
6009 func TestAllocsInterfaceSmall(t *testing.T) {
6010 if testing.Short() {
6011 t.Skip("skipping malloc count in short mode")
6013 v := ValueOf(int64(0))
6014 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6015 t.Error("allocs:", allocs)
6019 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6020 // The basic usage is:
6023 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6026 // Each iteration of the loop returns a different set of results, until all
6027 // possible result sets have been explored. It is okay for different code paths
6028 // to make different method call sequences on x, but there must be no
6029 // other source of non-determinism in the call sequences.
6031 // When faced with a new decision, x chooses randomly. Future explorations
6032 // of that path will choose successive values for the result. Thus, stopping
6033 // the loop after a fixed number of iterations gives somewhat stochastic
6039 // v := make([]bool, x.Choose(4))
6040 // for i := range v {
6046 // prints (in some order):
6055 // [false false false]
6058 // [false false false false]
6060 // [true true true true]
6062 type exhaustive struct {
6068 type choice struct {
6074 func (x *exhaustive) Next() bool {
6076 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6083 for i := len(x.last) - 1; i >= 0; i-- {
6087 x.last = x.last[:i+1]
6094 func (x *exhaustive) Choose(max int) int {
6095 if x.pos >= len(x.last) {
6096 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6101 panic("inconsistent use of exhaustive tester")
6103 return (c.n + c.off) % max
6106 func (x *exhaustive) Maybe() bool {
6107 return x.Choose(2) == 1
6110 func GCFunc(args []Value) []Value {
6115 func TestReflectFuncTraceback(t *testing.T) {
6116 f := MakeFunc(TypeOf(func() {}), GCFunc)
6120 func TestReflectMethodTraceback(t *testing.T) {
6122 m := ValueOf(p).MethodByName("GCMethod")
6123 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6125 t.Errorf("Call returned %d; want 8", i)
6129 func TestSmallZero(t *testing.T) {
6132 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6133 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6137 func TestBigZero(t *testing.T) {
6138 const size = 1 << 10
6140 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6141 for i := 0; i < size; i++ {
6143 t.Fatalf("Zero object not all zero, index %d", i)
6148 func TestZeroSet(t *testing.T) {
6156 a: 0xaaaaaaaaaaaaaaaa,
6157 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6158 b: 0xbbbbbbbbbbbbbbbb,
6160 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6162 a: 0xaaaaaaaaaaaaaaaa,
6163 b: 0xbbbbbbbbbbbbbbbb,
6165 t.Fatalf("Setting a field to a Zero value didn't work")
6169 func TestFieldByIndexNil(t *testing.T) {
6178 v.FieldByName("P") // should be fine
6181 if err := recover(); err == nil {
6182 t.Fatalf("no error")
6183 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6184 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6187 v.FieldByName("F") // should panic
6189 t.Fatalf("did not panic")
6193 // type Outer struct {
6197 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6198 // The implementation is logically:
6199 // func (p *Outer) M() {
6202 // but since the only change here is the replacement of one pointer receiver with another,
6203 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6204 // then jumps to the M method expecting the *Inner receiver.
6206 // During reflect.Value.Call, we create an argument frame and the associated data structures
6207 // to describe it to the garbage collector, populate the frame, call reflect.call to
6208 // run a function call using that frame, and then copy the results back out of the frame.
6209 // The reflect.call function does a memmove of the frame structure onto the
6210 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6211 // the frame structure (to preserve the outputs).
6213 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6214 // were for the full stack frame. However, in the case where the called function was
6215 // one of these wrappers, the rewritten receiver is almost certainly a different type
6216 // than the original receiver. This is not a problem on the stack, where we use the
6217 // program counter to determine the type information and understand that
6218 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6219 // memory word is now an *Inner. But in the statically typed argument frame created
6220 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6221 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6222 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6223 // memory as if it were an *Outer. If the two have different memory layouts, the
6224 // collection will interpret the memory incorrectly.
6226 // One such possible incorrect interpretation is to treat two arbitrary memory words
6227 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6228 // an interface requires dereferencing the itab word, the misinterpretation will try to
6229 // deference Inner.P1, causing a crash during garbage collection.
6231 // This came up in a real program in issue 7725.
6244 func (pi *Inner) M() {
6245 // Clear references to pi so that the only way the
6246 // garbage collection will find the pointer is in the
6247 // argument frame, typed as a *Outer.
6250 // Set up an interface value that will cause a crash.
6251 // P1 = 1 is a non-zero, so the interface looks non-nil.
6252 // P2 = pi ensures that the data word points into the
6253 // allocated heap; if not the collection skips the interface
6254 // value as irrelevant, without dereferencing P1.
6256 pi.P2 = uintptr(unsafe.Pointer(pi))
6259 func TestCallMethodJump(t *testing.T) {
6260 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6261 // returns but before the args frame has been discarded.
6262 // This is a little clumsy but makes the failure repeatable.
6265 p := &Outer{Inner: new(Inner)}
6267 ValueOf(p).Method(0).Call(nil)
6269 // Stop garbage collecting during reflect.call.
6273 func TestMakeFuncStackCopy(t *testing.T) {
6274 target := func(in []Value) []Value {
6277 return []Value{ValueOf(9)}
6280 var concrete func(*int, int) int
6281 fn := MakeFunc(ValueOf(concrete).Type(), target)
6282 ValueOf(&concrete).Elem().Set(fn)
6283 x := concrete(nil, 7)
6285 t.Errorf("have %#q want 9", x)
6289 // use about n KB of stack
6290 func useStack(n int) {
6294 var b [1024]byte // makes frame about 1KB
6295 useStack(n - 1 + int(b[99]))
6302 func TestValueString(t *testing.T) {
6303 rv := ValueOf(Impl{})
6304 if rv.String() != "<reflect_test.Impl Value>" {
6305 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6308 method := rv.Method(0)
6309 if method.String() != "<func() Value>" {
6310 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6314 func TestInvalid(t *testing.T) {
6315 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6316 type T struct{ v interface{} }
6318 v := ValueOf(T{}).Field(0)
6319 if v.IsValid() != true || v.Kind() != Interface {
6320 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6323 if v.IsValid() != false || v.Kind() != Invalid {
6324 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6329 func TestLargeGCProg(t *testing.T) {
6330 fv := ValueOf(func([256]*byte) {})
6331 fv.Call([]Value{ValueOf([256]*byte{})})
6334 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
6336 recovered = recover()
6344 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6345 typ := TypeOf(struct{ X int }{10})
6346 testIndices := [...]struct {
6355 for i, tt := range testIndices {
6356 recoveredErr := fieldIndexRecover(typ, tt.i)
6358 if recoveredErr == nil {
6359 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6362 if recoveredErr != nil {
6363 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6370 func TestCallGC(t *testing.T) {
6371 f := func(a, b, c, d, e string) {
6373 g := func(in []Value) []Value {
6377 typ := ValueOf(f).Type()
6378 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6379 f2("four", "five5", "six666", "seven77", "eight888")
6382 // Issue 18635 (function version).
6383 func TestKeepFuncLive(t *testing.T) {
6384 // Test that we keep makeFuncImpl live as long as it is
6385 // referenced on the stack.
6386 typ := TypeOf(func(i int) {})
6387 var f, g func(in []Value) []Value
6388 f = func(in []Value) []Value {
6390 i := int(in[0].Int())
6392 // We can't use Value.Call here because
6393 // runtime.call* will keep the makeFuncImpl
6394 // alive. However, by converting it to an
6395 // interface value and calling that,
6396 // reflect.callReflect is the only thing that
6397 // can keep the makeFuncImpl live.
6399 // Alternate between f and g so that if we do
6400 // reuse the memory prematurely it's more
6401 // likely to get obviously corrupted.
6402 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6406 g = func(in []Value) []Value {
6408 i := int(in[0].Int())
6409 MakeFunc(typ, f).Interface().(func(i int))(i)
6412 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6415 type UnExportedFirst int
6417 func (i UnExportedFirst) ΦExported() {}
6418 func (i UnExportedFirst) unexported() {}
6421 func TestMethodByNameUnExportedFirst(t *testing.T) {
6423 if recover() != nil {
6424 t.Errorf("should not panic")
6427 typ := TypeOf(UnExportedFirst(0))
6428 m, _ := typ.MethodByName("ΦExported")
6429 if m.Name != "ΦExported" {
6430 t.Errorf("got %s, expected ΦExported", m.Name)
6434 // Issue 18635 (method version).
6435 type KeepMethodLive struct{}
6437 func (k KeepMethodLive) Method1(i int) {
6440 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6444 func (k KeepMethodLive) Method2(i int) {
6446 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6449 func TestKeepMethodLive(t *testing.T) {
6450 // Test that we keep methodValue live as long as it is
6451 // referenced on the stack.
6452 KeepMethodLive{}.Method1(10)
6455 // clobber tries to clobber unreachable memory.
6458 for i := 1; i < 32; i++ {
6459 for j := 0; j < 10; j++ {
6460 obj := make([]*byte, i)
6467 func TestFuncLayout(t *testing.T) {
6468 align := func(x uintptr) uintptr {
6469 return (x + PtrSize - 1) &^ (PtrSize - 1)
6473 r = []byte{0, 0, 0, 1}
6485 size, argsize, retOffset uintptr
6486 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6487 intRegs, floatRegs int
6488 floatRegSize uintptr
6492 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6494 argsize: 4 * PtrSize,
6495 retOffset: 4 * PtrSize,
6496 stack: []byte{1, 0, 1, 0, 1},
6497 gc: []byte{1, 0, 1, 0, 1},
6500 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6501 size: align(align(3*4) + PtrSize + 2),
6502 argsize: align(3*4) + PtrSize + 2,
6503 retOffset: align(align(3*4) + PtrSize + 2),
6508 typ: ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
6510 argsize: 4 * PtrSize,
6511 retOffset: 4 * PtrSize,
6512 stack: []byte{1, 0, 1, 1},
6513 gc: []byte{1, 0, 1, 1},
6516 typ: ValueOf(func(a S) {}).Type(),
6518 argsize: 4 * PtrSize,
6519 retOffset: 4 * PtrSize,
6520 stack: []byte{0, 0, 1, 1},
6521 gc: []byte{0, 0, 1, 1},
6524 rcvr: ValueOf((*byte)(nil)).Type(),
6525 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6527 argsize: 3 * PtrSize,
6528 retOffset: 3 * PtrSize,
6529 stack: []byte{1, 0, 1},
6530 gc: []byte{1, 0, 1},
6533 typ: ValueOf(func(a uintptr) {}).Type(),
6541 typ: ValueOf(func() uintptr { return 0 }).Type(),
6549 rcvr: ValueOf(uintptr(0)).Type(),
6550 typ: ValueOf(func(a uintptr) {}).Type(),
6552 argsize: 2 * PtrSize,
6553 retOffset: 2 * PtrSize,
6556 // Note: this one is tricky, as the receiver is not a pointer. But we
6557 // pass the receiver by reference to the autogenerated pointer-receiver
6558 // version of the function.
6560 // TODO(mknyszek): Add tests for non-zero register count.
6562 for _, lt := range tests {
6563 name := lt.typ.String()
6565 name = lt.rcvr.String() + "." + name
6567 t.Run(name, func(t *testing.T) {
6568 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6570 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6571 if typ.Size() != lt.size {
6572 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6574 if argsize != lt.argsize {
6575 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6577 if retOffset != lt.retOffset {
6578 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6580 if !bytes.Equal(stack, lt.stack) {
6581 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6583 if !bytes.Equal(gc, lt.gc) {
6584 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6586 if !bytes.Equal(inRegs, lt.inRegs) {
6587 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6589 if !bytes.Equal(outRegs, lt.outRegs) {
6590 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6592 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6593 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6599 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6600 heapBits := GCBits(New(typ).Interface())
6601 if !bytes.Equal(heapBits, bits) {
6602 _, _, line, _ := runtime.Caller(1)
6603 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6607 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6608 // Creating a slice causes the runtime to repeat a bitmap,
6609 // which exercises a different path from making the compiler
6610 // repeat a bitmap for a small array or executing a repeat in
6612 val := MakeSlice(typ, 0, cap)
6613 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
6614 heapBits := GCBits(data.Interface())
6615 // Repeat the bitmap for the slice size, trimming scalars in
6616 // the last element.
6617 bits = rep(cap, bits)
6618 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6619 bits = bits[:len(bits)-1]
6621 if !bytes.Equal(heapBits, bits) {
6622 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6626 func TestGCBits(t *testing.T) {
6627 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6629 // Building blocks for types seen by the compiler (like [2]Xscalar).
6630 // The compiler will create the type structures for the derived types,
6631 // including their GC metadata.
6632 type Xscalar struct{ x uintptr }
6633 type Xptr struct{ x *byte }
6634 type Xptrscalar struct {
6638 type Xscalarptr struct {
6642 type Xbigptrscalar struct {
6647 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6649 // Building blocks for types constructed by reflect.
6650 // This code is in a separate block so that code below
6651 // cannot accidentally refer to these.
6652 // The compiler must NOT see types derived from these
6653 // (for example, [2]Scalar must NOT appear in the program),
6654 // or else reflect will use it instead of having to construct one.
6655 // The goal is to test the construction.
6656 type Scalar struct{ x uintptr }
6657 type Ptr struct{ x *byte }
6658 type Ptrscalar struct {
6662 type Scalarptr struct {
6666 type Bigptrscalar struct {
6671 Tscalar = TypeOf(Scalar{})
6672 Tint64 = TypeOf(Int64(0))
6673 Tptr = TypeOf(Ptr{})
6674 Tscalarptr = TypeOf(Scalarptr{})
6675 Tptrscalar = TypeOf(Ptrscalar{})
6676 Tbigptrscalar = TypeOf(Bigptrscalar{})
6681 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6682 verifyGCBits(t, Tscalar, empty)
6683 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6684 verifyGCBits(t, Tptr, lit(1))
6685 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6686 verifyGCBits(t, Tscalarptr, lit(0, 1))
6687 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6688 verifyGCBits(t, Tptrscalar, lit(1))
6690 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6691 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6692 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6693 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6694 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6695 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6696 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6697 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6698 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6699 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6700 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6701 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6702 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6703 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6704 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6705 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6706 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6707 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6708 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6709 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6710 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6711 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6712 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6713 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6714 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6715 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6717 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6718 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6719 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6720 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6721 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6722 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6723 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6724 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6725 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6726 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6727 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6728 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6729 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6730 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6731 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6732 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6733 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6734 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6735 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6736 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6737 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6738 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6739 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6740 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6741 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6742 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6744 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6745 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6747 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6748 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6750 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6751 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6753 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6754 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6756 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6757 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6759 hdr := make([]byte, 8/PtrSize)
6761 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6762 verifyGCBits(t, MapBucketOf(k, e), want)
6763 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6767 map[Xscalar]Xptr(nil),
6768 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6771 map[Xscalarptr]Xptr(nil),
6772 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6773 verifyMapBucket(t, Tint64, Tptr,
6774 map[int64]Xptr(nil),
6775 join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
6778 map[Xscalar]Xscalar(nil),
6781 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6782 map[[2]Xscalarptr][3]Xptrscalar(nil),
6783 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6785 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
6786 map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
6787 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
6789 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
6790 map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
6791 join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
6793 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
6794 map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
6795 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
6797 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
6798 map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
6799 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6802 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
6803 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
6804 func lit(x ...byte) []byte { return x }
6806 func TestTypeOfTypeOf(t *testing.T) {
6807 // Check that all the type constructors return concrete *rtype implementations.
6808 // It's difficult to test directly because the reflect package is only at arm's length.
6809 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6810 check := func(name string, typ Type) {
6811 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
6812 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
6816 type T struct{ int }
6817 check("TypeOf", TypeOf(T{}))
6819 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
6820 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
6821 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
6822 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
6823 check("PtrTo", PtrTo(TypeOf(T{})))
6824 check("SliceOf", SliceOf(TypeOf(T{})))
6827 type XM struct{ _ bool }
6829 func (*XM) String() string { return "" }
6831 func TestPtrToMethods(t *testing.T) {
6833 yp := New(TypeOf(y)).Interface()
6834 _, ok := yp.(fmt.Stringer)
6836 t.Fatal("does not implement Stringer, but should")
6840 func TestMapAlloc(t *testing.T) {
6841 m := ValueOf(make(map[int]int, 10))
6844 allocs := testing.AllocsPerRun(100, func() {
6848 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
6853 val := ValueOf(&tmp).Elem()
6854 allocs = testing.AllocsPerRun(100, func() {
6855 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
6856 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6857 for i := 0; i < size/2; i++ {
6858 val.SetInt(int64(i))
6859 mv.SetMapIndex(val, val)
6863 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
6865 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
6866 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
6867 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
6870 func TestChanAlloc(t *testing.T) {
6871 // Note: for a chan int, the return Value must be allocated, so we
6872 // use a chan *int instead.
6873 c := ValueOf(make(chan *int, 1))
6874 v := ValueOf(new(int))
6875 allocs := testing.AllocsPerRun(100, func() {
6879 if allocs < 0.5 || allocs > 1.5 {
6880 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
6882 // Note: there is one allocation in reflect.recv which seems to be
6883 // a limitation of escape analysis. If that is ever fixed the
6884 // allocs < 0.5 condition will trigger and this test should be fixed.
6887 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
6889 type nameTest struct {
6894 var nameTests = []nameTest{
6895 {(*int32)(nil), "int32"},
6898 {(*chan D1)(nil), ""},
6899 {(*func() D1)(nil), ""},
6900 {(*<-chan D1)(nil), ""},
6901 {(*chan<- D1)(nil), ""},
6902 {(*interface{})(nil), ""},
6906 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
6909 func TestNames(t *testing.T) {
6910 for _, test := range nameTests {
6911 typ := TypeOf(test.v).Elem()
6912 if got := typ.Name(); got != test.want {
6913 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
6918 func TestExported(t *testing.T) {
6919 type ΦExported struct{}
6920 type φUnexported struct{}
6927 type exportTest struct {
6931 exportTests := []exportTest{
6935 {(*big)(nil), false},
6936 {(BigP)(nil), true},
6937 {(*BigP)(nil), true},
6938 {ΦExported{}, true},
6939 {φUnexported{}, false},
6946 for i, test := range exportTests {
6947 typ := TypeOf(test.v)
6948 if got := IsExported(typ); got != test.want {
6949 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
6954 func TestTypeStrings(t *testing.T) {
6955 type stringTest struct {
6959 stringTests := []stringTest{
6960 {TypeOf(func(int) {}), "func(int)"},
6961 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
6962 {TypeOf(XM{}), "reflect_test.XM"},
6963 {TypeOf(new(XM)), "*reflect_test.XM"},
6964 {TypeOf(new(XM).String), "func() string"},
6965 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
6966 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
6967 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
6968 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
6969 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
6972 for i, test := range stringTests {
6973 if got, want := test.typ.String(), test.want; got != want {
6974 t.Errorf("type %d String()=%q, want %q", i, got, want)
6979 func TestOffsetLock(t *testing.T) {
6980 var wg sync.WaitGroup
6981 for i := 0; i < 4; i++ {
6985 for j := 0; j < 50; j++ {
6986 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
6994 func BenchmarkNew(b *testing.B) {
6996 b.RunParallel(func(pb *testing.PB) {
7003 func TestSwapper(t *testing.T) {
7009 type pairPtr struct {
7021 in: []int{1, 20, 300},
7024 want: []int{300, 20, 1},
7027 in: []uintptr{1, 20, 300},
7030 want: []uintptr{300, 20, 1},
7033 in: []int16{1, 20, 300},
7036 want: []int16{300, 20, 1},
7039 in: []int8{1, 20, 100},
7042 want: []int8{100, 20, 1},
7045 in: []*I{&a, &b, &c},
7048 want: []*I{&c, &b, &a},
7051 in: []string{"eric", "sergey", "larry"},
7054 want: []string{"larry", "sergey", "eric"},
7057 in: []S{"eric", "sergey", "larry"},
7060 want: []S{"larry", "sergey", "eric"},
7063 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7066 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7069 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7072 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7076 for i, tt := range tests {
7077 inStr := fmt.Sprint(tt.in)
7078 Swapper(tt.in)(tt.i, tt.j)
7079 if !DeepEqual(tt.in, tt.want) {
7080 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7085 // TestUnaddressableField tests that the reflect package will not allow
7086 // a type from another package to be used as a named type with an
7087 // unexported field.
7089 // This ensures that unexported fields cannot be modified by other packages.
7090 func TestUnaddressableField(t *testing.T) {
7091 var b Buffer // type defined in reflect, a different package
7092 var localBuffer struct {
7095 lv := ValueOf(&localBuffer).Elem()
7097 shouldPanic("Set", func() {
7106 type Talias1 struct {
7114 type Talias2 struct {
7119 func TestAliasNames(t *testing.T) {
7120 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7121 out := fmt.Sprintf("%#v", t1)
7122 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7124 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7127 t2 := Talias2{Tint: 1, Tint2: 2}
7128 out = fmt.Sprintf("%#v", t2)
7129 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7131 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7135 func TestIssue22031(t *testing.T) {
7136 type s []struct{ C int }
7139 type t2 struct{ f s }
7142 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7143 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7146 for i, test := range tests {
7148 t.Errorf("%d: CanSet: got true, want false", i)
7153 type NonExportedFirst int
7155 func (i NonExportedFirst) ΦExported() {}
7156 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7158 func TestIssue22073(t *testing.T) {
7159 m := ValueOf(NonExportedFirst(0)).Method(0)
7161 if got := m.Type().NumOut(); got != 0 {
7162 t.Errorf("NumOut: got %v, want 0", got)
7169 func TestMapIterNonEmptyMap(t *testing.T) {
7170 m := map[string]int{"one": 1, "two": 2, "three": 3}
7171 iter := ValueOf(m).MapRange()
7172 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7173 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7177 func TestMapIterNilMap(t *testing.T) {
7178 var m map[string]int
7179 iter := ValueOf(m).MapRange()
7180 if got, want := iterateToString(iter), `[]`; got != want {
7181 t.Errorf("non-empty result iteratoring nil map: %s", got)
7185 func TestMapIterSafety(t *testing.T) {
7186 // Using a zero MapIter causes a panic, but not a crash.
7188 defer func() { recover() }()
7190 t.Fatal("Key did not panic")
7193 defer func() { recover() }()
7194 new(MapIter).Value()
7195 t.Fatal("Value did not panic")
7198 defer func() { recover() }()
7200 t.Fatal("Next did not panic")
7203 // Calling Key/Value on a MapIter before Next
7204 // causes a panic, but not a crash.
7205 var m map[string]int
7206 iter := ValueOf(m).MapRange()
7209 defer func() { recover() }()
7211 t.Fatal("Key did not panic")
7214 defer func() { recover() }()
7216 t.Fatal("Value did not panic")
7219 // Calling Next, Key, or Value on an exhausted iterator
7220 // causes a panic, but not a crash.
7221 iter.Next() // -> false
7223 defer func() { recover() }()
7225 t.Fatal("Key did not panic")
7228 defer func() { recover() }()
7230 t.Fatal("Value did not panic")
7233 defer func() { recover() }()
7235 t.Fatal("Next did not panic")
7239 func TestMapIterNext(t *testing.T) {
7240 // The first call to Next should reflect any
7241 // insertions to the map since the iterator was created.
7242 m := map[string]int{}
7243 iter := ValueOf(m).MapRange()
7245 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7246 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7250 func TestMapIterDelete0(t *testing.T) {
7251 // Delete all elements before first iteration.
7252 m := map[string]int{"one": 1, "two": 2, "three": 3}
7253 iter := ValueOf(m).MapRange()
7257 if got, want := iterateToString(iter), `[]`; got != want {
7258 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7262 func TestMapIterDelete1(t *testing.T) {
7263 // Delete all elements after first iteration.
7264 m := map[string]int{"one": 1, "two": 2, "three": 3}
7265 iter := ValueOf(m).MapRange()
7268 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7274 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7278 // iterateToString returns the set of elements
7279 // returned by an iterator in readable form.
7280 func iterateToString(it *MapIter) string {
7283 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7284 got = append(got, line)
7287 return "[" + strings.Join(got, ", ") + "]"
7290 func TestConvertibleTo(t *testing.T) {
7291 t1 := ValueOf(example1.MyStruct{}).Type()
7292 t2 := ValueOf(example2.MyStruct{}).Type()
7294 // Shouldn't raise stack overflow
7295 if t1.ConvertibleTo(t2) {
7296 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)