1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
19 "reflect/internal/example1"
20 "reflect/internal/example2"
34 func TestBool(t *testing.T) {
37 t.Fatal("ValueOf(true).Bool() = false")
54 func assert(t *testing.T, s, want string) {
56 t.Errorf("have %#q want %#q", s, want)
60 var typeTests = []pair{
61 {struct{ x int }{}, "int"},
62 {struct{ x int8 }{}, "int8"},
63 {struct{ x int16 }{}, "int16"},
64 {struct{ x int32 }{}, "int32"},
65 {struct{ x int64 }{}, "int64"},
66 {struct{ x uint }{}, "uint"},
67 {struct{ x uint8 }{}, "uint8"},
68 {struct{ x uint16 }{}, "uint16"},
69 {struct{ x uint32 }{}, "uint32"},
70 {struct{ x uint64 }{}, "uint64"},
71 {struct{ x float32 }{}, "float32"},
72 {struct{ x float64 }{}, "float64"},
73 {struct{ x int8 }{}, "int8"},
74 {struct{ x (**int8) }{}, "**int8"},
75 {struct{ x (**integer) }{}, "**reflect_test.integer"},
76 {struct{ x ([32]int32) }{}, "[32]int32"},
77 {struct{ x ([]int8) }{}, "[]int8"},
78 {struct{ x (map[string]int32) }{}, "map[string]int32"},
79 {struct{ x (chan<- string) }{}, "chan<- string"},
80 {struct{ x (chan<- chan string) }{}, "chan<- chan string"},
81 {struct{ x (chan<- <-chan string) }{}, "chan<- <-chan string"},
82 {struct{ x (<-chan <-chan string) }{}, "<-chan <-chan string"},
83 {struct{ x (chan (<-chan string)) }{}, "chan (<-chan string)"},
90 "struct { c chan *int32; d float32 }",
92 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
95 c func(chan *integer, *int8)
98 "struct { c func(chan *reflect_test.integer, *int8) }",
106 "struct { a int8; b int32 }",
115 "struct { a int8; b int8; c int32 }",
125 "struct { a int8; b int8; c int8; d int32 }",
136 "struct { a int8; b int8; c int8; d int8; e int32 }",
148 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
152 a int8 `reflect:"hi there"`
155 `struct { a int8 "reflect:\"hi there\"" }`,
159 a int8 `reflect:"hi \x00there\t\n\"\\"`
162 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
169 "struct { f func(...int) }",
173 a(func(func(int) int) func(func(int)) int)
177 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
185 "struct { int32; int64 }",
189 var valueTests = []pair{
200 {new(float32), "256.25"},
201 {new(float64), "512.125"},
202 {new(complex64), "532.125+10i"},
203 {new(complex128), "564.25+1i"},
204 {new(string), "stringy cheese"},
206 {new(*int8), "*int8(0)"},
207 {new(**int8), "**int8(0)"},
208 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
209 {new(**integer), "**reflect_test.integer(0)"},
210 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
211 {new(chan<- string), "chan<- string"},
212 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
217 "struct { c chan *int32; d float32 }{chan *int32, 0}",
219 {new(struct{ c func(chan *integer, *int8) }),
220 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
226 "struct { a int8; b int32 }{0, 0}",
233 "struct { a int8; b int8; c int32 }{0, 0, 0}",
237 func testType(t *testing.T, i int, typ Type, want string) {
240 t.Errorf("#%d: have %#q, want %#q", i, s, want)
244 func TestTypes(t *testing.T) {
245 for i, tt := range typeTests {
246 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
250 func TestSet(t *testing.T) {
251 for i, tt := range valueTests {
280 v.SetComplex(532.125 + 10i)
282 v.SetComplex(564.25 + 1i)
284 v.SetString("stringy cheese")
288 s := valueToString(v)
290 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
295 func TestSetValue(t *testing.T) {
296 for i, tt := range valueTests {
297 v := ValueOf(tt.i).Elem()
300 v.Set(ValueOf(int(132)))
302 v.Set(ValueOf(int8(8)))
304 v.Set(ValueOf(int16(16)))
306 v.Set(ValueOf(int32(32)))
308 v.Set(ValueOf(int64(64)))
310 v.Set(ValueOf(uint(132)))
312 v.Set(ValueOf(uint8(8)))
314 v.Set(ValueOf(uint16(16)))
316 v.Set(ValueOf(uint32(32)))
318 v.Set(ValueOf(uint64(64)))
320 v.Set(ValueOf(float32(256.25)))
322 v.Set(ValueOf(512.125))
324 v.Set(ValueOf(complex64(532.125 + 10i)))
326 v.Set(ValueOf(complex128(564.25 + 1i)))
328 v.Set(ValueOf("stringy cheese"))
332 s := valueToString(v)
334 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
339 func TestMapIterSet(t *testing.T) {
340 m := make(map[string]interface{}, len(valueTests))
341 for _, tt := range valueTests {
346 k := New(v.Type().Key()).Elem()
347 e := New(v.Type().Elem()).Elem()
353 want := m[k.String()]
356 t.Errorf("%q: want (%T) %v, got (%T) %v", k.String(), want, want, got, got)
358 if setkey, key := valueToString(k), valueToString(iter.Key()); setkey != key {
359 t.Errorf("MapIter.Key() = %q, MapIter.SetKey() = %q", key, setkey)
361 if setval, val := valueToString(e), valueToString(iter.Value()); setval != val {
362 t.Errorf("MapIter.Value() = %q, MapIter.SetValue() = %q", val, setval)
366 got := int(testing.AllocsPerRun(10, func() {
373 // Making a *MapIter allocates. This should be the only allocation.
375 t.Errorf("wanted 1 alloc, got %d", got)
379 func TestCanSetField(t *testing.T) {
380 type embed struct{ x, X int }
381 type Embed struct{ x, X int }
399 type testCase struct {
400 // -1 means Addr().Elem() of current value
411 {[]int{0, -1}, false},
412 {[]int{0, 0}, false},
413 {[]int{0, 0, -1}, false},
414 {[]int{0, -1, 0}, false},
415 {[]int{0, -1, 0, -1}, false},
417 {[]int{0, 1, -1}, true},
418 {[]int{0, -1, 1}, true},
419 {[]int{0, -1, 1, -1}, true},
421 {[]int{1, -1}, false},
423 {[]int{2, -1}, true},
426 val: ValueOf(&S2{embed: &embed{}}),
429 {[]int{0, -1}, false},
430 {[]int{0, 0}, false},
431 {[]int{0, 0, -1}, false},
432 {[]int{0, -1, 0}, false},
433 {[]int{0, -1, 0, -1}, false},
435 {[]int{0, 1, -1}, true},
436 {[]int{0, -1, 1}, true},
437 {[]int{0, -1, 1, -1}, true},
445 {[]int{0, -1}, true},
446 {[]int{0, 0}, false},
447 {[]int{0, 0, -1}, false},
448 {[]int{0, -1, 0}, false},
449 {[]int{0, -1, 0, -1}, false},
451 {[]int{0, 1, -1}, true},
452 {[]int{0, -1, 1}, true},
453 {[]int{0, -1, 1, -1}, true},
458 val: ValueOf(&S4{Embed: &Embed{}}),
461 {[]int{0, -1}, true},
462 {[]int{0, 0}, false},
463 {[]int{0, 0, -1}, false},
464 {[]int{0, -1, 0}, false},
465 {[]int{0, -1, 0, -1}, false},
467 {[]int{0, 1, -1}, true},
468 {[]int{0, -1, 1}, true},
469 {[]int{0, -1, 1, -1}, true},
475 for _, tt := range tests {
476 t.Run(tt.val.Type().Name(), func(t *testing.T) {
477 for _, tc := range tt.cases {
479 for _, i := range tc.index {
489 if got := f.CanSet(); got != tc.canSet {
490 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
499 var valueToStringTests = []pair{
504 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
505 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
506 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
507 {&[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})"},
508 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
509 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
512 func TestValueToString(t *testing.T) {
513 for i, test := range valueToStringTests {
514 s := valueToString(ValueOf(test.i))
516 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
521 func TestArrayElemSet(t *testing.T) {
522 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
523 v.Index(4).SetInt(123)
524 s := valueToString(v)
525 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
527 t.Errorf("[10]int: have %#q want %#q", s, want)
530 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
531 v.Index(4).SetInt(123)
533 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
535 t.Errorf("[]int: have %#q want %#q", s, want1)
539 func TestPtrPointTo(t *testing.T) {
543 vi := ValueOf(&i).Elem()
544 vip.Elem().Set(vi.Addr())
546 t.Errorf("got %d, want 1234", *ip)
550 vp := ValueOf(&ip).Elem()
551 vp.Set(Zero(vp.Type()))
553 t.Errorf("got non-nil (%p), want nil", ip)
557 func TestPtrSetNil(t *testing.T) {
561 vip.Elem().Set(Zero(vip.Elem().Type()))
563 t.Errorf("got non-nil (%d), want nil", *ip)
567 func TestMapSetNil(t *testing.T) {
568 m := make(map[string]int)
570 vm.Elem().Set(Zero(vm.Elem().Type()))
572 t.Errorf("got non-nil (%p), want nil", m)
576 func TestAll(t *testing.T) {
577 testType(t, 1, TypeOf((int8)(0)), "int8")
578 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
580 typ := TypeOf((*struct {
584 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
586 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
589 testType(t, 5, f.Type, "chan *int32")
591 f, present := styp.FieldByName("d")
593 t.Errorf("FieldByName says present field is absent")
595 testType(t, 6, f.Type, "float32")
597 f, present = styp.FieldByName("absent")
599 t.Errorf("FieldByName says absent field is present")
602 typ = TypeOf([32]int32{})
603 testType(t, 7, typ, "[32]int32")
604 testType(t, 8, typ.Elem(), "int32")
606 typ = TypeOf((map[string]*int32)(nil))
607 testType(t, 9, typ, "map[string]*int32")
609 testType(t, 10, mtyp.Key(), "string")
610 testType(t, 11, mtyp.Elem(), "*int32")
612 typ = TypeOf((chan<- string)(nil))
613 testType(t, 12, typ, "chan<- string")
614 testType(t, 13, typ.Elem(), "string")
616 // make sure tag strings are not part of element type
617 typ = TypeOf(struct {
618 d []uint32 `reflect:"TAG"`
620 testType(t, 14, typ, "[]uint32")
623 func TestInterfaceGet(t *testing.T) {
628 v1 := ValueOf(&inter)
629 v2 := v1.Elem().Field(0)
630 assert(t, v2.Type().String(), "interface {}")
633 assert(t, v3.Type().String(), "float64")
636 func TestInterfaceValue(t *testing.T) {
641 v1 := ValueOf(&inter)
642 v2 := v1.Elem().Field(0)
643 assert(t, v2.Type().String(), "interface {}")
645 assert(t, v3.Type().String(), "float64")
648 if _, ok := i3.(float64); !ok {
649 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
653 func TestFunctionValue(t *testing.T) {
654 var x interface{} = func() {}
656 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
657 t.Fatalf("TestFunction returned wrong pointer")
659 assert(t, v.Type().String(), "func()")
662 var appendTests = []struct {
665 {make([]int, 2, 4), []int{22}},
666 {make([]int, 2, 4), []int{22, 33, 44}},
669 func sameInts(x, y []int) bool {
670 if len(x) != len(y) {
673 for i, xx := range x {
681 func TestAppend(t *testing.T) {
682 for i, test := range appendTests {
683 origLen, extraLen := len(test.orig), len(test.extra)
684 want := append(test.orig, test.extra...)
685 // Convert extra from []int to []Value.
686 e0 := make([]Value, len(test.extra))
687 for j, e := range test.extra {
690 // Convert extra from []int to *SliceValue.
691 e1 := ValueOf(test.extra)
693 a0 := ValueOf(test.orig)
694 have0 := Append(a0, e0...).Interface().([]int)
695 if !sameInts(have0, want) {
696 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
698 // Check that the orig and extra slices were not modified.
699 if len(test.orig) != origLen {
700 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
702 if len(test.extra) != extraLen {
703 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
706 a1 := ValueOf(test.orig)
707 have1 := AppendSlice(a1, e1).Interface().([]int)
708 if !sameInts(have1, want) {
709 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
711 // Check that the orig and extra slices were not modified.
712 if len(test.orig) != origLen {
713 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
715 if len(test.extra) != extraLen {
716 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
721 func TestCopy(t *testing.T) {
722 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
723 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
724 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
725 for i := 0; i < len(b); i++ {
727 t.Fatalf("b != c before test")
732 aa := ValueOf(&a1).Elem()
733 ab := ValueOf(&b1).Elem()
734 for tocopy := 1; tocopy <= 7; tocopy++ {
738 for i := 0; i < tocopy; i++ {
740 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
741 tocopy, i, a[i], i, b[i])
744 for i := tocopy; i < len(b); i++ {
747 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
748 tocopy, i, a[i], i, b[i], i, c[i])
750 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
751 tocopy, i, b[i], i, c[i])
754 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
760 func TestCopyString(t *testing.T) {
761 t.Run("Slice", func(t *testing.T) {
762 s := bytes.Repeat([]byte{'_'}, 8)
765 n := Copy(val, ValueOf(""))
766 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
767 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
770 n = Copy(val, ValueOf("hello"))
771 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
772 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
775 n = Copy(val, ValueOf("helloworld"))
776 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
777 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
780 t.Run("Array", func(t *testing.T) {
781 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
782 val := ValueOf(&s).Elem()
784 n := Copy(val, ValueOf(""))
785 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
786 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
789 n = Copy(val, ValueOf("hello"))
790 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
791 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
794 n = Copy(val, ValueOf("helloworld"))
795 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
796 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
801 func TestCopyArray(t *testing.T) {
802 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
803 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
805 aa := ValueOf(&a).Elem()
806 ab := ValueOf(&b).Elem()
808 for i := 0; i < len(a); i++ {
810 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
813 for i := len(a); i < len(b); i++ {
815 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
817 t.Logf("elem %d is okay\n", i)
822 func TestBigUnnamedStruct(t *testing.T) {
823 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
825 b1 := v.Interface().(struct {
828 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
829 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
837 func TestBigStruct(t *testing.T) {
838 b := big{1, 2, 3, 4, 5}
840 b1 := v.Interface().(big)
841 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
842 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
853 type DeepEqualTest struct {
858 // Simple functions for DeepEqual tests.
862 fn3 = func() { fn1() } // Not nil.
868 type Loopy interface{}
870 var loop1, loop2 Loop
871 var loopy1, loopy2 Loopy
872 var cycleMap1, cycleMap2, cycleMap3 map[string]interface{}
874 type structWithSelfPtr struct {
886 cycleMap1 = map[string]interface{}{}
887 cycleMap1["cycle"] = cycleMap1
888 cycleMap2 = map[string]interface{}{}
889 cycleMap2["cycle"] = cycleMap2
890 cycleMap3 = map[string]interface{}{}
891 cycleMap3["different"] = cycleMap3
894 var deepEqualTests = []DeepEqualTest{
898 {int32(1), int32(1), true},
900 {float32(0.5), float32(0.5), true},
901 {"hello", "hello", true},
902 {make([]int, 10), make([]int, 10), true},
903 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
904 {Basic{1, 0.5}, Basic{1, 0.5}, true},
905 {error(nil), error(nil), true},
906 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
908 {[]byte{1, 2, 3}, []byte{1, 2, 3}, true},
909 {[]MyByte{1, 2, 3}, []MyByte{1, 2, 3}, true},
910 {MyBytes{1, 2, 3}, MyBytes{1, 2, 3}, true},
914 {int32(1), int32(2), false},
916 {float32(0.5), float32(0.6), false},
917 {"hello", "hey", false},
918 {make([]int, 10), make([]int, 11), false},
919 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
920 {Basic{1, 0.5}, Basic{1, 0.6}, false},
921 {Basic{1, 0}, Basic{2, 0}, false},
922 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
923 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
924 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
925 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
930 {[][]int{{1}}, [][]int{{2}}, false},
931 {math.NaN(), math.NaN(), false},
932 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
933 {&[1]float64{math.NaN()}, self{}, true},
934 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
935 {[]float64{math.NaN()}, self{}, true},
936 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
937 {map[float64]float64{math.NaN(): 1}, self{}, true},
938 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
940 // Nil vs empty: not the same.
941 {[]int{}, []int(nil), false},
942 {[]int{}, []int{}, true},
943 {[]int(nil), []int(nil), true},
944 {map[int]int{}, map[int]int(nil), false},
945 {map[int]int{}, map[int]int{}, true},
946 {map[int]int(nil), map[int]int(nil), true},
950 {int32(1), int64(1), false},
951 {0.5, "hello", false},
952 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
953 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
954 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
955 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
956 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
957 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
958 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
961 {&loop1, &loop1, true},
962 {&loop1, &loop2, true},
963 {&loopy1, &loopy1, true},
964 {&loopy1, &loopy2, true},
965 {&cycleMap1, &cycleMap2, true},
966 {&cycleMap1, &cycleMap3, false},
969 func TestDeepEqual(t *testing.T) {
970 for _, test := range deepEqualTests {
971 if test.b == (self{}) {
974 if r := DeepEqual(test.a, test.b); r != test.eq {
975 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
980 func TestTypeOf(t *testing.T) {
981 // Special case for nil
982 if typ := TypeOf(nil); typ != nil {
983 t.Errorf("expected nil type for nil value; got %v", typ)
985 for _, test := range deepEqualTests {
990 typ := TypeOf(test.a)
992 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
997 type Recursive struct {
1002 func TestDeepEqualRecursiveStruct(t *testing.T) {
1003 a, b := new(Recursive), new(Recursive)
1004 *a = Recursive{12, a}
1005 *b = Recursive{12, b}
1006 if !DeepEqual(a, b) {
1007 t.Error("DeepEqual(recursive same) = false, want true")
1011 type _Complex struct {
1015 d map[float64]float64
1018 func TestDeepEqualComplexStruct(t *testing.T) {
1019 m := make(map[float64]float64)
1020 stra, strb := "hello", "hello"
1021 a, b := new(_Complex), new(_Complex)
1022 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1023 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1024 if !DeepEqual(a, b) {
1025 t.Error("DeepEqual(complex same) = false, want true")
1029 func TestDeepEqualComplexStructInequality(t *testing.T) {
1030 m := make(map[float64]float64)
1031 stra, strb := "hello", "helloo" // Difference is here
1032 a, b := new(_Complex), new(_Complex)
1033 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1034 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1035 if DeepEqual(a, b) {
1036 t.Error("DeepEqual(complex different) = true, want false")
1040 type UnexpT struct {
1044 func TestDeepEqualUnexportedMap(t *testing.T) {
1045 // Check that DeepEqual can look at unexported fields.
1046 x1 := UnexpT{map[int]int{1: 2}}
1047 x2 := UnexpT{map[int]int{1: 2}}
1048 if !DeepEqual(&x1, &x2) {
1049 t.Error("DeepEqual(x1, x2) = false, want true")
1052 y1 := UnexpT{map[int]int{2: 3}}
1053 if DeepEqual(&x1, &y1) {
1054 t.Error("DeepEqual(x1, y1) = true, want false")
1058 var deepEqualPerfTests = []struct {
1061 {x: int8(99), y: int8(99)},
1062 {x: []int8{99}, y: []int8{99}},
1063 {x: int16(99), y: int16(99)},
1064 {x: []int16{99}, y: []int16{99}},
1065 {x: int32(99), y: int32(99)},
1066 {x: []int32{99}, y: []int32{99}},
1067 {x: int64(99), y: int64(99)},
1068 {x: []int64{99}, y: []int64{99}},
1069 {x: int(999999), y: int(999999)},
1070 {x: []int{999999}, y: []int{999999}},
1072 {x: uint8(99), y: uint8(99)},
1073 {x: []uint8{99}, y: []uint8{99}},
1074 {x: uint16(99), y: uint16(99)},
1075 {x: []uint16{99}, y: []uint16{99}},
1076 {x: uint32(99), y: uint32(99)},
1077 {x: []uint32{99}, y: []uint32{99}},
1078 {x: uint64(99), y: uint64(99)},
1079 {x: []uint64{99}, y: []uint64{99}},
1080 {x: uint(999999), y: uint(999999)},
1081 {x: []uint{999999}, y: []uint{999999}},
1082 {x: uintptr(999999), y: uintptr(999999)},
1083 {x: []uintptr{999999}, y: []uintptr{999999}},
1085 {x: float32(1.414), y: float32(1.414)},
1086 {x: []float32{1.414}, y: []float32{1.414}},
1087 {x: float64(1.414), y: float64(1.414)},
1088 {x: []float64{1.414}, y: []float64{1.414}},
1090 {x: complex64(1.414), y: complex64(1.414)},
1091 {x: []complex64{1.414}, y: []complex64{1.414}},
1092 {x: complex128(1.414), y: complex128(1.414)},
1093 {x: []complex128{1.414}, y: []complex128{1.414}},
1096 {x: []bool{true}, y: []bool{true}},
1098 {x: "abcdef", y: "abcdef"},
1099 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1101 {x: []byte("abcdef"), y: []byte("abcdef")},
1102 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1104 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1105 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1108 func TestDeepEqualAllocs(t *testing.T) {
1109 for _, tt := range deepEqualPerfTests {
1110 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1111 got := testing.AllocsPerRun(100, func() {
1112 if !DeepEqual(tt.x, tt.y) {
1113 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1117 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1123 func BenchmarkDeepEqual(b *testing.B) {
1124 for _, bb := range deepEqualPerfTests {
1125 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1127 for i := 0; i < b.N; i++ {
1128 sink = DeepEqual(bb.x, bb.y)
1134 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
1136 f := s.Type().Field(1)
1137 if f.Offset != offs {
1138 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1142 // Check that structure alignment & offsets viewed through reflect agree with those
1143 // from the compiler itself.
1144 func TestAlignment(t *testing.T) {
1145 type T1inner struct {
1152 type T2inner struct {
1160 x := T1{T1inner{2}, 17}
1161 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1163 x1 := T2{T2inner{2, 3}, 17}
1164 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1167 func Nil(a interface{}, t *testing.T) {
1168 n := ValueOf(a).Field(0)
1170 t.Errorf("%v should be nil", a)
1174 func NotNil(a interface{}, t *testing.T) {
1175 n := ValueOf(a).Field(0)
1177 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1181 func TestIsNil(t *testing.T) {
1182 // These implement IsNil.
1183 // Wrap in extra struct to hide interface type.
1184 doNil := []interface{}{
1186 struct{ x interface{} }{},
1187 struct{ x map[string]int }{},
1188 struct{ x func() bool }{},
1189 struct{ x chan int }{},
1190 struct{ x []string }{},
1191 struct{ x unsafe.Pointer }{},
1193 for _, ts := range doNil {
1194 ty := TypeOf(ts).Field(0).Type
1196 v.IsNil() // panics if not okay to call
1199 // Check the implementations
1211 si.x = make([]int, 10)
1218 ci.x = make(chan int)
1225 mi.x = make(map[int]int)
1236 x func(t *testing.T)
1243 func TestIsZero(t *testing.T) {
1244 for i, tt := range []struct {
1273 {float32(1.2), false},
1275 {float64(1.2), false},
1276 {math.Copysign(0, -1), false},
1277 {complex64(0), true},
1278 {complex64(1.2), false},
1279 {complex128(0), true},
1280 {complex128(1.2), false},
1281 {complex(math.Copysign(0, -1), 0), false},
1282 {complex(0, math.Copysign(0, -1)), false},
1283 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1285 {uintptr(128), false},
1287 {Zero(TypeOf([5]string{})).Interface(), true},
1288 {[5]string{"", "", "", "", ""}, true},
1289 {[5]string{}, true},
1290 {[5]string{"", "", "", "a", ""}, false},
1292 {(chan string)(nil), true},
1293 {make(chan string), false},
1294 {time.After(1), false},
1296 {(func())(nil), true},
1299 {New(TypeOf(new(error)).Elem()).Elem(), true},
1300 {(io.Reader)(strings.NewReader("")), false},
1302 {(map[string]string)(nil), true},
1303 {map[string]string{}, false},
1304 {make(map[string]string), false},
1306 {(*func())(nil), true},
1307 {(*int)(nil), true},
1310 {[]string{}, false},
1311 {([]string)(nil), true},
1312 {make([]string, 0), false},
1315 {"not-zero", false},
1318 {T{123, 456.75, "hello", &_i}, false},
1320 {(unsafe.Pointer)(nil), true},
1321 {(unsafe.Pointer)(new(int)), false},
1324 if v, ok := tt.x.(Value); ok {
1332 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1335 if !Zero(TypeOf(tt.x)).IsZero() {
1336 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1342 if r := recover(); r == nil {
1343 t.Error("should panic for invalid value")
1350 func TestInterfaceExtraction(t *testing.T) {
1356 v := Indirect(ValueOf(&s)).Field(0).Interface()
1357 if v != s.W.(interface{}) {
1358 t.Error("Interface() on interface: ", v, s.W)
1362 func TestNilPtrValueSub(t *testing.T) {
1364 if pv := ValueOf(pi); pv.Elem().IsValid() {
1365 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1369 func TestMap(t *testing.T) {
1370 m := map[string]int{"a": 1, "b": 2}
1372 if n := mv.Len(); n != len(m) {
1373 t.Errorf("Len = %d, want %d", n, len(m))
1375 keys := mv.MapKeys()
1376 newmap := MakeMap(mv.Type())
1377 for k, v := range m {
1378 // Check that returned Keys match keys in range.
1379 // These aren't required to be in the same order.
1381 for _, kv := range keys {
1382 if kv.String() == k {
1388 t.Errorf("Missing key %q", k)
1391 // Check that value lookup is correct.
1392 vv := mv.MapIndex(ValueOf(k))
1393 if vi := vv.Int(); vi != int64(v) {
1394 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1397 // Copy into new map.
1398 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1400 vv := mv.MapIndex(ValueOf("not-present"))
1402 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1405 newm := newmap.Interface().(map[string]int)
1406 if len(newm) != len(m) {
1407 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1410 for k, v := range newm {
1413 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1417 newmap.SetMapIndex(ValueOf("a"), Value{})
1420 t.Errorf("newm[\"a\"] = %d after delete", v)
1423 mv = ValueOf(&m).Elem()
1424 mv.Set(Zero(mv.Type()))
1426 t.Errorf("mv.Set(nil) failed")
1430 func TestNilMap(t *testing.T) {
1431 var m map[string]int
1433 keys := mv.MapKeys()
1435 t.Errorf(">0 keys for nil map: %v", keys)
1438 // Check that value for missing key is zero.
1439 x := mv.MapIndex(ValueOf("hello"))
1440 if x.Kind() != Invalid {
1441 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1444 // Check big value too.
1445 var mbig map[string][10 << 20]byte
1446 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1447 if x.Kind() != Invalid {
1448 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1451 // Test that deletes from a nil map succeed.
1452 mv.SetMapIndex(ValueOf("hi"), Value{})
1455 func TestChan(t *testing.T) {
1456 for loop := 0; loop < 2; loop++ {
1460 // check both ways to allocate channels
1463 c = make(chan int, 1)
1466 cv = MakeChan(TypeOf(c), 1)
1467 c = cv.Interface().(chan int)
1472 if i := <-c; i != 2 {
1473 t.Errorf("reflect Send 2, native recv %d", i)
1478 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1479 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1483 val, ok := cv.TryRecv()
1484 if val.IsValid() || ok {
1485 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1490 val, ok = cv.TryRecv()
1492 t.Errorf("TryRecv on ready chan got nil")
1493 } else if i := val.Int(); i != 4 || !ok {
1494 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1499 ok = cv.TrySend(ValueOf(5))
1502 t.Errorf("TrySend on full chan succeeded: value %d", i)
1506 ok = cv.TrySend(ValueOf(6))
1508 t.Errorf("TrySend on empty chan failed")
1511 t.Errorf("TrySend failed but it did send %d", x)
1515 if i = <-c; i != 6 {
1516 t.Errorf("TrySend 6, recv %d", i)
1523 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1524 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1526 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1527 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1531 // check creation of unbuffered channel
1533 cv := MakeChan(TypeOf(c), 0)
1534 c = cv.Interface().(chan int)
1535 if cv.TrySend(ValueOf(7)) {
1536 t.Errorf("TrySend on sync chan succeeded")
1538 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1539 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1543 cv = MakeChan(TypeOf(c), 10)
1544 c = cv.Interface().(chan int)
1545 for i := 0; i < 3; i++ {
1548 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1549 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1553 // caseInfo describes a single case in a select test.
1554 type caseInfo struct {
1563 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1565 func TestSelect(t *testing.T) {
1566 selectWatch.once.Do(func() { go selectWatcher() })
1570 newop := func(n int, cap int) (ch, val Value) {
1573 c := make(chan int, cap)
1577 c := make(chan string, cap)
1579 val = ValueOf(fmt.Sprint(n))
1584 for n := 0; x.Next(); n++ {
1585 if testing.Short() && n >= 1000 {
1588 if n >= 100000 && !*allselect {
1591 if n%100000 == 0 && testing.Verbose() {
1592 println("TestSelect", n)
1594 var cases []SelectCase
1599 ch, val := newop(len(cases), 1)
1600 cases = append(cases, SelectCase{
1605 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1610 ch, val := newop(len(cases), 1)
1612 cases = append(cases, SelectCase{
1616 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1621 ch, val := newop(len(cases), 0)
1622 cases = append(cases, SelectCase{
1629 f := func() { ch.Recv() }
1630 info = append(info, caseInfo{desc: "blocking send", helper: f})
1632 info = append(info, caseInfo{desc: "blocking send"})
1638 ch, val := newop(len(cases), 0)
1639 cases = append(cases, SelectCase{
1645 f := func() { ch.Send(val) }
1646 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1648 info = append(info, caseInfo{desc: "blocking recv"})
1654 // Maybe include value to send.
1659 cases = append(cases, SelectCase{
1663 info = append(info, caseInfo{desc: "zero Chan send"})
1666 // Zero Chan receive.
1668 cases = append(cases, SelectCase{
1671 info = append(info, caseInfo{desc: "zero Chan recv"})
1676 cases = append(cases, SelectCase{
1678 Chan: ValueOf((chan int)(nil)),
1681 info = append(info, caseInfo{desc: "nil Chan send"})
1686 cases = append(cases, SelectCase{
1688 Chan: ValueOf((chan int)(nil)),
1690 info = append(info, caseInfo{desc: "nil Chan recv"})
1693 // closed Chan send.
1695 ch := make(chan int)
1697 cases = append(cases, SelectCase{
1702 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1705 // closed Chan recv.
1707 ch, val := newop(len(cases), 0)
1709 val = Zero(val.Type())
1710 cases = append(cases, SelectCase{
1714 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1717 var helper func() // goroutine to help the select complete
1719 // Add default? Must be last case here, but will permute.
1720 // Add the default if the select would otherwise
1721 // block forever, and maybe add it anyway.
1727 for i, c := range info {
1735 } else if c.helper != nil {
1737 helpers = append(helpers, i)
1740 if !canProceed || x.Maybe() {
1741 cases = append(cases, SelectCase{
1744 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1746 } else if canBlock {
1747 // Select needs to communicate with another goroutine.
1748 cas := &info[helpers[x.Choose(len(helpers))]]
1750 cas.canSelect = true
1754 // Permute cases and case info.
1755 // Doing too much here makes the exhaustive loop
1756 // too exhausting, so just do two swaps.
1757 for loop := 0; loop < 2; loop++ {
1758 i := x.Choose(len(cases))
1759 j := x.Choose(len(cases))
1760 cases[i], cases[j] = cases[j], cases[i]
1761 info[i], info[j] = info[j], info[i]
1765 // We wait before kicking off a goroutine to satisfy a blocked select.
1766 // The pause needs to be big enough to let the select block before
1767 // we run the helper, but if we lose that race once in a while it's okay: the
1768 // select will just proceed immediately. Not a big deal.
1769 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1770 pause := 10 * time.Microsecond
1771 if testing.Short() {
1772 pause = 100 * time.Microsecond
1774 time.AfterFunc(pause, helper)
1778 i, recv, recvOK, panicErr := runSelect(cases, info)
1779 if panicErr != nil && !canPanic {
1780 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1782 if panicErr == nil && canPanic && numCanSelect == 1 {
1783 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1785 if panicErr != nil {
1793 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1795 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1799 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1803 if cases[i].Dir == SelectRecv {
1804 if !recv.IsValid() {
1805 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1807 if !cas.recv.IsValid() {
1808 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1810 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1811 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1812 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1814 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1817 if recv.IsValid() || recvOK {
1818 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1824 func TestSelectMaxCases(t *testing.T) {
1825 var sCases []SelectCase
1826 channel := make(chan int)
1828 for i := 0; i < 65536; i++ {
1829 sCases = append(sCases, SelectCase{
1831 Chan: ValueOf(channel),
1835 _, _, _ = Select(sCases)
1836 sCases = append(sCases, SelectCase{
1838 Chan: ValueOf(channel),
1841 if err := recover(); err != nil {
1842 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1843 t.Fatalf("unexpected error from select call with greater than max supported cases")
1846 t.Fatalf("expected select call to panic with greater than max supported cases")
1850 _, _, _ = Select(sCases)
1853 func TestSelectNop(t *testing.T) {
1854 // "select { default: }" should always return the default case.
1855 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1857 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1861 func BenchmarkSelect(b *testing.B) {
1862 channel := make(chan int)
1864 var cases []SelectCase
1865 for i := 0; i < 8; i++ {
1866 cases = append(cases, SelectCase{
1868 Chan: ValueOf(channel),
1871 for _, numCases := range []int{1, 4, 8} {
1872 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1874 for i := 0; i < b.N; i++ {
1875 _, _, _ = Select(cases[:numCases])
1881 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1882 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1883 // an error describing the select and panics the entire test binary.
1884 var selectWatch struct {
1891 func selectWatcher() {
1893 time.Sleep(1 * time.Second)
1895 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1896 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1897 panic("select stuck")
1899 selectWatch.Unlock()
1903 // runSelect runs a single select test.
1904 // It returns the values returned by Select but also returns
1905 // a panic value if the Select panics.
1906 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1908 panicErr = recover()
1911 selectWatch.info = nil
1912 selectWatch.Unlock()
1916 selectWatch.now = time.Now()
1917 selectWatch.info = info
1918 selectWatch.Unlock()
1920 chosen, recv, recvOK = Select(cases)
1924 // fmtSelect formats the information about a single select test.
1925 func fmtSelect(info []caseInfo) string {
1926 var buf bytes.Buffer
1927 fmt.Fprintf(&buf, "\nselect {\n")
1928 for i, cas := range info {
1929 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1930 if cas.recv.IsValid() {
1931 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1934 fmt.Fprintf(&buf, " canselect")
1937 fmt.Fprintf(&buf, " panic")
1939 fmt.Fprintf(&buf, "\n")
1941 fmt.Fprintf(&buf, "}")
1947 // Difficult test for function call because of
1948 // implicit padding between arguments.
1949 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) {
1950 return b, c, d, e, f, g, h
1953 func TestFunc(t *testing.T) {
1954 ret := ValueOf(dummy).Call([]Value{
1958 ValueOf(two{40, 50}),
1960 ValueOf(float32(70)),
1964 t.Fatalf("Call returned %d values, want 7", len(ret))
1967 i := byte(ret[0].Uint())
1968 j := int(ret[1].Int())
1969 k := byte(ret[2].Uint())
1970 l := ret[3].Interface().(two)
1971 m := byte(ret[4].Uint())
1972 n := float32(ret[5].Float())
1973 o := byte(ret[6].Uint())
1975 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1976 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)
1979 for i, v := range ret {
1981 t.Errorf("result %d is addressable", i)
1986 func TestCallConvert(t *testing.T) {
1987 v := ValueOf(new(io.ReadWriter)).Elem()
1988 f := ValueOf(func(r io.Reader) io.Reader { return r })
1989 out := f.Call([]Value{v})
1990 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
1991 t.Errorf("expected [nil], got %v", out)
1995 type emptyStruct struct{}
1997 type nonEmptyStruct struct {
2001 func returnEmpty() emptyStruct {
2002 return emptyStruct{}
2005 func takesEmpty(e emptyStruct) {
2008 func returnNonEmpty(i int) nonEmptyStruct {
2009 return nonEmptyStruct{member: i}
2012 func takesNonEmpty(n nonEmptyStruct) int {
2016 func TestCallWithStruct(t *testing.T) {
2017 r := ValueOf(returnEmpty).Call(nil)
2018 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2019 t.Errorf("returning empty struct returned %#v instead", r)
2021 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2023 t.Errorf("takesEmpty returned values: %#v", r)
2025 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2026 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2027 t.Errorf("returnNonEmpty returned %#v", r)
2029 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2030 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2031 t.Errorf("takesNonEmpty returned %#v", r)
2035 func TestCallReturnsEmpty(t *testing.T) {
2036 // Issue 21717: past-the-end pointer write in Call with
2037 // nonzero-sized frame and zero-sized return value.
2039 var finalized uint32
2040 f := func() (emptyStruct, *[2]int64) {
2041 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2042 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2043 return emptyStruct{}, i
2045 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2046 timeout := time.After(5 * time.Second)
2047 for atomic.LoadUint32(&finalized) == 0 {
2050 t.Fatal("finalizer did not run")
2056 runtime.KeepAlive(v)
2059 func BenchmarkCall(b *testing.B) {
2060 fv := ValueOf(func(a, b string) {})
2062 b.RunParallel(func(pb *testing.PB) {
2063 args := []Value{ValueOf("a"), ValueOf("b")}
2072 func (i *myint) inc() {
2076 func BenchmarkCallMethod(b *testing.B) {
2081 for i := 0; i < b.N; i++ {
2086 func BenchmarkCallArgCopy(b *testing.B) {
2087 byteArray := func(n int) Value {
2088 return Zero(ArrayOf(n, TypeOf(byte(0))))
2090 sizes := [...]struct {
2094 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2095 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2096 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2097 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2098 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2100 for _, size := range sizes {
2101 bench := func(b *testing.B) {
2102 args := []Value{size.arg}
2103 b.SetBytes(int64(size.arg.Len()))
2105 b.RunParallel(func(pb *testing.PB) {
2111 name := fmt.Sprintf("size=%v", size.arg.Len())
2116 func TestMakeFunc(t *testing.T) {
2118 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2119 ValueOf(&f).Elem().Set(fv)
2121 // Call g with small arguments so that there is
2122 // something predictable (and different from the
2123 // correct results) in those positions on the stack.
2125 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2127 // Call constructed function f.
2128 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2129 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2130 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)
2134 func TestMakeFuncInterface(t *testing.T) {
2135 fn := func(i int) int { return i }
2136 incr := func(in []Value) []Value {
2137 return []Value{ValueOf(int(in[0].Int() + 1))}
2139 fv := MakeFunc(TypeOf(fn), incr)
2140 ValueOf(&fn).Elem().Set(fv)
2141 if r := fn(2); r != 3 {
2142 t.Errorf("Call returned %d, want 3", r)
2144 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2145 t.Errorf("Call returned %d, want 15", r)
2147 if r := fv.Interface().(func(int) int)(26); r != 27 {
2148 t.Errorf("Call returned %d, want 27", r)
2152 func TestMakeFuncVariadic(t *testing.T) {
2153 // Test that variadic arguments are packed into a slice and passed as last arg
2154 fn := func(_ int, is ...int) []int { return nil }
2155 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2156 ValueOf(&fn).Elem().Set(fv)
2159 if r[0] != 2 || r[1] != 3 {
2160 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2163 r = fn(1, []int{2, 3}...)
2164 if r[0] != 2 || r[1] != 3 {
2165 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2168 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2169 if r[0] != 2 || r[1] != 3 {
2170 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2173 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2174 if r[0] != 2 || r[1] != 3 {
2175 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2178 f := fv.Interface().(func(int, ...int) []int)
2181 if r[0] != 2 || r[1] != 3 {
2182 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2184 r = f(1, []int{2, 3}...)
2185 if r[0] != 2 || r[1] != 3 {
2186 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2190 // Dummy type that implements io.WriteCloser
2194 func (w *WC) Write(p []byte) (n int, err error) {
2197 func (w *WC) Close() error {
2201 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2202 // reflect.Values returned from the wrapped function should be assignment-converted
2203 // to the types returned by the result of MakeFunc.
2205 // Concrete types should be promotable to interfaces they implement.
2207 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2208 return []Value{ValueOf(io.EOF)}
2209 }).Interface().(func() error)
2212 // Super-interfaces should be promotable to simpler interfaces.
2213 var g func() io.Writer
2214 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2215 var w io.WriteCloser = &WC{}
2216 return []Value{ValueOf(&w).Elem()}
2217 }).Interface().(func() io.Writer)
2220 // Channels should be promotable to directional channels.
2221 var h func() <-chan int
2222 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2223 return []Value{ValueOf(make(chan int))}
2224 }).Interface().(func() <-chan int)
2227 // Unnamed types should be promotable to named types.
2228 type T struct{ a, b, c int }
2230 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2231 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2232 }).Interface().(func() T)
2236 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2237 // Type doesn't implement the required interface.
2238 shouldPanic("", func() {
2240 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2241 return []Value{ValueOf(int(7))}
2242 }).Interface().(func() error)
2245 // Assigning to an interface with additional methods.
2246 shouldPanic("", func() {
2247 var f func() io.ReadWriteCloser
2248 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2249 var w io.WriteCloser = &WC{}
2250 return []Value{ValueOf(&w).Elem()}
2251 }).Interface().(func() io.ReadWriteCloser)
2254 // Directional channels can't be assigned to bidirectional ones.
2255 shouldPanic("", func() {
2256 var f func() chan int
2257 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2258 var c <-chan int = make(chan int)
2259 return []Value{ValueOf(c)}
2260 }).Interface().(func() chan int)
2263 // Two named types which are otherwise identical.
2264 shouldPanic("", func() {
2265 type T struct{ a, b, c int }
2266 type U struct{ a, b, c int }
2268 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2269 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2270 }).Interface().(func() T)
2279 // This will be index 0.
2280 func (p Point) AnotherMethod(scale int) int {
2284 // This will be index 1.
2285 func (p Point) Dist(scale int) int {
2286 //println("Point.Dist", p.x, p.y, scale)
2287 return p.x*p.x*scale + p.y*p.y*scale
2290 // This will be index 2.
2291 func (p Point) GCMethod(k int) int {
2296 // This will be index 3.
2297 func (p Point) NoArgs() {
2298 // Exercise no-argument/no-result paths.
2301 // This will be index 4.
2302 func (p Point) TotalDist(points ...Point) int {
2304 for _, q := range points {
2307 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2313 // This will be index 5.
2314 func (p *Point) Int64Method(x int64) int64 {
2318 // This will be index 6.
2319 func (p *Point) Int32Method(x int32) int32 {
2323 func TestMethod(t *testing.T) {
2324 // Non-curried method of type.
2326 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2328 t.Errorf("Type Method returned %d; want 250", i)
2331 m, ok := TypeOf(p).MethodByName("Dist")
2333 t.Fatalf("method by name failed")
2335 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2337 t.Errorf("Type MethodByName returned %d; want 275", i)
2340 m, ok = TypeOf(p).MethodByName("NoArgs")
2342 t.Fatalf("method by name failed")
2344 n := len(m.Func.Call([]Value{ValueOf(p)}))
2346 t.Errorf("NoArgs returned %d values; want 0", n)
2349 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2351 t.Errorf("Pointer Type Method returned %d; want 300", i)
2354 m, ok = TypeOf(&p).MethodByName("Dist")
2356 t.Fatalf("ptr method by name failed")
2358 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2360 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2363 m, ok = TypeOf(&p).MethodByName("NoArgs")
2365 t.Fatalf("method by name failed")
2367 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2369 t.Errorf("NoArgs returned %d values; want 0", n)
2372 // Curried method of value.
2373 tfunc := TypeOf((func(int) int)(nil))
2374 v := ValueOf(p).Method(1)
2375 if tt := v.Type(); tt != tfunc {
2376 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2378 i = v.Call([]Value{ValueOf(14)})[0].Int()
2380 t.Errorf("Value Method returned %d; want 350", i)
2382 v = ValueOf(p).MethodByName("Dist")
2383 if tt := v.Type(); tt != tfunc {
2384 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2386 i = v.Call([]Value{ValueOf(15)})[0].Int()
2388 t.Errorf("Value MethodByName returned %d; want 375", i)
2390 v = ValueOf(p).MethodByName("NoArgs")
2393 // Curried method of pointer.
2394 v = ValueOf(&p).Method(1)
2395 if tt := v.Type(); tt != tfunc {
2396 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2398 i = v.Call([]Value{ValueOf(16)})[0].Int()
2400 t.Errorf("Pointer Value Method returned %d; want 400", i)
2402 v = ValueOf(&p).MethodByName("Dist")
2403 if tt := v.Type(); tt != tfunc {
2404 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2406 i = v.Call([]Value{ValueOf(17)})[0].Int()
2408 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2410 v = ValueOf(&p).MethodByName("NoArgs")
2413 // Curried method of interface value.
2414 // Have to wrap interface value in a struct to get at it.
2415 // Passing it to ValueOf directly would
2416 // access the underlying Point, not the interface.
2420 pv := ValueOf(&x).Elem()
2422 if tt := v.Type(); tt != tfunc {
2423 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2425 i = v.Call([]Value{ValueOf(18)})[0].Int()
2427 t.Errorf("Interface Method returned %d; want 450", i)
2429 v = pv.MethodByName("Dist")
2430 if tt := v.Type(); tt != tfunc {
2431 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2433 i = v.Call([]Value{ValueOf(19)})[0].Int()
2435 t.Errorf("Interface MethodByName returned %d; want 475", i)
2439 func TestMethodValue(t *testing.T) {
2443 // Curried method of value.
2444 tfunc := TypeOf((func(int) int)(nil))
2445 v := ValueOf(p).Method(1)
2446 if tt := v.Type(); tt != tfunc {
2447 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2449 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2451 t.Errorf("Value Method returned %d; want 250", i)
2453 v = ValueOf(p).MethodByName("Dist")
2454 if tt := v.Type(); tt != tfunc {
2455 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2457 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2459 t.Errorf("Value MethodByName returned %d; want 275", i)
2461 v = ValueOf(p).MethodByName("NoArgs")
2462 ValueOf(v.Interface()).Call(nil)
2463 v.Interface().(func())()
2465 // Curried method of pointer.
2466 v = ValueOf(&p).Method(1)
2467 if tt := v.Type(); tt != tfunc {
2468 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2470 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2472 t.Errorf("Pointer Value Method returned %d; want 300", i)
2474 v = ValueOf(&p).MethodByName("Dist")
2475 if tt := v.Type(); tt != tfunc {
2476 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2478 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2480 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2482 v = ValueOf(&p).MethodByName("NoArgs")
2483 ValueOf(v.Interface()).Call(nil)
2484 v.Interface().(func())()
2486 // Curried method of pointer to pointer.
2488 v = ValueOf(&pp).Elem().Method(1)
2489 if tt := v.Type(); tt != tfunc {
2490 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2492 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2494 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2496 v = ValueOf(&pp).Elem().MethodByName("Dist")
2497 if tt := v.Type(); tt != tfunc {
2498 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2500 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2502 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2505 // Curried method of interface value.
2506 // Have to wrap interface value in a struct to get at it.
2507 // Passing it to ValueOf directly would
2508 // access the underlying Point, not the interface.
2514 pv := ValueOf(s).Field(0)
2516 if tt := v.Type(); tt != tfunc {
2517 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2519 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2521 t.Errorf("Interface Method returned %d; want 400", i)
2523 v = pv.MethodByName("Dist")
2524 if tt := v.Type(); tt != tfunc {
2525 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2527 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2529 t.Errorf("Interface MethodByName returned %d; want 425", i)
2532 // For issue #33628: method args are not stored at the right offset
2534 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2535 if x := m64(123); x != 123 {
2536 t.Errorf("Int64Method returned %d; want 123", x)
2538 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2539 if x := m32(456); x != 456 {
2540 t.Errorf("Int32Method returned %d; want 456", x)
2544 func TestVariadicMethodValue(t *testing.T) {
2546 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2547 want := int64(p.TotalDist(points[0], points[1], points[2]))
2549 // Variadic method of type.
2550 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2551 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2552 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2555 // Curried method of value.
2556 tfunc = TypeOf((func(...Point) int)(nil))
2557 v := ValueOf(p).Method(4)
2558 if tt := v.Type(); tt != tfunc {
2559 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2561 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2563 t.Errorf("Variadic Method returned %d; want %d", i, want)
2565 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2567 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2570 f := v.Interface().(func(...Point) int)
2571 i = int64(f(points[0], points[1], points[2]))
2573 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2575 i = int64(f(points...))
2577 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2581 type DirectIfaceT struct {
2585 func (d DirectIfaceT) M() int { return *d.p }
2587 func TestDirectIfaceMethod(t *testing.T) {
2589 v := DirectIfaceT{&x}
2591 m, ok := typ.MethodByName("M")
2593 t.Fatalf("cannot find method M")
2595 in := []Value{ValueOf(v)}
2596 out := m.Func.Call(in)
2597 if got := out[0].Int(); got != 42 {
2598 t.Errorf("Call with value receiver got %d, want 42", got)
2603 m, ok = typ.MethodByName("M")
2605 t.Fatalf("cannot find method M")
2607 in = []Value{ValueOf(pv)}
2608 out = m.Func.Call(in)
2609 if got := out[0].Int(); got != 42 {
2610 t.Errorf("Call with pointer receiver got %d, want 42", got)
2614 // Reflect version of $GOROOT/test/method5.go
2616 // Concrete types implementing M method.
2617 // Smaller than a word, word-sized, larger than a word.
2618 // Value and pointer receivers.
2620 type Tinter interface {
2621 M(int, byte) (byte, int)
2626 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2630 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2634 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2638 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2640 type Tbigv [2]uintptr
2642 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2644 type Tbigp [2]uintptr
2646 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2648 type tinter interface {
2649 m(int, byte) (byte, int)
2652 // Embedding via pointer.
2669 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2671 func TestMethod5(t *testing.T) {
2672 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2674 if b != 99 || x != 1000+inc {
2675 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2679 CheckV := func(name string, i Value, inc int) {
2680 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2681 b := bx[0].Interface()
2682 x := bx[1].Interface()
2683 if b != byte(99) || x != 1000+inc {
2684 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2687 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2690 var TinterType = TypeOf(new(Tinter)).Elem()
2692 CheckI := func(name string, i interface{}, inc int) {
2694 CheckV(name, v, inc)
2695 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2700 CheckI("&sv", &sv, 1)
2703 CheckI("&sp", &sp, 2)
2707 CheckI("&wv", &wv, 3)
2710 CheckI("&wp", &wp, 4)
2712 bv := Tbigv([2]uintptr{5, 6})
2713 CheckI("bv", bv, 11)
2714 CheckI("&bv", &bv, 11)
2716 bp := Tbigp([2]uintptr{7, 8})
2717 CheckI("&bp", &bp, 15)
2723 CheckI("t4", t4, 40)
2724 CheckI("&t4", &t4, 40)
2725 CheckI("t3", t3, 40)
2726 CheckI("&t3", &t3, 40)
2727 CheckI("t2", t2, 40)
2728 CheckI("&t2", &t2, 40)
2729 CheckI("t1", t1, 40)
2730 CheckI("&t1", &t1, 40)
2733 vnil := ValueOf(&tnil).Elem()
2734 shouldPanic("Method", func() { vnil.Method(0) })
2737 func TestInterfaceSet(t *testing.T) {
2746 sv := ValueOf(&s).Elem()
2747 sv.Field(0).Set(ValueOf(p))
2748 if q := s.I.(*Point); q != p {
2749 t.Errorf("i: have %p want %p", q, p)
2754 if q := s.P.(*Point); q != p {
2755 t.Errorf("i: have %p want %p", q, p)
2758 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2760 t.Errorf("Interface Method returned %d; want 250", i)
2769 func TestAnonymousFields(t *testing.T) {
2770 var field StructField
2774 if field, ok = type1.FieldByName("int"); !ok {
2775 t.Fatal("no field 'int'")
2777 if field.Index[0] != 1 {
2778 t.Error("field index should be 1; is", field.Index)
2832 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2854 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2873 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2887 var fieldTests = []FTest{
2888 {struct{}{}, "", nil, 0},
2889 {struct{}{}, "Foo", nil, 0},
2890 {S0{A: 'a'}, "A", []int{0}, 'a'},
2891 {S0{}, "D", nil, 0},
2892 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2893 {S1{B: 'b'}, "B", []int{0}, 'b'},
2894 {S1{}, "S0", []int{1}, 0},
2895 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2896 {S2{A: 'a'}, "A", []int{0}, 'a'},
2897 {S2{}, "S1", []int{1}, 0},
2898 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2899 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2900 {S2{}, "D", nil, 0},
2901 {S3{}, "S1", nil, 0},
2902 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2903 {S3{}, "B", nil, 0},
2904 {S3{D: 'd'}, "D", []int{2}, 0},
2905 {S3{E: 'e'}, "E", []int{3}, 'e'},
2906 {S4{A: 'a'}, "A", []int{1}, 'a'},
2907 {S4{}, "B", nil, 0},
2908 {S5{}, "X", nil, 0},
2909 {S5{}, "Y", []int{2, 0, 1}, 0},
2910 {S10{}, "X", nil, 0},
2911 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2912 {S14{}, "X", nil, 0},
2915 func TestFieldByIndex(t *testing.T) {
2916 for _, test := range fieldTests {
2918 f := s.FieldByIndex(test.index)
2920 if test.index != nil {
2921 if f.Name != test.name {
2922 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2925 t.Errorf("%s.%s found", s.Name(), f.Name)
2927 } else if len(test.index) > 0 {
2928 t.Errorf("%s.%s not found", s.Name(), test.name)
2931 if test.value != 0 {
2932 v := ValueOf(test.s).FieldByIndex(test.index)
2934 if x, ok := v.Interface().(int); ok {
2935 if x != test.value {
2936 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2939 t.Errorf("%s%v value not an int", s.Name(), test.index)
2942 t.Errorf("%s%v value not found", s.Name(), test.index)
2948 func TestFieldByName(t *testing.T) {
2949 for _, test := range fieldTests {
2951 f, found := s.FieldByName(test.name)
2953 if test.index != nil {
2954 // Verify field depth and index.
2955 if len(f.Index) != len(test.index) {
2956 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)
2958 for i, x := range f.Index {
2959 if x != test.index[i] {
2960 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2965 t.Errorf("%s.%s found", s.Name(), f.Name)
2967 } else if len(test.index) > 0 {
2968 t.Errorf("%s.%s not found", s.Name(), test.name)
2971 if test.value != 0 {
2972 v := ValueOf(test.s).FieldByName(test.name)
2974 if x, ok := v.Interface().(int); ok {
2975 if x != test.value {
2976 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2979 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2982 t.Errorf("%s.%s value not found", s.Name(), test.name)
2988 func TestImportPath(t *testing.T) {
2993 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2994 {TypeOf(int(0)), ""},
2995 {TypeOf(int8(0)), ""},
2996 {TypeOf(int16(0)), ""},
2997 {TypeOf(int32(0)), ""},
2998 {TypeOf(int64(0)), ""},
2999 {TypeOf(uint(0)), ""},
3000 {TypeOf(uint8(0)), ""},
3001 {TypeOf(uint16(0)), ""},
3002 {TypeOf(uint32(0)), ""},
3003 {TypeOf(uint64(0)), ""},
3004 {TypeOf(uintptr(0)), ""},
3005 {TypeOf(float32(0)), ""},
3006 {TypeOf(float64(0)), ""},
3007 {TypeOf(complex64(0)), ""},
3008 {TypeOf(complex128(0)), ""},
3009 {TypeOf(byte(0)), ""},
3010 {TypeOf(rune(0)), ""},
3011 {TypeOf([]byte(nil)), ""},
3012 {TypeOf([]rune(nil)), ""},
3013 {TypeOf(string("")), ""},
3014 {TypeOf((*interface{})(nil)).Elem(), ""},
3015 {TypeOf((*byte)(nil)), ""},
3016 {TypeOf((*rune)(nil)), ""},
3017 {TypeOf((*int64)(nil)), ""},
3018 {TypeOf(map[string]int{}), ""},
3019 {TypeOf((*error)(nil)).Elem(), ""},
3020 {TypeOf((*Point)(nil)), ""},
3021 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3023 for _, test := range tests {
3024 if path := test.t.PkgPath(); path != test.path {
3025 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3030 func TestFieldPkgPath(t *testing.T) {
3032 typ := TypeOf(struct {
3040 type pkgpathTest struct {
3047 checkPkgPath := func(name string, s []pkgpathTest) {
3048 for _, test := range s {
3049 f := typ.FieldByIndex(test.index)
3050 if got, want := f.PkgPath, test.pkgPath; got != want {
3051 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3053 if got, want := f.Anonymous, test.embedded; got != want {
3054 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3056 if got, want := f.IsExported(), test.exported; got != want {
3057 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3062 checkPkgPath("testStruct", []pkgpathTest{
3063 {[]int{0}, "", false, true}, // Exported
3064 {[]int{1}, "reflect_test", false, false}, // unexported
3065 {[]int{2}, "", true, true}, // OtherPkgFields
3066 {[]int{2, 0}, "", false, true}, // OtherExported
3067 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3068 {[]int{3}, "reflect_test", true, false}, // int
3069 {[]int{4}, "reflect_test", true, false}, // *x
3072 type localOtherPkgFields OtherPkgFields
3073 typ = TypeOf(localOtherPkgFields{})
3074 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3075 {[]int{0}, "", false, true}, // OtherExported
3076 {[]int{1}, "reflect", false, false}, // otherUnexported
3080 func TestMethodPkgPath(t *testing.T) {
3085 typ := TypeOf((*interface {
3098 {"x", "reflect_test", false},
3099 {"y", "reflect_test", false},
3102 for _, test := range tests {
3103 m, _ := typ.MethodByName(test.name)
3104 if got, want := m.PkgPath, test.pkgPath; got != want {
3105 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3107 if got, want := m.IsExported(), test.exported; got != want {
3108 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3113 func TestVariadicType(t *testing.T) {
3114 // Test example from Type documentation.
3115 var f func(x int, y ...float64)
3117 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3119 if sl.Kind() == Slice {
3120 if sl.Elem() == TypeOf(0.0) {
3128 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3129 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3130 for i := 0; i < typ.NumIn(); i++ {
3131 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3145 func (*inner) M() {}
3146 func (*outer) M() {}
3148 func TestNestedMethods(t *testing.T) {
3149 typ := TypeOf((*outer)(nil))
3150 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
3151 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3152 for i := 0; i < typ.NumMethod(); i++ {
3154 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3161 func (*unexp) f() (int32, int8) { return 7, 7 }
3162 func (*unexp) g() (int64, int8) { return 8, 8 }
3164 type unexpI interface {
3168 var unexpi unexpI = new(unexp)
3170 func TestUnexportedMethods(t *testing.T) {
3171 typ := TypeOf(unexpi)
3173 if got := typ.NumMethod(); got != 0 {
3174 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3178 type InnerInt struct {
3182 type OuterInt struct {
3187 func (i *InnerInt) M() int {
3191 func TestEmbeddedMethods(t *testing.T) {
3192 typ := TypeOf((*OuterInt)(nil))
3193 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
3194 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3195 for i := 0; i < typ.NumMethod(); i++ {
3197 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3202 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3203 t.Errorf("i.M() = %d, want 3", v)
3206 o := &OuterInt{1, InnerInt{2}}
3207 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3208 t.Errorf("i.M() = %d, want 2", v)
3212 if v := f(o); v != 2 {
3213 t.Errorf("f(o) = %d, want 2", v)
3217 type FuncDDD func(...interface{}) error
3219 func (f FuncDDD) M() {}
3221 func TestNumMethodOnDDD(t *testing.T) {
3222 rv := ValueOf((FuncDDD)(nil))
3223 if n := rv.NumMethod(); n != 1 {
3224 t.Fatalf("NumMethod()=%d, want 1", n)
3228 func TestPtrTo(t *testing.T) {
3229 // This block of code means that the ptrToThis field of the
3230 // reflect data for *unsafe.Pointer is non zero, see
3231 // https://golang.org/issue/19003
3232 var x unsafe.Pointer
3239 for i = 0; i < 100; i++ {
3242 for i = 0; i < 100; i++ {
3245 if typ != TypeOf(z) {
3246 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
3250 func TestPtrToGC(t *testing.T) {
3252 tt := TypeOf(T(nil))
3256 for i := 0; i < n; i++ {
3261 v.Elem().Set(ValueOf(p).Convert(pt))
3262 x = append(x, v.Interface())
3266 for i, xi := range x {
3267 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3268 if k != uintptr(i) {
3269 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3274 func BenchmarkPtrTo(b *testing.B) {
3275 // Construct a type with a zero ptrToThis.
3276 type T struct{ int }
3277 t := SliceOf(TypeOf(T{}))
3278 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3279 if !ptrToThis.IsValid() {
3280 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3282 if ptrToThis.Int() != 0 {
3283 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3287 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
3289 b.RunParallel(func(pb *testing.PB) {
3296 func TestAddr(t *testing.T) {
3308 t.Errorf("Addr.Elem.Set failed to set value")
3311 // Again but take address of the ValueOf value.
3312 // Exercises generation of PtrTypes not present in the binary.
3314 v = ValueOf(&q).Elem()
3323 t.Errorf("Addr.Elem.Set failed to set value")
3326 // Starting without pointer we should get changed value
3329 v = ValueOf(&qq).Elem()
3335 if p.X != 3 { // should be unchanged from last time
3336 t.Errorf("somehow value Set changed original p")
3338 p = v0.Interface().(struct {
3342 t.Errorf("Addr.Elem.Set valued to set value in top value")
3345 // Verify that taking the address of a type gives us a pointer
3346 // which we can convert back using the usual interface
3351 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3352 *(ps.(**bool)) = new(bool)
3354 t.Errorf("Addr.Interface direct assignment failed")
3358 func noAlloc(t *testing.T, n int, f func(int)) {
3359 if testing.Short() {
3360 t.Skip("skipping malloc count in short mode")
3362 if runtime.GOMAXPROCS(0) > 1 {
3363 t.Skip("skipping; GOMAXPROCS>1")
3366 allocs := testing.AllocsPerRun(n, func() {
3371 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3375 func TestAllocations(t *testing.T) {
3376 noAlloc(t, 100, func(j int) {
3380 // We can uncomment this when compiler escape analysis
3381 // is good enough to see that the integer assigned to i
3382 // does not escape and therefore need not be allocated.
3386 // if int(v.Int()) != 42+j {
3387 // panic("wrong int")
3390 i = func(j int) int { return j }
3392 if v.Interface().(func(int) int)(j) != j {
3393 panic("wrong result")
3398 func TestSmallNegativeInt(t *testing.T) {
3402 t.Errorf("int16(-1).Int() returned %v", v.Int())
3406 func TestIndex(t *testing.T) {
3407 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3408 v := ValueOf(xs).Index(3).Interface().(byte)
3410 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3412 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3413 v = ValueOf(xa).Index(2).Interface().(byte)
3415 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3418 v = ValueOf(s).Index(3).Interface().(byte)
3420 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3424 func TestSlice(t *testing.T) {
3425 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3426 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3428 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3431 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3433 if !DeepEqual(v[0:5], xs[3:]) {
3434 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3436 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3437 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3439 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3442 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3444 if !DeepEqual(v[0:6], xa[2:]) {
3445 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3448 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3450 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3453 rv := ValueOf(&xs).Elem()
3455 ptr2 := rv.Pointer()
3457 ptr3 := rv.Pointer()
3459 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
3463 func TestSlice3(t *testing.T) {
3464 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3465 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3467 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3470 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3472 if !DeepEqual(v[0:4], xs[3:7:7]) {
3473 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3475 rv := ValueOf(&xs).Elem()
3476 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3477 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3478 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3480 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3481 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3483 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3486 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3488 if !DeepEqual(v[0:4], xa[2:6:6]) {
3489 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3491 rv = ValueOf(&xa).Elem()
3492 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3493 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3494 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3497 rv = ValueOf(&s).Elem()
3498 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3500 rv = ValueOf(&xs).Elem()
3501 rv = rv.Slice3(3, 5, 7)
3502 ptr2 := rv.Pointer()
3503 rv = rv.Slice3(4, 4, 4)
3504 ptr3 := rv.Pointer()
3506 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
3510 func TestSetLenCap(t *testing.T) {
3511 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3512 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3514 vs := ValueOf(&xs).Elem()
3515 shouldPanic("SetLen", func() { vs.SetLen(10) })
3516 shouldPanic("SetCap", func() { vs.SetCap(10) })
3517 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3518 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3519 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3521 if len(xs) != 5 || cap(xs) != 8 {
3522 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3525 if len(xs) != 5 || cap(xs) != 6 {
3526 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3529 if len(xs) != 5 || cap(xs) != 5 {
3530 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3532 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3533 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3535 va := ValueOf(&xa).Elem()
3536 shouldPanic("SetLen", func() { va.SetLen(8) })
3537 shouldPanic("SetCap", func() { va.SetCap(8) })
3540 func TestVariadic(t *testing.T) {
3545 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3546 if b.String() != "hello, 42 world" {
3547 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3551 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3552 if b.String() != "hello, 42 world" {
3553 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3557 func TestFuncArg(t *testing.T) {
3558 f1 := func(i int, f func(int) int) int { return f(i) }
3559 f2 := func(i int) int { return i + 1 }
3560 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3561 if r[0].Int() != 101 {
3562 t.Errorf("function returned %d, want 101", r[0].Int())
3566 func TestStructArg(t *testing.T) {
3567 type padded struct {
3574 wantA = padded{"3", 4}
3577 f := func(a padded, b uint32) {
3580 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3581 if gotA != wantA || gotB != wantB {
3582 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3586 var tagGetTests = []struct {
3591 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3592 {`protobuf:"PB(1,2)"`, `foo`, ``},
3593 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3594 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3595 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3596 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3597 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3600 func TestTagGet(t *testing.T) {
3601 for _, tt := range tagGetTests {
3602 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3603 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3608 func TestBytes(t *testing.T) {
3611 y := ValueOf(x).Bytes()
3612 if !bytes.Equal(x, y) {
3613 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3616 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3620 func TestSetBytes(t *testing.T) {
3623 y := []byte{1, 2, 3, 4}
3624 ValueOf(&x).Elem().SetBytes(y)
3625 if !bytes.Equal(x, y) {
3626 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3629 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3633 type Private struct {
3639 func (p *Private) m() {
3642 type private struct {
3650 func (p *private) P() {
3653 type Public struct {
3659 func (p *Public) M() {
3662 func TestUnexported(t *testing.T) {
3667 isValid(v.Elem().Field(0))
3668 isValid(v.Elem().Field(1))
3669 isValid(v.Elem().Field(2))
3670 isValid(v.Elem().FieldByName("X"))
3671 isValid(v.Elem().FieldByName("Y"))
3672 isValid(v.Elem().FieldByName("Z"))
3673 isValid(v.Type().Method(0).Func)
3674 m, _ := v.Type().MethodByName("M")
3676 m, _ = v.Type().MethodByName("P")
3678 isNonNil(v.Elem().Field(0).Interface())
3679 isNonNil(v.Elem().Field(1).Interface())
3680 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3681 isNonNil(v.Elem().FieldByName("X").Interface())
3682 isNonNil(v.Elem().FieldByName("Y").Interface())
3683 isNonNil(v.Elem().FieldByName("Z").Interface())
3684 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3685 isNonNil(v.Type().Method(0).Func.Interface())
3686 m, _ = v.Type().MethodByName("P")
3687 isNonNil(m.Func.Interface())
3691 isValid(v.Elem().Field(0))
3692 isValid(v.Elem().Field(1))
3693 isValid(v.Elem().FieldByName("x"))
3694 isValid(v.Elem().FieldByName("y"))
3695 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3696 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3697 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3698 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3699 shouldPanic("Method", func() { v.Type().Method(0) })
3702 func TestSetPanic(t *testing.T) {
3703 ok := func(f func()) { f() }
3704 bad := func(f func()) { shouldPanic("Set", f) }
3705 clear := func(v Value) { v.Set(Zero(v.Type())) }
3733 bad(func() { clear(v.Field(0)) }) // .X
3734 bad(func() { clear(v.Field(1)) }) // .t1
3735 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3736 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3737 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3738 bad(func() { clear(v.Field(2)) }) // .T2
3739 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3740 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3741 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3742 bad(func() { clear(v.Field(3)) }) // .NamedT1
3743 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3744 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3745 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3746 bad(func() { clear(v.Field(4)) }) // .NamedT2
3747 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3748 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3749 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3750 bad(func() { clear(v.Field(5)) }) // .namedT1
3751 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3752 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3753 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3754 bad(func() { clear(v.Field(6)) }) // .namedT2
3755 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3756 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3757 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3760 v = ValueOf(&T{}).Elem()
3761 ok(func() { clear(v.Field(0)) }) // .X
3762 bad(func() { clear(v.Field(1)) }) // .t1
3763 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3764 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3765 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3766 ok(func() { clear(v.Field(2)) }) // .T2
3767 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3768 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3769 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3770 ok(func() { clear(v.Field(3)) }) // .NamedT1
3771 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3772 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3773 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3774 ok(func() { clear(v.Field(4)) }) // .NamedT2
3775 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3776 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3777 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3778 bad(func() { clear(v.Field(5)) }) // .namedT1
3779 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3780 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3781 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3782 bad(func() { clear(v.Field(6)) }) // .namedT2
3783 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3784 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3785 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3790 func (t timp) W() {}
3791 func (t timp) Y() {}
3792 func (t timp) w() {}
3793 func (t timp) y() {}
3795 func TestCallPanic(t *testing.T) {
3820 ok := func(f func()) { f() }
3821 badCall := func(f func()) { shouldPanic("Call", f) }
3822 badMethod := func(f func()) { shouldPanic("Method", f) }
3823 call := func(v Value) { v.Call(nil) }
3826 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3827 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3828 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3829 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3830 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3831 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3832 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3833 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3834 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3836 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3837 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3838 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3839 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3841 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3842 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3843 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3844 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3846 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3847 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3848 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3849 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3851 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3852 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3853 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3854 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3856 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3857 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3858 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3859 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3861 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3862 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3863 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3864 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3867 func shouldPanic(expect string, f func()) {
3871 panic("did not panic")
3875 switch r := r.(type) {
3881 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3883 if !strings.HasPrefix(s, "reflect") {
3884 panic(`panic string does not start with "reflect": ` + s)
3886 if !strings.Contains(s, expect) {
3887 panic(`panic string does not contain "` + expect + `": ` + s)
3894 func isNonNil(x interface{}) {
3896 panic("nil interface")
3900 func isValid(v Value) {
3906 func TestAlias(t *testing.T) {
3907 x := string("hello")
3908 v := ValueOf(&x).Elem()
3909 oldvalue := v.Interface()
3910 v.SetString("world")
3911 newvalue := v.Interface()
3913 if oldvalue != "hello" || newvalue != "world" {
3914 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3920 func EmptyInterfaceV(x interface{}) Value {
3921 return ValueOf(&x).Elem()
3924 func ReaderV(x io.Reader) Value {
3925 return ValueOf(&x).Elem()
3928 func ReadWriterV(x io.ReadWriter) Value {
3929 return ValueOf(&x).Elem()
3933 type MyStruct struct {
3936 type MyStruct1 struct {
3941 type MyStruct2 struct {
3946 type MyString string
3948 type MyBytesArrayPtr0 *[0]byte
3949 type MyBytesArrayPtr *[4]byte
3950 type MyBytesArray0 [0]byte
3951 type MyBytesArray [4]byte
3952 type MyRunes []int32
3956 type IntChan chan int
3957 type IntChanRecv <-chan int
3958 type IntChanSend chan<- int
3959 type BytesChan chan []byte
3960 type BytesChanRecv <-chan []byte
3961 type BytesChanSend chan<- []byte
3963 var convertTests = []struct {
3969 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3975 var numbers = []string{
3976 "int8", "uint8", "int16", "uint16",
3977 "int32", "uint32", "int64", "uint64",
3978 "int", "uint", "uintptr",
3979 "float32", "float64",
3983 // all pairs but in an unusual order,
3984 // to emit all the int8, uint8 cases
3985 // before n grows too big.
3987 for i, f := range numbers {
3988 for _, g := range numbers[i:] {
3989 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3992 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3999 {V(int8(1)), V(int8(1))},
4000 {V(int8(2)), V(uint8(2))},
4001 {V(uint8(3)), V(int8(3))},
4002 {V(int8(4)), V(int16(4))},
4003 {V(int16(5)), V(int8(5))},
4004 {V(int8(6)), V(uint16(6))},
4005 {V(uint16(7)), V(int8(7))},
4006 {V(int8(8)), V(int32(8))},
4007 {V(int32(9)), V(int8(9))},
4008 {V(int8(10)), V(uint32(10))},
4009 {V(uint32(11)), V(int8(11))},
4010 {V(int8(12)), V(int64(12))},
4011 {V(int64(13)), V(int8(13))},
4012 {V(int8(14)), V(uint64(14))},
4013 {V(uint64(15)), V(int8(15))},
4014 {V(int8(16)), V(int(16))},
4015 {V(int(17)), V(int8(17))},
4016 {V(int8(18)), V(uint(18))},
4017 {V(uint(19)), V(int8(19))},
4018 {V(int8(20)), V(uintptr(20))},
4019 {V(uintptr(21)), V(int8(21))},
4020 {V(int8(22)), V(float32(22))},
4021 {V(float32(23)), V(int8(23))},
4022 {V(int8(24)), V(float64(24))},
4023 {V(float64(25)), V(int8(25))},
4024 {V(uint8(26)), V(uint8(26))},
4025 {V(uint8(27)), V(int16(27))},
4026 {V(int16(28)), V(uint8(28))},
4027 {V(uint8(29)), V(uint16(29))},
4028 {V(uint16(30)), V(uint8(30))},
4029 {V(uint8(31)), V(int32(31))},
4030 {V(int32(32)), V(uint8(32))},
4031 {V(uint8(33)), V(uint32(33))},
4032 {V(uint32(34)), V(uint8(34))},
4033 {V(uint8(35)), V(int64(35))},
4034 {V(int64(36)), V(uint8(36))},
4035 {V(uint8(37)), V(uint64(37))},
4036 {V(uint64(38)), V(uint8(38))},
4037 {V(uint8(39)), V(int(39))},
4038 {V(int(40)), V(uint8(40))},
4039 {V(uint8(41)), V(uint(41))},
4040 {V(uint(42)), V(uint8(42))},
4041 {V(uint8(43)), V(uintptr(43))},
4042 {V(uintptr(44)), V(uint8(44))},
4043 {V(uint8(45)), V(float32(45))},
4044 {V(float32(46)), V(uint8(46))},
4045 {V(uint8(47)), V(float64(47))},
4046 {V(float64(48)), V(uint8(48))},
4047 {V(int16(49)), V(int16(49))},
4048 {V(int16(50)), V(uint16(50))},
4049 {V(uint16(51)), V(int16(51))},
4050 {V(int16(52)), V(int32(52))},
4051 {V(int32(53)), V(int16(53))},
4052 {V(int16(54)), V(uint32(54))},
4053 {V(uint32(55)), V(int16(55))},
4054 {V(int16(56)), V(int64(56))},
4055 {V(int64(57)), V(int16(57))},
4056 {V(int16(58)), V(uint64(58))},
4057 {V(uint64(59)), V(int16(59))},
4058 {V(int16(60)), V(int(60))},
4059 {V(int(61)), V(int16(61))},
4060 {V(int16(62)), V(uint(62))},
4061 {V(uint(63)), V(int16(63))},
4062 {V(int16(64)), V(uintptr(64))},
4063 {V(uintptr(65)), V(int16(65))},
4064 {V(int16(66)), V(float32(66))},
4065 {V(float32(67)), V(int16(67))},
4066 {V(int16(68)), V(float64(68))},
4067 {V(float64(69)), V(int16(69))},
4068 {V(uint16(70)), V(uint16(70))},
4069 {V(uint16(71)), V(int32(71))},
4070 {V(int32(72)), V(uint16(72))},
4071 {V(uint16(73)), V(uint32(73))},
4072 {V(uint32(74)), V(uint16(74))},
4073 {V(uint16(75)), V(int64(75))},
4074 {V(int64(76)), V(uint16(76))},
4075 {V(uint16(77)), V(uint64(77))},
4076 {V(uint64(78)), V(uint16(78))},
4077 {V(uint16(79)), V(int(79))},
4078 {V(int(80)), V(uint16(80))},
4079 {V(uint16(81)), V(uint(81))},
4080 {V(uint(82)), V(uint16(82))},
4081 {V(uint16(83)), V(uintptr(83))},
4082 {V(uintptr(84)), V(uint16(84))},
4083 {V(uint16(85)), V(float32(85))},
4084 {V(float32(86)), V(uint16(86))},
4085 {V(uint16(87)), V(float64(87))},
4086 {V(float64(88)), V(uint16(88))},
4087 {V(int32(89)), V(int32(89))},
4088 {V(int32(90)), V(uint32(90))},
4089 {V(uint32(91)), V(int32(91))},
4090 {V(int32(92)), V(int64(92))},
4091 {V(int64(93)), V(int32(93))},
4092 {V(int32(94)), V(uint64(94))},
4093 {V(uint64(95)), V(int32(95))},
4094 {V(int32(96)), V(int(96))},
4095 {V(int(97)), V(int32(97))},
4096 {V(int32(98)), V(uint(98))},
4097 {V(uint(99)), V(int32(99))},
4098 {V(int32(100)), V(uintptr(100))},
4099 {V(uintptr(101)), V(int32(101))},
4100 {V(int32(102)), V(float32(102))},
4101 {V(float32(103)), V(int32(103))},
4102 {V(int32(104)), V(float64(104))},
4103 {V(float64(105)), V(int32(105))},
4104 {V(uint32(106)), V(uint32(106))},
4105 {V(uint32(107)), V(int64(107))},
4106 {V(int64(108)), V(uint32(108))},
4107 {V(uint32(109)), V(uint64(109))},
4108 {V(uint64(110)), V(uint32(110))},
4109 {V(uint32(111)), V(int(111))},
4110 {V(int(112)), V(uint32(112))},
4111 {V(uint32(113)), V(uint(113))},
4112 {V(uint(114)), V(uint32(114))},
4113 {V(uint32(115)), V(uintptr(115))},
4114 {V(uintptr(116)), V(uint32(116))},
4115 {V(uint32(117)), V(float32(117))},
4116 {V(float32(118)), V(uint32(118))},
4117 {V(uint32(119)), V(float64(119))},
4118 {V(float64(120)), V(uint32(120))},
4119 {V(int64(121)), V(int64(121))},
4120 {V(int64(122)), V(uint64(122))},
4121 {V(uint64(123)), V(int64(123))},
4122 {V(int64(124)), V(int(124))},
4123 {V(int(125)), V(int64(125))},
4124 {V(int64(126)), V(uint(126))},
4125 {V(uint(127)), V(int64(127))},
4126 {V(int64(128)), V(uintptr(128))},
4127 {V(uintptr(129)), V(int64(129))},
4128 {V(int64(130)), V(float32(130))},
4129 {V(float32(131)), V(int64(131))},
4130 {V(int64(132)), V(float64(132))},
4131 {V(float64(133)), V(int64(133))},
4132 {V(uint64(134)), V(uint64(134))},
4133 {V(uint64(135)), V(int(135))},
4134 {V(int(136)), V(uint64(136))},
4135 {V(uint64(137)), V(uint(137))},
4136 {V(uint(138)), V(uint64(138))},
4137 {V(uint64(139)), V(uintptr(139))},
4138 {V(uintptr(140)), V(uint64(140))},
4139 {V(uint64(141)), V(float32(141))},
4140 {V(float32(142)), V(uint64(142))},
4141 {V(uint64(143)), V(float64(143))},
4142 {V(float64(144)), V(uint64(144))},
4143 {V(int(145)), V(int(145))},
4144 {V(int(146)), V(uint(146))},
4145 {V(uint(147)), V(int(147))},
4146 {V(int(148)), V(uintptr(148))},
4147 {V(uintptr(149)), V(int(149))},
4148 {V(int(150)), V(float32(150))},
4149 {V(float32(151)), V(int(151))},
4150 {V(int(152)), V(float64(152))},
4151 {V(float64(153)), V(int(153))},
4152 {V(uint(154)), V(uint(154))},
4153 {V(uint(155)), V(uintptr(155))},
4154 {V(uintptr(156)), V(uint(156))},
4155 {V(uint(157)), V(float32(157))},
4156 {V(float32(158)), V(uint(158))},
4157 {V(uint(159)), V(float64(159))},
4158 {V(float64(160)), V(uint(160))},
4159 {V(uintptr(161)), V(uintptr(161))},
4160 {V(uintptr(162)), V(float32(162))},
4161 {V(float32(163)), V(uintptr(163))},
4162 {V(uintptr(164)), V(float64(164))},
4163 {V(float64(165)), V(uintptr(165))},
4164 {V(float32(166)), V(float32(166))},
4165 {V(float32(167)), V(float64(167))},
4166 {V(float64(168)), V(float32(168))},
4167 {V(float64(169)), V(float64(169))},
4170 {V(float64(1.5)), V(int(1))},
4173 {V(complex64(1i)), V(complex64(1i))},
4174 {V(complex64(2i)), V(complex128(2i))},
4175 {V(complex128(3i)), V(complex64(3i))},
4176 {V(complex128(4i)), V(complex128(4i))},
4179 {V(string("hello")), V(string("hello"))},
4180 {V(string("bytes1")), V([]byte("bytes1"))},
4181 {V([]byte("bytes2")), V(string("bytes2"))},
4182 {V([]byte("bytes3")), V([]byte("bytes3"))},
4183 {V(string("runes♝")), V([]rune("runes♝"))},
4184 {V([]rune("runes♕")), V(string("runes♕"))},
4185 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4186 {V(int('a')), V(string("a"))},
4187 {V(int8('a')), V(string("a"))},
4188 {V(int16('a')), V(string("a"))},
4189 {V(int32('a')), V(string("a"))},
4190 {V(int64('a')), V(string("a"))},
4191 {V(uint('a')), V(string("a"))},
4192 {V(uint8('a')), V(string("a"))},
4193 {V(uint16('a')), V(string("a"))},
4194 {V(uint32('a')), V(string("a"))},
4195 {V(uint64('a')), V(string("a"))},
4196 {V(uintptr('a')), V(string("a"))},
4197 {V(int(-1)), V(string("\uFFFD"))},
4198 {V(int8(-2)), V(string("\uFFFD"))},
4199 {V(int16(-3)), V(string("\uFFFD"))},
4200 {V(int32(-4)), V(string("\uFFFD"))},
4201 {V(int64(-5)), V(string("\uFFFD"))},
4202 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4203 {V(int64(1 << 32)), V(string("\uFFFD"))},
4204 {V(uint(0x110001)), V(string("\uFFFD"))},
4205 {V(uint32(0x110002)), V(string("\uFFFD"))},
4206 {V(uint64(0x110003)), V(string("\uFFFD"))},
4207 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4208 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4211 {V(MyString("hello")), V(string("hello"))},
4212 {V(string("hello")), V(MyString("hello"))},
4213 {V(string("hello")), V(string("hello"))},
4214 {V(MyString("hello")), V(MyString("hello"))},
4215 {V(MyString("bytes1")), V([]byte("bytes1"))},
4216 {V([]byte("bytes2")), V(MyString("bytes2"))},
4217 {V([]byte("bytes3")), V([]byte("bytes3"))},
4218 {V(MyString("runes♝")), V([]rune("runes♝"))},
4219 {V([]rune("runes♕")), V(MyString("runes♕"))},
4220 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4221 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4222 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4223 {V(int('a')), V(MyString("a"))},
4224 {V(int8('a')), V(MyString("a"))},
4225 {V(int16('a')), V(MyString("a"))},
4226 {V(int32('a')), V(MyString("a"))},
4227 {V(int64('a')), V(MyString("a"))},
4228 {V(uint('a')), V(MyString("a"))},
4229 {V(uint8('a')), V(MyString("a"))},
4230 {V(uint16('a')), V(MyString("a"))},
4231 {V(uint32('a')), V(MyString("a"))},
4232 {V(uint64('a')), V(MyString("a"))},
4233 {V(uintptr('a')), V(MyString("a"))},
4234 {V(int(-1)), V(MyString("\uFFFD"))},
4235 {V(int8(-2)), V(MyString("\uFFFD"))},
4236 {V(int16(-3)), V(MyString("\uFFFD"))},
4237 {V(int32(-4)), V(MyString("\uFFFD"))},
4238 {V(int64(-5)), V(MyString("\uFFFD"))},
4239 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4240 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4241 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4242 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4245 {V(string("bytes1")), V(MyBytes("bytes1"))},
4246 {V(MyBytes("bytes2")), V(string("bytes2"))},
4247 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4248 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4249 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4252 {V(string("runes♝")), V(MyRunes("runes♝"))},
4253 {V(MyRunes("runes♕")), V(string("runes♕"))},
4254 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4255 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4256 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4258 // slice to array pointer
4259 {V([]byte(nil)), V((*[0]byte)(nil))},
4260 {V([]byte{}), V(new([0]byte))},
4261 {V([]byte{7}), V(&[1]byte{7})},
4262 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4263 {V(MyBytes([]byte{})), V(new([0]byte))},
4264 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4265 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4266 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4267 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4268 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4269 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4271 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4272 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4273 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4274 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4275 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4276 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4277 {V(new([0]byte)), V(new(MyBytesArray0))},
4278 {V(new(MyBytesArray0)), V(new([0]byte))},
4279 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4280 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4282 // named types and equal underlying types
4283 {V(new(int)), V(new(integer))},
4284 {V(new(integer)), V(new(int))},
4285 {V(Empty{}), V(struct{}{})},
4286 {V(new(Empty)), V(new(struct{}))},
4287 {V(struct{}{}), V(Empty{})},
4288 {V(new(struct{})), V(new(Empty))},
4289 {V(Empty{}), V(Empty{})},
4290 {V(MyBytes{}), V([]byte{})},
4291 {V([]byte{}), V(MyBytes{})},
4292 {V((func())(nil)), V(MyFunc(nil))},
4293 {V((MyFunc)(nil)), V((func())(nil))},
4295 // structs with different tags
4308 {V(MyStruct{}), V(struct {
4314 }{}), V(MyStruct{})},
4316 {V(MyStruct{}), V(struct {
4322 }{}), V(MyStruct{})},
4324 {V(MyStruct1{}), V(MyStruct2{})},
4325 {V(MyStruct2{}), V(MyStruct1{})},
4327 // can convert *byte and *MyByte
4328 {V((*byte)(nil)), V((*MyByte)(nil))},
4329 {V((*MyByte)(nil)), V((*byte)(nil))},
4331 // cannot convert mismatched array sizes
4332 {V([2]byte{}), V([2]byte{})},
4333 {V([3]byte{}), V([3]byte{})},
4335 // cannot convert other instances
4336 {V((**byte)(nil)), V((**byte)(nil))},
4337 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4338 {V((chan byte)(nil)), V((chan byte)(nil))},
4339 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4340 {V(([]byte)(nil)), V(([]byte)(nil))},
4341 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4342 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4343 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4344 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4345 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4346 {V([2]byte{}), V([2]byte{})},
4347 {V([2]MyByte{}), V([2]MyByte{})},
4350 {V((***int)(nil)), V((***int)(nil))},
4351 {V((***byte)(nil)), V((***byte)(nil))},
4352 {V((***int32)(nil)), V((***int32)(nil))},
4353 {V((***int64)(nil)), V((***int64)(nil))},
4354 {V((chan byte)(nil)), V((chan byte)(nil))},
4355 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4356 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4357 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4358 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4359 {V([]uint(nil)), V([]uint(nil))},
4360 {V([]int(nil)), V([]int(nil))},
4361 {V(new(interface{})), V(new(interface{}))},
4362 {V(new(io.Reader)), V(new(io.Reader))},
4363 {V(new(io.Writer)), V(new(io.Writer))},
4366 {V(IntChan(nil)), V((chan<- int)(nil))},
4367 {V(IntChan(nil)), V((<-chan int)(nil))},
4368 {V((chan int)(nil)), V(IntChanRecv(nil))},
4369 {V((chan int)(nil)), V(IntChanSend(nil))},
4370 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4371 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4372 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4373 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4374 {V(IntChan(nil)), V((chan int)(nil))},
4375 {V((chan int)(nil)), V(IntChan(nil))},
4376 {V((chan int)(nil)), V((<-chan int)(nil))},
4377 {V((chan int)(nil)), V((chan<- int)(nil))},
4378 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4379 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4380 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4381 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4382 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4383 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4384 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4385 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4386 {V(BytesChan(nil)), V((chan []byte)(nil))},
4387 {V((chan []byte)(nil)), V(BytesChan(nil))},
4388 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4389 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4391 // cannot convert other instances (channels)
4392 {V(IntChan(nil)), V(IntChan(nil))},
4393 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4394 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4395 {V(BytesChan(nil)), V(BytesChan(nil))},
4396 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4397 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4400 {V(int(1)), EmptyInterfaceV(int(1))},
4401 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4402 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4403 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4404 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4407 func TestConvert(t *testing.T) {
4408 canConvert := map[[2]Type]bool{}
4409 all := map[Type]bool{}
4411 for _, tt := range convertTests {
4413 if !t1.ConvertibleTo(t1) {
4414 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4419 if !t1.ConvertibleTo(t2) {
4420 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4426 canConvert[[2]Type{t1, t2}] = true
4428 // vout1 represents the in value converted to the in type.
4430 if !v1.CanConvert(t1) {
4431 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4433 vout1 := v1.Convert(t1)
4434 out1 := vout1.Interface()
4435 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4436 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4439 // vout2 represents the in value converted to the out type.
4440 if !v1.CanConvert(t2) {
4441 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4443 vout2 := v1.Convert(t2)
4444 out2 := vout2.Interface()
4445 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4446 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4448 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4449 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4452 // vout3 represents a new value of the out type, set to vout2. This makes
4453 // sure the converted value vout2 is really usable as a regular value.
4454 vout3 := New(t2).Elem()
4456 out3 := vout3.Interface()
4457 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4458 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4462 t.Errorf("table entry %v is RO, should not be", v1)
4465 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4468 t.Errorf("conversion output %v is RO, should not be", vout2)
4471 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4473 if !IsRO(MakeRO(v1).Convert(t1)) {
4474 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4476 if !IsRO(MakeRO(v1).Convert(t2)) {
4477 t.Errorf("RO conversion output %v is not RO, should be", v1)
4481 // Assume that of all the types we saw during the tests,
4482 // if there wasn't an explicit entry for a conversion between
4483 // a pair of types, then it's not to be allowed. This checks for
4484 // things like 'int64' converting to '*int'.
4485 for t1 := range all {
4486 for t2 := range all {
4487 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4488 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4489 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4495 func TestConvertPanic(t *testing.T) {
4496 s := make([]byte, 4)
4500 if !v.Type().ConvertibleTo(pt) {
4501 t.Errorf("[]byte should be convertible to *[8]byte")
4503 if v.CanConvert(pt) {
4504 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4506 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4511 var gFloat32 float32
4513 const snan uint32 = 0x7f800001
4515 func TestConvertNaNs(t *testing.T) {
4516 // Test to see if a store followed by a load of a signaling NaN
4517 // maintains the signaling bit. (This used to fail on the 387 port.)
4518 gFloat32 = math.Float32frombits(snan)
4519 runtime.Gosched() // make sure we don't optimize the store/load away
4520 if got := math.Float32bits(gFloat32); got != snan {
4521 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4523 // Test reflect's conversion between float32s. See issue 36400.
4524 type myFloat32 float32
4525 x := V(myFloat32(math.Float32frombits(snan)))
4526 y := x.Convert(TypeOf(float32(0)))
4527 z := y.Interface().(float32)
4528 if got := math.Float32bits(z); got != snan {
4529 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4533 type ComparableStruct struct {
4537 type NonComparableStruct struct {
4542 var comparableTests = []struct {
4547 {TypeOf("hello"), true},
4548 {TypeOf(new(byte)), true},
4549 {TypeOf((func())(nil)), false},
4550 {TypeOf([]byte{}), false},
4551 {TypeOf(map[string]int{}), false},
4552 {TypeOf(make(chan int)), true},
4553 {TypeOf(1.5), true},
4554 {TypeOf(false), true},
4556 {TypeOf(ComparableStruct{}), true},
4557 {TypeOf(NonComparableStruct{}), false},
4558 {TypeOf([10]map[string]int{}), false},
4559 {TypeOf([10]string{}), true},
4560 {TypeOf(new(interface{})).Elem(), true},
4563 func TestComparable(t *testing.T) {
4564 for _, tt := range comparableTests {
4565 if ok := tt.typ.Comparable(); ok != tt.ok {
4566 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4571 func TestOverflow(t *testing.T) {
4572 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4573 t.Errorf("%v wrongly overflows float64", 1e300)
4576 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4577 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4578 t.Errorf("%v wrongly overflows float32", maxFloat32)
4580 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4581 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4582 t.Errorf("%v should overflow float32", ovfFloat32)
4584 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4585 t.Errorf("%v should overflow float32", -ovfFloat32)
4588 maxInt32 := int64(0x7fffffff)
4589 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4590 t.Errorf("%v wrongly overflows int32", maxInt32)
4592 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4593 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4595 ovfInt32 := int64(1 << 31)
4596 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4597 t.Errorf("%v should overflow int32", ovfInt32)
4600 maxUint32 := uint64(0xffffffff)
4601 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4602 t.Errorf("%v wrongly overflows uint32", maxUint32)
4604 ovfUint32 := uint64(1 << 32)
4605 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4606 t.Errorf("%v should overflow uint32", ovfUint32)
4610 func checkSameType(t *testing.T, x Type, y interface{}) {
4611 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4612 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4616 func TestArrayOf(t *testing.T) {
4617 // check construction and use of type not in binary
4620 value func(i int) interface{}
4626 value: func(i int) interface{} { type Tint int; return Tint(i) },
4632 value: func(i int) interface{} { type Tint int; return Tint(i) },
4634 want: "[0 1 2 3 4 5 6 7 8 9]",
4638 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
4640 want: "[0 1 2 3 4 5 6 7 8 9]",
4644 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
4646 want: "[0 1 2 3 4 5 6 7 8 9]",
4650 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
4652 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4656 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
4658 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4662 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
4664 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4668 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4670 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4674 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4676 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4680 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4682 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4686 value: func(i int) interface{} {
4687 type TstructUV struct {
4691 return TstructUV{i, float64(i)}
4694 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4698 for _, table := range tests {
4699 at := ArrayOf(table.n, TypeOf(table.value(0)))
4701 vok := New(at).Elem()
4702 vnot := New(at).Elem()
4703 for i := 0; i < v.Len(); i++ {
4704 v.Index(i).Set(ValueOf(table.value(i)))
4705 vok.Index(i).Set(ValueOf(table.value(i)))
4710 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4712 s := fmt.Sprint(v.Interface())
4713 if s != table.want {
4714 t.Errorf("constructed array = %s, want %s", s, table.want)
4717 if table.comparable != at.Comparable() {
4718 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4720 if table.comparable {
4722 if DeepEqual(vnot.Interface(), v.Interface()) {
4724 "arrays (%#v) compare ok (but should not)",
4729 if !DeepEqual(vok.Interface(), v.Interface()) {
4731 "arrays (%#v) compare NOT-ok (but should)",
4738 // check that type already in binary is found
4740 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4743 func TestArrayOfGC(t *testing.T) {
4745 tt := TypeOf(T(nil))
4748 for i := 0; i < n; i++ {
4749 v := New(ArrayOf(n, tt)).Elem()
4750 for j := 0; j < v.Len(); j++ {
4752 *p = uintptr(i*n + j)
4753 v.Index(j).Set(ValueOf(p).Convert(tt))
4755 x = append(x, v.Interface())
4759 for i, xi := range x {
4761 for j := 0; j < v.Len(); j++ {
4762 k := v.Index(j).Elem().Interface()
4763 if k != uintptr(i*n+j) {
4764 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4770 func TestArrayOfAlg(t *testing.T) {
4771 at := ArrayOf(6, TypeOf(byte(0)))
4772 v1 := New(at).Elem()
4773 v2 := New(at).Elem()
4774 if v1.Interface() != v1.Interface() {
4775 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4777 v1.Index(5).Set(ValueOf(byte(1)))
4778 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4779 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4782 at = ArrayOf(6, TypeOf([]int(nil)))
4784 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4787 func TestArrayOfGenericAlg(t *testing.T) {
4788 at1 := ArrayOf(5, TypeOf(string("")))
4789 at := ArrayOf(6, at1)
4790 v1 := New(at).Elem()
4791 v2 := New(at).Elem()
4792 if v1.Interface() != v1.Interface() {
4793 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4796 v1.Index(0).Index(0).Set(ValueOf("abc"))
4797 v2.Index(0).Index(0).Set(ValueOf("efg"))
4798 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4799 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4802 v1.Index(0).Index(0).Set(ValueOf("abc"))
4803 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4804 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4805 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4809 m := MakeMap(MapOf(at, TypeOf(int(0))))
4810 m.SetMapIndex(v1, ValueOf(1))
4811 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4812 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4816 func TestArrayOfDirectIface(t *testing.T) {
4819 i1 := Zero(TypeOf(T{})).Interface()
4820 v1 := ValueOf(&i1).Elem()
4821 p1 := v1.InterfaceData()[1]
4823 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4824 v2 := ValueOf(&i2).Elem()
4825 p2 := v2.InterfaceData()[1]
4828 t.Errorf("got p1=%v. want=%v", p1, nil)
4832 t.Errorf("got p2=%v. want=%v", p2, nil)
4837 i1 := Zero(TypeOf(T{})).Interface()
4838 v1 := ValueOf(&i1).Elem()
4839 p1 := v1.InterfaceData()[1]
4841 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4842 v2 := ValueOf(&i2).Elem()
4843 p2 := v2.InterfaceData()[1]
4846 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4850 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4855 // Ensure passing in negative lengths panics.
4856 // See https://golang.org/issue/43603
4857 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4858 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4859 ArrayOf(-1, TypeOf(byte(0)))
4863 func TestSliceOf(t *testing.T) {
4864 // check construction and use of type not in binary
4866 st := SliceOf(TypeOf(T(1)))
4867 if got, want := st.String(), "[]reflect_test.T"; got != want {
4868 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4870 v := MakeSlice(st, 10, 10)
4872 for i := 0; i < v.Len(); i++ {
4873 v.Index(i).Set(ValueOf(T(i)))
4876 s := fmt.Sprint(v.Interface())
4877 want := "[0 1 2 3 4 5 6 7 8 9]"
4879 t.Errorf("constructed slice = %s, want %s", s, want)
4882 // check that type already in binary is found
4884 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4887 func TestSliceOverflow(t *testing.T) {
4888 // check that MakeSlice panics when size of slice overflows uint
4891 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4893 t.Fatal("slice size does not overflow")
4896 st := SliceOf(TypeOf(x))
4900 t.Fatal("slice overflow does not panic")
4903 MakeSlice(st, int(l), int(l))
4906 func TestSliceOfGC(t *testing.T) {
4908 tt := TypeOf(T(nil))
4912 for i := 0; i < n; i++ {
4913 v := MakeSlice(st, n, n)
4914 for j := 0; j < v.Len(); j++ {
4916 *p = uintptr(i*n + j)
4917 v.Index(j).Set(ValueOf(p).Convert(tt))
4919 x = append(x, v.Interface())
4923 for i, xi := range x {
4925 for j := 0; j < v.Len(); j++ {
4926 k := v.Index(j).Elem().Interface()
4927 if k != uintptr(i*n+j) {
4928 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4934 func TestStructOfFieldName(t *testing.T) {
4935 // invalid field name "1nvalid"
4936 shouldPanic("has invalid name", func() {
4937 StructOf([]StructField{
4938 {Name: "Valid", Type: TypeOf("")},
4939 {Name: "1nvalid", Type: TypeOf("")},
4943 // invalid field name "+"
4944 shouldPanic("has invalid name", func() {
4945 StructOf([]StructField{
4946 {Name: "Val1d", Type: TypeOf("")},
4947 {Name: "+", Type: TypeOf("")},
4952 shouldPanic("has no name", func() {
4953 StructOf([]StructField{
4954 {Name: "", Type: TypeOf("")},
4958 // verify creation of a struct with valid struct fields
4959 validFields := []StructField{
4974 validStruct := StructOf(validFields)
4976 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
4977 if got, want := validStruct.String(), structStr; got != want {
4978 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
4982 func TestStructOf(t *testing.T) {
4983 // check construction and use of type not in binary
4984 fields := []StructField{
4993 Type: TypeOf(byte(0)),
4997 Type: TypeOf(uint64(0)),
5001 Type: TypeOf([3]uint16{}),
5005 st := StructOf(fields)
5008 v.FieldByName("X").Set(ValueOf(byte(2)))
5009 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5012 s := fmt.Sprint(v.Interface())
5013 want := `{ 1 0 [0 0 0]}`
5015 t.Errorf("constructed struct = %s, want %s", s, want)
5017 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5018 if got, want := st.String(), stStr; got != want {
5019 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5022 // check the size, alignment and field offsets
5023 stt := TypeOf(struct {
5029 if st.Size() != stt.Size() {
5030 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5032 if st.Align() != stt.Align() {
5033 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5035 if st.FieldAlign() != stt.FieldAlign() {
5036 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5038 for i := 0; i < st.NumField(); i++ {
5039 o1 := st.Field(i).Offset
5040 o2 := stt.Field(i).Offset
5042 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5046 // Check size and alignment with a trailing zero-sized field.
5047 st = StructOf([]StructField{
5050 Type: TypeOf(byte(0)),
5054 Type: TypeOf([0]*byte{}),
5057 stt = TypeOf(struct {
5061 if st.Size() != stt.Size() {
5062 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5064 if st.Align() != stt.Align() {
5065 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5067 if st.FieldAlign() != stt.FieldAlign() {
5068 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5070 for i := 0; i < st.NumField(); i++ {
5071 o1 := st.Field(i).Offset
5072 o2 := stt.Field(i).Offset
5074 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5078 // check duplicate names
5079 shouldPanic("duplicate field", func() {
5080 StructOf([]StructField{
5081 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5082 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5085 shouldPanic("has no name", func() {
5086 StructOf([]StructField{
5088 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5091 shouldPanic("has no name", func() {
5092 StructOf([]StructField{
5097 // check that type already in binary is found
5098 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5100 // gccgo used to fail this test.
5101 type structFieldType interface{}
5103 StructOf([]StructField{
5106 Type: TypeOf((*structFieldType)(nil)).Elem(),
5109 struct{ F structFieldType }{})
5112 func TestStructOfExportRules(t *testing.T) {
5118 testPanic := func(i int, mustPanic bool, f func()) {
5121 if err == nil && mustPanic {
5122 t.Errorf("test-%d did not panic", i)
5124 if err != nil && !mustPanic {
5125 t.Errorf("test-%d panicked: %v\n", i, err)
5137 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5141 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5145 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5149 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5153 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5157 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5161 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5165 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5169 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5173 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5177 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5180 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5183 field: StructField{Name: "S", Type: TypeOf(S1{})},
5187 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5191 field: StructField{Name: "S", Type: TypeOf(s2{})},
5195 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5199 field: StructField{Name: "s", Type: TypeOf(S1{})},
5203 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5207 field: StructField{Name: "s", Type: TypeOf(s2{})},
5211 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5215 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5218 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5221 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5224 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5227 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5231 field: StructField{Name: "", Type: TypeOf(φType{})},
5235 field: StructField{Name: "Φ", Type: TypeOf(0)},
5239 field: StructField{Name: "φ", Type: TypeOf(0)},
5244 for i, test := range tests {
5245 testPanic(i, test.mustPanic, func() {
5246 typ := StructOf([]StructField{test.field})
5248 t.Errorf("test-%d: error creating struct type", i)
5251 field := typ.Field(0)
5254 panic("field.Name must not be empty")
5256 exported := token.IsExported(n)
5257 if exported != test.exported {
5258 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5260 if field.PkgPath != test.field.PkgPath {
5261 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5267 func TestStructOfGC(t *testing.T) {
5269 tt := TypeOf(T(nil))
5270 fields := []StructField{
5271 {Name: "X", Type: tt},
5272 {Name: "Y", Type: tt},
5274 st := StructOf(fields)
5278 for i := 0; i < n; i++ {
5280 for j := 0; j < v.NumField(); j++ {
5282 *p = uintptr(i*n + j)
5283 v.Field(j).Set(ValueOf(p).Convert(tt))
5285 x = append(x, v.Interface())
5289 for i, xi := range x {
5291 for j := 0; j < v.NumField(); j++ {
5292 k := v.Field(j).Elem().Interface()
5293 if k != uintptr(i*n+j) {
5294 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5300 func TestStructOfAlg(t *testing.T) {
5301 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5302 v1 := New(st).Elem()
5303 v2 := New(st).Elem()
5304 if !DeepEqual(v1.Interface(), v1.Interface()) {
5305 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5307 v1.FieldByName("X").Set(ValueOf(int(1)))
5308 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5309 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5312 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5314 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5317 func TestStructOfGenericAlg(t *testing.T) {
5318 st1 := StructOf([]StructField{
5319 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5320 {Name: "Y", Type: TypeOf(string(""))},
5322 st := StructOf([]StructField{
5323 {Name: "S0", Type: st1},
5324 {Name: "S1", Type: st1},
5342 {Name: "XX", Type: TypeOf([0]int{})},
5343 {Name: "YY", Type: TypeOf("")},
5351 {Name: "XX", Type: TypeOf([0]int{})},
5352 {Name: "YY", Type: TypeOf("")},
5353 {Name: "ZZ", Type: TypeOf([2]int{})},
5361 {Name: "XX", Type: TypeOf([1]int{})},
5362 {Name: "YY", Type: TypeOf("")},
5370 {Name: "XX", Type: TypeOf([1]int{})},
5371 {Name: "YY", Type: TypeOf("")},
5372 {Name: "ZZ", Type: TypeOf([1]int{})},
5380 {Name: "XX", Type: TypeOf([2]int{})},
5381 {Name: "YY", Type: TypeOf("")},
5382 {Name: "ZZ", Type: TypeOf([2]int{})},
5390 {Name: "XX", Type: TypeOf(int64(0))},
5391 {Name: "YY", Type: TypeOf(byte(0))},
5392 {Name: "ZZ", Type: TypeOf("")},
5400 {Name: "XX", Type: TypeOf(int64(0))},
5401 {Name: "YY", Type: TypeOf(int64(0))},
5402 {Name: "ZZ", Type: TypeOf("")},
5403 {Name: "AA", Type: TypeOf([1]int64{})},
5410 for _, table := range tests {
5411 v1 := New(table.rt).Elem()
5412 v2 := New(table.rt).Elem()
5414 if !DeepEqual(v1.Interface(), v1.Interface()) {
5415 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5418 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5419 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5420 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5421 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5425 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5426 val := "+" + abc + "-"
5427 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5428 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5429 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5433 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5434 m.SetMapIndex(v1, ValueOf(1))
5435 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5436 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5439 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5440 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5441 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5444 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5445 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5450 func TestStructOfDirectIface(t *testing.T) {
5452 type T struct{ X [1]*byte }
5453 i1 := Zero(TypeOf(T{})).Interface()
5454 v1 := ValueOf(&i1).Elem()
5455 p1 := v1.InterfaceData()[1]
5457 i2 := Zero(StructOf([]StructField{
5460 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5463 v2 := ValueOf(&i2).Elem()
5464 p2 := v2.InterfaceData()[1]
5467 t.Errorf("got p1=%v. want=%v", p1, nil)
5471 t.Errorf("got p2=%v. want=%v", p2, nil)
5475 type T struct{ X [0]*byte }
5476 i1 := Zero(TypeOf(T{})).Interface()
5477 v1 := ValueOf(&i1).Elem()
5478 p1 := v1.InterfaceData()[1]
5480 i2 := Zero(StructOf([]StructField{
5483 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5486 v2 := ValueOf(&i2).Elem()
5487 p2 := v2.InterfaceData()[1]
5490 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5494 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5501 func (i StructI) Get() int { return int(i) }
5505 func (i *StructIPtr) Get() int { return int(*i) }
5506 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5508 type SettableStruct struct {
5512 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5514 type SettablePointer struct {
5518 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5520 func TestStructOfWithInterface(t *testing.T) {
5522 type Iface interface {
5525 type IfaceSet interface {
5536 typ: TypeOf(StructI(want)),
5537 val: ValueOf(StructI(want)),
5542 typ: PtrTo(TypeOf(StructI(want))),
5543 val: ValueOf(func() interface{} {
5551 typ: PtrTo(TypeOf(StructIPtr(want))),
5552 val: ValueOf(func() interface{} {
5553 v := StructIPtr(want)
5560 typ: TypeOf(StructIPtr(want)),
5561 val: ValueOf(StructIPtr(want)),
5565 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5566 // val: ValueOf(StructI(want)),
5571 for i, table := range tests {
5572 for j := 0; j < 2; j++ {
5573 var fields []StructField
5575 fields = append(fields, StructField{
5578 Type: TypeOf(int(0)),
5581 fields = append(fields, StructField{
5588 // We currently do not correctly implement methods
5589 // for embedded fields other than the first.
5590 // Therefore, for now, we expect those methods
5591 // to not exist. See issues 15924 and 20824.
5592 // When those issues are fixed, this test of panic
5593 // should be removed.
5594 if j == 1 && table.impl {
5597 if err := recover(); err == nil {
5598 t.Errorf("test-%d-%d did not panic", i, j)
5601 _ = StructOf(fields)
5606 rt := StructOf(fields)
5607 rv := New(rt).Elem()
5608 rv.Field(j).Set(table.val)
5610 if _, ok := rv.Interface().(Iface); ok != table.impl {
5612 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5614 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5623 v := rv.Interface().(Iface).Get()
5625 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5628 fct := rv.MethodByName("Get")
5629 out := fct.Call(nil)
5630 if !DeepEqual(out[0].Interface(), want) {
5631 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5636 // Test an embedded nil pointer with pointer methods.
5637 fields := []StructField{{
5640 Type: PtrTo(TypeOf(StructIPtr(want))),
5642 rt := StructOf(fields)
5643 rv := New(rt).Elem()
5644 // This should panic since the pointer is nil.
5645 shouldPanic("", func() {
5646 rv.Interface().(IfaceSet).Set(want)
5649 // Test an embedded nil pointer to a struct with pointer methods.
5651 fields = []StructField{{
5652 Name: "SettableStruct",
5654 Type: PtrTo(TypeOf(SettableStruct{})),
5656 rt = StructOf(fields)
5658 // This should panic since the pointer is nil.
5659 shouldPanic("", func() {
5660 rv.Interface().(IfaceSet).Set(want)
5663 // The behavior is different if there is a second field,
5664 // since now an interface value holds a pointer to the struct
5665 // rather than just holding a copy of the struct.
5666 fields = []StructField{
5668 Name: "SettableStruct",
5670 Type: PtrTo(TypeOf(SettableStruct{})),
5673 Name: "EmptyStruct",
5675 Type: StructOf(nil),
5678 // With the current implementation this is expected to panic.
5679 // Ideally it should work and we should be able to see a panic
5680 // if we call the Set method.
5681 shouldPanic("", func() {
5685 // Embed a field that can be stored directly in an interface,
5686 // with a second field.
5687 fields = []StructField{
5689 Name: "SettablePointer",
5691 Type: TypeOf(SettablePointer{}),
5694 Name: "EmptyStruct",
5696 Type: StructOf(nil),
5699 // With the current implementation this is expected to panic.
5700 // Ideally it should work and we should be able to call the
5701 // Set and Get methods.
5702 shouldPanic("", func() {
5707 func TestStructOfTooManyFields(t *testing.T) {
5708 // Bug Fix: #25402 - this should not panic
5709 tt := StructOf([]StructField{
5710 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5713 if _, present := tt.MethodByName("After"); !present {
5714 t.Errorf("Expected method `After` to be found")
5718 func TestStructOfDifferentPkgPath(t *testing.T) {
5719 fields := []StructField{
5723 Type: TypeOf(int(0)),
5728 Type: TypeOf(int(0)),
5731 shouldPanic("different PkgPath", func() {
5736 func TestChanOf(t *testing.T) {
5737 // check construction and use of type not in binary
5739 ct := ChanOf(BothDir, TypeOf(T("")))
5740 v := MakeChan(ct, 2)
5742 v.Send(ValueOf(T("hello")))
5744 v.Send(ValueOf(T("world")))
5751 if s1 != "hello" || s2 != "world" {
5752 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5755 // check that type already in binary is found
5757 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5759 // Check arrow token association in undefined chan types.
5760 var left chan<- chan T
5761 var right chan (<-chan T)
5762 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5763 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5764 if tLeft != TypeOf(left) {
5765 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5767 if tRight != TypeOf(right) {
5768 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5772 func TestChanOfDir(t *testing.T) {
5773 // check construction and use of type not in binary
5775 crt := ChanOf(RecvDir, TypeOf(T("")))
5776 cst := ChanOf(SendDir, TypeOf(T("")))
5778 // check that type already in binary is found
5780 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5781 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5783 // check String form of ChanDir
5784 if crt.ChanDir().String() != "<-chan" {
5785 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5787 if cst.ChanDir().String() != "chan<-" {
5788 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5792 func TestChanOfGC(t *testing.T) {
5793 done := make(chan bool, 1)
5797 case <-time.After(5 * time.Second):
5798 panic("deadlock in TestChanOfGC")
5807 tt := TypeOf(T(nil))
5808 ct := ChanOf(BothDir, tt)
5810 // NOTE: The garbage collector handles allocated channels specially,
5811 // so we have to save pointers to channels in x; the pointer code will
5812 // use the gc info in the newly constructed chan type.
5815 for i := 0; i < n; i++ {
5816 v := MakeChan(ct, n)
5817 for j := 0; j < n; j++ {
5819 *p = uintptr(i*n + j)
5820 v.Send(ValueOf(p).Convert(tt))
5824 x = append(x, pv.Interface())
5828 for i, xi := range x {
5829 v := ValueOf(xi).Elem()
5830 for j := 0; j < n; j++ {
5832 k := pv.Elem().Interface()
5833 if k != uintptr(i*n+j) {
5834 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5840 func TestMapOf(t *testing.T) {
5841 // check construction and use of type not in binary
5845 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5847 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5850 s := fmt.Sprint(v.Interface())
5853 t.Errorf("constructed map = %s, want %s", s, want)
5856 // check that type already in binary is found
5857 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5859 // check that invalid key type panics
5860 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5863 func TestMapOfGCKeys(t *testing.T) {
5865 tt := TypeOf(T(nil))
5866 mt := MapOf(tt, TypeOf(false))
5868 // NOTE: The garbage collector handles allocated maps specially,
5869 // so we have to save pointers to maps in x; the pointer code will
5870 // use the gc info in the newly constructed map type.
5873 for i := 0; i < n; i++ {
5875 for j := 0; j < n; j++ {
5877 *p = uintptr(i*n + j)
5878 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5882 x = append(x, pv.Interface())
5886 for i, xi := range x {
5887 v := ValueOf(xi).Elem()
5889 for _, kv := range v.MapKeys() {
5890 out = append(out, int(kv.Elem().Interface().(uintptr)))
5893 for j, k := range out {
5895 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5901 func TestMapOfGCValues(t *testing.T) {
5903 tt := TypeOf(T(nil))
5904 mt := MapOf(TypeOf(1), tt)
5906 // NOTE: The garbage collector handles allocated maps specially,
5907 // so we have to save pointers to maps in x; the pointer code will
5908 // use the gc info in the newly constructed map type.
5911 for i := 0; i < n; i++ {
5913 for j := 0; j < n; j++ {
5915 *p = uintptr(i*n + j)
5916 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5920 x = append(x, pv.Interface())
5924 for i, xi := range x {
5925 v := ValueOf(xi).Elem()
5926 for j := 0; j < n; j++ {
5927 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
5928 if k != uintptr(i*n+j) {
5929 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5935 func TestTypelinksSorted(t *testing.T) {
5937 for i, n := range TypeLinks() {
5939 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
5945 func TestFuncOf(t *testing.T) {
5946 // check construction and use of type not in binary
5950 fn := func(args []Value) []Value {
5952 t.Errorf("args == %v, want exactly one arg", args)
5953 } else if args[0].Type() != TypeOf(K("")) {
5954 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
5955 } else if args[0].String() != "gopher" {
5956 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
5958 return []Value{ValueOf(V(3.14))}
5960 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
5962 outs := v.Call([]Value{ValueOf(K("gopher"))})
5964 t.Fatalf("v.Call returned %v, want exactly one result", outs)
5965 } else if outs[0].Type() != TypeOf(V(0)) {
5966 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
5968 f := outs[0].Float()
5970 t.Errorf("constructed func returned %f, want %f", f, 3.14)
5973 // check that types already in binary are found
5975 testCases := []struct {
5980 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
5981 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
5982 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
5983 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
5984 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
5986 for _, tt := range testCases {
5987 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
5990 // check that variadic requires last element be a slice.
5991 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5992 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5993 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6002 func BenchmarkFieldByName1(b *testing.B) {
6004 b.RunParallel(func(pb *testing.PB) {
6011 func BenchmarkFieldByName2(b *testing.B) {
6013 b.RunParallel(func(pb *testing.PB) {
6090 func TestEmbed(t *testing.T) {
6092 f, ok := typ.FieldByName("X")
6094 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6098 func BenchmarkFieldByName3(b *testing.B) {
6100 b.RunParallel(func(pb *testing.PB) {
6112 func BenchmarkInterfaceBig(b *testing.B) {
6114 b.RunParallel(func(pb *testing.PB) {
6122 func TestAllocsInterfaceBig(t *testing.T) {
6123 if testing.Short() {
6124 t.Skip("skipping malloc count in short mode")
6127 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6128 t.Error("allocs:", allocs)
6132 func BenchmarkInterfaceSmall(b *testing.B) {
6133 v := ValueOf(int64(0))
6134 b.RunParallel(func(pb *testing.PB) {
6141 func TestAllocsInterfaceSmall(t *testing.T) {
6142 if testing.Short() {
6143 t.Skip("skipping malloc count in short mode")
6145 v := ValueOf(int64(0))
6146 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6147 t.Error("allocs:", allocs)
6151 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6152 // The basic usage is:
6155 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6158 // Each iteration of the loop returns a different set of results, until all
6159 // possible result sets have been explored. It is okay for different code paths
6160 // to make different method call sequences on x, but there must be no
6161 // other source of non-determinism in the call sequences.
6163 // When faced with a new decision, x chooses randomly. Future explorations
6164 // of that path will choose successive values for the result. Thus, stopping
6165 // the loop after a fixed number of iterations gives somewhat stochastic
6171 // v := make([]bool, x.Choose(4))
6172 // for i := range v {
6178 // prints (in some order):
6187 // [false false false]
6190 // [false false false false]
6192 // [true true true true]
6194 type exhaustive struct {
6200 type choice struct {
6206 func (x *exhaustive) Next() bool {
6208 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6215 for i := len(x.last) - 1; i >= 0; i-- {
6219 x.last = x.last[:i+1]
6226 func (x *exhaustive) Choose(max int) int {
6227 if x.pos >= len(x.last) {
6228 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6233 panic("inconsistent use of exhaustive tester")
6235 return (c.n + c.off) % max
6238 func (x *exhaustive) Maybe() bool {
6239 return x.Choose(2) == 1
6242 func GCFunc(args []Value) []Value {
6247 func TestReflectFuncTraceback(t *testing.T) {
6248 f := MakeFunc(TypeOf(func() {}), GCFunc)
6252 func TestReflectMethodTraceback(t *testing.T) {
6254 m := ValueOf(p).MethodByName("GCMethod")
6255 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6257 t.Errorf("Call returned %d; want 8", i)
6261 func TestSmallZero(t *testing.T) {
6264 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6265 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6269 func TestBigZero(t *testing.T) {
6270 const size = 1 << 10
6272 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6273 for i := 0; i < size; i++ {
6275 t.Fatalf("Zero object not all zero, index %d", i)
6280 func TestZeroSet(t *testing.T) {
6288 a: 0xaaaaaaaaaaaaaaaa,
6289 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6290 b: 0xbbbbbbbbbbbbbbbb,
6292 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6294 a: 0xaaaaaaaaaaaaaaaa,
6295 b: 0xbbbbbbbbbbbbbbbb,
6297 t.Fatalf("Setting a field to a Zero value didn't work")
6301 func TestFieldByIndexNil(t *testing.T) {
6310 v.FieldByName("P") // should be fine
6313 if err := recover(); err == nil {
6314 t.Fatalf("no error")
6315 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6316 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6319 v.FieldByName("F") // should panic
6321 t.Fatalf("did not panic")
6325 // type Outer struct {
6329 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6330 // The implementation is logically:
6331 // func (p *Outer) M() {
6334 // but since the only change here is the replacement of one pointer receiver with another,
6335 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6336 // then jumps to the M method expecting the *Inner receiver.
6338 // During reflect.Value.Call, we create an argument frame and the associated data structures
6339 // to describe it to the garbage collector, populate the frame, call reflect.call to
6340 // run a function call using that frame, and then copy the results back out of the frame.
6341 // The reflect.call function does a memmove of the frame structure onto the
6342 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6343 // the frame structure (to preserve the outputs).
6345 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6346 // were for the full stack frame. However, in the case where the called function was
6347 // one of these wrappers, the rewritten receiver is almost certainly a different type
6348 // than the original receiver. This is not a problem on the stack, where we use the
6349 // program counter to determine the type information and understand that
6350 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6351 // memory word is now an *Inner. But in the statically typed argument frame created
6352 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6353 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6354 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6355 // memory as if it were an *Outer. If the two have different memory layouts, the
6356 // collection will interpret the memory incorrectly.
6358 // One such possible incorrect interpretation is to treat two arbitrary memory words
6359 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6360 // an interface requires dereferencing the itab word, the misinterpretation will try to
6361 // deference Inner.P1, causing a crash during garbage collection.
6363 // This came up in a real program in issue 7725.
6376 func (pi *Inner) M() {
6377 // Clear references to pi so that the only way the
6378 // garbage collection will find the pointer is in the
6379 // argument frame, typed as a *Outer.
6382 // Set up an interface value that will cause a crash.
6383 // P1 = 1 is a non-zero, so the interface looks non-nil.
6384 // P2 = pi ensures that the data word points into the
6385 // allocated heap; if not the collection skips the interface
6386 // value as irrelevant, without dereferencing P1.
6388 pi.P2 = uintptr(unsafe.Pointer(pi))
6391 func TestCallMethodJump(t *testing.T) {
6392 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6393 // returns but before the args frame has been discarded.
6394 // This is a little clumsy but makes the failure repeatable.
6397 p := &Outer{Inner: new(Inner)}
6399 ValueOf(p).Method(0).Call(nil)
6401 // Stop garbage collecting during reflect.call.
6405 func TestMakeFuncStackCopy(t *testing.T) {
6406 target := func(in []Value) []Value {
6409 return []Value{ValueOf(9)}
6412 var concrete func(*int, int) int
6413 fn := MakeFunc(ValueOf(concrete).Type(), target)
6414 ValueOf(&concrete).Elem().Set(fn)
6415 x := concrete(nil, 7)
6417 t.Errorf("have %#q want 9", x)
6421 // use about n KB of stack
6422 func useStack(n int) {
6426 var b [1024]byte // makes frame about 1KB
6427 useStack(n - 1 + int(b[99]))
6434 func TestValueString(t *testing.T) {
6435 rv := ValueOf(Impl{})
6436 if rv.String() != "<reflect_test.Impl Value>" {
6437 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6440 method := rv.Method(0)
6441 if method.String() != "<func() Value>" {
6442 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6446 func TestInvalid(t *testing.T) {
6447 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6448 type T struct{ v interface{} }
6450 v := ValueOf(T{}).Field(0)
6451 if v.IsValid() != true || v.Kind() != Interface {
6452 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6455 if v.IsValid() != false || v.Kind() != Invalid {
6456 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6461 func TestLargeGCProg(t *testing.T) {
6462 fv := ValueOf(func([256]*byte) {})
6463 fv.Call([]Value{ValueOf([256]*byte{})})
6466 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
6468 recovered = recover()
6476 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6477 typ := TypeOf(struct{ X int }{10})
6478 testIndices := [...]struct {
6487 for i, tt := range testIndices {
6488 recoveredErr := fieldIndexRecover(typ, tt.i)
6490 if recoveredErr == nil {
6491 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6494 if recoveredErr != nil {
6495 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6502 func TestCallGC(t *testing.T) {
6503 f := func(a, b, c, d, e string) {
6505 g := func(in []Value) []Value {
6509 typ := ValueOf(f).Type()
6510 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6511 f2("four", "five5", "six666", "seven77", "eight888")
6514 // Issue 18635 (function version).
6515 func TestKeepFuncLive(t *testing.T) {
6516 // Test that we keep makeFuncImpl live as long as it is
6517 // referenced on the stack.
6518 typ := TypeOf(func(i int) {})
6519 var f, g func(in []Value) []Value
6520 f = func(in []Value) []Value {
6522 i := int(in[0].Int())
6524 // We can't use Value.Call here because
6525 // runtime.call* will keep the makeFuncImpl
6526 // alive. However, by converting it to an
6527 // interface value and calling that,
6528 // reflect.callReflect is the only thing that
6529 // can keep the makeFuncImpl live.
6531 // Alternate between f and g so that if we do
6532 // reuse the memory prematurely it's more
6533 // likely to get obviously corrupted.
6534 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6538 g = func(in []Value) []Value {
6540 i := int(in[0].Int())
6541 MakeFunc(typ, f).Interface().(func(i int))(i)
6544 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6547 type UnExportedFirst int
6549 func (i UnExportedFirst) ΦExported() {}
6550 func (i UnExportedFirst) unexported() {}
6553 func TestMethodByNameUnExportedFirst(t *testing.T) {
6555 if recover() != nil {
6556 t.Errorf("should not panic")
6559 typ := TypeOf(UnExportedFirst(0))
6560 m, _ := typ.MethodByName("ΦExported")
6561 if m.Name != "ΦExported" {
6562 t.Errorf("got %s, expected ΦExported", m.Name)
6566 // Issue 18635 (method version).
6567 type KeepMethodLive struct{}
6569 func (k KeepMethodLive) Method1(i int) {
6572 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6576 func (k KeepMethodLive) Method2(i int) {
6578 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6581 func TestKeepMethodLive(t *testing.T) {
6582 // Test that we keep methodValue live as long as it is
6583 // referenced on the stack.
6584 KeepMethodLive{}.Method1(10)
6587 // clobber tries to clobber unreachable memory.
6590 for i := 1; i < 32; i++ {
6591 for j := 0; j < 10; j++ {
6592 obj := make([]*byte, i)
6599 func TestFuncLayout(t *testing.T) {
6600 align := func(x uintptr) uintptr {
6601 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6604 if goarch.PtrSize == 4 {
6605 r = []byte{0, 0, 0, 1}
6617 size, argsize, retOffset uintptr
6618 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6619 intRegs, floatRegs int
6620 floatRegSize uintptr
6624 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6625 size: 6 * goarch.PtrSize,
6626 argsize: 4 * goarch.PtrSize,
6627 retOffset: 4 * goarch.PtrSize,
6628 stack: []byte{1, 0, 1, 0, 1},
6629 gc: []byte{1, 0, 1, 0, 1},
6632 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6633 size: align(align(3*4) + goarch.PtrSize + 2),
6634 argsize: align(3*4) + goarch.PtrSize + 2,
6635 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6640 typ: ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
6641 size: 4 * goarch.PtrSize,
6642 argsize: 4 * goarch.PtrSize,
6643 retOffset: 4 * goarch.PtrSize,
6644 stack: []byte{1, 0, 1, 1},
6645 gc: []byte{1, 0, 1, 1},
6648 typ: ValueOf(func(a S) {}).Type(),
6649 size: 4 * goarch.PtrSize,
6650 argsize: 4 * goarch.PtrSize,
6651 retOffset: 4 * goarch.PtrSize,
6652 stack: []byte{0, 0, 1, 1},
6653 gc: []byte{0, 0, 1, 1},
6656 rcvr: ValueOf((*byte)(nil)).Type(),
6657 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6658 size: 3 * goarch.PtrSize,
6659 argsize: 3 * goarch.PtrSize,
6660 retOffset: 3 * goarch.PtrSize,
6661 stack: []byte{1, 0, 1},
6662 gc: []byte{1, 0, 1},
6665 typ: ValueOf(func(a uintptr) {}).Type(),
6666 size: goarch.PtrSize,
6667 argsize: goarch.PtrSize,
6668 retOffset: goarch.PtrSize,
6673 typ: ValueOf(func() uintptr { return 0 }).Type(),
6674 size: goarch.PtrSize,
6681 rcvr: ValueOf(uintptr(0)).Type(),
6682 typ: ValueOf(func(a uintptr) {}).Type(),
6683 size: 2 * goarch.PtrSize,
6684 argsize: 2 * goarch.PtrSize,
6685 retOffset: 2 * goarch.PtrSize,
6688 // Note: this one is tricky, as the receiver is not a pointer. But we
6689 // pass the receiver by reference to the autogenerated pointer-receiver
6690 // version of the function.
6692 // TODO(mknyszek): Add tests for non-zero register count.
6694 for _, lt := range tests {
6695 name := lt.typ.String()
6697 name = lt.rcvr.String() + "." + name
6699 t.Run(name, func(t *testing.T) {
6700 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6702 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6703 if typ.Size() != lt.size {
6704 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6706 if argsize != lt.argsize {
6707 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6709 if retOffset != lt.retOffset {
6710 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6712 if !bytes.Equal(stack, lt.stack) {
6713 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6715 if !bytes.Equal(gc, lt.gc) {
6716 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6718 if !bytes.Equal(inRegs, lt.inRegs) {
6719 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6721 if !bytes.Equal(outRegs, lt.outRegs) {
6722 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6724 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6725 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6731 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6732 heapBits := GCBits(New(typ).Interface())
6733 if !bytes.Equal(heapBits, bits) {
6734 _, _, line, _ := runtime.Caller(1)
6735 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6739 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6740 // Creating a slice causes the runtime to repeat a bitmap,
6741 // which exercises a different path from making the compiler
6742 // repeat a bitmap for a small array or executing a repeat in
6744 val := MakeSlice(typ, 0, cap)
6745 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
6746 heapBits := GCBits(data.Interface())
6747 // Repeat the bitmap for the slice size, trimming scalars in
6748 // the last element.
6749 bits = rep(cap, bits)
6750 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6751 bits = bits[:len(bits)-1]
6753 if !bytes.Equal(heapBits, bits) {
6754 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6758 func TestGCBits(t *testing.T) {
6759 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6761 // Building blocks for types seen by the compiler (like [2]Xscalar).
6762 // The compiler will create the type structures for the derived types,
6763 // including their GC metadata.
6764 type Xscalar struct{ x uintptr }
6765 type Xptr struct{ x *byte }
6766 type Xptrscalar struct {
6770 type Xscalarptr struct {
6774 type Xbigptrscalar struct {
6779 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6781 // Building blocks for types constructed by reflect.
6782 // This code is in a separate block so that code below
6783 // cannot accidentally refer to these.
6784 // The compiler must NOT see types derived from these
6785 // (for example, [2]Scalar must NOT appear in the program),
6786 // or else reflect will use it instead of having to construct one.
6787 // The goal is to test the construction.
6788 type Scalar struct{ x uintptr }
6789 type Ptr struct{ x *byte }
6790 type Ptrscalar struct {
6794 type Scalarptr struct {
6798 type Bigptrscalar struct {
6803 Tscalar = TypeOf(Scalar{})
6804 Tint64 = TypeOf(Int64(0))
6805 Tptr = TypeOf(Ptr{})
6806 Tscalarptr = TypeOf(Scalarptr{})
6807 Tptrscalar = TypeOf(Ptrscalar{})
6808 Tbigptrscalar = TypeOf(Bigptrscalar{})
6813 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6814 verifyGCBits(t, Tscalar, empty)
6815 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6816 verifyGCBits(t, Tptr, lit(1))
6817 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6818 verifyGCBits(t, Tscalarptr, lit(0, 1))
6819 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6820 verifyGCBits(t, Tptrscalar, lit(1))
6822 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6823 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6824 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6825 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6826 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6827 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6828 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6829 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6830 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6831 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6832 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6833 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6834 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6835 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6836 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6837 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6838 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6839 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6840 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6841 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6842 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6843 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6844 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6845 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6846 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6847 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6849 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6850 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6851 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6852 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6853 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6854 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6855 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6856 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6857 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6858 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6859 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6860 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6861 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6862 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6863 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6864 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6865 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6866 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6867 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6868 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6869 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6870 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6871 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6872 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6873 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6874 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6876 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6877 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6879 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6880 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6882 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6883 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6885 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6886 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6888 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6889 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6891 hdr := make([]byte, 8/goarch.PtrSize)
6893 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6894 verifyGCBits(t, MapBucketOf(k, e), want)
6895 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6899 map[Xscalar]Xptr(nil),
6900 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6903 map[Xscalarptr]Xptr(nil),
6904 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6905 verifyMapBucket(t, Tint64, Tptr,
6906 map[int64]Xptr(nil),
6907 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
6910 map[Xscalar]Xscalar(nil),
6913 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6914 map[[2]Xscalarptr][3]Xptrscalar(nil),
6915 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6917 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6918 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6919 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6921 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6922 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6923 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6925 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6926 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6927 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
6929 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6930 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6931 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6934 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
6935 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
6936 func lit(x ...byte) []byte { return x }
6938 func TestTypeOfTypeOf(t *testing.T) {
6939 // Check that all the type constructors return concrete *rtype implementations.
6940 // It's difficult to test directly because the reflect package is only at arm's length.
6941 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6942 check := func(name string, typ Type) {
6943 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
6944 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
6948 type T struct{ int }
6949 check("TypeOf", TypeOf(T{}))
6951 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
6952 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
6953 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
6954 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
6955 check("PtrTo", PtrTo(TypeOf(T{})))
6956 check("SliceOf", SliceOf(TypeOf(T{})))
6959 type XM struct{ _ bool }
6961 func (*XM) String() string { return "" }
6963 func TestPtrToMethods(t *testing.T) {
6965 yp := New(TypeOf(y)).Interface()
6966 _, ok := yp.(fmt.Stringer)
6968 t.Fatal("does not implement Stringer, but should")
6972 func TestMapAlloc(t *testing.T) {
6973 m := ValueOf(make(map[int]int, 10))
6976 allocs := testing.AllocsPerRun(100, func() {
6980 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
6985 val := ValueOf(&tmp).Elem()
6986 allocs = testing.AllocsPerRun(100, func() {
6987 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
6988 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6989 for i := 0; i < size/2; i++ {
6990 val.SetInt(int64(i))
6991 mv.SetMapIndex(val, val)
6995 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
6997 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
6998 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
6999 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7002 func TestChanAlloc(t *testing.T) {
7003 // Note: for a chan int, the return Value must be allocated, so we
7004 // use a chan *int instead.
7005 c := ValueOf(make(chan *int, 1))
7006 v := ValueOf(new(int))
7007 allocs := testing.AllocsPerRun(100, func() {
7011 if allocs < 0.5 || allocs > 1.5 {
7012 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7014 // Note: there is one allocation in reflect.recv which seems to be
7015 // a limitation of escape analysis. If that is ever fixed the
7016 // allocs < 0.5 condition will trigger and this test should be fixed.
7019 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7021 type nameTest struct {
7026 var nameTests = []nameTest{
7027 {(*int32)(nil), "int32"},
7030 {(*chan D1)(nil), ""},
7031 {(*func() D1)(nil), ""},
7032 {(*<-chan D1)(nil), ""},
7033 {(*chan<- D1)(nil), ""},
7034 {(*interface{})(nil), ""},
7038 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7041 func TestNames(t *testing.T) {
7042 for _, test := range nameTests {
7043 typ := TypeOf(test.v).Elem()
7044 if got := typ.Name(); got != test.want {
7045 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7050 func TestExported(t *testing.T) {
7051 type ΦExported struct{}
7052 type φUnexported struct{}
7059 type exportTest struct {
7063 exportTests := []exportTest{
7067 {(*big)(nil), false},
7068 {(BigP)(nil), true},
7069 {(*BigP)(nil), true},
7070 {ΦExported{}, true},
7071 {φUnexported{}, false},
7078 for i, test := range exportTests {
7079 typ := TypeOf(test.v)
7080 if got := IsExported(typ); got != test.want {
7081 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7086 func TestTypeStrings(t *testing.T) {
7087 type stringTest struct {
7091 stringTests := []stringTest{
7092 {TypeOf(func(int) {}), "func(int)"},
7093 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7094 {TypeOf(XM{}), "reflect_test.XM"},
7095 {TypeOf(new(XM)), "*reflect_test.XM"},
7096 {TypeOf(new(XM).String), "func() string"},
7097 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7098 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7099 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7100 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7101 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7104 for i, test := range stringTests {
7105 if got, want := test.typ.String(), test.want; got != want {
7106 t.Errorf("type %d String()=%q, want %q", i, got, want)
7111 func TestOffsetLock(t *testing.T) {
7112 var wg sync.WaitGroup
7113 for i := 0; i < 4; i++ {
7117 for j := 0; j < 50; j++ {
7118 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7126 func BenchmarkNew(b *testing.B) {
7128 b.RunParallel(func(pb *testing.PB) {
7135 func BenchmarkMap(b *testing.B) {
7137 value := ValueOf((V)(nil))
7138 stringKeys := []string{}
7139 mapOfStrings := map[string]V{}
7140 uint64Keys := []uint64{}
7141 mapOfUint64s := map[uint64]V{}
7142 for i := 0; i < 100; i++ {
7143 stringKey := fmt.Sprintf("key%d", i)
7144 stringKeys = append(stringKeys, stringKey)
7145 mapOfStrings[stringKey] = nil
7147 uint64Key := uint64(i)
7148 uint64Keys = append(uint64Keys, uint64Key)
7149 mapOfUint64s[uint64Key] = nil
7154 m, keys, value Value
7156 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7157 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7160 for _, tt := range tests {
7161 b.Run(tt.label, func(b *testing.B) {
7162 b.Run("MapIndex", func(b *testing.B) {
7164 for i := 0; i < b.N; i++ {
7165 for j := tt.keys.Len() - 1; j >= 0; j-- {
7166 tt.m.MapIndex(tt.keys.Index(j))
7170 b.Run("SetMapIndex", func(b *testing.B) {
7172 for i := 0; i < b.N; i++ {
7173 for j := tt.keys.Len() - 1; j >= 0; j-- {
7174 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7182 func TestSwapper(t *testing.T) {
7188 type pairPtr struct {
7200 in: []int{1, 20, 300},
7203 want: []int{300, 20, 1},
7206 in: []uintptr{1, 20, 300},
7209 want: []uintptr{300, 20, 1},
7212 in: []int16{1, 20, 300},
7215 want: []int16{300, 20, 1},
7218 in: []int8{1, 20, 100},
7221 want: []int8{100, 20, 1},
7224 in: []*I{&a, &b, &c},
7227 want: []*I{&c, &b, &a},
7230 in: []string{"eric", "sergey", "larry"},
7233 want: []string{"larry", "sergey", "eric"},
7236 in: []S{"eric", "sergey", "larry"},
7239 want: []S{"larry", "sergey", "eric"},
7242 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7245 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7248 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7251 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7255 for i, tt := range tests {
7256 inStr := fmt.Sprint(tt.in)
7257 Swapper(tt.in)(tt.i, tt.j)
7258 if !DeepEqual(tt.in, tt.want) {
7259 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7264 // TestUnaddressableField tests that the reflect package will not allow
7265 // a type from another package to be used as a named type with an
7266 // unexported field.
7268 // This ensures that unexported fields cannot be modified by other packages.
7269 func TestUnaddressableField(t *testing.T) {
7270 var b Buffer // type defined in reflect, a different package
7271 var localBuffer struct {
7274 lv := ValueOf(&localBuffer).Elem()
7276 shouldPanic("Set", func() {
7285 type Talias1 struct {
7293 type Talias2 struct {
7298 func TestAliasNames(t *testing.T) {
7299 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7300 out := fmt.Sprintf("%#v", t1)
7301 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7303 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7306 t2 := Talias2{Tint: 1, Tint2: 2}
7307 out = fmt.Sprintf("%#v", t2)
7308 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7310 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7314 func TestIssue22031(t *testing.T) {
7315 type s []struct{ C int }
7318 type t2 struct{ f s }
7321 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7322 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7325 for i, test := range tests {
7327 t.Errorf("%d: CanSet: got true, want false", i)
7332 type NonExportedFirst int
7334 func (i NonExportedFirst) ΦExported() {}
7335 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7337 func TestIssue22073(t *testing.T) {
7338 m := ValueOf(NonExportedFirst(0)).Method(0)
7340 if got := m.Type().NumOut(); got != 0 {
7341 t.Errorf("NumOut: got %v, want 0", got)
7348 func TestMapIterNonEmptyMap(t *testing.T) {
7349 m := map[string]int{"one": 1, "two": 2, "three": 3}
7350 iter := ValueOf(m).MapRange()
7351 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7352 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7356 func TestMapIterNilMap(t *testing.T) {
7357 var m map[string]int
7358 iter := ValueOf(m).MapRange()
7359 if got, want := iterateToString(iter), `[]`; got != want {
7360 t.Errorf("non-empty result iteratoring nil map: %s", got)
7364 func TestMapIterReset(t *testing.T) {
7365 iter := new(MapIter)
7367 // Use of zero iterator should panic.
7369 defer func() { recover() }()
7371 t.Error("Next did not panic")
7374 // Reset to new Map should work.
7375 m := map[string]int{"one": 1, "two": 2, "three": 3}
7376 iter.Reset(ValueOf(m))
7377 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7378 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7381 // Reset to Zero value should work, but iterating over it should panic.
7384 defer func() { recover() }()
7386 t.Error("Next did not panic")
7389 // Reset to a different Map with different types should work.
7390 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7391 iter.Reset(ValueOf(m2))
7392 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7393 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7396 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7397 m3 := map[uint64]uint64{
7402 kv := New(TypeOf(uint64(0))).Elem()
7403 for i := 0; i < 5; i++ {
7404 var seenk, seenv uint64
7405 iter.Reset(ValueOf(m3))
7413 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7415 if seenv != 0b1110 {
7416 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7420 // Reset should not allocate.
7421 n := int(testing.AllocsPerRun(10, func() {
7422 iter.Reset(ValueOf(m2))
7426 t.Errorf("MapIter.Reset allocated %d times", n)
7430 func TestMapIterSafety(t *testing.T) {
7431 // Using a zero MapIter causes a panic, but not a crash.
7433 defer func() { recover() }()
7435 t.Fatal("Key did not panic")
7438 defer func() { recover() }()
7439 new(MapIter).Value()
7440 t.Fatal("Value did not panic")
7443 defer func() { recover() }()
7445 t.Fatal("Next did not panic")
7448 // Calling Key/Value on a MapIter before Next
7449 // causes a panic, but not a crash.
7450 var m map[string]int
7451 iter := ValueOf(m).MapRange()
7454 defer func() { recover() }()
7456 t.Fatal("Key did not panic")
7459 defer func() { recover() }()
7461 t.Fatal("Value did not panic")
7464 // Calling Next, Key, or Value on an exhausted iterator
7465 // causes a panic, but not a crash.
7466 iter.Next() // -> false
7468 defer func() { recover() }()
7470 t.Fatal("Key did not panic")
7473 defer func() { recover() }()
7475 t.Fatal("Value did not panic")
7478 defer func() { recover() }()
7480 t.Fatal("Next did not panic")
7484 func TestMapIterNext(t *testing.T) {
7485 // The first call to Next should reflect any
7486 // insertions to the map since the iterator was created.
7487 m := map[string]int{}
7488 iter := ValueOf(m).MapRange()
7490 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7491 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7495 func TestMapIterDelete0(t *testing.T) {
7496 // Delete all elements before first iteration.
7497 m := map[string]int{"one": 1, "two": 2, "three": 3}
7498 iter := ValueOf(m).MapRange()
7502 if got, want := iterateToString(iter), `[]`; got != want {
7503 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7507 func TestMapIterDelete1(t *testing.T) {
7508 // Delete all elements after first iteration.
7509 m := map[string]int{"one": 1, "two": 2, "three": 3}
7510 iter := ValueOf(m).MapRange()
7513 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7519 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7523 // iterateToString returns the set of elements
7524 // returned by an iterator in readable form.
7525 func iterateToString(it *MapIter) string {
7528 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7529 got = append(got, line)
7532 return "[" + strings.Join(got, ", ") + "]"
7535 func TestConvertibleTo(t *testing.T) {
7536 t1 := ValueOf(example1.MyStruct{}).Type()
7537 t2 := ValueOf(example2.MyStruct{}).Type()
7539 // Shouldn't raise stack overflow
7540 if t1.ConvertibleTo(t2) {
7541 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7544 t3 := ValueOf([]example1.MyStruct{}).Type()
7545 t4 := ValueOf([]example2.MyStruct{}).Type()
7547 if t3.ConvertibleTo(t4) {
7548 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)