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 {&structWithSelfPtr{p: &structWithSelfPtr{s: "a"}}, &structWithSelfPtr{p: &structWithSelfPtr{s: "b"}}, false},
933 // Fun with floating point.
934 {math.NaN(), math.NaN(), false},
935 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
936 {&[1]float64{math.NaN()}, self{}, true},
937 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
938 {[]float64{math.NaN()}, self{}, true},
939 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
940 {map[float64]float64{math.NaN(): 1}, self{}, true},
942 // Nil vs empty: not the same.
943 {[]int{}, []int(nil), false},
944 {[]int{}, []int{}, true},
945 {[]int(nil), []int(nil), true},
946 {map[int]int{}, map[int]int(nil), false},
947 {map[int]int{}, map[int]int{}, true},
948 {map[int]int(nil), map[int]int(nil), true},
952 {int32(1), int64(1), false},
953 {0.5, "hello", false},
954 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
955 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
956 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
957 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
958 {[]byte{1, 2, 3}, []MyByte{1, 2, 3}, false},
959 {[]MyByte{1, 2, 3}, MyBytes{1, 2, 3}, false},
960 {[]byte{1, 2, 3}, MyBytes{1, 2, 3}, false},
963 {&loop1, &loop1, true},
964 {&loop1, &loop2, true},
965 {&loopy1, &loopy1, true},
966 {&loopy1, &loopy2, true},
967 {&cycleMap1, &cycleMap2, true},
968 {&cycleMap1, &cycleMap3, false},
971 func TestDeepEqual(t *testing.T) {
972 for _, test := range deepEqualTests {
973 if test.b == (self{}) {
976 if r := DeepEqual(test.a, test.b); r != test.eq {
977 t.Errorf("DeepEqual(%#v, %#v) = %v, want %v", test.a, test.b, r, test.eq)
982 func TestTypeOf(t *testing.T) {
983 // Special case for nil
984 if typ := TypeOf(nil); typ != nil {
985 t.Errorf("expected nil type for nil value; got %v", typ)
987 for _, test := range deepEqualTests {
992 typ := TypeOf(test.a)
994 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
999 type Recursive struct {
1004 func TestDeepEqualRecursiveStruct(t *testing.T) {
1005 a, b := new(Recursive), new(Recursive)
1006 *a = Recursive{12, a}
1007 *b = Recursive{12, b}
1008 if !DeepEqual(a, b) {
1009 t.Error("DeepEqual(recursive same) = false, want true")
1013 type _Complex struct {
1017 d map[float64]float64
1020 func TestDeepEqualComplexStruct(t *testing.T) {
1021 m := make(map[float64]float64)
1022 stra, strb := "hello", "hello"
1023 a, b := new(_Complex), new(_Complex)
1024 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1025 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1026 if !DeepEqual(a, b) {
1027 t.Error("DeepEqual(complex same) = false, want true")
1031 func TestDeepEqualComplexStructInequality(t *testing.T) {
1032 m := make(map[float64]float64)
1033 stra, strb := "hello", "helloo" // Difference is here
1034 a, b := new(_Complex), new(_Complex)
1035 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
1036 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
1037 if DeepEqual(a, b) {
1038 t.Error("DeepEqual(complex different) = true, want false")
1042 type UnexpT struct {
1046 func TestDeepEqualUnexportedMap(t *testing.T) {
1047 // Check that DeepEqual can look at unexported fields.
1048 x1 := UnexpT{map[int]int{1: 2}}
1049 x2 := UnexpT{map[int]int{1: 2}}
1050 if !DeepEqual(&x1, &x2) {
1051 t.Error("DeepEqual(x1, x2) = false, want true")
1054 y1 := UnexpT{map[int]int{2: 3}}
1055 if DeepEqual(&x1, &y1) {
1056 t.Error("DeepEqual(x1, y1) = true, want false")
1060 var deepEqualPerfTests = []struct {
1063 {x: int8(99), y: int8(99)},
1064 {x: []int8{99}, y: []int8{99}},
1065 {x: int16(99), y: int16(99)},
1066 {x: []int16{99}, y: []int16{99}},
1067 {x: int32(99), y: int32(99)},
1068 {x: []int32{99}, y: []int32{99}},
1069 {x: int64(99), y: int64(99)},
1070 {x: []int64{99}, y: []int64{99}},
1071 {x: int(999999), y: int(999999)},
1072 {x: []int{999999}, y: []int{999999}},
1074 {x: uint8(99), y: uint8(99)},
1075 {x: []uint8{99}, y: []uint8{99}},
1076 {x: uint16(99), y: uint16(99)},
1077 {x: []uint16{99}, y: []uint16{99}},
1078 {x: uint32(99), y: uint32(99)},
1079 {x: []uint32{99}, y: []uint32{99}},
1080 {x: uint64(99), y: uint64(99)},
1081 {x: []uint64{99}, y: []uint64{99}},
1082 {x: uint(999999), y: uint(999999)},
1083 {x: []uint{999999}, y: []uint{999999}},
1084 {x: uintptr(999999), y: uintptr(999999)},
1085 {x: []uintptr{999999}, y: []uintptr{999999}},
1087 {x: float32(1.414), y: float32(1.414)},
1088 {x: []float32{1.414}, y: []float32{1.414}},
1089 {x: float64(1.414), y: float64(1.414)},
1090 {x: []float64{1.414}, y: []float64{1.414}},
1092 {x: complex64(1.414), y: complex64(1.414)},
1093 {x: []complex64{1.414}, y: []complex64{1.414}},
1094 {x: complex128(1.414), y: complex128(1.414)},
1095 {x: []complex128{1.414}, y: []complex128{1.414}},
1098 {x: []bool{true}, y: []bool{true}},
1100 {x: "abcdef", y: "abcdef"},
1101 {x: []string{"abcdef"}, y: []string{"abcdef"}},
1103 {x: []byte("abcdef"), y: []byte("abcdef")},
1104 {x: [][]byte{[]byte("abcdef")}, y: [][]byte{[]byte("abcdef")}},
1106 {x: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}, y: [6]byte{'a', 'b', 'c', 'a', 'b', 'c'}},
1107 {x: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}, y: [][6]byte{[6]byte{'a', 'b', 'c', 'a', 'b', 'c'}}},
1110 func TestDeepEqualAllocs(t *testing.T) {
1111 for _, tt := range deepEqualPerfTests {
1112 t.Run(ValueOf(tt.x).Type().String(), func(t *testing.T) {
1113 got := testing.AllocsPerRun(100, func() {
1114 if !DeepEqual(tt.x, tt.y) {
1115 t.Errorf("DeepEqual(%v, %v)=false", tt.x, tt.y)
1119 t.Errorf("DeepEqual(%v, %v) allocated %d times", tt.x, tt.y, int(got))
1125 func BenchmarkDeepEqual(b *testing.B) {
1126 for _, bb := range deepEqualPerfTests {
1127 b.Run(ValueOf(bb.x).Type().String(), func(b *testing.B) {
1129 for i := 0; i < b.N; i++ {
1130 sink = DeepEqual(bb.x, bb.y)
1136 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
1138 f := s.Type().Field(1)
1139 if f.Offset != offs {
1140 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
1144 // Check that structure alignment & offsets viewed through reflect agree with those
1145 // from the compiler itself.
1146 func TestAlignment(t *testing.T) {
1147 type T1inner struct {
1154 type T2inner struct {
1162 x := T1{T1inner{2}, 17}
1163 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
1165 x1 := T2{T2inner{2, 3}, 17}
1166 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
1169 func Nil(a interface{}, t *testing.T) {
1170 n := ValueOf(a).Field(0)
1172 t.Errorf("%v should be nil", a)
1176 func NotNil(a interface{}, t *testing.T) {
1177 n := ValueOf(a).Field(0)
1179 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1183 func TestIsNil(t *testing.T) {
1184 // These implement IsNil.
1185 // Wrap in extra struct to hide interface type.
1186 doNil := []interface{}{
1188 struct{ x interface{} }{},
1189 struct{ x map[string]int }{},
1190 struct{ x func() bool }{},
1191 struct{ x chan int }{},
1192 struct{ x []string }{},
1193 struct{ x unsafe.Pointer }{},
1195 for _, ts := range doNil {
1196 ty := TypeOf(ts).Field(0).Type
1198 v.IsNil() // panics if not okay to call
1201 // Check the implementations
1213 si.x = make([]int, 10)
1220 ci.x = make(chan int)
1227 mi.x = make(map[int]int)
1238 x func(t *testing.T)
1245 func TestIsZero(t *testing.T) {
1246 for i, tt := range []struct {
1275 {float32(1.2), false},
1277 {float64(1.2), false},
1278 {math.Copysign(0, -1), false},
1279 {complex64(0), true},
1280 {complex64(1.2), false},
1281 {complex128(0), true},
1282 {complex128(1.2), false},
1283 {complex(math.Copysign(0, -1), 0), false},
1284 {complex(0, math.Copysign(0, -1)), false},
1285 {complex(math.Copysign(0, -1), math.Copysign(0, -1)), false},
1287 {uintptr(128), false},
1289 {Zero(TypeOf([5]string{})).Interface(), true},
1290 {[5]string{"", "", "", "", ""}, true},
1291 {[5]string{}, true},
1292 {[5]string{"", "", "", "a", ""}, false},
1294 {(chan string)(nil), true},
1295 {make(chan string), false},
1296 {time.After(1), false},
1298 {(func())(nil), true},
1301 {New(TypeOf(new(error)).Elem()).Elem(), true},
1302 {(io.Reader)(strings.NewReader("")), false},
1304 {(map[string]string)(nil), true},
1305 {map[string]string{}, false},
1306 {make(map[string]string), false},
1308 {(*func())(nil), true},
1309 {(*int)(nil), true},
1312 {[]string{}, false},
1313 {([]string)(nil), true},
1314 {make([]string, 0), false},
1317 {"not-zero", false},
1320 {T{123, 456.75, "hello", &_i}, false},
1322 {(unsafe.Pointer)(nil), true},
1323 {(unsafe.Pointer)(new(int)), false},
1326 if v, ok := tt.x.(Value); ok {
1334 t.Errorf("%d: IsZero((%s)(%+v)) = %t, want %t", i, x.Kind(), tt.x, b, tt.want)
1337 if !Zero(TypeOf(tt.x)).IsZero() {
1338 t.Errorf("%d: IsZero(Zero(TypeOf((%s)(%+v)))) is false", i, x.Kind(), tt.x)
1344 if r := recover(); r == nil {
1345 t.Error("should panic for invalid value")
1352 func TestInterfaceExtraction(t *testing.T) {
1358 v := Indirect(ValueOf(&s)).Field(0).Interface()
1359 if v != s.W.(interface{}) {
1360 t.Error("Interface() on interface: ", v, s.W)
1364 func TestNilPtrValueSub(t *testing.T) {
1366 if pv := ValueOf(pi); pv.Elem().IsValid() {
1367 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1371 func TestMap(t *testing.T) {
1372 m := map[string]int{"a": 1, "b": 2}
1374 if n := mv.Len(); n != len(m) {
1375 t.Errorf("Len = %d, want %d", n, len(m))
1377 keys := mv.MapKeys()
1378 newmap := MakeMap(mv.Type())
1379 for k, v := range m {
1380 // Check that returned Keys match keys in range.
1381 // These aren't required to be in the same order.
1383 for _, kv := range keys {
1384 if kv.String() == k {
1390 t.Errorf("Missing key %q", k)
1393 // Check that value lookup is correct.
1394 vv := mv.MapIndex(ValueOf(k))
1395 if vi := vv.Int(); vi != int64(v) {
1396 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1399 // Copy into new map.
1400 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1402 vv := mv.MapIndex(ValueOf("not-present"))
1404 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1407 newm := newmap.Interface().(map[string]int)
1408 if len(newm) != len(m) {
1409 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1412 for k, v := range newm {
1415 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1419 newmap.SetMapIndex(ValueOf("a"), Value{})
1422 t.Errorf("newm[\"a\"] = %d after delete", v)
1425 mv = ValueOf(&m).Elem()
1426 mv.Set(Zero(mv.Type()))
1428 t.Errorf("mv.Set(nil) failed")
1432 func TestNilMap(t *testing.T) {
1433 var m map[string]int
1435 keys := mv.MapKeys()
1437 t.Errorf(">0 keys for nil map: %v", keys)
1440 // Check that value for missing key is zero.
1441 x := mv.MapIndex(ValueOf("hello"))
1442 if x.Kind() != Invalid {
1443 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1446 // Check big value too.
1447 var mbig map[string][10 << 20]byte
1448 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1449 if x.Kind() != Invalid {
1450 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1453 // Test that deletes from a nil map succeed.
1454 mv.SetMapIndex(ValueOf("hi"), Value{})
1457 func TestChan(t *testing.T) {
1458 for loop := 0; loop < 2; loop++ {
1462 // check both ways to allocate channels
1465 c = make(chan int, 1)
1468 cv = MakeChan(TypeOf(c), 1)
1469 c = cv.Interface().(chan int)
1474 if i := <-c; i != 2 {
1475 t.Errorf("reflect Send 2, native recv %d", i)
1480 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1481 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1485 val, ok := cv.TryRecv()
1486 if val.IsValid() || ok {
1487 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1492 val, ok = cv.TryRecv()
1494 t.Errorf("TryRecv on ready chan got nil")
1495 } else if i := val.Int(); i != 4 || !ok {
1496 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1501 ok = cv.TrySend(ValueOf(5))
1504 t.Errorf("TrySend on full chan succeeded: value %d", i)
1508 ok = cv.TrySend(ValueOf(6))
1510 t.Errorf("TrySend on empty chan failed")
1513 t.Errorf("TrySend failed but it did send %d", x)
1517 if i = <-c; i != 6 {
1518 t.Errorf("TrySend 6, recv %d", i)
1525 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1526 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1528 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1529 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1533 // check creation of unbuffered channel
1535 cv := MakeChan(TypeOf(c), 0)
1536 c = cv.Interface().(chan int)
1537 if cv.TrySend(ValueOf(7)) {
1538 t.Errorf("TrySend on sync chan succeeded")
1540 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1541 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1545 cv = MakeChan(TypeOf(c), 10)
1546 c = cv.Interface().(chan int)
1547 for i := 0; i < 3; i++ {
1550 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1551 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1555 // caseInfo describes a single case in a select test.
1556 type caseInfo struct {
1565 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1567 func TestSelect(t *testing.T) {
1568 selectWatch.once.Do(func() { go selectWatcher() })
1572 newop := func(n int, cap int) (ch, val Value) {
1575 c := make(chan int, cap)
1579 c := make(chan string, cap)
1581 val = ValueOf(fmt.Sprint(n))
1586 for n := 0; x.Next(); n++ {
1587 if testing.Short() && n >= 1000 {
1590 if n >= 100000 && !*allselect {
1593 if n%100000 == 0 && testing.Verbose() {
1594 println("TestSelect", n)
1596 var cases []SelectCase
1601 ch, val := newop(len(cases), 1)
1602 cases = append(cases, SelectCase{
1607 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1612 ch, val := newop(len(cases), 1)
1614 cases = append(cases, SelectCase{
1618 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1623 ch, val := newop(len(cases), 0)
1624 cases = append(cases, SelectCase{
1631 f := func() { ch.Recv() }
1632 info = append(info, caseInfo{desc: "blocking send", helper: f})
1634 info = append(info, caseInfo{desc: "blocking send"})
1640 ch, val := newop(len(cases), 0)
1641 cases = append(cases, SelectCase{
1647 f := func() { ch.Send(val) }
1648 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1650 info = append(info, caseInfo{desc: "blocking recv"})
1656 // Maybe include value to send.
1661 cases = append(cases, SelectCase{
1665 info = append(info, caseInfo{desc: "zero Chan send"})
1668 // Zero Chan receive.
1670 cases = append(cases, SelectCase{
1673 info = append(info, caseInfo{desc: "zero Chan recv"})
1678 cases = append(cases, SelectCase{
1680 Chan: ValueOf((chan int)(nil)),
1683 info = append(info, caseInfo{desc: "nil Chan send"})
1688 cases = append(cases, SelectCase{
1690 Chan: ValueOf((chan int)(nil)),
1692 info = append(info, caseInfo{desc: "nil Chan recv"})
1695 // closed Chan send.
1697 ch := make(chan int)
1699 cases = append(cases, SelectCase{
1704 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1707 // closed Chan recv.
1709 ch, val := newop(len(cases), 0)
1711 val = Zero(val.Type())
1712 cases = append(cases, SelectCase{
1716 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1719 var helper func() // goroutine to help the select complete
1721 // Add default? Must be last case here, but will permute.
1722 // Add the default if the select would otherwise
1723 // block forever, and maybe add it anyway.
1729 for i, c := range info {
1737 } else if c.helper != nil {
1739 helpers = append(helpers, i)
1742 if !canProceed || x.Maybe() {
1743 cases = append(cases, SelectCase{
1746 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1748 } else if canBlock {
1749 // Select needs to communicate with another goroutine.
1750 cas := &info[helpers[x.Choose(len(helpers))]]
1752 cas.canSelect = true
1756 // Permute cases and case info.
1757 // Doing too much here makes the exhaustive loop
1758 // too exhausting, so just do two swaps.
1759 for loop := 0; loop < 2; loop++ {
1760 i := x.Choose(len(cases))
1761 j := x.Choose(len(cases))
1762 cases[i], cases[j] = cases[j], cases[i]
1763 info[i], info[j] = info[j], info[i]
1767 // We wait before kicking off a goroutine to satisfy a blocked select.
1768 // The pause needs to be big enough to let the select block before
1769 // we run the helper, but if we lose that race once in a while it's okay: the
1770 // select will just proceed immediately. Not a big deal.
1771 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1772 pause := 10 * time.Microsecond
1773 if testing.Short() {
1774 pause = 100 * time.Microsecond
1776 time.AfterFunc(pause, helper)
1780 i, recv, recvOK, panicErr := runSelect(cases, info)
1781 if panicErr != nil && !canPanic {
1782 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1784 if panicErr == nil && canPanic && numCanSelect == 1 {
1785 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1787 if panicErr != nil {
1795 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1797 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1801 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1805 if cases[i].Dir == SelectRecv {
1806 if !recv.IsValid() {
1807 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1809 if !cas.recv.IsValid() {
1810 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1812 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1813 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1814 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1816 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1819 if recv.IsValid() || recvOK {
1820 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1826 func TestSelectMaxCases(t *testing.T) {
1827 var sCases []SelectCase
1828 channel := make(chan int)
1830 for i := 0; i < 65536; i++ {
1831 sCases = append(sCases, SelectCase{
1833 Chan: ValueOf(channel),
1837 _, _, _ = Select(sCases)
1838 sCases = append(sCases, SelectCase{
1840 Chan: ValueOf(channel),
1843 if err := recover(); err != nil {
1844 if err.(string) != "reflect.Select: too many cases (max 65536)" {
1845 t.Fatalf("unexpected error from select call with greater than max supported cases")
1848 t.Fatalf("expected select call to panic with greater than max supported cases")
1852 _, _, _ = Select(sCases)
1855 func TestSelectNop(t *testing.T) {
1856 // "select { default: }" should always return the default case.
1857 chosen, _, _ := Select([]SelectCase{{Dir: SelectDefault}})
1859 t.Fatalf("expected Select to return 0, but got %#v", chosen)
1863 func BenchmarkSelect(b *testing.B) {
1864 channel := make(chan int)
1866 var cases []SelectCase
1867 for i := 0; i < 8; i++ {
1868 cases = append(cases, SelectCase{
1870 Chan: ValueOf(channel),
1873 for _, numCases := range []int{1, 4, 8} {
1874 b.Run(strconv.Itoa(numCases), func(b *testing.B) {
1876 for i := 0; i < b.N; i++ {
1877 _, _, _ = Select(cases[:numCases])
1883 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1884 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1885 // an error describing the select and panics the entire test binary.
1886 var selectWatch struct {
1893 func selectWatcher() {
1895 time.Sleep(1 * time.Second)
1897 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1898 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1899 panic("select stuck")
1901 selectWatch.Unlock()
1905 // runSelect runs a single select test.
1906 // It returns the values returned by Select but also returns
1907 // a panic value if the Select panics.
1908 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1910 panicErr = recover()
1913 selectWatch.info = nil
1914 selectWatch.Unlock()
1918 selectWatch.now = time.Now()
1919 selectWatch.info = info
1920 selectWatch.Unlock()
1922 chosen, recv, recvOK = Select(cases)
1926 // fmtSelect formats the information about a single select test.
1927 func fmtSelect(info []caseInfo) string {
1928 var buf bytes.Buffer
1929 fmt.Fprintf(&buf, "\nselect {\n")
1930 for i, cas := range info {
1931 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1932 if cas.recv.IsValid() {
1933 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1936 fmt.Fprintf(&buf, " canselect")
1939 fmt.Fprintf(&buf, " panic")
1941 fmt.Fprintf(&buf, "\n")
1943 fmt.Fprintf(&buf, "}")
1949 // Difficult test for function call because of
1950 // implicit padding between arguments.
1951 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) {
1952 return b, c, d, e, f, g, h
1955 func TestFunc(t *testing.T) {
1956 ret := ValueOf(dummy).Call([]Value{
1960 ValueOf(two{40, 50}),
1962 ValueOf(float32(70)),
1966 t.Fatalf("Call returned %d values, want 7", len(ret))
1969 i := byte(ret[0].Uint())
1970 j := int(ret[1].Int())
1971 k := byte(ret[2].Uint())
1972 l := ret[3].Interface().(two)
1973 m := byte(ret[4].Uint())
1974 n := float32(ret[5].Float())
1975 o := byte(ret[6].Uint())
1977 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1978 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)
1981 for i, v := range ret {
1983 t.Errorf("result %d is addressable", i)
1988 func TestCallConvert(t *testing.T) {
1989 v := ValueOf(new(io.ReadWriter)).Elem()
1990 f := ValueOf(func(r io.Reader) io.Reader { return r })
1991 out := f.Call([]Value{v})
1992 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
1993 t.Errorf("expected [nil], got %v", out)
1997 type emptyStruct struct{}
1999 type nonEmptyStruct struct {
2003 func returnEmpty() emptyStruct {
2004 return emptyStruct{}
2007 func takesEmpty(e emptyStruct) {
2010 func returnNonEmpty(i int) nonEmptyStruct {
2011 return nonEmptyStruct{member: i}
2014 func takesNonEmpty(n nonEmptyStruct) int {
2018 func TestCallWithStruct(t *testing.T) {
2019 r := ValueOf(returnEmpty).Call(nil)
2020 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
2021 t.Errorf("returning empty struct returned %#v instead", r)
2023 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
2025 t.Errorf("takesEmpty returned values: %#v", r)
2027 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
2028 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
2029 t.Errorf("returnNonEmpty returned %#v", r)
2031 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
2032 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
2033 t.Errorf("takesNonEmpty returned %#v", r)
2037 func TestCallReturnsEmpty(t *testing.T) {
2038 // Issue 21717: past-the-end pointer write in Call with
2039 // nonzero-sized frame and zero-sized return value.
2041 var finalized uint32
2042 f := func() (emptyStruct, *[2]int64) {
2043 i := new([2]int64) // big enough to not be tinyalloc'd, so finalizer always runs when i dies
2044 runtime.SetFinalizer(i, func(*[2]int64) { atomic.StoreUint32(&finalized, 1) })
2045 return emptyStruct{}, i
2047 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
2048 timeout := time.After(5 * time.Second)
2049 for atomic.LoadUint32(&finalized) == 0 {
2052 t.Fatal("finalizer did not run")
2058 runtime.KeepAlive(v)
2061 func BenchmarkCall(b *testing.B) {
2062 fv := ValueOf(func(a, b string) {})
2064 b.RunParallel(func(pb *testing.PB) {
2065 args := []Value{ValueOf("a"), ValueOf("b")}
2074 func (i *myint) inc() {
2078 func BenchmarkCallMethod(b *testing.B) {
2083 for i := 0; i < b.N; i++ {
2088 func BenchmarkCallArgCopy(b *testing.B) {
2089 byteArray := func(n int) Value {
2090 return Zero(ArrayOf(n, TypeOf(byte(0))))
2092 sizes := [...]struct {
2096 {ValueOf(func(a [128]byte) {}), byteArray(128)},
2097 {ValueOf(func(a [256]byte) {}), byteArray(256)},
2098 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
2099 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
2100 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
2102 for _, size := range sizes {
2103 bench := func(b *testing.B) {
2104 args := []Value{size.arg}
2105 b.SetBytes(int64(size.arg.Len()))
2107 b.RunParallel(func(pb *testing.PB) {
2113 name := fmt.Sprintf("size=%v", size.arg.Len())
2118 func TestMakeFunc(t *testing.T) {
2120 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
2121 ValueOf(&f).Elem().Set(fv)
2123 // Call g with small arguments so that there is
2124 // something predictable (and different from the
2125 // correct results) in those positions on the stack.
2127 g(1, 2, 3, two{4, 5}, 6, 7, 8)
2129 // Call constructed function f.
2130 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
2131 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
2132 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)
2136 func TestMakeFuncInterface(t *testing.T) {
2137 fn := func(i int) int { return i }
2138 incr := func(in []Value) []Value {
2139 return []Value{ValueOf(int(in[0].Int() + 1))}
2141 fv := MakeFunc(TypeOf(fn), incr)
2142 ValueOf(&fn).Elem().Set(fv)
2143 if r := fn(2); r != 3 {
2144 t.Errorf("Call returned %d, want 3", r)
2146 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
2147 t.Errorf("Call returned %d, want 15", r)
2149 if r := fv.Interface().(func(int) int)(26); r != 27 {
2150 t.Errorf("Call returned %d, want 27", r)
2154 func TestMakeFuncVariadic(t *testing.T) {
2155 // Test that variadic arguments are packed into a slice and passed as last arg
2156 fn := func(_ int, is ...int) []int { return nil }
2157 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
2158 ValueOf(&fn).Elem().Set(fv)
2161 if r[0] != 2 || r[1] != 3 {
2162 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2165 r = fn(1, []int{2, 3}...)
2166 if r[0] != 2 || r[1] != 3 {
2167 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2170 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
2171 if r[0] != 2 || r[1] != 3 {
2172 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2175 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
2176 if r[0] != 2 || r[1] != 3 {
2177 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2180 f := fv.Interface().(func(int, ...int) []int)
2183 if r[0] != 2 || r[1] != 3 {
2184 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2186 r = f(1, []int{2, 3}...)
2187 if r[0] != 2 || r[1] != 3 {
2188 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
2192 // Dummy type that implements io.WriteCloser
2196 func (w *WC) Write(p []byte) (n int, err error) {
2199 func (w *WC) Close() error {
2203 func TestMakeFuncValidReturnAssignments(t *testing.T) {
2204 // reflect.Values returned from the wrapped function should be assignment-converted
2205 // to the types returned by the result of MakeFunc.
2207 // Concrete types should be promotable to interfaces they implement.
2209 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2210 return []Value{ValueOf(io.EOF)}
2211 }).Interface().(func() error)
2214 // Super-interfaces should be promotable to simpler interfaces.
2215 var g func() io.Writer
2216 g = MakeFunc(TypeOf(g), func([]Value) []Value {
2217 var w io.WriteCloser = &WC{}
2218 return []Value{ValueOf(&w).Elem()}
2219 }).Interface().(func() io.Writer)
2222 // Channels should be promotable to directional channels.
2223 var h func() <-chan int
2224 h = MakeFunc(TypeOf(h), func([]Value) []Value {
2225 return []Value{ValueOf(make(chan int))}
2226 }).Interface().(func() <-chan int)
2229 // Unnamed types should be promotable to named types.
2230 type T struct{ a, b, c int }
2232 i = MakeFunc(TypeOf(i), func([]Value) []Value {
2233 return []Value{ValueOf(struct{ a, b, c int }{a: 1, b: 2, c: 3})}
2234 }).Interface().(func() T)
2238 func TestMakeFuncInvalidReturnAssignments(t *testing.T) {
2239 // Type doesn't implement the required interface.
2240 shouldPanic("", func() {
2242 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2243 return []Value{ValueOf(int(7))}
2244 }).Interface().(func() error)
2247 // Assigning to an interface with additional methods.
2248 shouldPanic("", func() {
2249 var f func() io.ReadWriteCloser
2250 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2251 var w io.WriteCloser = &WC{}
2252 return []Value{ValueOf(&w).Elem()}
2253 }).Interface().(func() io.ReadWriteCloser)
2256 // Directional channels can't be assigned to bidirectional ones.
2257 shouldPanic("", func() {
2258 var f func() chan int
2259 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2260 var c <-chan int = make(chan int)
2261 return []Value{ValueOf(c)}
2262 }).Interface().(func() chan int)
2265 // Two named types which are otherwise identical.
2266 shouldPanic("", func() {
2267 type T struct{ a, b, c int }
2268 type U struct{ a, b, c int }
2270 f = MakeFunc(TypeOf(f), func([]Value) []Value {
2271 return []Value{ValueOf(U{a: 1, b: 2, c: 3})}
2272 }).Interface().(func() T)
2281 // This will be index 0.
2282 func (p Point) AnotherMethod(scale int) int {
2286 // This will be index 1.
2287 func (p Point) Dist(scale int) int {
2288 //println("Point.Dist", p.x, p.y, scale)
2289 return p.x*p.x*scale + p.y*p.y*scale
2292 // This will be index 2.
2293 func (p Point) GCMethod(k int) int {
2298 // This will be index 3.
2299 func (p Point) NoArgs() {
2300 // Exercise no-argument/no-result paths.
2303 // This will be index 4.
2304 func (p Point) TotalDist(points ...Point) int {
2306 for _, q := range points {
2309 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
2315 // This will be index 5.
2316 func (p *Point) Int64Method(x int64) int64 {
2320 // This will be index 6.
2321 func (p *Point) Int32Method(x int32) int32 {
2325 func TestMethod(t *testing.T) {
2326 // Non-curried method of type.
2328 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
2330 t.Errorf("Type Method returned %d; want 250", i)
2333 m, ok := TypeOf(p).MethodByName("Dist")
2335 t.Fatalf("method by name failed")
2337 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
2339 t.Errorf("Type MethodByName returned %d; want 275", i)
2342 m, ok = TypeOf(p).MethodByName("NoArgs")
2344 t.Fatalf("method by name failed")
2346 n := len(m.Func.Call([]Value{ValueOf(p)}))
2348 t.Errorf("NoArgs returned %d values; want 0", n)
2351 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
2353 t.Errorf("Pointer Type Method returned %d; want 300", i)
2356 m, ok = TypeOf(&p).MethodByName("Dist")
2358 t.Fatalf("ptr method by name failed")
2360 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
2362 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
2365 m, ok = TypeOf(&p).MethodByName("NoArgs")
2367 t.Fatalf("method by name failed")
2369 n = len(m.Func.Call([]Value{ValueOf(&p)}))
2371 t.Errorf("NoArgs returned %d values; want 0", n)
2374 // Curried method of value.
2375 tfunc := TypeOf((func(int) int)(nil))
2376 v := ValueOf(p).Method(1)
2377 if tt := v.Type(); tt != tfunc {
2378 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2380 i = v.Call([]Value{ValueOf(14)})[0].Int()
2382 t.Errorf("Value Method returned %d; want 350", i)
2384 v = ValueOf(p).MethodByName("Dist")
2385 if tt := v.Type(); tt != tfunc {
2386 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2388 i = v.Call([]Value{ValueOf(15)})[0].Int()
2390 t.Errorf("Value MethodByName returned %d; want 375", i)
2392 v = ValueOf(p).MethodByName("NoArgs")
2395 // Curried method of pointer.
2396 v = ValueOf(&p).Method(1)
2397 if tt := v.Type(); tt != tfunc {
2398 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2400 i = v.Call([]Value{ValueOf(16)})[0].Int()
2402 t.Errorf("Pointer Value Method returned %d; want 400", i)
2404 v = ValueOf(&p).MethodByName("Dist")
2405 if tt := v.Type(); tt != tfunc {
2406 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2408 i = v.Call([]Value{ValueOf(17)})[0].Int()
2410 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
2412 v = ValueOf(&p).MethodByName("NoArgs")
2415 // Curried method of interface value.
2416 // Have to wrap interface value in a struct to get at it.
2417 // Passing it to ValueOf directly would
2418 // access the underlying Point, not the interface.
2422 pv := ValueOf(&x).Elem()
2424 if tt := v.Type(); tt != tfunc {
2425 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2427 i = v.Call([]Value{ValueOf(18)})[0].Int()
2429 t.Errorf("Interface Method returned %d; want 450", i)
2431 v = pv.MethodByName("Dist")
2432 if tt := v.Type(); tt != tfunc {
2433 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2435 i = v.Call([]Value{ValueOf(19)})[0].Int()
2437 t.Errorf("Interface MethodByName returned %d; want 475", i)
2441 func TestMethodValue(t *testing.T) {
2445 // Curried method of value.
2446 tfunc := TypeOf((func(int) int)(nil))
2447 v := ValueOf(p).Method(1)
2448 if tt := v.Type(); tt != tfunc {
2449 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
2451 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
2453 t.Errorf("Value Method returned %d; want 250", i)
2455 v = ValueOf(p).MethodByName("Dist")
2456 if tt := v.Type(); tt != tfunc {
2457 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2459 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2461 t.Errorf("Value MethodByName returned %d; want 275", i)
2463 v = ValueOf(p).MethodByName("NoArgs")
2464 ValueOf(v.Interface()).Call(nil)
2465 v.Interface().(func())()
2467 // Curried method of pointer.
2468 v = ValueOf(&p).Method(1)
2469 if tt := v.Type(); tt != tfunc {
2470 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2472 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2474 t.Errorf("Pointer Value Method returned %d; want 300", i)
2476 v = ValueOf(&p).MethodByName("Dist")
2477 if tt := v.Type(); tt != tfunc {
2478 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2480 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2482 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2484 v = ValueOf(&p).MethodByName("NoArgs")
2485 ValueOf(v.Interface()).Call(nil)
2486 v.Interface().(func())()
2488 // Curried method of pointer to pointer.
2490 v = ValueOf(&pp).Elem().Method(1)
2491 if tt := v.Type(); tt != tfunc {
2492 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2494 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2496 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2498 v = ValueOf(&pp).Elem().MethodByName("Dist")
2499 if tt := v.Type(); tt != tfunc {
2500 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2502 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2504 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2507 // Curried method of interface value.
2508 // Have to wrap interface value in a struct to get at it.
2509 // Passing it to ValueOf directly would
2510 // access the underlying Point, not the interface.
2516 pv := ValueOf(s).Field(0)
2518 if tt := v.Type(); tt != tfunc {
2519 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2521 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2523 t.Errorf("Interface Method returned %d; want 400", i)
2525 v = pv.MethodByName("Dist")
2526 if tt := v.Type(); tt != tfunc {
2527 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2529 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2531 t.Errorf("Interface MethodByName returned %d; want 425", i)
2534 // For issue #33628: method args are not stored at the right offset
2536 m64 := ValueOf(&p).MethodByName("Int64Method").Interface().(func(int64) int64)
2537 if x := m64(123); x != 123 {
2538 t.Errorf("Int64Method returned %d; want 123", x)
2540 m32 := ValueOf(&p).MethodByName("Int32Method").Interface().(func(int32) int32)
2541 if x := m32(456); x != 456 {
2542 t.Errorf("Int32Method returned %d; want 456", x)
2546 func TestVariadicMethodValue(t *testing.T) {
2548 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2549 want := int64(p.TotalDist(points[0], points[1], points[2]))
2551 // Variadic method of type.
2552 tfunc := TypeOf((func(Point, ...Point) int)(nil))
2553 if tt := TypeOf(p).Method(4).Type; tt != tfunc {
2554 t.Errorf("Variadic Method Type from TypeOf is %s; want %s", tt, tfunc)
2557 // Curried method of value.
2558 tfunc = TypeOf((func(...Point) int)(nil))
2559 v := ValueOf(p).Method(4)
2560 if tt := v.Type(); tt != tfunc {
2561 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2563 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2565 t.Errorf("Variadic Method returned %d; want %d", i, want)
2567 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2569 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2572 f := v.Interface().(func(...Point) int)
2573 i = int64(f(points[0], points[1], points[2]))
2575 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2577 i = int64(f(points...))
2579 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2583 type DirectIfaceT struct {
2587 func (d DirectIfaceT) M() int { return *d.p }
2589 func TestDirectIfaceMethod(t *testing.T) {
2591 v := DirectIfaceT{&x}
2593 m, ok := typ.MethodByName("M")
2595 t.Fatalf("cannot find method M")
2597 in := []Value{ValueOf(v)}
2598 out := m.Func.Call(in)
2599 if got := out[0].Int(); got != 42 {
2600 t.Errorf("Call with value receiver got %d, want 42", got)
2605 m, ok = typ.MethodByName("M")
2607 t.Fatalf("cannot find method M")
2609 in = []Value{ValueOf(pv)}
2610 out = m.Func.Call(in)
2611 if got := out[0].Int(); got != 42 {
2612 t.Errorf("Call with pointer receiver got %d, want 42", got)
2616 // Reflect version of $GOROOT/test/method5.go
2618 // Concrete types implementing M method.
2619 // Smaller than a word, word-sized, larger than a word.
2620 // Value and pointer receivers.
2622 type Tinter interface {
2623 M(int, byte) (byte, int)
2628 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2632 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2636 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2640 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2642 type Tbigv [2]uintptr
2644 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2646 type Tbigp [2]uintptr
2648 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2650 type tinter interface {
2651 m(int, byte) (byte, int)
2654 // Embedding via pointer.
2671 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2673 func TestMethod5(t *testing.T) {
2674 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2676 if b != 99 || x != 1000+inc {
2677 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2681 CheckV := func(name string, i Value, inc int) {
2682 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2683 b := bx[0].Interface()
2684 x := bx[1].Interface()
2685 if b != byte(99) || x != 1000+inc {
2686 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2689 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2692 var TinterType = TypeOf(new(Tinter)).Elem()
2694 CheckI := func(name string, i interface{}, inc int) {
2696 CheckV(name, v, inc)
2697 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2702 CheckI("&sv", &sv, 1)
2705 CheckI("&sp", &sp, 2)
2709 CheckI("&wv", &wv, 3)
2712 CheckI("&wp", &wp, 4)
2714 bv := Tbigv([2]uintptr{5, 6})
2715 CheckI("bv", bv, 11)
2716 CheckI("&bv", &bv, 11)
2718 bp := Tbigp([2]uintptr{7, 8})
2719 CheckI("&bp", &bp, 15)
2725 CheckI("t4", t4, 40)
2726 CheckI("&t4", &t4, 40)
2727 CheckI("t3", t3, 40)
2728 CheckI("&t3", &t3, 40)
2729 CheckI("t2", t2, 40)
2730 CheckI("&t2", &t2, 40)
2731 CheckI("t1", t1, 40)
2732 CheckI("&t1", &t1, 40)
2735 vnil := ValueOf(&tnil).Elem()
2736 shouldPanic("Method", func() { vnil.Method(0) })
2739 func TestInterfaceSet(t *testing.T) {
2748 sv := ValueOf(&s).Elem()
2749 sv.Field(0).Set(ValueOf(p))
2750 if q := s.I.(*Point); q != p {
2751 t.Errorf("i: have %p want %p", q, p)
2756 if q := s.P.(*Point); q != p {
2757 t.Errorf("i: have %p want %p", q, p)
2760 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2762 t.Errorf("Interface Method returned %d; want 250", i)
2771 func TestAnonymousFields(t *testing.T) {
2772 var field StructField
2776 if field, ok = type1.FieldByName("int"); !ok {
2777 t.Fatal("no field 'int'")
2779 if field.Index[0] != 1 {
2780 t.Error("field index should be 1; is", field.Index)
2834 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2856 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2875 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2889 var fieldTests = []FTest{
2890 {struct{}{}, "", nil, 0},
2891 {struct{}{}, "Foo", nil, 0},
2892 {S0{A: 'a'}, "A", []int{0}, 'a'},
2893 {S0{}, "D", nil, 0},
2894 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2895 {S1{B: 'b'}, "B", []int{0}, 'b'},
2896 {S1{}, "S0", []int{1}, 0},
2897 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2898 {S2{A: 'a'}, "A", []int{0}, 'a'},
2899 {S2{}, "S1", []int{1}, 0},
2900 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2901 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2902 {S2{}, "D", nil, 0},
2903 {S3{}, "S1", nil, 0},
2904 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2905 {S3{}, "B", nil, 0},
2906 {S3{D: 'd'}, "D", []int{2}, 0},
2907 {S3{E: 'e'}, "E", []int{3}, 'e'},
2908 {S4{A: 'a'}, "A", []int{1}, 'a'},
2909 {S4{}, "B", nil, 0},
2910 {S5{}, "X", nil, 0},
2911 {S5{}, "Y", []int{2, 0, 1}, 0},
2912 {S10{}, "X", nil, 0},
2913 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2914 {S14{}, "X", nil, 0},
2917 func TestFieldByIndex(t *testing.T) {
2918 for _, test := range fieldTests {
2920 f := s.FieldByIndex(test.index)
2922 if test.index != nil {
2923 if f.Name != test.name {
2924 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2927 t.Errorf("%s.%s found", s.Name(), f.Name)
2929 } else if len(test.index) > 0 {
2930 t.Errorf("%s.%s not found", s.Name(), test.name)
2933 if test.value != 0 {
2934 v := ValueOf(test.s).FieldByIndex(test.index)
2936 if x, ok := v.Interface().(int); ok {
2937 if x != test.value {
2938 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2941 t.Errorf("%s%v value not an int", s.Name(), test.index)
2944 t.Errorf("%s%v value not found", s.Name(), test.index)
2950 func TestFieldByName(t *testing.T) {
2951 for _, test := range fieldTests {
2953 f, found := s.FieldByName(test.name)
2955 if test.index != nil {
2956 // Verify field depth and index.
2957 if len(f.Index) != len(test.index) {
2958 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)
2960 for i, x := range f.Index {
2961 if x != test.index[i] {
2962 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2967 t.Errorf("%s.%s found", s.Name(), f.Name)
2969 } else if len(test.index) > 0 {
2970 t.Errorf("%s.%s not found", s.Name(), test.name)
2973 if test.value != 0 {
2974 v := ValueOf(test.s).FieldByName(test.name)
2976 if x, ok := v.Interface().(int); ok {
2977 if x != test.value {
2978 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2981 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2984 t.Errorf("%s.%s value not found", s.Name(), test.name)
2990 func TestImportPath(t *testing.T) {
2995 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2996 {TypeOf(int(0)), ""},
2997 {TypeOf(int8(0)), ""},
2998 {TypeOf(int16(0)), ""},
2999 {TypeOf(int32(0)), ""},
3000 {TypeOf(int64(0)), ""},
3001 {TypeOf(uint(0)), ""},
3002 {TypeOf(uint8(0)), ""},
3003 {TypeOf(uint16(0)), ""},
3004 {TypeOf(uint32(0)), ""},
3005 {TypeOf(uint64(0)), ""},
3006 {TypeOf(uintptr(0)), ""},
3007 {TypeOf(float32(0)), ""},
3008 {TypeOf(float64(0)), ""},
3009 {TypeOf(complex64(0)), ""},
3010 {TypeOf(complex128(0)), ""},
3011 {TypeOf(byte(0)), ""},
3012 {TypeOf(rune(0)), ""},
3013 {TypeOf([]byte(nil)), ""},
3014 {TypeOf([]rune(nil)), ""},
3015 {TypeOf(string("")), ""},
3016 {TypeOf((*interface{})(nil)).Elem(), ""},
3017 {TypeOf((*byte)(nil)), ""},
3018 {TypeOf((*rune)(nil)), ""},
3019 {TypeOf((*int64)(nil)), ""},
3020 {TypeOf(map[string]int{}), ""},
3021 {TypeOf((*error)(nil)).Elem(), ""},
3022 {TypeOf((*Point)(nil)), ""},
3023 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
3025 for _, test := range tests {
3026 if path := test.t.PkgPath(); path != test.path {
3027 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
3032 func TestFieldPkgPath(t *testing.T) {
3034 typ := TypeOf(struct {
3042 type pkgpathTest struct {
3049 checkPkgPath := func(name string, s []pkgpathTest) {
3050 for _, test := range s {
3051 f := typ.FieldByIndex(test.index)
3052 if got, want := f.PkgPath, test.pkgPath; got != want {
3053 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
3055 if got, want := f.Anonymous, test.embedded; got != want {
3056 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
3058 if got, want := f.IsExported(), test.exported; got != want {
3059 t.Errorf("%s: Field(%d).IsExported = %v, want %v", name, test.index, got, want)
3064 checkPkgPath("testStruct", []pkgpathTest{
3065 {[]int{0}, "", false, true}, // Exported
3066 {[]int{1}, "reflect_test", false, false}, // unexported
3067 {[]int{2}, "", true, true}, // OtherPkgFields
3068 {[]int{2, 0}, "", false, true}, // OtherExported
3069 {[]int{2, 1}, "reflect", false, false}, // otherUnexported
3070 {[]int{3}, "reflect_test", true, false}, // int
3071 {[]int{4}, "reflect_test", true, false}, // *x
3074 type localOtherPkgFields OtherPkgFields
3075 typ = TypeOf(localOtherPkgFields{})
3076 checkPkgPath("localOtherPkgFields", []pkgpathTest{
3077 {[]int{0}, "", false, true}, // OtherExported
3078 {[]int{1}, "reflect", false, false}, // otherUnexported
3082 func TestMethodPkgPath(t *testing.T) {
3087 typ := TypeOf((*interface {
3100 {"x", "reflect_test", false},
3101 {"y", "reflect_test", false},
3104 for _, test := range tests {
3105 m, _ := typ.MethodByName(test.name)
3106 if got, want := m.PkgPath, test.pkgPath; got != want {
3107 t.Errorf("MethodByName(%q).PkgPath = %q, want %q", test.name, got, want)
3109 if got, want := m.IsExported(), test.exported; got != want {
3110 t.Errorf("MethodByName(%q).IsExported = %v, want %v", test.name, got, want)
3115 func TestVariadicType(t *testing.T) {
3116 // Test example from Type documentation.
3117 var f func(x int, y ...float64)
3119 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
3121 if sl.Kind() == Slice {
3122 if sl.Elem() == TypeOf(0.0) {
3130 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
3131 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
3132 for i := 0; i < typ.NumIn(); i++ {
3133 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
3147 func (*inner) M() {}
3148 func (*outer) M() {}
3150 func TestNestedMethods(t *testing.T) {
3151 typ := TypeOf((*outer)(nil))
3152 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
3153 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
3154 for i := 0; i < typ.NumMethod(); i++ {
3156 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3163 func (*unexp) f() (int32, int8) { return 7, 7 }
3164 func (*unexp) g() (int64, int8) { return 8, 8 }
3166 type unexpI interface {
3170 var unexpi unexpI = new(unexp)
3172 func TestUnexportedMethods(t *testing.T) {
3173 typ := TypeOf(unexpi)
3175 if got := typ.NumMethod(); got != 0 {
3176 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
3180 type InnerInt struct {
3184 type OuterInt struct {
3189 func (i *InnerInt) M() int {
3193 func TestEmbeddedMethods(t *testing.T) {
3194 typ := TypeOf((*OuterInt)(nil))
3195 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
3196 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
3197 for i := 0; i < typ.NumMethod(); i++ {
3199 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
3204 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
3205 t.Errorf("i.M() = %d, want 3", v)
3208 o := &OuterInt{1, InnerInt{2}}
3209 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
3210 t.Errorf("i.M() = %d, want 2", v)
3214 if v := f(o); v != 2 {
3215 t.Errorf("f(o) = %d, want 2", v)
3219 type FuncDDD func(...interface{}) error
3221 func (f FuncDDD) M() {}
3223 func TestNumMethodOnDDD(t *testing.T) {
3224 rv := ValueOf((FuncDDD)(nil))
3225 if n := rv.NumMethod(); n != 1 {
3226 t.Fatalf("NumMethod()=%d, want 1", n)
3230 func TestPtrTo(t *testing.T) {
3231 // This block of code means that the ptrToThis field of the
3232 // reflect data for *unsafe.Pointer is non zero, see
3233 // https://golang.org/issue/19003
3234 var x unsafe.Pointer
3241 for i = 0; i < 100; i++ {
3244 for i = 0; i < 100; i++ {
3247 if typ != TypeOf(z) {
3248 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
3252 func TestPtrToGC(t *testing.T) {
3254 tt := TypeOf(T(nil))
3258 for i := 0; i < n; i++ {
3263 v.Elem().Set(ValueOf(p).Convert(pt))
3264 x = append(x, v.Interface())
3268 for i, xi := range x {
3269 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
3270 if k != uintptr(i) {
3271 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
3276 func BenchmarkPtrTo(b *testing.B) {
3277 // Construct a type with a zero ptrToThis.
3278 type T struct{ int }
3279 t := SliceOf(TypeOf(T{}))
3280 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
3281 if !ptrToThis.IsValid() {
3282 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
3284 if ptrToThis.Int() != 0 {
3285 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
3289 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
3291 b.RunParallel(func(pb *testing.PB) {
3298 func TestAddr(t *testing.T) {
3310 t.Errorf("Addr.Elem.Set failed to set value")
3313 // Again but take address of the ValueOf value.
3314 // Exercises generation of PtrTypes not present in the binary.
3316 v = ValueOf(&q).Elem()
3325 t.Errorf("Addr.Elem.Set failed to set value")
3328 // Starting without pointer we should get changed value
3331 v = ValueOf(&qq).Elem()
3337 if p.X != 3 { // should be unchanged from last time
3338 t.Errorf("somehow value Set changed original p")
3340 p = v0.Interface().(struct {
3344 t.Errorf("Addr.Elem.Set valued to set value in top value")
3347 // Verify that taking the address of a type gives us a pointer
3348 // which we can convert back using the usual interface
3353 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
3354 *(ps.(**bool)) = new(bool)
3356 t.Errorf("Addr.Interface direct assignment failed")
3360 func noAlloc(t *testing.T, n int, f func(int)) {
3361 if testing.Short() {
3362 t.Skip("skipping malloc count in short mode")
3364 if runtime.GOMAXPROCS(0) > 1 {
3365 t.Skip("skipping; GOMAXPROCS>1")
3368 allocs := testing.AllocsPerRun(n, func() {
3373 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
3377 func TestAllocations(t *testing.T) {
3378 noAlloc(t, 100, func(j int) {
3382 // We can uncomment this when compiler escape analysis
3383 // is good enough to see that the integer assigned to i
3384 // does not escape and therefore need not be allocated.
3388 // if int(v.Int()) != 42+j {
3389 // panic("wrong int")
3392 i = func(j int) int { return j }
3394 if v.Interface().(func(int) int)(j) != j {
3395 panic("wrong result")
3400 func TestSmallNegativeInt(t *testing.T) {
3404 t.Errorf("int16(-1).Int() returned %v", v.Int())
3408 func TestIndex(t *testing.T) {
3409 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
3410 v := ValueOf(xs).Index(3).Interface().(byte)
3412 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
3414 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
3415 v = ValueOf(xa).Index(2).Interface().(byte)
3417 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
3420 v = ValueOf(s).Index(3).Interface().(byte)
3422 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
3426 func TestSlice(t *testing.T) {
3427 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3428 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
3430 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
3433 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
3435 if !DeepEqual(v[0:5], xs[3:]) {
3436 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
3438 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3439 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
3441 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
3444 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
3446 if !DeepEqual(v[0:6], xa[2:]) {
3447 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
3450 vs := ValueOf(s).Slice(3, 5).Interface().(string)
3452 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
3455 rv := ValueOf(&xs).Elem()
3457 ptr2 := rv.Pointer()
3459 ptr3 := rv.Pointer()
3461 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
3465 func TestSlice3(t *testing.T) {
3466 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3467 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
3469 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
3472 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
3474 if !DeepEqual(v[0:4], xs[3:7:7]) {
3475 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
3477 rv := ValueOf(&xs).Elem()
3478 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3479 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3480 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3482 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3483 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
3485 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
3488 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
3490 if !DeepEqual(v[0:4], xa[2:6:6]) {
3491 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
3493 rv = ValueOf(&xa).Elem()
3494 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 1) })
3495 shouldPanic("Slice3", func() { rv.Slice3(1, 1, 11) })
3496 shouldPanic("Slice3", func() { rv.Slice3(2, 2, 1) })
3499 rv = ValueOf(&s).Elem()
3500 shouldPanic("Slice3", func() { rv.Slice3(1, 2, 3) })
3502 rv = ValueOf(&xs).Elem()
3503 rv = rv.Slice3(3, 5, 7)
3504 ptr2 := rv.Pointer()
3505 rv = rv.Slice3(4, 4, 4)
3506 ptr3 := rv.Pointer()
3508 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
3512 func TestSetLenCap(t *testing.T) {
3513 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
3514 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
3516 vs := ValueOf(&xs).Elem()
3517 shouldPanic("SetLen", func() { vs.SetLen(10) })
3518 shouldPanic("SetCap", func() { vs.SetCap(10) })
3519 shouldPanic("SetLen", func() { vs.SetLen(-1) })
3520 shouldPanic("SetCap", func() { vs.SetCap(-1) })
3521 shouldPanic("SetCap", func() { vs.SetCap(6) }) // smaller than len
3523 if len(xs) != 5 || cap(xs) != 8 {
3524 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
3527 if len(xs) != 5 || cap(xs) != 6 {
3528 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
3531 if len(xs) != 5 || cap(xs) != 5 {
3532 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3534 shouldPanic("SetCap", func() { vs.SetCap(4) }) // smaller than len
3535 shouldPanic("SetLen", func() { vs.SetLen(6) }) // bigger than cap
3537 va := ValueOf(&xa).Elem()
3538 shouldPanic("SetLen", func() { va.SetLen(8) })
3539 shouldPanic("SetCap", func() { va.SetCap(8) })
3542 func TestVariadic(t *testing.T) {
3547 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3548 if b.String() != "hello, 42 world" {
3549 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3553 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3554 if b.String() != "hello, 42 world" {
3555 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3559 func TestFuncArg(t *testing.T) {
3560 f1 := func(i int, f func(int) int) int { return f(i) }
3561 f2 := func(i int) int { return i + 1 }
3562 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3563 if r[0].Int() != 101 {
3564 t.Errorf("function returned %d, want 101", r[0].Int())
3568 func TestStructArg(t *testing.T) {
3569 type padded struct {
3576 wantA = padded{"3", 4}
3579 f := func(a padded, b uint32) {
3582 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3583 if gotA != wantA || gotB != wantB {
3584 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3588 var tagGetTests = []struct {
3593 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3594 {`protobuf:"PB(1,2)"`, `foo`, ``},
3595 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3596 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3597 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3598 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3599 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3602 func TestTagGet(t *testing.T) {
3603 for _, tt := range tagGetTests {
3604 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3605 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3610 func TestBytes(t *testing.T) {
3613 y := ValueOf(x).Bytes()
3614 if !bytes.Equal(x, y) {
3615 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3618 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3622 func TestSetBytes(t *testing.T) {
3625 y := []byte{1, 2, 3, 4}
3626 ValueOf(&x).Elem().SetBytes(y)
3627 if !bytes.Equal(x, y) {
3628 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3631 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3635 type Private struct {
3641 func (p *Private) m() {
3644 type private struct {
3652 func (p *private) P() {
3655 type Public struct {
3661 func (p *Public) M() {
3664 func TestUnexported(t *testing.T) {
3669 isValid(v.Elem().Field(0))
3670 isValid(v.Elem().Field(1))
3671 isValid(v.Elem().Field(2))
3672 isValid(v.Elem().FieldByName("X"))
3673 isValid(v.Elem().FieldByName("Y"))
3674 isValid(v.Elem().FieldByName("Z"))
3675 isValid(v.Type().Method(0).Func)
3676 m, _ := v.Type().MethodByName("M")
3678 m, _ = v.Type().MethodByName("P")
3680 isNonNil(v.Elem().Field(0).Interface())
3681 isNonNil(v.Elem().Field(1).Interface())
3682 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3683 isNonNil(v.Elem().FieldByName("X").Interface())
3684 isNonNil(v.Elem().FieldByName("Y").Interface())
3685 isNonNil(v.Elem().FieldByName("Z").Interface())
3686 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3687 isNonNil(v.Type().Method(0).Func.Interface())
3688 m, _ = v.Type().MethodByName("P")
3689 isNonNil(m.Func.Interface())
3693 isValid(v.Elem().Field(0))
3694 isValid(v.Elem().Field(1))
3695 isValid(v.Elem().FieldByName("x"))
3696 isValid(v.Elem().FieldByName("y"))
3697 shouldPanic("Interface", func() { v.Elem().Field(0).Interface() })
3698 shouldPanic("Interface", func() { v.Elem().Field(1).Interface() })
3699 shouldPanic("Interface", func() { v.Elem().FieldByName("x").Interface() })
3700 shouldPanic("Interface", func() { v.Elem().FieldByName("y").Interface() })
3701 shouldPanic("Method", func() { v.Type().Method(0) })
3704 func TestSetPanic(t *testing.T) {
3705 ok := func(f func()) { f() }
3706 bad := func(f func()) { shouldPanic("Set", f) }
3707 clear := func(v Value) { v.Set(Zero(v.Type())) }
3735 bad(func() { clear(v.Field(0)) }) // .X
3736 bad(func() { clear(v.Field(1)) }) // .t1
3737 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3738 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3739 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3740 bad(func() { clear(v.Field(2)) }) // .T2
3741 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3742 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3743 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3744 bad(func() { clear(v.Field(3)) }) // .NamedT1
3745 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3746 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3747 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3748 bad(func() { clear(v.Field(4)) }) // .NamedT2
3749 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3750 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3751 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3752 bad(func() { clear(v.Field(5)) }) // .namedT1
3753 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3754 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3755 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3756 bad(func() { clear(v.Field(6)) }) // .namedT2
3757 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3758 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3759 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3762 v = ValueOf(&T{}).Elem()
3763 ok(func() { clear(v.Field(0)) }) // .X
3764 bad(func() { clear(v.Field(1)) }) // .t1
3765 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3766 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3767 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3768 ok(func() { clear(v.Field(2)) }) // .T2
3769 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3770 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3771 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3772 ok(func() { clear(v.Field(3)) }) // .NamedT1
3773 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3774 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3775 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3776 ok(func() { clear(v.Field(4)) }) // .NamedT2
3777 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3778 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3779 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3780 bad(func() { clear(v.Field(5)) }) // .namedT1
3781 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3782 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3783 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3784 bad(func() { clear(v.Field(6)) }) // .namedT2
3785 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3786 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3787 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3792 func (t timp) W() {}
3793 func (t timp) Y() {}
3794 func (t timp) w() {}
3795 func (t timp) y() {}
3797 func TestCallPanic(t *testing.T) {
3822 ok := func(f func()) { f() }
3823 badCall := func(f func()) { shouldPanic("Call", f) }
3824 badMethod := func(f func()) { shouldPanic("Method", f) }
3825 call := func(v Value) { v.Call(nil) }
3828 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3829 badCall(func() { call(v.Field(0).Method(0)) }) // .t0.W
3830 badCall(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3831 badCall(func() { call(v.Field(0).Method(1)) }) // .t0.w
3832 badMethod(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3833 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3834 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3835 badCall(func() { call(v.Field(1).Method(1)) }) // .T1.y
3836 badMethod(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3838 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3839 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3840 badCall(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3841 badMethod(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3843 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3844 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3845 badCall(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3846 badMethod(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3848 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3849 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3850 badCall(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3851 badCall(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3853 badCall(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3854 badCall(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3855 badCall(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3856 badMethod(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3858 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3859 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3860 badCall(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3861 badCall(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3863 badCall(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3864 badCall(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3865 badCall(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3866 badCall(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3869 func shouldPanic(expect string, f func()) {
3873 panic("did not panic")
3877 switch r := r.(type) {
3883 panic(fmt.Sprintf("panicked with unexpected type %T", r))
3885 if !strings.HasPrefix(s, "reflect") {
3886 panic(`panic string does not start with "reflect": ` + s)
3888 if !strings.Contains(s, expect) {
3889 panic(`panic string does not contain "` + expect + `": ` + s)
3896 func isNonNil(x interface{}) {
3898 panic("nil interface")
3902 func isValid(v Value) {
3908 func TestAlias(t *testing.T) {
3909 x := string("hello")
3910 v := ValueOf(&x).Elem()
3911 oldvalue := v.Interface()
3912 v.SetString("world")
3913 newvalue := v.Interface()
3915 if oldvalue != "hello" || newvalue != "world" {
3916 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3922 func EmptyInterfaceV(x interface{}) Value {
3923 return ValueOf(&x).Elem()
3926 func ReaderV(x io.Reader) Value {
3927 return ValueOf(&x).Elem()
3930 func ReadWriterV(x io.ReadWriter) Value {
3931 return ValueOf(&x).Elem()
3935 type MyStruct struct {
3938 type MyStruct1 struct {
3943 type MyStruct2 struct {
3948 type MyString string
3950 type MyBytesArrayPtr0 *[0]byte
3951 type MyBytesArrayPtr *[4]byte
3952 type MyBytesArray0 [0]byte
3953 type MyBytesArray [4]byte
3954 type MyRunes []int32
3958 type IntChan chan int
3959 type IntChanRecv <-chan int
3960 type IntChanSend chan<- int
3961 type BytesChan chan []byte
3962 type BytesChanRecv <-chan []byte
3963 type BytesChanSend chan<- []byte
3965 var convertTests = []struct {
3971 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3977 var numbers = []string{
3978 "int8", "uint8", "int16", "uint16",
3979 "int32", "uint32", "int64", "uint64",
3980 "int", "uint", "uintptr",
3981 "float32", "float64",
3985 // all pairs but in an unusual order,
3986 // to emit all the int8, uint8 cases
3987 // before n grows too big.
3989 for i, f := range numbers {
3990 for _, g := range numbers[i:] {
3991 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3994 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
4001 {V(int8(1)), V(int8(1))},
4002 {V(int8(2)), V(uint8(2))},
4003 {V(uint8(3)), V(int8(3))},
4004 {V(int8(4)), V(int16(4))},
4005 {V(int16(5)), V(int8(5))},
4006 {V(int8(6)), V(uint16(6))},
4007 {V(uint16(7)), V(int8(7))},
4008 {V(int8(8)), V(int32(8))},
4009 {V(int32(9)), V(int8(9))},
4010 {V(int8(10)), V(uint32(10))},
4011 {V(uint32(11)), V(int8(11))},
4012 {V(int8(12)), V(int64(12))},
4013 {V(int64(13)), V(int8(13))},
4014 {V(int8(14)), V(uint64(14))},
4015 {V(uint64(15)), V(int8(15))},
4016 {V(int8(16)), V(int(16))},
4017 {V(int(17)), V(int8(17))},
4018 {V(int8(18)), V(uint(18))},
4019 {V(uint(19)), V(int8(19))},
4020 {V(int8(20)), V(uintptr(20))},
4021 {V(uintptr(21)), V(int8(21))},
4022 {V(int8(22)), V(float32(22))},
4023 {V(float32(23)), V(int8(23))},
4024 {V(int8(24)), V(float64(24))},
4025 {V(float64(25)), V(int8(25))},
4026 {V(uint8(26)), V(uint8(26))},
4027 {V(uint8(27)), V(int16(27))},
4028 {V(int16(28)), V(uint8(28))},
4029 {V(uint8(29)), V(uint16(29))},
4030 {V(uint16(30)), V(uint8(30))},
4031 {V(uint8(31)), V(int32(31))},
4032 {V(int32(32)), V(uint8(32))},
4033 {V(uint8(33)), V(uint32(33))},
4034 {V(uint32(34)), V(uint8(34))},
4035 {V(uint8(35)), V(int64(35))},
4036 {V(int64(36)), V(uint8(36))},
4037 {V(uint8(37)), V(uint64(37))},
4038 {V(uint64(38)), V(uint8(38))},
4039 {V(uint8(39)), V(int(39))},
4040 {V(int(40)), V(uint8(40))},
4041 {V(uint8(41)), V(uint(41))},
4042 {V(uint(42)), V(uint8(42))},
4043 {V(uint8(43)), V(uintptr(43))},
4044 {V(uintptr(44)), V(uint8(44))},
4045 {V(uint8(45)), V(float32(45))},
4046 {V(float32(46)), V(uint8(46))},
4047 {V(uint8(47)), V(float64(47))},
4048 {V(float64(48)), V(uint8(48))},
4049 {V(int16(49)), V(int16(49))},
4050 {V(int16(50)), V(uint16(50))},
4051 {V(uint16(51)), V(int16(51))},
4052 {V(int16(52)), V(int32(52))},
4053 {V(int32(53)), V(int16(53))},
4054 {V(int16(54)), V(uint32(54))},
4055 {V(uint32(55)), V(int16(55))},
4056 {V(int16(56)), V(int64(56))},
4057 {V(int64(57)), V(int16(57))},
4058 {V(int16(58)), V(uint64(58))},
4059 {V(uint64(59)), V(int16(59))},
4060 {V(int16(60)), V(int(60))},
4061 {V(int(61)), V(int16(61))},
4062 {V(int16(62)), V(uint(62))},
4063 {V(uint(63)), V(int16(63))},
4064 {V(int16(64)), V(uintptr(64))},
4065 {V(uintptr(65)), V(int16(65))},
4066 {V(int16(66)), V(float32(66))},
4067 {V(float32(67)), V(int16(67))},
4068 {V(int16(68)), V(float64(68))},
4069 {V(float64(69)), V(int16(69))},
4070 {V(uint16(70)), V(uint16(70))},
4071 {V(uint16(71)), V(int32(71))},
4072 {V(int32(72)), V(uint16(72))},
4073 {V(uint16(73)), V(uint32(73))},
4074 {V(uint32(74)), V(uint16(74))},
4075 {V(uint16(75)), V(int64(75))},
4076 {V(int64(76)), V(uint16(76))},
4077 {V(uint16(77)), V(uint64(77))},
4078 {V(uint64(78)), V(uint16(78))},
4079 {V(uint16(79)), V(int(79))},
4080 {V(int(80)), V(uint16(80))},
4081 {V(uint16(81)), V(uint(81))},
4082 {V(uint(82)), V(uint16(82))},
4083 {V(uint16(83)), V(uintptr(83))},
4084 {V(uintptr(84)), V(uint16(84))},
4085 {V(uint16(85)), V(float32(85))},
4086 {V(float32(86)), V(uint16(86))},
4087 {V(uint16(87)), V(float64(87))},
4088 {V(float64(88)), V(uint16(88))},
4089 {V(int32(89)), V(int32(89))},
4090 {V(int32(90)), V(uint32(90))},
4091 {V(uint32(91)), V(int32(91))},
4092 {V(int32(92)), V(int64(92))},
4093 {V(int64(93)), V(int32(93))},
4094 {V(int32(94)), V(uint64(94))},
4095 {V(uint64(95)), V(int32(95))},
4096 {V(int32(96)), V(int(96))},
4097 {V(int(97)), V(int32(97))},
4098 {V(int32(98)), V(uint(98))},
4099 {V(uint(99)), V(int32(99))},
4100 {V(int32(100)), V(uintptr(100))},
4101 {V(uintptr(101)), V(int32(101))},
4102 {V(int32(102)), V(float32(102))},
4103 {V(float32(103)), V(int32(103))},
4104 {V(int32(104)), V(float64(104))},
4105 {V(float64(105)), V(int32(105))},
4106 {V(uint32(106)), V(uint32(106))},
4107 {V(uint32(107)), V(int64(107))},
4108 {V(int64(108)), V(uint32(108))},
4109 {V(uint32(109)), V(uint64(109))},
4110 {V(uint64(110)), V(uint32(110))},
4111 {V(uint32(111)), V(int(111))},
4112 {V(int(112)), V(uint32(112))},
4113 {V(uint32(113)), V(uint(113))},
4114 {V(uint(114)), V(uint32(114))},
4115 {V(uint32(115)), V(uintptr(115))},
4116 {V(uintptr(116)), V(uint32(116))},
4117 {V(uint32(117)), V(float32(117))},
4118 {V(float32(118)), V(uint32(118))},
4119 {V(uint32(119)), V(float64(119))},
4120 {V(float64(120)), V(uint32(120))},
4121 {V(int64(121)), V(int64(121))},
4122 {V(int64(122)), V(uint64(122))},
4123 {V(uint64(123)), V(int64(123))},
4124 {V(int64(124)), V(int(124))},
4125 {V(int(125)), V(int64(125))},
4126 {V(int64(126)), V(uint(126))},
4127 {V(uint(127)), V(int64(127))},
4128 {V(int64(128)), V(uintptr(128))},
4129 {V(uintptr(129)), V(int64(129))},
4130 {V(int64(130)), V(float32(130))},
4131 {V(float32(131)), V(int64(131))},
4132 {V(int64(132)), V(float64(132))},
4133 {V(float64(133)), V(int64(133))},
4134 {V(uint64(134)), V(uint64(134))},
4135 {V(uint64(135)), V(int(135))},
4136 {V(int(136)), V(uint64(136))},
4137 {V(uint64(137)), V(uint(137))},
4138 {V(uint(138)), V(uint64(138))},
4139 {V(uint64(139)), V(uintptr(139))},
4140 {V(uintptr(140)), V(uint64(140))},
4141 {V(uint64(141)), V(float32(141))},
4142 {V(float32(142)), V(uint64(142))},
4143 {V(uint64(143)), V(float64(143))},
4144 {V(float64(144)), V(uint64(144))},
4145 {V(int(145)), V(int(145))},
4146 {V(int(146)), V(uint(146))},
4147 {V(uint(147)), V(int(147))},
4148 {V(int(148)), V(uintptr(148))},
4149 {V(uintptr(149)), V(int(149))},
4150 {V(int(150)), V(float32(150))},
4151 {V(float32(151)), V(int(151))},
4152 {V(int(152)), V(float64(152))},
4153 {V(float64(153)), V(int(153))},
4154 {V(uint(154)), V(uint(154))},
4155 {V(uint(155)), V(uintptr(155))},
4156 {V(uintptr(156)), V(uint(156))},
4157 {V(uint(157)), V(float32(157))},
4158 {V(float32(158)), V(uint(158))},
4159 {V(uint(159)), V(float64(159))},
4160 {V(float64(160)), V(uint(160))},
4161 {V(uintptr(161)), V(uintptr(161))},
4162 {V(uintptr(162)), V(float32(162))},
4163 {V(float32(163)), V(uintptr(163))},
4164 {V(uintptr(164)), V(float64(164))},
4165 {V(float64(165)), V(uintptr(165))},
4166 {V(float32(166)), V(float32(166))},
4167 {V(float32(167)), V(float64(167))},
4168 {V(float64(168)), V(float32(168))},
4169 {V(float64(169)), V(float64(169))},
4172 {V(float64(1.5)), V(int(1))},
4175 {V(complex64(1i)), V(complex64(1i))},
4176 {V(complex64(2i)), V(complex128(2i))},
4177 {V(complex128(3i)), V(complex64(3i))},
4178 {V(complex128(4i)), V(complex128(4i))},
4181 {V(string("hello")), V(string("hello"))},
4182 {V(string("bytes1")), V([]byte("bytes1"))},
4183 {V([]byte("bytes2")), V(string("bytes2"))},
4184 {V([]byte("bytes3")), V([]byte("bytes3"))},
4185 {V(string("runes♝")), V([]rune("runes♝"))},
4186 {V([]rune("runes♕")), V(string("runes♕"))},
4187 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4188 {V(int('a')), V(string("a"))},
4189 {V(int8('a')), V(string("a"))},
4190 {V(int16('a')), V(string("a"))},
4191 {V(int32('a')), V(string("a"))},
4192 {V(int64('a')), V(string("a"))},
4193 {V(uint('a')), V(string("a"))},
4194 {V(uint8('a')), V(string("a"))},
4195 {V(uint16('a')), V(string("a"))},
4196 {V(uint32('a')), V(string("a"))},
4197 {V(uint64('a')), V(string("a"))},
4198 {V(uintptr('a')), V(string("a"))},
4199 {V(int(-1)), V(string("\uFFFD"))},
4200 {V(int8(-2)), V(string("\uFFFD"))},
4201 {V(int16(-3)), V(string("\uFFFD"))},
4202 {V(int32(-4)), V(string("\uFFFD"))},
4203 {V(int64(-5)), V(string("\uFFFD"))},
4204 {V(int64(-1 << 32)), V(string("\uFFFD"))},
4205 {V(int64(1 << 32)), V(string("\uFFFD"))},
4206 {V(uint(0x110001)), V(string("\uFFFD"))},
4207 {V(uint32(0x110002)), V(string("\uFFFD"))},
4208 {V(uint64(0x110003)), V(string("\uFFFD"))},
4209 {V(uint64(1 << 32)), V(string("\uFFFD"))},
4210 {V(uintptr(0x110004)), V(string("\uFFFD"))},
4213 {V(MyString("hello")), V(string("hello"))},
4214 {V(string("hello")), V(MyString("hello"))},
4215 {V(string("hello")), V(string("hello"))},
4216 {V(MyString("hello")), V(MyString("hello"))},
4217 {V(MyString("bytes1")), V([]byte("bytes1"))},
4218 {V([]byte("bytes2")), V(MyString("bytes2"))},
4219 {V([]byte("bytes3")), V([]byte("bytes3"))},
4220 {V(MyString("runes♝")), V([]rune("runes♝"))},
4221 {V([]rune("runes♕")), V(MyString("runes♕"))},
4222 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4223 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4224 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
4225 {V(int('a')), V(MyString("a"))},
4226 {V(int8('a')), V(MyString("a"))},
4227 {V(int16('a')), V(MyString("a"))},
4228 {V(int32('a')), V(MyString("a"))},
4229 {V(int64('a')), V(MyString("a"))},
4230 {V(uint('a')), V(MyString("a"))},
4231 {V(uint8('a')), V(MyString("a"))},
4232 {V(uint16('a')), V(MyString("a"))},
4233 {V(uint32('a')), V(MyString("a"))},
4234 {V(uint64('a')), V(MyString("a"))},
4235 {V(uintptr('a')), V(MyString("a"))},
4236 {V(int(-1)), V(MyString("\uFFFD"))},
4237 {V(int8(-2)), V(MyString("\uFFFD"))},
4238 {V(int16(-3)), V(MyString("\uFFFD"))},
4239 {V(int32(-4)), V(MyString("\uFFFD"))},
4240 {V(int64(-5)), V(MyString("\uFFFD"))},
4241 {V(uint(0x110001)), V(MyString("\uFFFD"))},
4242 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
4243 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
4244 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
4247 {V(string("bytes1")), V(MyBytes("bytes1"))},
4248 {V(MyBytes("bytes2")), V(string("bytes2"))},
4249 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
4250 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
4251 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
4254 {V(string("runes♝")), V(MyRunes("runes♝"))},
4255 {V(MyRunes("runes♕")), V(string("runes♕"))},
4256 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
4257 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
4258 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
4260 // slice to array pointer
4261 {V([]byte(nil)), V((*[0]byte)(nil))},
4262 {V([]byte{}), V(new([0]byte))},
4263 {V([]byte{7}), V(&[1]byte{7})},
4264 {V(MyBytes([]byte(nil))), V((*[0]byte)(nil))},
4265 {V(MyBytes([]byte{})), V(new([0]byte))},
4266 {V(MyBytes([]byte{9})), V(&[1]byte{9})},
4267 {V([]byte(nil)), V(MyBytesArrayPtr0(nil))},
4268 {V([]byte{}), V(MyBytesArrayPtr0(new([0]byte)))},
4269 {V([]byte{1, 2, 3, 4}), V(MyBytesArrayPtr(&[4]byte{1, 2, 3, 4}))},
4270 {V(MyBytes([]byte{})), V(MyBytesArrayPtr0(new([0]byte)))},
4271 {V(MyBytes([]byte{5, 6, 7, 8})), V(MyBytesArrayPtr(&[4]byte{5, 6, 7, 8}))},
4273 {V([]byte(nil)), V((*MyBytesArray0)(nil))},
4274 {V([]byte{}), V((*MyBytesArray0)(new([0]byte)))},
4275 {V([]byte{1, 2, 3, 4}), V(&MyBytesArray{1, 2, 3, 4})},
4276 {V(MyBytes([]byte(nil))), V((*MyBytesArray0)(nil))},
4277 {V(MyBytes([]byte{})), V((*MyBytesArray0)(new([0]byte)))},
4278 {V(MyBytes([]byte{5, 6, 7, 8})), V(&MyBytesArray{5, 6, 7, 8})},
4279 {V(new([0]byte)), V(new(MyBytesArray0))},
4280 {V(new(MyBytesArray0)), V(new([0]byte))},
4281 {V(MyBytesArrayPtr0(nil)), V((*[0]byte)(nil))},
4282 {V((*[0]byte)(nil)), V(MyBytesArrayPtr0(nil))},
4284 // named types and equal underlying types
4285 {V(new(int)), V(new(integer))},
4286 {V(new(integer)), V(new(int))},
4287 {V(Empty{}), V(struct{}{})},
4288 {V(new(Empty)), V(new(struct{}))},
4289 {V(struct{}{}), V(Empty{})},
4290 {V(new(struct{})), V(new(Empty))},
4291 {V(Empty{}), V(Empty{})},
4292 {V(MyBytes{}), V([]byte{})},
4293 {V([]byte{}), V(MyBytes{})},
4294 {V((func())(nil)), V(MyFunc(nil))},
4295 {V((MyFunc)(nil)), V((func())(nil))},
4297 // structs with different tags
4310 {V(MyStruct{}), V(struct {
4316 }{}), V(MyStruct{})},
4318 {V(MyStruct{}), V(struct {
4324 }{}), V(MyStruct{})},
4326 {V(MyStruct1{}), V(MyStruct2{})},
4327 {V(MyStruct2{}), V(MyStruct1{})},
4329 // can convert *byte and *MyByte
4330 {V((*byte)(nil)), V((*MyByte)(nil))},
4331 {V((*MyByte)(nil)), V((*byte)(nil))},
4333 // cannot convert mismatched array sizes
4334 {V([2]byte{}), V([2]byte{})},
4335 {V([3]byte{}), V([3]byte{})},
4337 // cannot convert other instances
4338 {V((**byte)(nil)), V((**byte)(nil))},
4339 {V((**MyByte)(nil)), V((**MyByte)(nil))},
4340 {V((chan byte)(nil)), V((chan byte)(nil))},
4341 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4342 {V(([]byte)(nil)), V(([]byte)(nil))},
4343 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
4344 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4345 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
4346 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
4347 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
4348 {V([2]byte{}), V([2]byte{})},
4349 {V([2]MyByte{}), V([2]MyByte{})},
4352 {V((***int)(nil)), V((***int)(nil))},
4353 {V((***byte)(nil)), V((***byte)(nil))},
4354 {V((***int32)(nil)), V((***int32)(nil))},
4355 {V((***int64)(nil)), V((***int64)(nil))},
4356 {V((chan byte)(nil)), V((chan byte)(nil))},
4357 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
4358 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
4359 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
4360 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
4361 {V([]uint(nil)), V([]uint(nil))},
4362 {V([]int(nil)), V([]int(nil))},
4363 {V(new(interface{})), V(new(interface{}))},
4364 {V(new(io.Reader)), V(new(io.Reader))},
4365 {V(new(io.Writer)), V(new(io.Writer))},
4368 {V(IntChan(nil)), V((chan<- int)(nil))},
4369 {V(IntChan(nil)), V((<-chan int)(nil))},
4370 {V((chan int)(nil)), V(IntChanRecv(nil))},
4371 {V((chan int)(nil)), V(IntChanSend(nil))},
4372 {V(IntChanRecv(nil)), V((<-chan int)(nil))},
4373 {V((<-chan int)(nil)), V(IntChanRecv(nil))},
4374 {V(IntChanSend(nil)), V((chan<- int)(nil))},
4375 {V((chan<- int)(nil)), V(IntChanSend(nil))},
4376 {V(IntChan(nil)), V((chan int)(nil))},
4377 {V((chan int)(nil)), V(IntChan(nil))},
4378 {V((chan int)(nil)), V((<-chan int)(nil))},
4379 {V((chan int)(nil)), V((chan<- int)(nil))},
4380 {V(BytesChan(nil)), V((chan<- []byte)(nil))},
4381 {V(BytesChan(nil)), V((<-chan []byte)(nil))},
4382 {V((chan []byte)(nil)), V(BytesChanRecv(nil))},
4383 {V((chan []byte)(nil)), V(BytesChanSend(nil))},
4384 {V(BytesChanRecv(nil)), V((<-chan []byte)(nil))},
4385 {V((<-chan []byte)(nil)), V(BytesChanRecv(nil))},
4386 {V(BytesChanSend(nil)), V((chan<- []byte)(nil))},
4387 {V((chan<- []byte)(nil)), V(BytesChanSend(nil))},
4388 {V(BytesChan(nil)), V((chan []byte)(nil))},
4389 {V((chan []byte)(nil)), V(BytesChan(nil))},
4390 {V((chan []byte)(nil)), V((<-chan []byte)(nil))},
4391 {V((chan []byte)(nil)), V((chan<- []byte)(nil))},
4393 // cannot convert other instances (channels)
4394 {V(IntChan(nil)), V(IntChan(nil))},
4395 {V(IntChanRecv(nil)), V(IntChanRecv(nil))},
4396 {V(IntChanSend(nil)), V(IntChanSend(nil))},
4397 {V(BytesChan(nil)), V(BytesChan(nil))},
4398 {V(BytesChanRecv(nil)), V(BytesChanRecv(nil))},
4399 {V(BytesChanSend(nil)), V(BytesChanSend(nil))},
4402 {V(int(1)), EmptyInterfaceV(int(1))},
4403 {V(string("hello")), EmptyInterfaceV(string("hello"))},
4404 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4405 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
4406 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
4409 func TestConvert(t *testing.T) {
4410 canConvert := map[[2]Type]bool{}
4411 all := map[Type]bool{}
4413 for _, tt := range convertTests {
4415 if !t1.ConvertibleTo(t1) {
4416 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
4421 if !t1.ConvertibleTo(t2) {
4422 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
4428 canConvert[[2]Type{t1, t2}] = true
4430 // vout1 represents the in value converted to the in type.
4432 if !v1.CanConvert(t1) {
4433 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t1)
4435 vout1 := v1.Convert(t1)
4436 out1 := vout1.Interface()
4437 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
4438 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
4441 // vout2 represents the in value converted to the out type.
4442 if !v1.CanConvert(t2) {
4443 t.Errorf("ValueOf(%T(%[1]v)).CanConvert(%s) = false, want true", tt.in.Interface(), t2)
4445 vout2 := v1.Convert(t2)
4446 out2 := vout2.Interface()
4447 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
4448 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
4450 if got, want := vout2.Kind(), vout2.Type().Kind(); got != want {
4451 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) has internal kind %v want %v", tt.in.Interface(), t1, got, want)
4454 // vout3 represents a new value of the out type, set to vout2. This makes
4455 // sure the converted value vout2 is really usable as a regular value.
4456 vout3 := New(t2).Elem()
4458 out3 := vout3.Interface()
4459 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
4460 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
4464 t.Errorf("table entry %v is RO, should not be", v1)
4467 t.Errorf("self-conversion output %v is RO, should not be", vout1)
4470 t.Errorf("conversion output %v is RO, should not be", vout2)
4473 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
4475 if !IsRO(MakeRO(v1).Convert(t1)) {
4476 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
4478 if !IsRO(MakeRO(v1).Convert(t2)) {
4479 t.Errorf("RO conversion output %v is not RO, should be", v1)
4483 // Assume that of all the types we saw during the tests,
4484 // if there wasn't an explicit entry for a conversion between
4485 // a pair of types, then it's not to be allowed. This checks for
4486 // things like 'int64' converting to '*int'.
4487 for t1 := range all {
4488 for t2 := range all {
4489 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
4490 if ok := t1.ConvertibleTo(t2); ok != expectOK {
4491 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
4497 func TestConvertPanic(t *testing.T) {
4498 s := make([]byte, 4)
4502 if !v.Type().ConvertibleTo(pt) {
4503 t.Errorf("[]byte should be convertible to *[8]byte")
4505 if v.CanConvert(pt) {
4506 t.Errorf("slice with length 4 should not be convertible to *[8]byte")
4508 shouldPanic("reflect: cannot convert slice with length 4 to pointer to array with length 8", func() {
4513 var gFloat32 float32
4515 const snan uint32 = 0x7f800001
4517 func TestConvertNaNs(t *testing.T) {
4518 // Test to see if a store followed by a load of a signaling NaN
4519 // maintains the signaling bit. (This used to fail on the 387 port.)
4520 gFloat32 = math.Float32frombits(snan)
4521 runtime.Gosched() // make sure we don't optimize the store/load away
4522 if got := math.Float32bits(gFloat32); got != snan {
4523 t.Errorf("store/load of sNaN not faithful, got %x want %x", got, snan)
4525 // Test reflect's conversion between float32s. See issue 36400.
4526 type myFloat32 float32
4527 x := V(myFloat32(math.Float32frombits(snan)))
4528 y := x.Convert(TypeOf(float32(0)))
4529 z := y.Interface().(float32)
4530 if got := math.Float32bits(z); got != snan {
4531 t.Errorf("signaling nan conversion got %x, want %x", got, snan)
4535 type ComparableStruct struct {
4539 type NonComparableStruct struct {
4544 var comparableTests = []struct {
4549 {TypeOf("hello"), true},
4550 {TypeOf(new(byte)), true},
4551 {TypeOf((func())(nil)), false},
4552 {TypeOf([]byte{}), false},
4553 {TypeOf(map[string]int{}), false},
4554 {TypeOf(make(chan int)), true},
4555 {TypeOf(1.5), true},
4556 {TypeOf(false), true},
4558 {TypeOf(ComparableStruct{}), true},
4559 {TypeOf(NonComparableStruct{}), false},
4560 {TypeOf([10]map[string]int{}), false},
4561 {TypeOf([10]string{}), true},
4562 {TypeOf(new(interface{})).Elem(), true},
4565 func TestComparable(t *testing.T) {
4566 for _, tt := range comparableTests {
4567 if ok := tt.typ.Comparable(); ok != tt.ok {
4568 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
4573 func TestOverflow(t *testing.T) {
4574 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
4575 t.Errorf("%v wrongly overflows float64", 1e300)
4578 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
4579 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
4580 t.Errorf("%v wrongly overflows float32", maxFloat32)
4582 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
4583 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
4584 t.Errorf("%v should overflow float32", ovfFloat32)
4586 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
4587 t.Errorf("%v should overflow float32", -ovfFloat32)
4590 maxInt32 := int64(0x7fffffff)
4591 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
4592 t.Errorf("%v wrongly overflows int32", maxInt32)
4594 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
4595 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
4597 ovfInt32 := int64(1 << 31)
4598 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
4599 t.Errorf("%v should overflow int32", ovfInt32)
4602 maxUint32 := uint64(0xffffffff)
4603 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
4604 t.Errorf("%v wrongly overflows uint32", maxUint32)
4606 ovfUint32 := uint64(1 << 32)
4607 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
4608 t.Errorf("%v should overflow uint32", ovfUint32)
4612 func checkSameType(t *testing.T, x Type, y interface{}) {
4613 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
4614 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
4618 func TestArrayOf(t *testing.T) {
4619 // check construction and use of type not in binary
4622 value func(i int) interface{}
4628 value: func(i int) interface{} { type Tint int; return Tint(i) },
4634 value: func(i int) interface{} { type Tint int; return Tint(i) },
4636 want: "[0 1 2 3 4 5 6 7 8 9]",
4640 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
4642 want: "[0 1 2 3 4 5 6 7 8 9]",
4646 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
4648 want: "[0 1 2 3 4 5 6 7 8 9]",
4652 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
4654 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
4658 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
4660 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4664 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
4666 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
4670 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
4672 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4676 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
4678 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4682 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4684 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4688 value: func(i int) interface{} {
4689 type TstructUV struct {
4693 return TstructUV{i, float64(i)}
4696 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4700 for _, table := range tests {
4701 at := ArrayOf(table.n, TypeOf(table.value(0)))
4703 vok := New(at).Elem()
4704 vnot := New(at).Elem()
4705 for i := 0; i < v.Len(); i++ {
4706 v.Index(i).Set(ValueOf(table.value(i)))
4707 vok.Index(i).Set(ValueOf(table.value(i)))
4712 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4714 s := fmt.Sprint(v.Interface())
4715 if s != table.want {
4716 t.Errorf("constructed array = %s, want %s", s, table.want)
4719 if table.comparable != at.Comparable() {
4720 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4722 if table.comparable {
4724 if DeepEqual(vnot.Interface(), v.Interface()) {
4726 "arrays (%#v) compare ok (but should not)",
4731 if !DeepEqual(vok.Interface(), v.Interface()) {
4733 "arrays (%#v) compare NOT-ok (but should)",
4740 // check that type already in binary is found
4742 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4745 func TestArrayOfGC(t *testing.T) {
4747 tt := TypeOf(T(nil))
4750 for i := 0; i < n; i++ {
4751 v := New(ArrayOf(n, tt)).Elem()
4752 for j := 0; j < v.Len(); j++ {
4754 *p = uintptr(i*n + j)
4755 v.Index(j).Set(ValueOf(p).Convert(tt))
4757 x = append(x, v.Interface())
4761 for i, xi := range x {
4763 for j := 0; j < v.Len(); j++ {
4764 k := v.Index(j).Elem().Interface()
4765 if k != uintptr(i*n+j) {
4766 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4772 func TestArrayOfAlg(t *testing.T) {
4773 at := ArrayOf(6, TypeOf(byte(0)))
4774 v1 := New(at).Elem()
4775 v2 := New(at).Elem()
4776 if v1.Interface() != v1.Interface() {
4777 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4779 v1.Index(5).Set(ValueOf(byte(1)))
4780 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4781 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4784 at = ArrayOf(6, TypeOf([]int(nil)))
4786 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
4789 func TestArrayOfGenericAlg(t *testing.T) {
4790 at1 := ArrayOf(5, TypeOf(string("")))
4791 at := ArrayOf(6, at1)
4792 v1 := New(at).Elem()
4793 v2 := New(at).Elem()
4794 if v1.Interface() != v1.Interface() {
4795 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4798 v1.Index(0).Index(0).Set(ValueOf("abc"))
4799 v2.Index(0).Index(0).Set(ValueOf("efg"))
4800 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4801 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4804 v1.Index(0).Index(0).Set(ValueOf("abc"))
4805 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4806 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4807 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4811 m := MakeMap(MapOf(at, TypeOf(int(0))))
4812 m.SetMapIndex(v1, ValueOf(1))
4813 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4814 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4818 func TestArrayOfDirectIface(t *testing.T) {
4821 i1 := Zero(TypeOf(T{})).Interface()
4822 v1 := ValueOf(&i1).Elem()
4823 p1 := v1.InterfaceData()[1]
4825 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4826 v2 := ValueOf(&i2).Elem()
4827 p2 := v2.InterfaceData()[1]
4830 t.Errorf("got p1=%v. want=%v", p1, nil)
4834 t.Errorf("got p2=%v. want=%v", p2, nil)
4839 i1 := Zero(TypeOf(T{})).Interface()
4840 v1 := ValueOf(&i1).Elem()
4841 p1 := v1.InterfaceData()[1]
4843 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4844 v2 := ValueOf(&i2).Elem()
4845 p2 := v2.InterfaceData()[1]
4848 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4852 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4857 // Ensure passing in negative lengths panics.
4858 // See https://golang.org/issue/43603
4859 func TestArrayOfPanicOnNegativeLength(t *testing.T) {
4860 shouldPanic("reflect: negative length passed to ArrayOf", func() {
4861 ArrayOf(-1, TypeOf(byte(0)))
4865 func TestSliceOf(t *testing.T) {
4866 // check construction and use of type not in binary
4868 st := SliceOf(TypeOf(T(1)))
4869 if got, want := st.String(), "[]reflect_test.T"; got != want {
4870 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4872 v := MakeSlice(st, 10, 10)
4874 for i := 0; i < v.Len(); i++ {
4875 v.Index(i).Set(ValueOf(T(i)))
4878 s := fmt.Sprint(v.Interface())
4879 want := "[0 1 2 3 4 5 6 7 8 9]"
4881 t.Errorf("constructed slice = %s, want %s", s, want)
4884 // check that type already in binary is found
4886 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4889 func TestSliceOverflow(t *testing.T) {
4890 // check that MakeSlice panics when size of slice overflows uint
4893 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4895 t.Fatal("slice size does not overflow")
4898 st := SliceOf(TypeOf(x))
4902 t.Fatal("slice overflow does not panic")
4905 MakeSlice(st, int(l), int(l))
4908 func TestSliceOfGC(t *testing.T) {
4910 tt := TypeOf(T(nil))
4914 for i := 0; i < n; i++ {
4915 v := MakeSlice(st, n, n)
4916 for j := 0; j < v.Len(); j++ {
4918 *p = uintptr(i*n + j)
4919 v.Index(j).Set(ValueOf(p).Convert(tt))
4921 x = append(x, v.Interface())
4925 for i, xi := range x {
4927 for j := 0; j < v.Len(); j++ {
4928 k := v.Index(j).Elem().Interface()
4929 if k != uintptr(i*n+j) {
4930 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4936 func TestStructOfFieldName(t *testing.T) {
4937 // invalid field name "1nvalid"
4938 shouldPanic("has invalid name", func() {
4939 StructOf([]StructField{
4940 {Name: "Valid", Type: TypeOf("")},
4941 {Name: "1nvalid", Type: TypeOf("")},
4945 // invalid field name "+"
4946 shouldPanic("has invalid name", func() {
4947 StructOf([]StructField{
4948 {Name: "Val1d", Type: TypeOf("")},
4949 {Name: "+", Type: TypeOf("")},
4954 shouldPanic("has no name", func() {
4955 StructOf([]StructField{
4956 {Name: "", Type: TypeOf("")},
4960 // verify creation of a struct with valid struct fields
4961 validFields := []StructField{
4976 validStruct := StructOf(validFields)
4978 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
4979 if got, want := validStruct.String(), structStr; got != want {
4980 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
4984 func TestStructOf(t *testing.T) {
4985 // check construction and use of type not in binary
4986 fields := []StructField{
4995 Type: TypeOf(byte(0)),
4999 Type: TypeOf(uint64(0)),
5003 Type: TypeOf([3]uint16{}),
5007 st := StructOf(fields)
5010 v.FieldByName("X").Set(ValueOf(byte(2)))
5011 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
5014 s := fmt.Sprint(v.Interface())
5015 want := `{ 1 0 [0 0 0]}`
5017 t.Errorf("constructed struct = %s, want %s", s, want)
5019 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
5020 if got, want := st.String(), stStr; got != want {
5021 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
5024 // check the size, alignment and field offsets
5025 stt := TypeOf(struct {
5031 if st.Size() != stt.Size() {
5032 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
5034 if st.Align() != stt.Align() {
5035 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
5037 if st.FieldAlign() != stt.FieldAlign() {
5038 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5040 for i := 0; i < st.NumField(); i++ {
5041 o1 := st.Field(i).Offset
5042 o2 := stt.Field(i).Offset
5044 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
5048 // Check size and alignment with a trailing zero-sized field.
5049 st = StructOf([]StructField{
5052 Type: TypeOf(byte(0)),
5056 Type: TypeOf([0]*byte{}),
5059 stt = TypeOf(struct {
5063 if st.Size() != stt.Size() {
5064 t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
5066 if st.Align() != stt.Align() {
5067 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
5069 if st.FieldAlign() != stt.FieldAlign() {
5070 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
5072 for i := 0; i < st.NumField(); i++ {
5073 o1 := st.Field(i).Offset
5074 o2 := stt.Field(i).Offset
5076 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
5080 // check duplicate names
5081 shouldPanic("duplicate field", func() {
5082 StructOf([]StructField{
5083 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5084 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5087 shouldPanic("has no name", func() {
5088 StructOf([]StructField{
5090 {Name: "string", PkgPath: "p", Type: TypeOf("")},
5093 shouldPanic("has no name", func() {
5094 StructOf([]StructField{
5099 // check that type already in binary is found
5100 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
5102 // gccgo used to fail this test.
5103 type structFieldType interface{}
5105 StructOf([]StructField{
5108 Type: TypeOf((*structFieldType)(nil)).Elem(),
5111 struct{ F structFieldType }{})
5114 func TestStructOfExportRules(t *testing.T) {
5120 testPanic := func(i int, mustPanic bool, f func()) {
5123 if err == nil && mustPanic {
5124 t.Errorf("test-%d did not panic", i)
5126 if err != nil && !mustPanic {
5127 t.Errorf("test-%d panicked: %v\n", i, err)
5139 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
5143 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
5147 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
5151 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
5155 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
5159 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
5163 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5167 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5171 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5175 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5179 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5182 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
5185 field: StructField{Name: "S", Type: TypeOf(S1{})},
5189 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
5193 field: StructField{Name: "S", Type: TypeOf(s2{})},
5197 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
5201 field: StructField{Name: "s", Type: TypeOf(S1{})},
5205 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
5209 field: StructField{Name: "s", Type: TypeOf(s2{})},
5213 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
5217 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
5220 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
5223 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
5226 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
5229 field: StructField{Name: "", Type: TypeOf(ΦType{})},
5233 field: StructField{Name: "", Type: TypeOf(φType{})},
5237 field: StructField{Name: "Φ", Type: TypeOf(0)},
5241 field: StructField{Name: "φ", Type: TypeOf(0)},
5246 for i, test := range tests {
5247 testPanic(i, test.mustPanic, func() {
5248 typ := StructOf([]StructField{test.field})
5250 t.Errorf("test-%d: error creating struct type", i)
5253 field := typ.Field(0)
5256 panic("field.Name must not be empty")
5258 exported := token.IsExported(n)
5259 if exported != test.exported {
5260 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
5262 if field.PkgPath != test.field.PkgPath {
5263 t.Errorf("test-%d: got PkgPath=%q want pkgPath=%q", i, field.PkgPath, test.field.PkgPath)
5269 func TestStructOfGC(t *testing.T) {
5271 tt := TypeOf(T(nil))
5272 fields := []StructField{
5273 {Name: "X", Type: tt},
5274 {Name: "Y", Type: tt},
5276 st := StructOf(fields)
5280 for i := 0; i < n; i++ {
5282 for j := 0; j < v.NumField(); j++ {
5284 *p = uintptr(i*n + j)
5285 v.Field(j).Set(ValueOf(p).Convert(tt))
5287 x = append(x, v.Interface())
5291 for i, xi := range x {
5293 for j := 0; j < v.NumField(); j++ {
5294 k := v.Field(j).Elem().Interface()
5295 if k != uintptr(i*n+j) {
5296 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
5302 func TestStructOfAlg(t *testing.T) {
5303 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
5304 v1 := New(st).Elem()
5305 v2 := New(st).Elem()
5306 if !DeepEqual(v1.Interface(), v1.Interface()) {
5307 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5309 v1.FieldByName("X").Set(ValueOf(int(1)))
5310 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5311 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5314 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
5316 shouldPanic("", func() { _ = v1.Interface() == v1.Interface() })
5319 func TestStructOfGenericAlg(t *testing.T) {
5320 st1 := StructOf([]StructField{
5321 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
5322 {Name: "Y", Type: TypeOf(string(""))},
5324 st := StructOf([]StructField{
5325 {Name: "S0", Type: st1},
5326 {Name: "S1", Type: st1},
5344 {Name: "XX", Type: TypeOf([0]int{})},
5345 {Name: "YY", Type: TypeOf("")},
5353 {Name: "XX", Type: TypeOf([0]int{})},
5354 {Name: "YY", Type: TypeOf("")},
5355 {Name: "ZZ", Type: TypeOf([2]int{})},
5363 {Name: "XX", Type: TypeOf([1]int{})},
5364 {Name: "YY", Type: TypeOf("")},
5372 {Name: "XX", Type: TypeOf([1]int{})},
5373 {Name: "YY", Type: TypeOf("")},
5374 {Name: "ZZ", Type: TypeOf([1]int{})},
5382 {Name: "XX", Type: TypeOf([2]int{})},
5383 {Name: "YY", Type: TypeOf("")},
5384 {Name: "ZZ", Type: TypeOf([2]int{})},
5392 {Name: "XX", Type: TypeOf(int64(0))},
5393 {Name: "YY", Type: TypeOf(byte(0))},
5394 {Name: "ZZ", Type: TypeOf("")},
5402 {Name: "XX", Type: TypeOf(int64(0))},
5403 {Name: "YY", Type: TypeOf(int64(0))},
5404 {Name: "ZZ", Type: TypeOf("")},
5405 {Name: "AA", Type: TypeOf([1]int64{})},
5412 for _, table := range tests {
5413 v1 := New(table.rt).Elem()
5414 v2 := New(table.rt).Elem()
5416 if !DeepEqual(v1.Interface(), v1.Interface()) {
5417 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
5420 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
5421 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
5422 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
5423 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
5427 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
5428 val := "+" + abc + "-"
5429 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
5430 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5431 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5435 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
5436 m.SetMapIndex(v1, ValueOf(1))
5437 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5438 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
5441 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
5442 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
5443 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
5446 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
5447 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
5452 func TestStructOfDirectIface(t *testing.T) {
5454 type T struct{ X [1]*byte }
5455 i1 := Zero(TypeOf(T{})).Interface()
5456 v1 := ValueOf(&i1).Elem()
5457 p1 := v1.InterfaceData()[1]
5459 i2 := Zero(StructOf([]StructField{
5462 Type: ArrayOf(1, TypeOf((*int8)(nil))),
5465 v2 := ValueOf(&i2).Elem()
5466 p2 := v2.InterfaceData()[1]
5469 t.Errorf("got p1=%v. want=%v", p1, nil)
5473 t.Errorf("got p2=%v. want=%v", p2, nil)
5477 type T struct{ X [0]*byte }
5478 i1 := Zero(TypeOf(T{})).Interface()
5479 v1 := ValueOf(&i1).Elem()
5480 p1 := v1.InterfaceData()[1]
5482 i2 := Zero(StructOf([]StructField{
5485 Type: ArrayOf(0, TypeOf((*int8)(nil))),
5488 v2 := ValueOf(&i2).Elem()
5489 p2 := v2.InterfaceData()[1]
5492 t.Errorf("got p1=%v. want=not-%v", p1, nil)
5496 t.Errorf("got p2=%v. want=not-%v", p2, nil)
5503 func (i StructI) Get() int { return int(i) }
5507 func (i *StructIPtr) Get() int { return int(*i) }
5508 func (i *StructIPtr) Set(v int) { *(*int)(i) = v }
5510 type SettableStruct struct {
5514 func (p *SettableStruct) Set(v int) { p.SettableField = v }
5516 type SettablePointer struct {
5520 func (p *SettablePointer) Set(v int) { *p.SettableField = v }
5522 func TestStructOfWithInterface(t *testing.T) {
5524 type Iface interface {
5527 type IfaceSet interface {
5538 typ: TypeOf(StructI(want)),
5539 val: ValueOf(StructI(want)),
5544 typ: PtrTo(TypeOf(StructI(want))),
5545 val: ValueOf(func() interface{} {
5553 typ: PtrTo(TypeOf(StructIPtr(want))),
5554 val: ValueOf(func() interface{} {
5555 v := StructIPtr(want)
5562 typ: TypeOf(StructIPtr(want)),
5563 val: ValueOf(StructIPtr(want)),
5567 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
5568 // val: ValueOf(StructI(want)),
5573 for i, table := range tests {
5574 for j := 0; j < 2; j++ {
5575 var fields []StructField
5577 fields = append(fields, StructField{
5580 Type: TypeOf(int(0)),
5583 fields = append(fields, StructField{
5590 // We currently do not correctly implement methods
5591 // for embedded fields other than the first.
5592 // Therefore, for now, we expect those methods
5593 // to not exist. See issues 15924 and 20824.
5594 // When those issues are fixed, this test of panic
5595 // should be removed.
5596 if j == 1 && table.impl {
5599 if err := recover(); err == nil {
5600 t.Errorf("test-%d-%d did not panic", i, j)
5603 _ = StructOf(fields)
5608 rt := StructOf(fields)
5609 rv := New(rt).Elem()
5610 rv.Field(j).Set(table.val)
5612 if _, ok := rv.Interface().(Iface); ok != table.impl {
5614 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
5616 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
5625 v := rv.Interface().(Iface).Get()
5627 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
5630 fct := rv.MethodByName("Get")
5631 out := fct.Call(nil)
5632 if !DeepEqual(out[0].Interface(), want) {
5633 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
5638 // Test an embedded nil pointer with pointer methods.
5639 fields := []StructField{{
5642 Type: PtrTo(TypeOf(StructIPtr(want))),
5644 rt := StructOf(fields)
5645 rv := New(rt).Elem()
5646 // This should panic since the pointer is nil.
5647 shouldPanic("", func() {
5648 rv.Interface().(IfaceSet).Set(want)
5651 // Test an embedded nil pointer to a struct with pointer methods.
5653 fields = []StructField{{
5654 Name: "SettableStruct",
5656 Type: PtrTo(TypeOf(SettableStruct{})),
5658 rt = StructOf(fields)
5660 // This should panic since the pointer is nil.
5661 shouldPanic("", func() {
5662 rv.Interface().(IfaceSet).Set(want)
5665 // The behavior is different if there is a second field,
5666 // since now an interface value holds a pointer to the struct
5667 // rather than just holding a copy of the struct.
5668 fields = []StructField{
5670 Name: "SettableStruct",
5672 Type: PtrTo(TypeOf(SettableStruct{})),
5675 Name: "EmptyStruct",
5677 Type: StructOf(nil),
5680 // With the current implementation this is expected to panic.
5681 // Ideally it should work and we should be able to see a panic
5682 // if we call the Set method.
5683 shouldPanic("", func() {
5687 // Embed a field that can be stored directly in an interface,
5688 // with a second field.
5689 fields = []StructField{
5691 Name: "SettablePointer",
5693 Type: TypeOf(SettablePointer{}),
5696 Name: "EmptyStruct",
5698 Type: StructOf(nil),
5701 // With the current implementation this is expected to panic.
5702 // Ideally it should work and we should be able to call the
5703 // Set and Get methods.
5704 shouldPanic("", func() {
5709 func TestStructOfTooManyFields(t *testing.T) {
5710 // Bug Fix: #25402 - this should not panic
5711 tt := StructOf([]StructField{
5712 {Name: "Time", Type: TypeOf(time.Time{}), Anonymous: true},
5715 if _, present := tt.MethodByName("After"); !present {
5716 t.Errorf("Expected method `After` to be found")
5720 func TestStructOfDifferentPkgPath(t *testing.T) {
5721 fields := []StructField{
5725 Type: TypeOf(int(0)),
5730 Type: TypeOf(int(0)),
5733 shouldPanic("different PkgPath", func() {
5738 func TestChanOf(t *testing.T) {
5739 // check construction and use of type not in binary
5741 ct := ChanOf(BothDir, TypeOf(T("")))
5742 v := MakeChan(ct, 2)
5744 v.Send(ValueOf(T("hello")))
5746 v.Send(ValueOf(T("world")))
5753 if s1 != "hello" || s2 != "world" {
5754 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
5757 // check that type already in binary is found
5759 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
5761 // Check arrow token association in undefined chan types.
5762 var left chan<- chan T
5763 var right chan (<-chan T)
5764 tLeft := ChanOf(SendDir, ChanOf(BothDir, TypeOf(T(""))))
5765 tRight := ChanOf(BothDir, ChanOf(RecvDir, TypeOf(T(""))))
5766 if tLeft != TypeOf(left) {
5767 t.Errorf("chan<-chan: have %s, want %T", tLeft, left)
5769 if tRight != TypeOf(right) {
5770 t.Errorf("chan<-chan: have %s, want %T", tRight, right)
5774 func TestChanOfDir(t *testing.T) {
5775 // check construction and use of type not in binary
5777 crt := ChanOf(RecvDir, TypeOf(T("")))
5778 cst := ChanOf(SendDir, TypeOf(T("")))
5780 // check that type already in binary is found
5782 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
5783 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
5785 // check String form of ChanDir
5786 if crt.ChanDir().String() != "<-chan" {
5787 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
5789 if cst.ChanDir().String() != "chan<-" {
5790 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5794 func TestChanOfGC(t *testing.T) {
5795 done := make(chan bool, 1)
5799 case <-time.After(5 * time.Second):
5800 panic("deadlock in TestChanOfGC")
5809 tt := TypeOf(T(nil))
5810 ct := ChanOf(BothDir, tt)
5812 // NOTE: The garbage collector handles allocated channels specially,
5813 // so we have to save pointers to channels in x; the pointer code will
5814 // use the gc info in the newly constructed chan type.
5817 for i := 0; i < n; i++ {
5818 v := MakeChan(ct, n)
5819 for j := 0; j < n; j++ {
5821 *p = uintptr(i*n + j)
5822 v.Send(ValueOf(p).Convert(tt))
5826 x = append(x, pv.Interface())
5830 for i, xi := range x {
5831 v := ValueOf(xi).Elem()
5832 for j := 0; j < n; j++ {
5834 k := pv.Elem().Interface()
5835 if k != uintptr(i*n+j) {
5836 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5842 func TestMapOf(t *testing.T) {
5843 // check construction and use of type not in binary
5847 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5849 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5852 s := fmt.Sprint(v.Interface())
5855 t.Errorf("constructed map = %s, want %s", s, want)
5858 // check that type already in binary is found
5859 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5861 // check that invalid key type panics
5862 shouldPanic("invalid key type", func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5865 func TestMapOfGCKeys(t *testing.T) {
5867 tt := TypeOf(T(nil))
5868 mt := MapOf(tt, TypeOf(false))
5870 // NOTE: The garbage collector handles allocated maps specially,
5871 // so we have to save pointers to maps in x; the pointer code will
5872 // use the gc info in the newly constructed map type.
5875 for i := 0; i < n; i++ {
5877 for j := 0; j < n; j++ {
5879 *p = uintptr(i*n + j)
5880 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5884 x = append(x, pv.Interface())
5888 for i, xi := range x {
5889 v := ValueOf(xi).Elem()
5891 for _, kv := range v.MapKeys() {
5892 out = append(out, int(kv.Elem().Interface().(uintptr)))
5895 for j, k := range out {
5897 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5903 func TestMapOfGCValues(t *testing.T) {
5905 tt := TypeOf(T(nil))
5906 mt := MapOf(TypeOf(1), tt)
5908 // NOTE: The garbage collector handles allocated maps specially,
5909 // so we have to save pointers to maps in x; the pointer code will
5910 // use the gc info in the newly constructed map type.
5913 for i := 0; i < n; i++ {
5915 for j := 0; j < n; j++ {
5917 *p = uintptr(i*n + j)
5918 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5922 x = append(x, pv.Interface())
5926 for i, xi := range x {
5927 v := ValueOf(xi).Elem()
5928 for j := 0; j < n; j++ {
5929 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
5930 if k != uintptr(i*n+j) {
5931 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5937 func TestTypelinksSorted(t *testing.T) {
5939 for i, n := range TypeLinks() {
5941 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
5947 func TestFuncOf(t *testing.T) {
5948 // check construction and use of type not in binary
5952 fn := func(args []Value) []Value {
5954 t.Errorf("args == %v, want exactly one arg", args)
5955 } else if args[0].Type() != TypeOf(K("")) {
5956 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
5957 } else if args[0].String() != "gopher" {
5958 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
5960 return []Value{ValueOf(V(3.14))}
5962 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
5964 outs := v.Call([]Value{ValueOf(K("gopher"))})
5966 t.Fatalf("v.Call returned %v, want exactly one result", outs)
5967 } else if outs[0].Type() != TypeOf(V(0)) {
5968 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
5970 f := outs[0].Float()
5972 t.Errorf("constructed func returned %f, want %f", f, 3.14)
5975 // check that types already in binary are found
5977 testCases := []struct {
5982 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
5983 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
5984 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
5985 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
5986 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
5988 for _, tt := range testCases {
5989 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
5992 // check that variadic requires last element be a slice.
5993 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5994 shouldPanic("must be slice", func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5995 shouldPanic("must be slice", func() { FuncOf(nil, nil, true) })
6004 func BenchmarkFieldByName1(b *testing.B) {
6006 b.RunParallel(func(pb *testing.PB) {
6013 func BenchmarkFieldByName2(b *testing.B) {
6015 b.RunParallel(func(pb *testing.PB) {
6092 func TestEmbed(t *testing.T) {
6094 f, ok := typ.FieldByName("X")
6096 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
6100 func BenchmarkFieldByName3(b *testing.B) {
6102 b.RunParallel(func(pb *testing.PB) {
6114 func BenchmarkInterfaceBig(b *testing.B) {
6116 b.RunParallel(func(pb *testing.PB) {
6124 func TestAllocsInterfaceBig(t *testing.T) {
6125 if testing.Short() {
6126 t.Skip("skipping malloc count in short mode")
6129 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6130 t.Error("allocs:", allocs)
6134 func BenchmarkInterfaceSmall(b *testing.B) {
6135 v := ValueOf(int64(0))
6136 b.RunParallel(func(pb *testing.PB) {
6143 func TestAllocsInterfaceSmall(t *testing.T) {
6144 if testing.Short() {
6145 t.Skip("skipping malloc count in short mode")
6147 v := ValueOf(int64(0))
6148 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
6149 t.Error("allocs:", allocs)
6153 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
6154 // The basic usage is:
6157 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
6160 // Each iteration of the loop returns a different set of results, until all
6161 // possible result sets have been explored. It is okay for different code paths
6162 // to make different method call sequences on x, but there must be no
6163 // other source of non-determinism in the call sequences.
6165 // When faced with a new decision, x chooses randomly. Future explorations
6166 // of that path will choose successive values for the result. Thus, stopping
6167 // the loop after a fixed number of iterations gives somewhat stochastic
6173 // v := make([]bool, x.Choose(4))
6174 // for i := range v {
6180 // prints (in some order):
6189 // [false false false]
6192 // [false false false false]
6194 // [true true true true]
6196 type exhaustive struct {
6202 type choice struct {
6208 func (x *exhaustive) Next() bool {
6210 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
6217 for i := len(x.last) - 1; i >= 0; i-- {
6221 x.last = x.last[:i+1]
6228 func (x *exhaustive) Choose(max int) int {
6229 if x.pos >= len(x.last) {
6230 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
6235 panic("inconsistent use of exhaustive tester")
6237 return (c.n + c.off) % max
6240 func (x *exhaustive) Maybe() bool {
6241 return x.Choose(2) == 1
6244 func GCFunc(args []Value) []Value {
6249 func TestReflectFuncTraceback(t *testing.T) {
6250 f := MakeFunc(TypeOf(func() {}), GCFunc)
6254 func TestReflectMethodTraceback(t *testing.T) {
6256 m := ValueOf(p).MethodByName("GCMethod")
6257 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
6259 t.Errorf("Call returned %d; want 8", i)
6263 func TestSmallZero(t *testing.T) {
6266 if allocs := testing.AllocsPerRun(100, func() { Zero(typ) }); allocs > 0 {
6267 t.Errorf("Creating small zero values caused %f allocs, want 0", allocs)
6271 func TestBigZero(t *testing.T) {
6272 const size = 1 << 10
6274 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
6275 for i := 0; i < size; i++ {
6277 t.Fatalf("Zero object not all zero, index %d", i)
6282 func TestZeroSet(t *testing.T) {
6290 a: 0xaaaaaaaaaaaaaaaa,
6291 T: T{9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9},
6292 b: 0xbbbbbbbbbbbbbbbb,
6294 ValueOf(&v).Elem().Field(1).Set(Zero(TypeOf(T{})))
6296 a: 0xaaaaaaaaaaaaaaaa,
6297 b: 0xbbbbbbbbbbbbbbbb,
6299 t.Fatalf("Setting a field to a Zero value didn't work")
6303 func TestFieldByIndexNil(t *testing.T) {
6312 v.FieldByName("P") // should be fine
6315 if err := recover(); err == nil {
6316 t.Fatalf("no error")
6317 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
6318 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
6321 v.FieldByName("F") // should panic
6323 t.Fatalf("did not panic")
6327 // type Outer struct {
6331 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
6332 // The implementation is logically:
6333 // func (p *Outer) M() {
6336 // but since the only change here is the replacement of one pointer receiver with another,
6337 // the actual generated code overwrites the original receiver with the p.Inner pointer and
6338 // then jumps to the M method expecting the *Inner receiver.
6340 // During reflect.Value.Call, we create an argument frame and the associated data structures
6341 // to describe it to the garbage collector, populate the frame, call reflect.call to
6342 // run a function call using that frame, and then copy the results back out of the frame.
6343 // The reflect.call function does a memmove of the frame structure onto the
6344 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
6345 // the frame structure (to preserve the outputs).
6347 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
6348 // were for the full stack frame. However, in the case where the called function was
6349 // one of these wrappers, the rewritten receiver is almost certainly a different type
6350 // than the original receiver. This is not a problem on the stack, where we use the
6351 // program counter to determine the type information and understand that
6352 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
6353 // memory word is now an *Inner. But in the statically typed argument frame created
6354 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
6355 // off the stack into the frame will store an *Inner there, and then if a garbage collection
6356 // happens to scan that argument frame before it is discarded, it will scan the *Inner
6357 // memory as if it were an *Outer. If the two have different memory layouts, the
6358 // collection will interpret the memory incorrectly.
6360 // One such possible incorrect interpretation is to treat two arbitrary memory words
6361 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
6362 // an interface requires dereferencing the itab word, the misinterpretation will try to
6363 // deference Inner.P1, causing a crash during garbage collection.
6365 // This came up in a real program in issue 7725.
6378 func (pi *Inner) M() {
6379 // Clear references to pi so that the only way the
6380 // garbage collection will find the pointer is in the
6381 // argument frame, typed as a *Outer.
6384 // Set up an interface value that will cause a crash.
6385 // P1 = 1 is a non-zero, so the interface looks non-nil.
6386 // P2 = pi ensures that the data word points into the
6387 // allocated heap; if not the collection skips the interface
6388 // value as irrelevant, without dereferencing P1.
6390 pi.P2 = uintptr(unsafe.Pointer(pi))
6393 func TestCallMethodJump(t *testing.T) {
6394 // In reflect.Value.Call, trigger a garbage collection after reflect.call
6395 // returns but before the args frame has been discarded.
6396 // This is a little clumsy but makes the failure repeatable.
6399 p := &Outer{Inner: new(Inner)}
6401 ValueOf(p).Method(0).Call(nil)
6403 // Stop garbage collecting during reflect.call.
6407 func TestMakeFuncStackCopy(t *testing.T) {
6408 target := func(in []Value) []Value {
6411 return []Value{ValueOf(9)}
6414 var concrete func(*int, int) int
6415 fn := MakeFunc(ValueOf(concrete).Type(), target)
6416 ValueOf(&concrete).Elem().Set(fn)
6417 x := concrete(nil, 7)
6419 t.Errorf("have %#q want 9", x)
6423 // use about n KB of stack
6424 func useStack(n int) {
6428 var b [1024]byte // makes frame about 1KB
6429 useStack(n - 1 + int(b[99]))
6436 func TestValueString(t *testing.T) {
6437 rv := ValueOf(Impl{})
6438 if rv.String() != "<reflect_test.Impl Value>" {
6439 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
6442 method := rv.Method(0)
6443 if method.String() != "<func() Value>" {
6444 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
6448 func TestInvalid(t *testing.T) {
6449 // Used to have inconsistency between IsValid() and Kind() != Invalid.
6450 type T struct{ v interface{} }
6452 v := ValueOf(T{}).Field(0)
6453 if v.IsValid() != true || v.Kind() != Interface {
6454 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
6457 if v.IsValid() != false || v.Kind() != Invalid {
6458 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
6463 func TestLargeGCProg(t *testing.T) {
6464 fv := ValueOf(func([256]*byte) {})
6465 fv.Call([]Value{ValueOf([256]*byte{})})
6468 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
6470 recovered = recover()
6478 func TestTypeFieldOutOfRangePanic(t *testing.T) {
6479 typ := TypeOf(struct{ X int }{10})
6480 testIndices := [...]struct {
6489 for i, tt := range testIndices {
6490 recoveredErr := fieldIndexRecover(typ, tt.i)
6492 if recoveredErr == nil {
6493 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
6496 if recoveredErr != nil {
6497 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
6504 func TestCallGC(t *testing.T) {
6505 f := func(a, b, c, d, e string) {
6507 g := func(in []Value) []Value {
6511 typ := ValueOf(f).Type()
6512 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
6513 f2("four", "five5", "six666", "seven77", "eight888")
6516 // Issue 18635 (function version).
6517 func TestKeepFuncLive(t *testing.T) {
6518 // Test that we keep makeFuncImpl live as long as it is
6519 // referenced on the stack.
6520 typ := TypeOf(func(i int) {})
6521 var f, g func(in []Value) []Value
6522 f = func(in []Value) []Value {
6524 i := int(in[0].Int())
6526 // We can't use Value.Call here because
6527 // runtime.call* will keep the makeFuncImpl
6528 // alive. However, by converting it to an
6529 // interface value and calling that,
6530 // reflect.callReflect is the only thing that
6531 // can keep the makeFuncImpl live.
6533 // Alternate between f and g so that if we do
6534 // reuse the memory prematurely it's more
6535 // likely to get obviously corrupted.
6536 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
6540 g = func(in []Value) []Value {
6542 i := int(in[0].Int())
6543 MakeFunc(typ, f).Interface().(func(i int))(i)
6546 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
6549 type UnExportedFirst int
6551 func (i UnExportedFirst) ΦExported() {}
6552 func (i UnExportedFirst) unexported() {}
6555 func TestMethodByNameUnExportedFirst(t *testing.T) {
6557 if recover() != nil {
6558 t.Errorf("should not panic")
6561 typ := TypeOf(UnExportedFirst(0))
6562 m, _ := typ.MethodByName("ΦExported")
6563 if m.Name != "ΦExported" {
6564 t.Errorf("got %s, expected ΦExported", m.Name)
6568 // Issue 18635 (method version).
6569 type KeepMethodLive struct{}
6571 func (k KeepMethodLive) Method1(i int) {
6574 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
6578 func (k KeepMethodLive) Method2(i int) {
6580 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
6583 func TestKeepMethodLive(t *testing.T) {
6584 // Test that we keep methodValue live as long as it is
6585 // referenced on the stack.
6586 KeepMethodLive{}.Method1(10)
6589 // clobber tries to clobber unreachable memory.
6592 for i := 1; i < 32; i++ {
6593 for j := 0; j < 10; j++ {
6594 obj := make([]*byte, i)
6601 func TestFuncLayout(t *testing.T) {
6602 align := func(x uintptr) uintptr {
6603 return (x + goarch.PtrSize - 1) &^ (goarch.PtrSize - 1)
6606 if goarch.PtrSize == 4 {
6607 r = []byte{0, 0, 0, 1}
6619 size, argsize, retOffset uintptr
6620 stack, gc, inRegs, outRegs []byte // pointer bitmap: 1 is pointer, 0 is scalar
6621 intRegs, floatRegs int
6622 floatRegSize uintptr
6626 typ: ValueOf(func(a, b string) string { return "" }).Type(),
6627 size: 6 * goarch.PtrSize,
6628 argsize: 4 * goarch.PtrSize,
6629 retOffset: 4 * goarch.PtrSize,
6630 stack: []byte{1, 0, 1, 0, 1},
6631 gc: []byte{1, 0, 1, 0, 1},
6634 typ: ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
6635 size: align(align(3*4) + goarch.PtrSize + 2),
6636 argsize: align(3*4) + goarch.PtrSize + 2,
6637 retOffset: align(align(3*4) + goarch.PtrSize + 2),
6642 typ: ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
6643 size: 4 * goarch.PtrSize,
6644 argsize: 4 * goarch.PtrSize,
6645 retOffset: 4 * goarch.PtrSize,
6646 stack: []byte{1, 0, 1, 1},
6647 gc: []byte{1, 0, 1, 1},
6650 typ: ValueOf(func(a S) {}).Type(),
6651 size: 4 * goarch.PtrSize,
6652 argsize: 4 * goarch.PtrSize,
6653 retOffset: 4 * goarch.PtrSize,
6654 stack: []byte{0, 0, 1, 1},
6655 gc: []byte{0, 0, 1, 1},
6658 rcvr: ValueOf((*byte)(nil)).Type(),
6659 typ: ValueOf(func(a uintptr, b *int) {}).Type(),
6660 size: 3 * goarch.PtrSize,
6661 argsize: 3 * goarch.PtrSize,
6662 retOffset: 3 * goarch.PtrSize,
6663 stack: []byte{1, 0, 1},
6664 gc: []byte{1, 0, 1},
6667 typ: ValueOf(func(a uintptr) {}).Type(),
6668 size: goarch.PtrSize,
6669 argsize: goarch.PtrSize,
6670 retOffset: goarch.PtrSize,
6675 typ: ValueOf(func() uintptr { return 0 }).Type(),
6676 size: goarch.PtrSize,
6683 rcvr: ValueOf(uintptr(0)).Type(),
6684 typ: ValueOf(func(a uintptr) {}).Type(),
6685 size: 2 * goarch.PtrSize,
6686 argsize: 2 * goarch.PtrSize,
6687 retOffset: 2 * goarch.PtrSize,
6690 // Note: this one is tricky, as the receiver is not a pointer. But we
6691 // pass the receiver by reference to the autogenerated pointer-receiver
6692 // version of the function.
6694 // TODO(mknyszek): Add tests for non-zero register count.
6696 for _, lt := range tests {
6697 name := lt.typ.String()
6699 name = lt.rcvr.String() + "." + name
6701 t.Run(name, func(t *testing.T) {
6702 defer SetArgRegs(SetArgRegs(lt.intRegs, lt.floatRegs, lt.floatRegSize))
6704 typ, argsize, retOffset, stack, gc, inRegs, outRegs, ptrs := FuncLayout(lt.typ, lt.rcvr)
6705 if typ.Size() != lt.size {
6706 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.typ, lt.rcvr, typ.Size(), lt.size)
6708 if argsize != lt.argsize {
6709 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.typ, lt.rcvr, argsize, lt.argsize)
6711 if retOffset != lt.retOffset {
6712 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.typ, lt.rcvr, retOffset, lt.retOffset)
6714 if !bytes.Equal(stack, lt.stack) {
6715 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.typ, lt.rcvr, stack, lt.stack)
6717 if !bytes.Equal(gc, lt.gc) {
6718 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.typ, lt.rcvr, gc, lt.gc)
6720 if !bytes.Equal(inRegs, lt.inRegs) {
6721 t.Errorf("funcLayout(%v, %v).inRegs=%v, want %v", lt.typ, lt.rcvr, inRegs, lt.inRegs)
6723 if !bytes.Equal(outRegs, lt.outRegs) {
6724 t.Errorf("funcLayout(%v, %v).outRegs=%v, want %v", lt.typ, lt.rcvr, outRegs, lt.outRegs)
6726 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
6727 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.typ, lt.rcvr, ptrs, !ptrs)
6733 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
6734 heapBits := GCBits(New(typ).Interface())
6735 if !bytes.Equal(heapBits, bits) {
6736 _, _, line, _ := runtime.Caller(1)
6737 t.Errorf("line %d: heapBits incorrect for %v\nhave %v\nwant %v", line, typ, heapBits, bits)
6741 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
6742 // Creating a slice causes the runtime to repeat a bitmap,
6743 // which exercises a different path from making the compiler
6744 // repeat a bitmap for a small array or executing a repeat in
6746 val := MakeSlice(typ, 0, cap)
6747 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
6748 heapBits := GCBits(data.Interface())
6749 // Repeat the bitmap for the slice size, trimming scalars in
6750 // the last element.
6751 bits = rep(cap, bits)
6752 for len(bits) > 0 && bits[len(bits)-1] == 0 {
6753 bits = bits[:len(bits)-1]
6755 if !bytes.Equal(heapBits, bits) {
6756 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
6760 func TestGCBits(t *testing.T) {
6761 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
6763 // Building blocks for types seen by the compiler (like [2]Xscalar).
6764 // The compiler will create the type structures for the derived types,
6765 // including their GC metadata.
6766 type Xscalar struct{ x uintptr }
6767 type Xptr struct{ x *byte }
6768 type Xptrscalar struct {
6772 type Xscalarptr struct {
6776 type Xbigptrscalar struct {
6781 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
6783 // Building blocks for types constructed by reflect.
6784 // This code is in a separate block so that code below
6785 // cannot accidentally refer to these.
6786 // The compiler must NOT see types derived from these
6787 // (for example, [2]Scalar must NOT appear in the program),
6788 // or else reflect will use it instead of having to construct one.
6789 // The goal is to test the construction.
6790 type Scalar struct{ x uintptr }
6791 type Ptr struct{ x *byte }
6792 type Ptrscalar struct {
6796 type Scalarptr struct {
6800 type Bigptrscalar struct {
6805 Tscalar = TypeOf(Scalar{})
6806 Tint64 = TypeOf(Int64(0))
6807 Tptr = TypeOf(Ptr{})
6808 Tscalarptr = TypeOf(Scalarptr{})
6809 Tptrscalar = TypeOf(Ptrscalar{})
6810 Tbigptrscalar = TypeOf(Bigptrscalar{})
6815 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6816 verifyGCBits(t, Tscalar, empty)
6817 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6818 verifyGCBits(t, Tptr, lit(1))
6819 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6820 verifyGCBits(t, Tscalarptr, lit(0, 1))
6821 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6822 verifyGCBits(t, Tptrscalar, lit(1))
6824 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6825 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6826 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6827 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6828 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6829 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6830 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6831 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6832 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6833 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6834 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6835 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6836 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6837 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6838 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6839 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6840 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6841 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6842 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6843 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6844 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6845 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6846 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6847 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6848 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6849 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6851 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6852 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6853 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6854 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6855 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6856 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6857 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6858 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6859 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6860 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6861 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6862 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6863 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6864 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6865 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6866 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6867 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6868 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6869 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6870 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6871 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6872 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6873 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6874 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6875 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6876 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6878 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6879 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6881 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6882 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6884 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6885 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6887 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6888 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6890 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6891 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6893 hdr := make([]byte, 8/goarch.PtrSize)
6895 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6896 verifyGCBits(t, MapBucketOf(k, e), want)
6897 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6901 map[Xscalar]Xptr(nil),
6902 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6905 map[Xscalarptr]Xptr(nil),
6906 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6907 verifyMapBucket(t, Tint64, Tptr,
6908 map[int64]Xptr(nil),
6909 join(hdr, rep(8, rep(8/goarch.PtrSize, lit(0))), rep(8, lit(1)), lit(1)))
6912 map[Xscalar]Xscalar(nil),
6915 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6916 map[[2]Xscalarptr][3]Xptrscalar(nil),
6917 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6919 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6920 map[[64 / goarch.PtrSize]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6921 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6923 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize, Tptrscalar),
6924 map[[64/goarch.PtrSize + 1]Xscalarptr][64 / goarch.PtrSize]Xptrscalar(nil),
6925 join(hdr, rep(8, lit(1)), rep(8*64/goarch.PtrSize, lit(1, 0)), lit(1)))
6927 ArrayOf(64/goarch.PtrSize, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6928 map[[64 / goarch.PtrSize]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6929 join(hdr, rep(8*64/goarch.PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
6931 ArrayOf(64/goarch.PtrSize+1, Tscalarptr), ArrayOf(64/goarch.PtrSize+1, Tptrscalar),
6932 map[[64/goarch.PtrSize + 1]Xscalarptr][64/goarch.PtrSize + 1]Xptrscalar(nil),
6933 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6936 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
6937 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
6938 func lit(x ...byte) []byte { return x }
6940 func TestTypeOfTypeOf(t *testing.T) {
6941 // Check that all the type constructors return concrete *rtype implementations.
6942 // It's difficult to test directly because the reflect package is only at arm's length.
6943 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6944 check := func(name string, typ Type) {
6945 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
6946 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
6950 type T struct{ int }
6951 check("TypeOf", TypeOf(T{}))
6953 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
6954 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
6955 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
6956 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
6957 check("PtrTo", PtrTo(TypeOf(T{})))
6958 check("SliceOf", SliceOf(TypeOf(T{})))
6961 type XM struct{ _ bool }
6963 func (*XM) String() string { return "" }
6965 func TestPtrToMethods(t *testing.T) {
6967 yp := New(TypeOf(y)).Interface()
6968 _, ok := yp.(fmt.Stringer)
6970 t.Fatal("does not implement Stringer, but should")
6974 func TestMapAlloc(t *testing.T) {
6975 m := ValueOf(make(map[int]int, 10))
6978 allocs := testing.AllocsPerRun(100, func() {
6982 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
6987 val := ValueOf(&tmp).Elem()
6988 allocs = testing.AllocsPerRun(100, func() {
6989 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
6990 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6991 for i := 0; i < size/2; i++ {
6992 val.SetInt(int64(i))
6993 mv.SetMapIndex(val, val)
6997 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
6999 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
7000 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
7001 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
7004 func TestChanAlloc(t *testing.T) {
7005 // Note: for a chan int, the return Value must be allocated, so we
7006 // use a chan *int instead.
7007 c := ValueOf(make(chan *int, 1))
7008 v := ValueOf(new(int))
7009 allocs := testing.AllocsPerRun(100, func() {
7013 if allocs < 0.5 || allocs > 1.5 {
7014 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
7016 // Note: there is one allocation in reflect.recv which seems to be
7017 // a limitation of escape analysis. If that is ever fixed the
7018 // allocs < 0.5 condition will trigger and this test should be fixed.
7021 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
7023 type nameTest struct {
7028 var nameTests = []nameTest{
7029 {(*int32)(nil), "int32"},
7032 {(*chan D1)(nil), ""},
7033 {(*func() D1)(nil), ""},
7034 {(*<-chan D1)(nil), ""},
7035 {(*chan<- D1)(nil), ""},
7036 {(*interface{})(nil), ""},
7040 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
7043 func TestNames(t *testing.T) {
7044 for _, test := range nameTests {
7045 typ := TypeOf(test.v).Elem()
7046 if got := typ.Name(); got != test.want {
7047 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
7052 func TestExported(t *testing.T) {
7053 type ΦExported struct{}
7054 type φUnexported struct{}
7061 type exportTest struct {
7065 exportTests := []exportTest{
7069 {(*big)(nil), false},
7070 {(BigP)(nil), true},
7071 {(*BigP)(nil), true},
7072 {ΦExported{}, true},
7073 {φUnexported{}, false},
7080 for i, test := range exportTests {
7081 typ := TypeOf(test.v)
7082 if got := IsExported(typ); got != test.want {
7083 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
7088 func TestTypeStrings(t *testing.T) {
7089 type stringTest struct {
7093 stringTests := []stringTest{
7094 {TypeOf(func(int) {}), "func(int)"},
7095 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
7096 {TypeOf(XM{}), "reflect_test.XM"},
7097 {TypeOf(new(XM)), "*reflect_test.XM"},
7098 {TypeOf(new(XM).String), "func() string"},
7099 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
7100 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
7101 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
7102 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
7103 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
7106 for i, test := range stringTests {
7107 if got, want := test.typ.String(), test.want; got != want {
7108 t.Errorf("type %d String()=%q, want %q", i, got, want)
7113 func TestOffsetLock(t *testing.T) {
7114 var wg sync.WaitGroup
7115 for i := 0; i < 4; i++ {
7119 for j := 0; j < 50; j++ {
7120 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
7128 func BenchmarkNew(b *testing.B) {
7130 b.RunParallel(func(pb *testing.PB) {
7137 func BenchmarkMap(b *testing.B) {
7139 value := ValueOf((V)(nil))
7140 stringKeys := []string{}
7141 mapOfStrings := map[string]V{}
7142 uint64Keys := []uint64{}
7143 mapOfUint64s := map[uint64]V{}
7144 for i := 0; i < 100; i++ {
7145 stringKey := fmt.Sprintf("key%d", i)
7146 stringKeys = append(stringKeys, stringKey)
7147 mapOfStrings[stringKey] = nil
7149 uint64Key := uint64(i)
7150 uint64Keys = append(uint64Keys, uint64Key)
7151 mapOfUint64s[uint64Key] = nil
7156 m, keys, value Value
7158 {"StringKeys", ValueOf(mapOfStrings), ValueOf(stringKeys), value},
7159 {"Uint64Keys", ValueOf(mapOfUint64s), ValueOf(uint64Keys), value},
7162 for _, tt := range tests {
7163 b.Run(tt.label, func(b *testing.B) {
7164 b.Run("MapIndex", func(b *testing.B) {
7166 for i := 0; i < b.N; i++ {
7167 for j := tt.keys.Len() - 1; j >= 0; j-- {
7168 tt.m.MapIndex(tt.keys.Index(j))
7172 b.Run("SetMapIndex", func(b *testing.B) {
7174 for i := 0; i < b.N; i++ {
7175 for j := tt.keys.Len() - 1; j >= 0; j-- {
7176 tt.m.SetMapIndex(tt.keys.Index(j), tt.value)
7184 func TestSwapper(t *testing.T) {
7190 type pairPtr struct {
7202 in: []int{1, 20, 300},
7205 want: []int{300, 20, 1},
7208 in: []uintptr{1, 20, 300},
7211 want: []uintptr{300, 20, 1},
7214 in: []int16{1, 20, 300},
7217 want: []int16{300, 20, 1},
7220 in: []int8{1, 20, 100},
7223 want: []int8{100, 20, 1},
7226 in: []*I{&a, &b, &c},
7229 want: []*I{&c, &b, &a},
7232 in: []string{"eric", "sergey", "larry"},
7235 want: []string{"larry", "sergey", "eric"},
7238 in: []S{"eric", "sergey", "larry"},
7241 want: []S{"larry", "sergey", "eric"},
7244 in: []pair{{1, 2}, {3, 4}, {5, 6}},
7247 want: []pair{{5, 6}, {3, 4}, {1, 2}},
7250 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
7253 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
7257 for i, tt := range tests {
7258 inStr := fmt.Sprint(tt.in)
7259 Swapper(tt.in)(tt.i, tt.j)
7260 if !DeepEqual(tt.in, tt.want) {
7261 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
7266 // TestUnaddressableField tests that the reflect package will not allow
7267 // a type from another package to be used as a named type with an
7268 // unexported field.
7270 // This ensures that unexported fields cannot be modified by other packages.
7271 func TestUnaddressableField(t *testing.T) {
7272 var b Buffer // type defined in reflect, a different package
7273 var localBuffer struct {
7276 lv := ValueOf(&localBuffer).Elem()
7278 shouldPanic("Set", func() {
7287 type Talias1 struct {
7295 type Talias2 struct {
7300 func TestAliasNames(t *testing.T) {
7301 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
7302 out := fmt.Sprintf("%#v", t1)
7303 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
7305 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
7308 t2 := Talias2{Tint: 1, Tint2: 2}
7309 out = fmt.Sprintf("%#v", t2)
7310 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
7312 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
7316 func TestIssue22031(t *testing.T) {
7317 type s []struct{ C int }
7320 type t2 struct{ f s }
7323 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
7324 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
7327 for i, test := range tests {
7329 t.Errorf("%d: CanSet: got true, want false", i)
7334 type NonExportedFirst int
7336 func (i NonExportedFirst) ΦExported() {}
7337 func (i NonExportedFirst) nonexported() int { panic("wrong") }
7339 func TestIssue22073(t *testing.T) {
7340 m := ValueOf(NonExportedFirst(0)).Method(0)
7342 if got := m.Type().NumOut(); got != 0 {
7343 t.Errorf("NumOut: got %v, want 0", got)
7350 func TestMapIterNonEmptyMap(t *testing.T) {
7351 m := map[string]int{"one": 1, "two": 2, "three": 3}
7352 iter := ValueOf(m).MapRange()
7353 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7354 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7358 func TestMapIterNilMap(t *testing.T) {
7359 var m map[string]int
7360 iter := ValueOf(m).MapRange()
7361 if got, want := iterateToString(iter), `[]`; got != want {
7362 t.Errorf("non-empty result iteratoring nil map: %s", got)
7366 func TestMapIterReset(t *testing.T) {
7367 iter := new(MapIter)
7369 // Use of zero iterator should panic.
7371 defer func() { recover() }()
7373 t.Error("Next did not panic")
7376 // Reset to new Map should work.
7377 m := map[string]int{"one": 1, "two": 2, "three": 3}
7378 iter.Reset(ValueOf(m))
7379 if got, want := iterateToString(iter), `[one: 1, three: 3, two: 2]`; got != want {
7380 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7383 // Reset to Zero value should work, but iterating over it should panic.
7386 defer func() { recover() }()
7388 t.Error("Next did not panic")
7391 // Reset to a different Map with different types should work.
7392 m2 := map[int]string{1: "one", 2: "two", 3: "three"}
7393 iter.Reset(ValueOf(m2))
7394 if got, want := iterateToString(iter), `[1: one, 2: two, 3: three]`; got != want {
7395 t.Errorf("iterator returned %s (after sorting), want %s", got, want)
7398 // Check that Reset, Next, and SetKey/SetValue play nicely together.
7399 m3 := map[uint64]uint64{
7404 kv := New(TypeOf(uint64(0))).Elem()
7405 for i := 0; i < 5; i++ {
7406 var seenk, seenv uint64
7407 iter.Reset(ValueOf(m3))
7415 t.Errorf("iteration yielded keys %b, want %b", seenk, 0b111)
7417 if seenv != 0b1110 {
7418 t.Errorf("iteration yielded values %b, want %b", seenv, 0b1110)
7422 // Reset should not allocate.
7423 n := int(testing.AllocsPerRun(10, func() {
7424 iter.Reset(ValueOf(m2))
7428 t.Errorf("MapIter.Reset allocated %d times", n)
7432 func TestMapIterSafety(t *testing.T) {
7433 // Using a zero MapIter causes a panic, but not a crash.
7435 defer func() { recover() }()
7437 t.Fatal("Key did not panic")
7440 defer func() { recover() }()
7441 new(MapIter).Value()
7442 t.Fatal("Value did not panic")
7445 defer func() { recover() }()
7447 t.Fatal("Next did not panic")
7450 // Calling Key/Value on a MapIter before Next
7451 // causes a panic, but not a crash.
7452 var m map[string]int
7453 iter := ValueOf(m).MapRange()
7456 defer func() { recover() }()
7458 t.Fatal("Key did not panic")
7461 defer func() { recover() }()
7463 t.Fatal("Value did not panic")
7466 // Calling Next, Key, or Value on an exhausted iterator
7467 // causes a panic, but not a crash.
7468 iter.Next() // -> false
7470 defer func() { recover() }()
7472 t.Fatal("Key did not panic")
7475 defer func() { recover() }()
7477 t.Fatal("Value did not panic")
7480 defer func() { recover() }()
7482 t.Fatal("Next did not panic")
7486 func TestMapIterNext(t *testing.T) {
7487 // The first call to Next should reflect any
7488 // insertions to the map since the iterator was created.
7489 m := map[string]int{}
7490 iter := ValueOf(m).MapRange()
7492 if got, want := iterateToString(iter), `[one: 1]`; got != want {
7493 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7497 func TestMapIterDelete0(t *testing.T) {
7498 // Delete all elements before first iteration.
7499 m := map[string]int{"one": 1, "two": 2, "three": 3}
7500 iter := ValueOf(m).MapRange()
7504 if got, want := iterateToString(iter), `[]`; got != want {
7505 t.Errorf("iterator returned deleted elements: got %s, want %s", got, want)
7509 func TestMapIterDelete1(t *testing.T) {
7510 // Delete all elements after first iteration.
7511 m := map[string]int{"one": 1, "two": 2, "three": 3}
7512 iter := ValueOf(m).MapRange()
7515 got = append(got, fmt.Sprint(iter.Key(), iter.Value()))
7521 t.Errorf("iterator returned wrong number of elements: got %d, want 1", len(got))
7525 // iterateToString returns the set of elements
7526 // returned by an iterator in readable form.
7527 func iterateToString(it *MapIter) string {
7530 line := fmt.Sprintf("%v: %v", it.Key(), it.Value())
7531 got = append(got, line)
7534 return "[" + strings.Join(got, ", ") + "]"
7537 func TestConvertibleTo(t *testing.T) {
7538 t1 := ValueOf(example1.MyStruct{}).Type()
7539 t2 := ValueOf(example2.MyStruct{}).Type()
7541 // Shouldn't raise stack overflow
7542 if t1.ConvertibleTo(t2) {
7543 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t1, t2)
7546 t3 := ValueOf([]example1.MyStruct{}).Type()
7547 t4 := ValueOf([]example2.MyStruct{}).Type()
7549 if t3.ConvertibleTo(t4) {
7550 t.Fatalf("(%s).ConvertibleTo(%s) = true, want false", t3, t4)