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.
32 func TestBool(t
*testing
.T
) {
35 t
.Fatal("ValueOf(true).Bool() = false")
52 func assert(t
*testing
.T
, s
, want
string) {
54 t
.Errorf("have %#q want %#q", s
, want
)
58 var typeTests
= []pair
{
59 {struct{ x
int }{}, "int"},
60 {struct{ x
int8 }{}, "int8"},
61 {struct{ x
int16 }{}, "int16"},
62 {struct{ x
int32 }{}, "int32"},
63 {struct{ x
int64 }{}, "int64"},
64 {struct{ x
uint }{}, "uint"},
65 {struct{ x
uint8 }{}, "uint8"},
66 {struct{ x
uint16 }{}, "uint16"},
67 {struct{ x
uint32 }{}, "uint32"},
68 {struct{ x
uint64 }{}, "uint64"},
69 {struct{ x
float32 }{}, "float32"},
70 {struct{ x
float64 }{}, "float64"},
71 {struct{ x
int8 }{}, "int8"},
72 {struct{ x (**int8) }{}, "**int8"},
73 {struct{ x (**integer
) }{}, "**reflect_test.integer"},
74 {struct{ x ([32]int32) }{}, "[32]int32"},
75 {struct{ x ([]int8) }{}, "[]int8"},
76 {struct{ x (map[string]int32) }{}, "map[string]int32"},
77 {struct{ x (chan<- string) }{}, "chan<- string"},
84 "struct { c chan *int32; d float32 }",
86 {struct{ x (func(a
int8, b
int32)) }{}, "func(int8, int32)"},
89 c
func(chan *integer
, *int8)
92 "struct { c func(chan *reflect_test.integer, *int8) }",
100 "struct { a int8; b int32 }",
109 "struct { a int8; b int8; c int32 }",
119 "struct { a int8; b int8; c int8; d int32 }",
130 "struct { a int8; b int8; c int8; d int8; e int32 }",
142 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
146 a
int8 `reflect:"hi there"`
149 `struct { a int8 "reflect:\"hi there\"" }`,
153 a
int8 `reflect:"hi \x00there\t\n\"\\"`
156 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
163 "struct { f func(...int) }",
167 a(func(func(int) int) func(func(int)) int)
171 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
179 "struct { int32; int64 }",
183 var valueTests
= []pair
{
194 {new(float32), "256.25"},
195 {new(float64), "512.125"},
196 {new(complex64
), "532.125+10i"},
197 {new(complex128
), "564.25+1i"},
198 {new(string), "stringy cheese"},
200 {new(*int8), "*int8(0)"},
201 {new(**int8), "**int8(0)"},
202 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
203 {new(**integer
), "**reflect_test.integer(0)"},
204 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
205 {new(chan<- string), "chan<- string"},
206 {new(func(a
int8, b
int32)), "func(int8, int32)(0)"},
211 "struct { c chan *int32; d float32 }{chan *int32, 0}",
213 {new(struct{ c
func(chan *integer
, *int8) }),
214 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
220 "struct { a int8; b int32 }{0, 0}",
227 "struct { a int8; b int8; c int32 }{0, 0, 0}",
231 func testType(t
*testing
.T
, i
int, typ Type
, want
string) {
234 t
.Errorf("#%d: have %#q, want %#q", i
, s
, want
)
238 func TestTypes(t
*testing
.T
) {
239 for i
, tt
:= range typeTests
{
240 testType(t
, i
, ValueOf(tt
.i
).Field(0).Type(), tt
.s
)
244 func TestSet(t
*testing
.T
) {
245 for i
, tt
:= range valueTests
{
274 v
.SetComplex(532.125 + 10i
)
276 v
.SetComplex(564.25 + 1i
)
278 v
.SetString("stringy cheese")
282 s
:= valueToString(v
)
284 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
289 func TestSetValue(t
*testing
.T
) {
290 for i
, tt
:= range valueTests
{
291 v
:= ValueOf(tt
.i
).Elem()
294 v
.Set(ValueOf(int(132)))
296 v
.Set(ValueOf(int8(8)))
298 v
.Set(ValueOf(int16(16)))
300 v
.Set(ValueOf(int32(32)))
302 v
.Set(ValueOf(int64(64)))
304 v
.Set(ValueOf(uint(132)))
306 v
.Set(ValueOf(uint8(8)))
308 v
.Set(ValueOf(uint16(16)))
310 v
.Set(ValueOf(uint32(32)))
312 v
.Set(ValueOf(uint64(64)))
314 v
.Set(ValueOf(float32(256.25)))
316 v
.Set(ValueOf(512.125))
318 v
.Set(ValueOf(complex64(532.125 + 10i
)))
320 v
.Set(ValueOf(complex128(564.25 + 1i
)))
322 v
.Set(ValueOf("stringy cheese"))
326 s
:= valueToString(v
)
328 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
333 func TestCanSetField(t
*testing
.T
) {
334 type embed
struct{ x
, X
int }
335 type Embed
struct{ x
, X
int }
353 type testCase
struct {
364 {[]int{0, 0}, false},
370 val
: ValueOf(&S2
{embed
: &embed
{}}),
373 {[]int{0, 0}, false},
382 {[]int{0, 0}, false},
388 val
: ValueOf(&S4
{Embed
: &Embed
{}}),
391 {[]int{0, 0}, false},
398 for _
, tt
:= range tests
{
399 t
.Run(tt
.val
.Type().Name(), func(t
*testing
.T
) {
400 for _
, tc
:= range tt
.cases
{
402 for _
, i
:= range tc
.index
{
408 if got
:= f
.CanSet(); got
!= tc
.canSet
{
409 t
.Errorf("CanSet() = %v, want %v", got
, tc
.canSet
)
418 var valueToStringTests
= []pair
{
423 {T
{123, 456.75, "hello", &_i
}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
424 {new(chan *T
), "*chan *reflect_test.T(&chan *reflect_test.T)"},
425 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
426 {&[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})"},
427 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
428 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
431 func TestValueToString(t
*testing
.T
) {
432 for i
, test
:= range valueToStringTests
{
433 s
:= valueToString(ValueOf(test
.i
))
435 t
.Errorf("#%d: have %#q, want %#q", i
, s
, test
.s
)
440 func TestArrayElemSet(t
*testing
.T
) {
441 v
:= ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
442 v
.Index(4).SetInt(123)
443 s
:= valueToString(v
)
444 const want
= "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
446 t
.Errorf("[10]int: have %#q want %#q", s
, want
)
449 v
= ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
450 v
.Index(4).SetInt(123)
452 const want1
= "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
454 t
.Errorf("[]int: have %#q want %#q", s
, want1
)
458 func TestPtrPointTo(t
*testing
.T
) {
462 vi
:= ValueOf(&i
).Elem()
463 vip
.Elem().Set(vi
.Addr())
465 t
.Errorf("got %d, want 1234", *ip
)
469 vp
:= ValueOf(&ip
).Elem()
470 vp
.Set(Zero(vp
.Type()))
472 t
.Errorf("got non-nil (%p), want nil", ip
)
476 func TestPtrSetNil(t
*testing
.T
) {
480 vip
.Elem().Set(Zero(vip
.Elem().Type()))
482 t
.Errorf("got non-nil (%d), want nil", *ip
)
486 func TestMapSetNil(t
*testing
.T
) {
487 m
:= make(map[string]int)
489 vm
.Elem().Set(Zero(vm
.Elem().Type()))
491 t
.Errorf("got non-nil (%p), want nil", m
)
495 func TestAll(t
*testing
.T
) {
496 testType(t
, 1, TypeOf((int8)(0)), "int8")
497 testType(t
, 2, TypeOf((*int8)(nil)).Elem(), "int8")
499 typ
:= TypeOf((*struct {
503 testType(t
, 3, typ
, "*struct { c chan *int32; d float32 }")
505 testType(t
, 4, etyp
, "struct { c chan *int32; d float32 }")
508 testType(t
, 5, f
.Type
, "chan *int32")
510 f
, present
:= styp
.FieldByName("d")
512 t
.Errorf("FieldByName says present field is absent")
514 testType(t
, 6, f
.Type
, "float32")
516 f
, present
= styp
.FieldByName("absent")
518 t
.Errorf("FieldByName says absent field is present")
521 typ
= TypeOf([32]int32{})
522 testType(t
, 7, typ
, "[32]int32")
523 testType(t
, 8, typ
.Elem(), "int32")
525 typ
= TypeOf((map[string]*int32)(nil))
526 testType(t
, 9, typ
, "map[string]*int32")
528 testType(t
, 10, mtyp
.Key(), "string")
529 testType(t
, 11, mtyp
.Elem(), "*int32")
531 typ
= TypeOf((chan<- string)(nil))
532 testType(t
, 12, typ
, "chan<- string")
533 testType(t
, 13, typ
.Elem(), "string")
535 // make sure tag strings are not part of element type
536 typ
= TypeOf(struct {
537 d
[]uint32 `reflect:"TAG"`
539 testType(t
, 14, typ
, "[]uint32")
542 func TestInterfaceGet(t
*testing
.T
) {
547 v1
:= ValueOf(&inter
)
548 v2
:= v1
.Elem().Field(0)
549 assert(t
, v2
.Type().String(), "interface {}")
552 assert(t
, v3
.Type().String(), "float64")
555 func TestInterfaceValue(t
*testing
.T
) {
560 v1
:= ValueOf(&inter
)
561 v2
:= v1
.Elem().Field(0)
562 assert(t
, v2
.Type().String(), "interface {}")
564 assert(t
, v3
.Type().String(), "float64")
567 if _
, ok
:= i3
.(float64); !ok
{
568 t
.Error("v2.Interface() did not return float64, got ", TypeOf(i3
))
572 func TestFunctionValue(t
*testing
.T
) {
573 var x
interface{} = func() {}
575 if fmt
.Sprint(v
.Interface()) != fmt
.Sprint(x
) {
576 t
.Fatalf("TestFunction returned wrong pointer")
578 assert(t
, v
.Type().String(), "func()")
581 var appendTests
= []struct {
584 {make([]int, 2, 4), []int{22}},
585 {make([]int, 2, 4), []int{22, 33, 44}},
588 func sameInts(x
, y
[]int) bool {
589 if len(x
) != len(y
) {
592 for i
, xx
:= range x
{
600 func TestAppend(t
*testing
.T
) {
601 for i
, test
:= range appendTests
{
602 origLen
, extraLen
:= len(test
.orig
), len(test
.extra
)
603 want
:= append(test
.orig
, test
.extra
...)
604 // Convert extra from []int to []Value.
605 e0
:= make([]Value
, len(test
.extra
))
606 for j
, e
:= range test
.extra
{
609 // Convert extra from []int to *SliceValue.
610 e1
:= ValueOf(test
.extra
)
612 a0
:= ValueOf(test
.orig
)
613 have0
:= Append(a0
, e0
...).Interface().([]int)
614 if !sameInts(have0
, want
) {
615 t
.Errorf("Append #%d: have %v, want %v (%p %p)", i
, have0
, want
, test
.orig
, have0
)
617 // Check that the orig and extra slices were not modified.
618 if len(test
.orig
) != origLen
{
619 t
.Errorf("Append #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
621 if len(test
.extra
) != extraLen
{
622 t
.Errorf("Append #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
625 a1
:= ValueOf(test
.orig
)
626 have1
:= AppendSlice(a1
, e1
).Interface().([]int)
627 if !sameInts(have1
, want
) {
628 t
.Errorf("AppendSlice #%d: have %v, want %v", i
, have1
, want
)
630 // Check that the orig and extra slices were not modified.
631 if len(test
.orig
) != origLen
{
632 t
.Errorf("AppendSlice #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
634 if len(test
.extra
) != extraLen
{
635 t
.Errorf("AppendSlice #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
640 func TestCopy(t
*testing
.T
) {
641 a
:= []int{1, 2, 3, 4, 10, 9, 8, 7}
642 b
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
643 c
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
644 for i
:= 0; i
< len(b
); i
++ {
646 t
.Fatalf("b != c before test")
651 aa
:= ValueOf(&a1
).Elem()
652 ab
:= ValueOf(&b1
).Elem()
653 for tocopy
:= 1; tocopy
<= 7; tocopy
++ {
657 for i
:= 0; i
< tocopy
; i
++ {
659 t
.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
660 tocopy
, i
, a
[i
], i
, b
[i
])
663 for i
:= tocopy
; i
< len(b
); i
++ {
666 t
.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
667 tocopy
, i
, a
[i
], i
, b
[i
], i
, c
[i
])
669 t
.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
670 tocopy
, i
, b
[i
], i
, c
[i
])
673 t
.Logf("tocopy=%d elem %d is okay\n", tocopy
, i
)
679 func TestCopyString(t
*testing
.T
) {
680 t
.Run("Slice", func(t
*testing
.T
) {
681 s
:= bytes
.Repeat([]byte{'_'}, 8)
684 n
:= Copy(val
, ValueOf(""))
685 if expecting
:= []byte("________"); n
!= 0 ||
!bytes
.Equal(s
, expecting
) {
686 t
.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n
, s
, expecting
)
689 n
= Copy(val
, ValueOf("hello"))
690 if expecting
:= []byte("hello___"); n
!= 5 ||
!bytes
.Equal(s
, expecting
) {
691 t
.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n
, s
, expecting
)
694 n
= Copy(val
, ValueOf("helloworld"))
695 if expecting
:= []byte("hellowor"); n
!= 8 ||
!bytes
.Equal(s
, expecting
) {
696 t
.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n
, s
, expecting
)
699 t
.Run("Array", func(t
*testing
.T
) {
700 s
:= [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
701 val
:= ValueOf(&s
).Elem()
703 n
:= Copy(val
, ValueOf(""))
704 if expecting
:= []byte("________"); n
!= 0 ||
!bytes
.Equal(s
[:], expecting
) {
705 t
.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n
, s
[:], expecting
)
708 n
= Copy(val
, ValueOf("hello"))
709 if expecting
:= []byte("hello___"); n
!= 5 ||
!bytes
.Equal(s
[:], expecting
) {
710 t
.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n
, s
[:], expecting
)
713 n
= Copy(val
, ValueOf("helloworld"))
714 if expecting
:= []byte("hellowor"); n
!= 8 ||
!bytes
.Equal(s
[:], expecting
) {
715 t
.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n
, s
[:], expecting
)
720 func TestCopyArray(t
*testing
.T
) {
721 a
:= [8]int{1, 2, 3, 4, 10, 9, 8, 7}
722 b
:= [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
724 aa
:= ValueOf(&a
).Elem()
725 ab
:= ValueOf(&b
).Elem()
727 for i
:= 0; i
< len(a
); i
++ {
729 t
.Errorf("(i) a[%d]=%d, b[%d]=%d", i
, a
[i
], i
, b
[i
])
732 for i
:= len(a
); i
< len(b
); i
++ {
734 t
.Errorf("(ii) b[%d]=%d, c[%d]=%d", i
, b
[i
], i
, c
[i
])
736 t
.Logf("elem %d is okay\n", i
)
741 func TestBigUnnamedStruct(t
*testing
.T
) {
742 b
:= struct{ a
, b
, c
, d
int64 }{1, 2, 3, 4}
744 b1
:= v
.Interface().(struct {
747 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d
{
748 t
.Errorf("ValueOf(%v).Interface().(*Big) = %v", b
, b1
)
756 func TestBigStruct(t
*testing
.T
) {
757 b
:= big
{1, 2, 3, 4, 5}
759 b1
:= v
.Interface().(big
)
760 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d || b1
.e
!= b
.e
{
761 t
.Errorf("ValueOf(%v).Interface().(big) = %v", b
, b1
)
772 type DeepEqualTest
struct {
777 // Simple functions for DeepEqual tests.
781 fn3
= func() { fn1() } // Not nil.
787 type Loopy
interface{}
789 var loop1
, loop2 Loop
790 var loopy1
, loopy2 Loopy
800 var deepEqualTests
= []DeepEqualTest
{
804 {int32(1), int32(1), true},
806 {float32(0.5), float32(0.5), true},
807 {"hello", "hello", true},
808 {make([]int, 10), make([]int, 10), true},
809 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
810 {Basic
{1, 0.5}, Basic
{1, 0.5}, true},
811 {error(nil), error(nil), true},
812 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
817 {int32(1), int32(2), false},
819 {float32(0.5), float32(0.6), false},
820 {"hello", "hey", false},
821 {make([]int, 10), make([]int, 11), false},
822 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
823 {Basic
{1, 0.5}, Basic
{1, 0.6}, false},
824 {Basic
{1, 0}, Basic
{2, 0}, false},
825 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
826 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
827 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
828 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
833 {[][]int{{1}}, [][]int{{2}}, false},
834 {math
.NaN(), math
.NaN(), false},
835 {&[1]float64{math
.NaN()}, &[1]float64{math
.NaN()}, false},
836 {&[1]float64{math
.NaN()}, self
{}, true},
837 {[]float64{math
.NaN()}, []float64{math
.NaN()}, false},
838 {[]float64{math
.NaN()}, self
{}, true},
839 {map[float64]float64{math
.NaN(): 1}, map[float64]float64{1: 2}, false},
840 {map[float64]float64{math
.NaN(): 1}, self
{}, true},
842 // Nil vs empty: not the same.
843 {[]int{}, []int(nil), false},
844 {[]int{}, []int{}, true},
845 {[]int(nil), []int(nil), true},
846 {map[int]int{}, map[int]int(nil), false},
847 {map[int]int{}, map[int]int{}, true},
848 {map[int]int(nil), map[int]int(nil), true},
852 {int32(1), int64(1), false},
853 {0.5, "hello", false},
854 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
855 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
856 {Basic
{1, 0.5}, NotBasic
{1, 0.5}, false},
857 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
860 {&loop1
, &loop1
, true},
861 {&loop1
, &loop2
, true},
862 {&loopy1
, &loopy1
, true},
863 {&loopy1
, &loopy2
, true},
866 func TestDeepEqual(t
*testing
.T
) {
867 for _
, test
:= range deepEqualTests
{
868 if test
.b
== (self
{}) {
871 if r
:= DeepEqual(test
.a
, test
.b
); r
!= test
.eq
{
872 t
.Errorf("DeepEqual(%v, %v) = %v, want %v", test
.a
, test
.b
, r
, test
.eq
)
877 func TestTypeOf(t
*testing
.T
) {
878 // Special case for nil
879 if typ
:= TypeOf(nil); typ
!= nil {
880 t
.Errorf("expected nil type for nil value; got %v", typ
)
882 for _
, test
:= range deepEqualTests
{
887 typ
:= TypeOf(test
.a
)
889 t
.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test
.a
, typ
, test
.a
, v
.Type())
894 type Recursive
struct {
899 func TestDeepEqualRecursiveStruct(t
*testing
.T
) {
900 a
, b
:= new(Recursive
), new(Recursive
)
901 *a
= Recursive
{12, a
}
902 *b
= Recursive
{12, b
}
903 if !DeepEqual(a
, b
) {
904 t
.Error("DeepEqual(recursive same) = false, want true")
908 type _Complex
struct {
912 d
map[float64]float64
915 func TestDeepEqualComplexStruct(t
*testing
.T
) {
916 m
:= make(map[float64]float64)
917 stra
, strb
:= "hello", "hello"
918 a
, b
:= new(_Complex
), new(_Complex
)
919 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
920 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
921 if !DeepEqual(a
, b
) {
922 t
.Error("DeepEqual(complex same) = false, want true")
926 func TestDeepEqualComplexStructInequality(t
*testing
.T
) {
927 m
:= make(map[float64]float64)
928 stra
, strb
:= "hello", "helloo" // Difference is here
929 a
, b
:= new(_Complex
), new(_Complex
)
930 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
931 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
933 t
.Error("DeepEqual(complex different) = true, want false")
941 func TestDeepEqualUnexportedMap(t
*testing
.T
) {
942 // Check that DeepEqual can look at unexported fields.
943 x1
:= UnexpT
{map[int]int{1: 2}}
944 x2
:= UnexpT
{map[int]int{1: 2}}
945 if !DeepEqual(&x1
, &x2
) {
946 t
.Error("DeepEqual(x1, x2) = false, want true")
949 y1
:= UnexpT
{map[int]int{2: 3}}
950 if DeepEqual(&x1
, &y1
) {
951 t
.Error("DeepEqual(x1, y1) = true, want false")
955 func check2ndField(x
interface{}, offs
uintptr, t
*testing
.T
) {
957 f
:= s
.Type().Field(1)
958 if f
.Offset
!= offs
{
959 t
.Error("mismatched offsets in structure alignment:", f
.Offset
, offs
)
963 // Check that structure alignment & offsets viewed through reflect agree with those
964 // from the compiler itself.
965 func TestAlignment(t
*testing
.T
) {
966 type T1inner
struct {
973 type T2inner
struct {
981 x
:= T1
{T1inner
{2}, 17}
982 check2ndField(x
, uintptr(unsafe
.Pointer(&x
.f
))-uintptr(unsafe
.Pointer(&x
)), t
)
984 x1
:= T2
{T2inner
{2, 3}, 17}
985 check2ndField(x1
, uintptr(unsafe
.Pointer(&x1
.f
))-uintptr(unsafe
.Pointer(&x1
)), t
)
988 func Nil(a
interface{}, t
*testing
.T
) {
989 n
:= ValueOf(a
).Field(0)
991 t
.Errorf("%v should be nil", a
)
995 func NotNil(a
interface{}, t
*testing
.T
) {
996 n
:= ValueOf(a
).Field(0)
998 t
.Errorf("value of type %v should not be nil", ValueOf(a
).Type().String())
1002 func TestIsNil(t
*testing
.T
) {
1003 // These implement IsNil.
1004 // Wrap in extra struct to hide interface type.
1005 doNil
:= []interface{}{
1007 struct{ x
interface{} }{},
1008 struct{ x
map[string]int }{},
1009 struct{ x
func() bool }{},
1010 struct{ x
chan int }{},
1011 struct{ x
[]string }{},
1013 for _
, ts
:= range doNil
{
1014 ty
:= TypeOf(ts
).Field(0).Type
1016 v
.IsNil() // panics if not okay to call
1019 // Check the implementations
1031 si
.x
= make([]int, 10)
1038 ci
.x
= make(chan int)
1045 mi
.x
= make(map[int]int)
1056 x
func(t
*testing
.T
)
1063 func TestInterfaceExtraction(t
*testing
.T
) {
1069 v
:= Indirect(ValueOf(&s
)).Field(0).Interface()
1070 if v
!= s
.W
.(interface{}) {
1071 t
.Error("Interface() on interface: ", v
, s
.W
)
1075 func TestNilPtrValueSub(t
*testing
.T
) {
1077 if pv
:= ValueOf(pi
); pv
.Elem().IsValid() {
1078 t
.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1082 func TestMap(t
*testing
.T
) {
1083 m
:= map[string]int{"a": 1, "b": 2}
1085 if n
:= mv
.Len(); n
!= len(m
) {
1086 t
.Errorf("Len = %d, want %d", n
, len(m
))
1088 keys
:= mv
.MapKeys()
1089 newmap
:= MakeMap(mv
.Type())
1090 for k
, v
:= range m
{
1091 // Check that returned Keys match keys in range.
1092 // These aren't required to be in the same order.
1094 for _
, kv
:= range keys
{
1095 if kv
.String() == k
{
1101 t
.Errorf("Missing key %q", k
)
1104 // Check that value lookup is correct.
1105 vv
:= mv
.MapIndex(ValueOf(k
))
1106 if vi
:= vv
.Int(); vi
!= int64(v
) {
1107 t
.Errorf("Key %q: have value %d, want %d", k
, vi
, v
)
1110 // Copy into new map.
1111 newmap
.SetMapIndex(ValueOf(k
), ValueOf(v
))
1113 vv
:= mv
.MapIndex(ValueOf("not-present"))
1115 t
.Errorf("Invalid key: got non-nil value %s", valueToString(vv
))
1118 newm
:= newmap
.Interface().(map[string]int)
1119 if len(newm
) != len(m
) {
1120 t
.Errorf("length after copy: newm=%d, m=%d", len(newm
), len(m
))
1123 for k
, v
:= range newm
{
1126 t
.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k
, v
, k
, mv
, ok
)
1130 newmap
.SetMapIndex(ValueOf("a"), Value
{})
1133 t
.Errorf("newm[\"a\"] = %d after delete", v
)
1136 mv
= ValueOf(&m
).Elem()
1137 mv
.Set(Zero(mv
.Type()))
1139 t
.Errorf("mv.Set(nil) failed")
1143 func TestNilMap(t
*testing
.T
) {
1144 var m
map[string]int
1146 keys
:= mv
.MapKeys()
1148 t
.Errorf(">0 keys for nil map: %v", keys
)
1151 // Check that value for missing key is zero.
1152 x
:= mv
.MapIndex(ValueOf("hello"))
1153 if x
.Kind() != Invalid
{
1154 t
.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x
)
1157 // Check big value too.
1158 var mbig
map[string][10 << 20]byte
1159 x
= ValueOf(mbig
).MapIndex(ValueOf("hello"))
1160 if x
.Kind() != Invalid
{
1161 t
.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x
)
1164 // Test that deletes from a nil map succeed.
1165 mv
.SetMapIndex(ValueOf("hi"), Value
{})
1168 func TestChan(t
*testing
.T
) {
1169 for loop
:= 0; loop
< 2; loop
++ {
1173 // check both ways to allocate channels
1176 c
= make(chan int, 1)
1179 cv
= MakeChan(TypeOf(c
), 1)
1180 c
= cv
.Interface().(chan int)
1185 if i
:= <-c
; i
!= 2 {
1186 t
.Errorf("reflect Send 2, native recv %d", i
)
1191 if i
, ok
:= cv
.Recv(); i
.Int() != 3 ||
!ok
{
1192 t
.Errorf("native send 3, reflect Recv %d, %t", i
.Int(), ok
)
1196 val
, ok
:= cv
.TryRecv()
1197 if val
.IsValid() || ok
{
1198 t
.Errorf("TryRecv on empty chan: %s, %t", valueToString(val
), ok
)
1203 val
, ok
= cv
.TryRecv()
1205 t
.Errorf("TryRecv on ready chan got nil")
1206 } else if i
:= val
.Int(); i
!= 4 ||
!ok
{
1207 t
.Errorf("native send 4, TryRecv %d, %t", i
, ok
)
1212 ok
= cv
.TrySend(ValueOf(5))
1215 t
.Errorf("TrySend on full chan succeeded: value %d", i
)
1219 ok
= cv
.TrySend(ValueOf(6))
1221 t
.Errorf("TrySend on empty chan failed")
1224 t
.Errorf("TrySend failed but it did send %d", x
)
1228 if i
= <-c
; i
!= 6 {
1229 t
.Errorf("TrySend 6, recv %d", i
)
1236 if i
, ok
:= cv
.Recv(); i
.Int() != 123 ||
!ok
{
1237 t
.Errorf("send 123 then close; Recv %d, %t", i
.Int(), ok
)
1239 if i
, ok
:= cv
.Recv(); i
.Int() != 0 || ok
{
1240 t
.Errorf("after close Recv %d, %t", i
.Int(), ok
)
1244 // check creation of unbuffered channel
1246 cv
:= MakeChan(TypeOf(c
), 0)
1247 c
= cv
.Interface().(chan int)
1248 if cv
.TrySend(ValueOf(7)) {
1249 t
.Errorf("TrySend on sync chan succeeded")
1251 if v
, ok
:= cv
.TryRecv(); v
.IsValid() || ok
{
1252 t
.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v
.IsValid(), ok
)
1256 cv
= MakeChan(TypeOf(c
), 10)
1257 c
= cv
.Interface().(chan int)
1258 for i
:= 0; i
< 3; i
++ {
1261 if l
, m
:= cv
.Len(), cv
.Cap(); l
!= len(c
) || m
!= cap(c
) {
1262 t
.Errorf("Len/Cap = %d/%d want %d/%d", l
, m
, len(c
), cap(c
))
1266 // caseInfo describes a single case in a select test.
1267 type caseInfo
struct {
1276 var allselect
= flag
.Bool("allselect", false, "exhaustive select test")
1278 func TestSelect(t
*testing
.T
) {
1279 selectWatch
.once
.Do(func() { go selectWatcher() })
1283 newop
:= func(n
int, cap int) (ch
, val Value
) {
1286 c
:= make(chan int, cap)
1290 c
:= make(chan string, cap)
1292 val
= ValueOf(fmt
.Sprint(n
))
1297 for n
:= 0; x
.Next(); n
++ {
1298 if testing
.Short() && n
>= 1000 {
1301 if n
>= 100000 && !*allselect
{
1304 if n%100000
== 0 && testing
.Verbose() {
1305 println("TestSelect", n
)
1307 var cases
[]SelectCase
1312 ch
, val
:= newop(len(cases
), 1)
1313 cases
= append(cases
, SelectCase
{
1318 info
= append(info
, caseInfo
{desc
: "ready send", canSelect
: true})
1323 ch
, val
:= newop(len(cases
), 1)
1325 cases
= append(cases
, SelectCase
{
1329 info
= append(info
, caseInfo
{desc
: "ready recv", canSelect
: true, recv
: val
})
1334 ch
, val
:= newop(len(cases
), 0)
1335 cases
= append(cases
, SelectCase
{
1342 f
:= func() { ch
.Recv() }
1343 info
= append(info
, caseInfo
{desc
: "blocking send", helper
: f
})
1345 info
= append(info
, caseInfo
{desc
: "blocking send"})
1351 ch
, val
:= newop(len(cases
), 0)
1352 cases
= append(cases
, SelectCase
{
1358 f
:= func() { ch
.Send(val
) }
1359 info
= append(info
, caseInfo
{desc
: "blocking recv", recv
: val
, helper
: f
})
1361 info
= append(info
, caseInfo
{desc
: "blocking recv"})
1367 // Maybe include value to send.
1372 cases
= append(cases
, SelectCase
{
1376 info
= append(info
, caseInfo
{desc
: "zero Chan send"})
1379 // Zero Chan receive.
1381 cases
= append(cases
, SelectCase
{
1384 info
= append(info
, caseInfo
{desc
: "zero Chan recv"})
1389 cases
= append(cases
, SelectCase
{
1391 Chan
: ValueOf((chan int)(nil)),
1394 info
= append(info
, caseInfo
{desc
: "nil Chan send"})
1399 cases
= append(cases
, SelectCase
{
1401 Chan
: ValueOf((chan int)(nil)),
1403 info
= append(info
, caseInfo
{desc
: "nil Chan recv"})
1406 // closed Chan send.
1408 ch
:= make(chan int)
1410 cases
= append(cases
, SelectCase
{
1415 info
= append(info
, caseInfo
{desc
: "closed Chan send", canSelect
: true, panic: true})
1418 // closed Chan recv.
1420 ch
, val
:= newop(len(cases
), 0)
1422 val
= Zero(val
.Type())
1423 cases
= append(cases
, SelectCase
{
1427 info
= append(info
, caseInfo
{desc
: "closed Chan recv", canSelect
: true, closed: true, recv
: val
})
1430 var helper
func() // goroutine to help the select complete
1432 // Add default? Must be last case here, but will permute.
1433 // Add the default if the select would otherwise
1434 // block forever, and maybe add it anyway.
1440 for i
, c
:= range info
{
1448 } else if c
.helper
!= nil {
1450 helpers
= append(helpers
, i
)
1453 if !canProceed || x
.Maybe() {
1454 cases
= append(cases
, SelectCase
{
1457 info
= append(info
, caseInfo
{desc
: "default", canSelect
: canBlock
})
1459 } else if canBlock
{
1460 // Select needs to communicate with another goroutine.
1461 cas
:= &info
[helpers
[x
.Choose(len(helpers
))]]
1463 cas
.canSelect
= true
1467 // Permute cases and case info.
1468 // Doing too much here makes the exhaustive loop
1469 // too exhausting, so just do two swaps.
1470 for loop
:= 0; loop
< 2; loop
++ {
1471 i
:= x
.Choose(len(cases
))
1472 j
:= x
.Choose(len(cases
))
1473 cases
[i
], cases
[j
] = cases
[j
], cases
[i
]
1474 info
[i
], info
[j
] = info
[j
], info
[i
]
1478 // We wait before kicking off a goroutine to satisfy a blocked select.
1479 // The pause needs to be big enough to let the select block before
1480 // we run the helper, but if we lose that race once in a while it's okay: the
1481 // select will just proceed immediately. Not a big deal.
1482 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1483 pause
:= 10 * time
.Microsecond
1484 if testing
.Short() {
1485 pause
= 100 * time
.Microsecond
1487 time
.AfterFunc(pause
, helper
)
1491 i
, recv
, recvOK
, panicErr
:= runSelect(cases
, info
)
1492 if panicErr
!= nil && !canPanic
{
1493 t
.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info
), panicErr
)
1495 if panicErr
== nil && canPanic
&& numCanSelect
== 1 {
1496 t
.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info
), i
)
1498 if panicErr
!= nil {
1506 recvStr
= fmt
.Sprintf(", received %v, %v", recv
.Interface(), recvOK
)
1508 t
.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info
), i
, recvStr
)
1512 t
.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info
), i
)
1516 if cases
[i
].Dir
== SelectRecv
{
1517 if !recv
.IsValid() {
1518 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, cas
.recv
.Interface(), !cas
.closed)
1520 if !cas
.recv
.IsValid() {
1521 t
.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info
), i
)
1523 if recv
.Interface() != cas
.recv
.Interface() || recvOK
!= !cas
.closed {
1524 if recv
.Interface() == cas
.recv
.Interface() && recvOK
== !cas
.closed {
1525 t
.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info
), i
, recv
.Interface(), recvOK
, recv
.Interface())
1527 t
.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info
), i
, recv
.Interface(), recvOK
, cas
.recv
.Interface(), !cas
.closed)
1530 if recv
.IsValid() || recvOK
{
1531 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, Value
{}, false)
1537 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1538 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1539 // an error describing the select and panics the entire test binary.
1540 var selectWatch
struct {
1547 func selectWatcher() {
1549 time
.Sleep(1 * time
.Second
)
1551 if selectWatch
.info
!= nil && time
.Since(selectWatch
.now
) > 10*time
.Second
{
1552 fmt
.Fprintf(os
.Stderr
, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch
.info
))
1553 panic("select stuck")
1555 selectWatch
.Unlock()
1559 // runSelect runs a single select test.
1560 // It returns the values returned by Select but also returns
1561 // a panic value if the Select panics.
1562 func runSelect(cases
[]SelectCase
, info
[]caseInfo
) (chosen
int, recv Value
, recvOK
bool, panicErr
interface{}) {
1564 panicErr
= recover()
1567 selectWatch
.info
= nil
1568 selectWatch
.Unlock()
1572 selectWatch
.now
= time
.Now()
1573 selectWatch
.info
= info
1574 selectWatch
.Unlock()
1576 chosen
, recv
, recvOK
= Select(cases
)
1580 // fmtSelect formats the information about a single select test.
1581 func fmtSelect(info
[]caseInfo
) string {
1582 var buf bytes
.Buffer
1583 fmt
.Fprintf(&buf
, "\nselect {\n")
1584 for i
, cas
:= range info
{
1585 fmt
.Fprintf(&buf
, "%d: %s", i
, cas
.desc
)
1586 if cas
.recv
.IsValid() {
1587 fmt
.Fprintf(&buf
, " val=%#v", cas
.recv
.Interface())
1590 fmt
.Fprintf(&buf
, " canselect")
1593 fmt
.Fprintf(&buf
, " panic")
1595 fmt
.Fprintf(&buf
, "\n")
1597 fmt
.Fprintf(&buf
, "}")
1603 // Difficult test for function call because of
1604 // implicit padding between arguments.
1605 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) {
1606 return b
, c
, d
, e
, f
, g
, h
1609 func TestFunc(t
*testing
.T
) {
1610 ret
:= ValueOf(dummy
).Call([]Value
{
1614 ValueOf(two
{40, 50}),
1616 ValueOf(float32(70)),
1620 t
.Fatalf("Call returned %d values, want 7", len(ret
))
1623 i
:= byte(ret
[0].Uint())
1624 j
:= int(ret
[1].Int())
1625 k
:= byte(ret
[2].Uint())
1626 l
:= ret
[3].Interface().(two
)
1627 m
:= byte(ret
[4].Uint())
1628 n
:= float32(ret
[5].Float())
1629 o
:= byte(ret
[6].Uint())
1631 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1632 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
)
1635 for i
, v
:= range ret
{
1637 t
.Errorf("result %d is addressable", i
)
1642 func TestCallConvert(t
*testing
.T
) {
1643 v
:= ValueOf(new(io
.ReadWriter
)).Elem()
1644 f
:= ValueOf(func(r io
.Reader
) io
.Reader
{ return r
})
1645 out
:= f
.Call([]Value
{v
})
1646 if len(out
) != 1 || out
[0].Type() != TypeOf(new(io
.Reader
)).Elem() ||
!out
[0].IsNil() {
1647 t
.Errorf("expected [nil], got %v", out
)
1651 type emptyStruct
struct{}
1653 type nonEmptyStruct
struct {
1657 func returnEmpty() emptyStruct
{
1658 return emptyStruct
{}
1661 func takesEmpty(e emptyStruct
) {
1664 func returnNonEmpty(i
int) nonEmptyStruct
{
1665 return nonEmptyStruct
{member
: i
}
1668 func takesNonEmpty(n nonEmptyStruct
) int {
1672 func TestCallWithStruct(t
*testing
.T
) {
1673 r
:= ValueOf(returnEmpty
).Call(nil)
1674 if len(r
) != 1 || r
[0].Type() != TypeOf(emptyStruct
{}) {
1675 t
.Errorf("returning empty struct returned %#v instead", r
)
1677 r
= ValueOf(takesEmpty
).Call([]Value
{ValueOf(emptyStruct
{})})
1679 t
.Errorf("takesEmpty returned values: %#v", r
)
1681 r
= ValueOf(returnNonEmpty
).Call([]Value
{ValueOf(42)})
1682 if len(r
) != 1 || r
[0].Type() != TypeOf(nonEmptyStruct
{}) || r
[0].Field(0).Int() != 42 {
1683 t
.Errorf("returnNonEmpty returned %#v", r
)
1685 r
= ValueOf(takesNonEmpty
).Call([]Value
{ValueOf(nonEmptyStruct
{member
: 42})})
1686 if len(r
) != 1 || r
[0].Type() != TypeOf(1) || r
[0].Int() != 42 {
1687 t
.Errorf("takesNonEmpty returned %#v", r
)
1691 func TestCallReturnsEmpty(t
*testing
.T
) {
1692 if runtime
.Compiler
== "gccgo" {
1693 t
.Skip("skipping on gccgo: imprecise stack can keep i live")
1695 // Issue 21717: past-the-end pointer write in Call with
1696 // nonzero-sized frame and zero-sized return value.
1698 var finalized
uint32
1699 f
:= func() (emptyStruct
, *int) {
1701 runtime
.SetFinalizer(i
, func(*int) { atomic
.StoreUint32(&finalized
, 1) })
1702 return emptyStruct
{}, i
1704 v
:= ValueOf(f
).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
1705 timeout
:= time
.After(5 * time
.Second
)
1706 for atomic
.LoadUint32(&finalized
) == 0 {
1709 t
.Fatal("finalizer did not run")
1715 runtime
.KeepAlive(v
)
1718 func BenchmarkCall(b
*testing
.B
) {
1719 fv
:= ValueOf(func(a
, b
string) {})
1721 b
.RunParallel(func(pb
*testing
.PB
) {
1722 args
:= []Value
{ValueOf("a"), ValueOf("b")}
1729 func BenchmarkCallArgCopy(b
*testing
.B
) {
1730 byteArray
:= func(n
int) Value
{
1731 return Zero(ArrayOf(n
, TypeOf(byte(0))))
1733 sizes
:= [...]struct {
1737 {ValueOf(func(a
[128]byte) {}), byteArray(128)},
1738 {ValueOf(func(a
[256]byte) {}), byteArray(256)},
1739 {ValueOf(func(a
[1024]byte) {}), byteArray(1024)},
1740 {ValueOf(func(a
[4096]byte) {}), byteArray(4096)},
1741 {ValueOf(func(a
[65536]byte) {}), byteArray(65536)},
1743 for _
, size
:= range sizes
{
1744 bench
:= func(b
*testing
.B
) {
1745 args
:= []Value
{size
.arg
}
1746 b
.SetBytes(int64(size
.arg
.Len()))
1748 b
.RunParallel(func(pb
*testing
.PB
) {
1754 name
:= fmt
.Sprintf("size=%v", size
.arg
.Len())
1759 func TestMakeFunc(t
*testing
.T
) {
1761 fv
:= MakeFunc(TypeOf(f
), func(in
[]Value
) []Value
{ return in
})
1762 ValueOf(&f
).Elem().Set(fv
)
1764 // Call g with small arguments so that there is
1765 // something predictable (and different from the
1766 // correct results) in those positions on the stack.
1768 g(1, 2, 3, two
{4, 5}, 6, 7, 8)
1770 // Call constructed function f.
1771 i
, j
, k
, l
, m
, n
, o
:= f(10, 20, 30, two
{40, 50}, 60, 70, 80)
1772 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1773 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
)
1777 func TestMakeFuncInterface(t
*testing
.T
) {
1778 fn
:= func(i
int) int { return i
}
1779 incr
:= func(in
[]Value
) []Value
{
1780 return []Value
{ValueOf(int(in
[0].Int() + 1))}
1782 fv
:= MakeFunc(TypeOf(fn
), incr
)
1783 ValueOf(&fn
).Elem().Set(fv
)
1784 if r
:= fn(2); r
!= 3 {
1785 t
.Errorf("Call returned %d, want 3", r
)
1787 if r
:= fv
.Call([]Value
{ValueOf(14)})[0].Int(); r
!= 15 {
1788 t
.Errorf("Call returned %d, want 15", r
)
1790 if r
:= fv
.Interface().(func(int) int)(26); r
!= 27 {
1791 t
.Errorf("Call returned %d, want 27", r
)
1795 func TestMakeFuncVariadic(t
*testing
.T
) {
1796 // Test that variadic arguments are packed into a slice and passed as last arg
1797 fn
:= func(_
int, is
...int) []int { return nil }
1798 fv
:= MakeFunc(TypeOf(fn
), func(in
[]Value
) []Value
{ return in
[1:2] })
1799 ValueOf(&fn
).Elem().Set(fv
)
1802 if r
[0] != 2 || r
[1] != 3 {
1803 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1806 r
= fn(1, []int{2, 3}...)
1807 if r
[0] != 2 || r
[1] != 3 {
1808 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1811 r
= fv
.Call([]Value
{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1812 if r
[0] != 2 || r
[1] != 3 {
1813 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1816 r
= fv
.CallSlice([]Value
{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1817 if r
[0] != 2 || r
[1] != 3 {
1818 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1821 f
:= fv
.Interface().(func(int, ...int) []int)
1824 if r
[0] != 2 || r
[1] != 3 {
1825 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1827 r
= f(1, []int{2, 3}...)
1828 if r
[0] != 2 || r
[1] != 3 {
1829 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1837 // This will be index 0.
1838 func (p Point
) AnotherMethod(scale
int) int {
1842 // This will be index 1.
1843 func (p Point
) Dist(scale
int) int {
1844 //println("Point.Dist", p.x, p.y, scale)
1845 return p
.x
*p
.x
*scale
+ p
.y
*p
.y
*scale
1848 // This will be index 2.
1849 func (p Point
) GCMethod(k
int) int {
1854 // This will be index 3.
1855 func (p Point
) NoArgs() {
1856 // Exercise no-argument/no-result paths.
1859 // This will be index 4.
1860 func (p Point
) TotalDist(points
...Point
) int {
1862 for _
, q
:= range points
{
1865 tot
+= dx
*dx
+ dy
*dy
// Should call Sqrt, but it's just a test.
1871 func TestMethod(t
*testing
.T
) {
1872 // Non-curried method of type.
1874 i
:= TypeOf(p
).Method(1).Func
.Call([]Value
{ValueOf(p
), ValueOf(10)})[0].Int()
1876 t
.Errorf("Type Method returned %d; want 250", i
)
1879 m
, ok
:= TypeOf(p
).MethodByName("Dist")
1881 t
.Fatalf("method by name failed")
1883 i
= m
.Func
.Call([]Value
{ValueOf(p
), ValueOf(11)})[0].Int()
1885 t
.Errorf("Type MethodByName returned %d; want 275", i
)
1888 m
, ok
= TypeOf(p
).MethodByName("NoArgs")
1890 t
.Fatalf("method by name failed")
1892 n
:= len(m
.Func
.Call([]Value
{ValueOf(p
)}))
1894 t
.Errorf("NoArgs returned %d values; want 0", n
)
1897 i
= TypeOf(&p
).Method(1).Func
.Call([]Value
{ValueOf(&p
), ValueOf(12)})[0].Int()
1899 t
.Errorf("Pointer Type Method returned %d; want 300", i
)
1902 m
, ok
= TypeOf(&p
).MethodByName("Dist")
1904 t
.Fatalf("ptr method by name failed")
1906 i
= m
.Func
.Call([]Value
{ValueOf(&p
), ValueOf(13)})[0].Int()
1908 t
.Errorf("Pointer Type MethodByName returned %d; want 325", i
)
1911 m
, ok
= TypeOf(&p
).MethodByName("NoArgs")
1913 t
.Fatalf("method by name failed")
1915 n
= len(m
.Func
.Call([]Value
{ValueOf(&p
)}))
1917 t
.Errorf("NoArgs returned %d values; want 0", n
)
1920 // Curried method of value.
1921 tfunc
:= TypeOf((func(int) int)(nil))
1922 v
:= ValueOf(p
).Method(1)
1923 if tt
:= v
.Type(); tt
!= tfunc
{
1924 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1926 i
= v
.Call([]Value
{ValueOf(14)})[0].Int()
1928 t
.Errorf("Value Method returned %d; want 350", i
)
1930 v
= ValueOf(p
).MethodByName("Dist")
1931 if tt
:= v
.Type(); tt
!= tfunc
{
1932 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
1934 i
= v
.Call([]Value
{ValueOf(15)})[0].Int()
1936 t
.Errorf("Value MethodByName returned %d; want 375", i
)
1938 v
= ValueOf(p
).MethodByName("NoArgs")
1941 // Curried method of pointer.
1942 v
= ValueOf(&p
).Method(1)
1943 if tt
:= v
.Type(); tt
!= tfunc
{
1944 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1946 i
= v
.Call([]Value
{ValueOf(16)})[0].Int()
1948 t
.Errorf("Pointer Value Method returned %d; want 400", i
)
1950 v
= ValueOf(&p
).MethodByName("Dist")
1951 if tt
:= v
.Type(); tt
!= tfunc
{
1952 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1954 i
= v
.Call([]Value
{ValueOf(17)})[0].Int()
1956 t
.Errorf("Pointer Value MethodByName returned %d; want 425", i
)
1958 v
= ValueOf(&p
).MethodByName("NoArgs")
1961 // Curried method of interface value.
1962 // Have to wrap interface value in a struct to get at it.
1963 // Passing it to ValueOf directly would
1964 // access the underlying Point, not the interface.
1968 pv
:= ValueOf(&x
).Elem()
1970 if tt
:= v
.Type(); tt
!= tfunc
{
1971 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
1973 i
= v
.Call([]Value
{ValueOf(18)})[0].Int()
1975 t
.Errorf("Interface Method returned %d; want 450", i
)
1977 v
= pv
.MethodByName("Dist")
1978 if tt
:= v
.Type(); tt
!= tfunc
{
1979 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
1981 i
= v
.Call([]Value
{ValueOf(19)})[0].Int()
1983 t
.Errorf("Interface MethodByName returned %d; want 475", i
)
1987 func TestMethodValue(t
*testing
.T
) {
1991 // Curried method of value.
1992 tfunc
:= TypeOf((func(int) int)(nil))
1993 v
:= ValueOf(p
).Method(1)
1994 if tt
:= v
.Type(); tt
!= tfunc
{
1995 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1997 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(10)})[0].Int()
1999 t
.Errorf("Value Method returned %d; want 250", i
)
2001 v
= ValueOf(p
).MethodByName("Dist")
2002 if tt
:= v
.Type(); tt
!= tfunc
{
2003 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
2005 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(11)})[0].Int()
2007 t
.Errorf("Value MethodByName returned %d; want 275", i
)
2009 v
= ValueOf(p
).MethodByName("NoArgs")
2010 ValueOf(v
.Interface()).Call(nil)
2011 v
.Interface().(func())()
2013 // Curried method of pointer.
2014 v
= ValueOf(&p
).Method(1)
2015 if tt
:= v
.Type(); tt
!= tfunc
{
2016 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
2018 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(12)})[0].Int()
2020 t
.Errorf("Pointer Value Method returned %d; want 300", i
)
2022 v
= ValueOf(&p
).MethodByName("Dist")
2023 if tt
:= v
.Type(); tt
!= tfunc
{
2024 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
2026 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(13)})[0].Int()
2028 t
.Errorf("Pointer Value MethodByName returned %d; want 325", i
)
2030 v
= ValueOf(&p
).MethodByName("NoArgs")
2031 ValueOf(v
.Interface()).Call(nil)
2032 v
.Interface().(func())()
2034 // Curried method of pointer to pointer.
2036 v
= ValueOf(&pp
).Elem().Method(1)
2037 if tt
:= v
.Type(); tt
!= tfunc
{
2038 t
.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt
, tfunc
)
2040 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(14)})[0].Int()
2042 t
.Errorf("Pointer Pointer Value Method returned %d; want 350", i
)
2044 v
= ValueOf(&pp
).Elem().MethodByName("Dist")
2045 if tt
:= v
.Type(); tt
!= tfunc
{
2046 t
.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
2048 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(15)})[0].Int()
2050 t
.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i
)
2053 // Curried method of interface value.
2054 // Have to wrap interface value in a struct to get at it.
2055 // Passing it to ValueOf directly would
2056 // access the underlying Point, not the interface.
2062 pv
:= ValueOf(s
).Field(0)
2064 if tt
:= v
.Type(); tt
!= tfunc
{
2065 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
2067 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(16)})[0].Int()
2069 t
.Errorf("Interface Method returned %d; want 400", i
)
2071 v
= pv
.MethodByName("Dist")
2072 if tt
:= v
.Type(); tt
!= tfunc
{
2073 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
2075 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(17)})[0].Int()
2077 t
.Errorf("Interface MethodByName returned %d; want 425", i
)
2081 func TestVariadicMethodValue(t
*testing
.T
) {
2083 points
:= []Point
{{20, 21}, {22, 23}, {24, 25}}
2084 want
:= int64(p
.TotalDist(points
[0], points
[1], points
[2]))
2086 // Curried method of value.
2087 tfunc
:= TypeOf((func(...Point
) int)(nil))
2088 v
:= ValueOf(p
).Method(4)
2089 if tt
:= v
.Type(); tt
!= tfunc
{
2090 t
.Errorf("Variadic Method Type is %s; want %s", tt
, tfunc
)
2092 i
:= ValueOf(v
.Interface()).Call([]Value
{ValueOf(points
[0]), ValueOf(points
[1]), ValueOf(points
[2])})[0].Int()
2094 t
.Errorf("Variadic Method returned %d; want %d", i
, want
)
2096 i
= ValueOf(v
.Interface()).CallSlice([]Value
{ValueOf(points
)})[0].Int()
2098 t
.Errorf("Variadic Method CallSlice returned %d; want %d", i
, want
)
2101 f
:= v
.Interface().(func(...Point
) int)
2102 i
= int64(f(points
[0], points
[1], points
[2]))
2104 t
.Errorf("Variadic Method Interface returned %d; want %d", i
, want
)
2106 i
= int64(f(points
...))
2108 t
.Errorf("Variadic Method Interface Slice returned %d; want %d", i
, want
)
2112 // Reflect version of $GOROOT/test/method5.go
2114 // Concrete types implementing M method.
2115 // Smaller than a word, word-sized, larger than a word.
2116 // Value and pointer receivers.
2118 type Tinter
interface {
2119 M(int, byte) (byte, int)
2124 func (v Tsmallv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
2128 func (p
*Tsmallp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
2132 func (v Twordv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
2136 func (p
*Twordp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
2138 type Tbigv
[2]uintptr
2140 func (v Tbigv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
2142 type Tbigp
[2]uintptr
2144 func (p
*Tbigp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
2146 type tinter
interface {
2147 m(int, byte) (byte, int)
2150 // Embedding via pointer.
2167 func (t4 Tm4
) M(x
int, b
byte) (byte, int) { return b
, x
+ 40 }
2169 func TestMethod5(t
*testing
.T
) {
2170 CheckF
:= func(name
string, f
func(int, byte) (byte, int), inc
int) {
2172 if b
!= 99 || x
!= 1000+inc
{
2173 t
.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
2177 CheckV
:= func(name
string, i Value
, inc
int) {
2178 bx
:= i
.Method(0).Call([]Value
{ValueOf(1000), ValueOf(byte(99))})
2179 b
:= bx
[0].Interface()
2180 x
:= bx
[1].Interface()
2181 if b
!= byte(99) || x
!= 1000+inc
{
2182 t
.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
2185 CheckF(name
+".M", i
.Method(0).Interface().(func(int, byte) (byte, int)), inc
)
2188 var TinterType
= TypeOf(new(Tinter
)).Elem()
2190 CheckI
:= func(name
string, i
interface{}, inc
int) {
2192 CheckV(name
, v
, inc
)
2193 CheckV("(i="+name
+")", v
.Convert(TinterType
), inc
)
2198 CheckI("&sv", &sv
, 1)
2201 CheckI("&sp", &sp
, 2)
2205 CheckI("&wv", &wv
, 3)
2208 CheckI("&wp", &wp
, 4)
2210 bv
:= Tbigv([2]uintptr{5, 6})
2211 CheckI("bv", bv
, 11)
2212 CheckI("&bv", &bv
, 11)
2214 bp
:= Tbigp([2]uintptr{7, 8})
2215 CheckI("&bp", &bp
, 15)
2221 CheckI("t4", t4
, 40)
2222 CheckI("&t4", &t4
, 40)
2223 CheckI("t3", t3
, 40)
2224 CheckI("&t3", &t3
, 40)
2225 CheckI("t2", t2
, 40)
2226 CheckI("&t2", &t2
, 40)
2227 CheckI("t1", t1
, 40)
2228 CheckI("&t1", &t1
, 40)
2231 vnil
:= ValueOf(&tnil
).Elem()
2232 shouldPanic(func() { vnil
.Method(0) })
2235 func TestInterfaceSet(t
*testing
.T
) {
2244 sv
:= ValueOf(&s
).Elem()
2245 sv
.Field(0).Set(ValueOf(p
))
2246 if q
:= s
.I
.(*Point
); q
!= p
{
2247 t
.Errorf("i: have %p want %p", q
, p
)
2252 if q
:= s
.P
.(*Point
); q
!= p
{
2253 t
.Errorf("i: have %p want %p", q
, p
)
2256 i
:= pv
.Method(0).Call([]Value
{ValueOf(10)})[0].Int()
2258 t
.Errorf("Interface Method returned %d; want 250", i
)
2267 func TestAnonymousFields(t
*testing
.T
) {
2268 var field StructField
2272 if field
, ok
= type1
.FieldByName("int"); !ok
{
2273 t
.Fatal("no field 'int'")
2275 if field
.Index
[0] != 1 {
2276 t
.Error("field index should be 1; is", field
.Index
)
2330 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2352 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2371 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2385 var fieldTests
= []FTest
{
2386 {struct{}{}, "", nil, 0},
2387 {struct{}{}, "Foo", nil, 0},
2388 {S0
{A
: 'a'}, "A", []int{0}, 'a'},
2389 {S0
{}, "D", nil, 0},
2390 {S1
{S0
: S0
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2391 {S1
{B
: 'b'}, "B", []int{0}, 'b'},
2392 {S1
{}, "S0", []int{1}, 0},
2393 {S1
{S0
: S0
{C
: 'c'}}, "C", []int{1, 2}, 'c'},
2394 {S2
{A
: 'a'}, "A", []int{0}, 'a'},
2395 {S2
{}, "S1", []int{1}, 0},
2396 {S2
{S1
: &S1
{B
: 'b'}}, "B", []int{1, 0}, 'b'},
2397 {S2
{S1
: &S1
{S0
: S0
{C
: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2398 {S2
{}, "D", nil, 0},
2399 {S3
{}, "S1", nil, 0},
2400 {S3
{S2
: S2
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2401 {S3
{}, "B", nil, 0},
2402 {S3
{D
: 'd'}, "D", []int{2}, 0},
2403 {S3
{E
: 'e'}, "E", []int{3}, 'e'},
2404 {S4
{A
: 'a'}, "A", []int{1}, 'a'},
2405 {S4
{}, "B", nil, 0},
2406 {S5
{}, "X", nil, 0},
2407 {S5
{}, "Y", []int{2, 0, 1}, 0},
2408 {S10
{}, "X", nil, 0},
2409 {S10
{}, "Y", []int{2, 0, 0, 1}, 0},
2410 {S14
{}, "X", nil, 0},
2413 func TestFieldByIndex(t
*testing
.T
) {
2414 for _
, test
:= range fieldTests
{
2416 f
:= s
.FieldByIndex(test
.index
)
2418 if test
.index
!= nil {
2419 if f
.Name
!= test
.name
{
2420 t
.Errorf("%s.%s found; want %s", s
.Name(), f
.Name
, test
.name
)
2423 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2425 } else if len(test
.index
) > 0 {
2426 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2429 if test
.value
!= 0 {
2430 v
:= ValueOf(test
.s
).FieldByIndex(test
.index
)
2432 if x
, ok
:= v
.Interface().(int); ok
{
2433 if x
!= test
.value
{
2434 t
.Errorf("%s%v is %d; want %d", s
.Name(), test
.index
, x
, test
.value
)
2437 t
.Errorf("%s%v value not an int", s
.Name(), test
.index
)
2440 t
.Errorf("%s%v value not found", s
.Name(), test
.index
)
2446 func TestFieldByName(t
*testing
.T
) {
2447 for _
, test
:= range fieldTests
{
2449 f
, found
:= s
.FieldByName(test
.name
)
2451 if test
.index
!= nil {
2452 // Verify field depth and index.
2453 if len(f
.Index
) != len(test
.index
) {
2454 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
)
2456 for i
, x
:= range f
.Index
{
2457 if x
!= test
.index
[i
] {
2458 t
.Errorf("%s.%s.Index[%d] is %d; want %d", s
.Name(), test
.name
, i
, x
, test
.index
[i
])
2463 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2465 } else if len(test
.index
) > 0 {
2466 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2469 if test
.value
!= 0 {
2470 v
:= ValueOf(test
.s
).FieldByName(test
.name
)
2472 if x
, ok
:= v
.Interface().(int); ok
{
2473 if x
!= test
.value
{
2474 t
.Errorf("%s.%s is %d; want %d", s
.Name(), test
.name
, x
, test
.value
)
2477 t
.Errorf("%s.%s value not an int", s
.Name(), test
.name
)
2480 t
.Errorf("%s.%s value not found", s
.Name(), test
.name
)
2486 func TestImportPath(t
*testing
.T
) {
2491 {TypeOf(&base64
.Encoding
{}).Elem(), "encoding/base64"},
2492 {TypeOf(int(0)), ""},
2493 {TypeOf(int8(0)), ""},
2494 {TypeOf(int16(0)), ""},
2495 {TypeOf(int32(0)), ""},
2496 {TypeOf(int64(0)), ""},
2497 {TypeOf(uint(0)), ""},
2498 {TypeOf(uint8(0)), ""},
2499 {TypeOf(uint16(0)), ""},
2500 {TypeOf(uint32(0)), ""},
2501 {TypeOf(uint64(0)), ""},
2502 {TypeOf(uintptr(0)), ""},
2503 {TypeOf(float32(0)), ""},
2504 {TypeOf(float64(0)), ""},
2505 {TypeOf(complex64(0)), ""},
2506 {TypeOf(complex128(0)), ""},
2507 {TypeOf(byte(0)), ""},
2508 {TypeOf(rune(0)), ""},
2509 {TypeOf([]byte(nil)), ""},
2510 {TypeOf([]rune(nil)), ""},
2511 {TypeOf(string("")), ""},
2512 {TypeOf((*interface{})(nil)).Elem(), ""},
2513 {TypeOf((*byte)(nil)), ""},
2514 {TypeOf((*rune
)(nil)), ""},
2515 {TypeOf((*int64)(nil)), ""},
2516 {TypeOf(map[string]int{}), ""},
2517 {TypeOf((*error
)(nil)).Elem(), ""},
2518 {TypeOf((*Point
)(nil)), ""},
2519 {TypeOf((*Point
)(nil)).Elem(), "reflect_test"},
2521 for _
, test
:= range tests
{
2522 if path
:= test
.t
.PkgPath(); path
!= test
.path
{
2523 t
.Errorf("%v.PkgPath() = %q, want %q", test
.t
, path
, test
.path
)
2528 func TestFieldPkgPath(t
*testing
.T
) {
2530 typ
:= TypeOf(struct {
2538 type pkgpathTest
struct {
2544 checkPkgPath
:= func(name
string, s
[]pkgpathTest
) {
2545 for _
, test
:= range s
{
2546 f
:= typ
.FieldByIndex(test
.index
)
2547 if got
, want
:= f
.PkgPath
, test
.pkgPath
; got
!= want
{
2548 t
.Errorf("%s: Field(%d).PkgPath = %q, want %q", name
, test
.index
, got
, want
)
2550 if got
, want
:= f
.Anonymous
, test
.anonymous
; got
!= want
{
2551 t
.Errorf("%s: Field(%d).Anonymous = %v, want %v", name
, test
.index
, got
, want
)
2556 checkPkgPath("testStruct", []pkgpathTest
{
2557 {[]int{0}, "", false}, // Exported
2558 {[]int{1}, "reflect_test", false}, // unexported
2559 {[]int{2}, "", true}, // OtherPkgFields
2560 {[]int{2, 0}, "", false}, // OtherExported
2561 {[]int{2, 1}, "reflect", false}, // otherUnexported
2562 {[]int{3}, "reflect_test", true}, // int
2563 {[]int{4}, "reflect_test", true}, // *x
2566 type localOtherPkgFields OtherPkgFields
2567 typ
= TypeOf(localOtherPkgFields
{})
2568 checkPkgPath("localOtherPkgFields", []pkgpathTest
{
2569 {[]int{0}, "", false}, // OtherExported
2570 {[]int{1}, "reflect", false}, // otherUnexported
2574 func TestVariadicType(t
*testing
.T
) {
2575 // Test example from Type documentation.
2576 var f
func(x
int, y
...float64)
2578 if typ
.NumIn() == 2 && typ
.In(0) == TypeOf(int(0)) {
2580 if sl
.Kind() == Slice
{
2581 if sl
.Elem() == TypeOf(0.0) {
2589 t
.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2590 s
:= fmt
.Sprintf("have NumIn() = %d", typ
.NumIn())
2591 for i
:= 0; i
< typ
.NumIn(); i
++ {
2592 s
+= fmt
.Sprintf(", In(%d) = %s", i
, typ
.In(i
))
2606 func (*inner
) M() {}
2607 func (*outer
) M() {}
2609 func TestNestedMethods(t
*testing
.T
) {
2610 t
.Skip("fails on gccgo due to function wrappers")
2611 typ
:= TypeOf((*outer
)(nil))
2612 if typ
.NumMethod() != 1 || typ
.Method(0).Func
.Pointer() != ValueOf((*outer
).M
).Pointer() {
2613 t
.Errorf("Wrong method table for outer: (M=%p)", (*outer
).M
)
2614 for i
:= 0; i
< typ
.NumMethod(); i
++ {
2616 t
.Errorf("\t%d: %s %#x\n", i
, m
.Name
, m
.Func
.Pointer())
2623 func (*unexp
) f() (int32, int8) { return 7, 7 }
2624 func (*unexp
) g() (int64, int8) { return 8, 8 }
2626 type unexpI
interface {
2630 var unexpi unexpI
= new(unexp
)
2632 func TestUnexportedMethods(t
*testing
.T
) {
2633 typ
:= TypeOf(unexpi
)
2635 if got
:= typ
.NumMethod(); got
!= 0 {
2636 t
.Errorf("NumMethod=%d, want 0 satisfied methods", got
)
2640 type InnerInt
struct {
2644 type OuterInt
struct {
2649 func (i
*InnerInt
) M() int {
2653 func TestEmbeddedMethods(t
*testing
.T
) {
2654 /* This part of the test fails on gccgo due to function wrappers.
2655 typ := TypeOf((*OuterInt)(nil))
2656 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2657 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2658 for i := 0; i < typ.NumMethod(); i++ {
2660 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2666 if v
:= ValueOf(i
).Method(0).Call(nil)[0].Int(); v
!= 3 {
2667 t
.Errorf("i.M() = %d, want 3", v
)
2670 o
:= &OuterInt
{1, InnerInt
{2}}
2671 if v
:= ValueOf(o
).Method(0).Call(nil)[0].Int(); v
!= 2 {
2672 t
.Errorf("i.M() = %d, want 2", v
)
2676 if v
:= f(o
); v
!= 2 {
2677 t
.Errorf("f(o) = %d, want 2", v
)
2681 type FuncDDD
func(...interface{}) error
2683 func (f FuncDDD
) M() {}
2685 func TestNumMethodOnDDD(t
*testing
.T
) {
2686 rv
:= ValueOf((FuncDDD
)(nil))
2687 if n
:= rv
.NumMethod(); n
!= 1 {
2688 t
.Fatalf("NumMethod()=%d, want 1", n
)
2692 func TestPtrTo(t
*testing
.T
) {
2693 // This block of code means that the ptrToThis field of the
2694 // reflect data for *unsafe.Pointer is non zero, see
2695 // https://golang.org/issue/19003
2696 var x unsafe
.Pointer
2703 for i
= 0; i
< 100; i
++ {
2706 for i
= 0; i
< 100; i
++ {
2709 if typ
!= TypeOf(z
) {
2710 t
.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ
, TypeOf(z
))
2714 func TestPtrToGC(t
*testing
.T
) {
2716 tt
:= TypeOf(T(nil))
2720 for i
:= 0; i
< n
; i
++ {
2725 v
.Elem().Set(ValueOf(p
).Convert(pt
))
2726 x
= append(x
, v
.Interface())
2730 for i
, xi
:= range x
{
2731 k
:= ValueOf(xi
).Elem().Elem().Elem().Interface().(uintptr)
2732 if k
!= uintptr(i
) {
2733 t
.Errorf("lost x[%d] = %d, want %d", i
, k
, i
)
2738 func BenchmarkPtrTo(b
*testing
.B
) {
2739 // Construct a type with a zero ptrToThis.
2740 type T
struct{ int }
2741 t
:= SliceOf(TypeOf(T
{}))
2742 ptrToThis
:= ValueOf(t
).Elem().FieldByName("ptrToThis")
2743 if !ptrToThis
.IsValid() {
2744 b
.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t
)
2746 if ptrToThis
.Int() != 0 {
2747 b
.Fatalf("%v.ptrToThis unexpectedly nonzero", t
)
2751 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
2753 b
.RunParallel(func(pb
*testing
.PB
) {
2760 func TestAddr(t
*testing
.T
) {
2772 t
.Errorf("Addr.Elem.Set failed to set value")
2775 // Again but take address of the ValueOf value.
2776 // Exercises generation of PtrTypes not present in the binary.
2778 v
= ValueOf(&q
).Elem()
2787 t
.Errorf("Addr.Elem.Set failed to set value")
2790 // Starting without pointer we should get changed value
2793 v
= ValueOf(&qq
).Elem()
2799 if p
.X
!= 3 { // should be unchanged from last time
2800 t
.Errorf("somehow value Set changed original p")
2802 p
= v0
.Interface().(struct {
2806 t
.Errorf("Addr.Elem.Set valued to set value in top value")
2809 // Verify that taking the address of a type gives us a pointer
2810 // which we can convert back using the usual interface
2815 ps
:= ValueOf(&s
).Elem().Field(0).Addr().Interface()
2816 *(ps
.(**bool)) = new(bool)
2818 t
.Errorf("Addr.Interface direct assignment failed")
2822 /* gccgo does do allocations here.
2824 func noAlloc(t *testing.T, n int, f func(int)) {
2825 if testing.Short() {
2826 t.Skip("skipping malloc count in short mode")
2828 if runtime.GOMAXPROCS(0) > 1 {
2829 t.Skip("skipping; GOMAXPROCS>1")
2832 allocs := testing.AllocsPerRun(n, func() {
2837 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2841 func TestAllocations(t *testing.T) {
2842 noAlloc(t, 100, func(j int) {
2846 // We can uncomment this when compiler escape analysis
2847 // is good enough to see that the integer assigned to i
2848 // does not escape and therefore need not be allocated.
2852 // if int(v.Int()) != 42+j {
2853 // panic("wrong int")
2856 i = func(j int) int { return j }
2858 if v.Interface().(func(int) int)(j) != j {
2859 panic("wrong result")
2866 func TestSmallNegativeInt(t
*testing
.T
) {
2870 t
.Errorf("int16(-1).Int() returned %v", v
.Int())
2874 func TestIndex(t
*testing
.T
) {
2875 xs
:= []byte{1, 2, 3, 4, 5, 6, 7, 8}
2876 v
:= ValueOf(xs
).Index(3).Interface().(byte)
2878 t
.Errorf("xs.Index(3) = %v; expected %v", v
, xs
[3])
2880 xa
:= [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2881 v
= ValueOf(xa
).Index(2).Interface().(byte)
2883 t
.Errorf("xa.Index(2) = %v; expected %v", v
, xa
[2])
2886 v
= ValueOf(s
).Index(3).Interface().(byte)
2888 t
.Errorf("s.Index(3) = %v; expected %v", v
, s
[3])
2892 func TestSlice(t
*testing
.T
) {
2893 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2894 v
:= ValueOf(xs
).Slice(3, 5).Interface().([]int)
2896 t
.Errorf("len(xs.Slice(3, 5)) = %d", len(v
))
2899 t
.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v
))
2901 if !DeepEqual(v
[0:5], xs
[3:]) {
2902 t
.Errorf("xs.Slice(3, 5)[0:5] = %v", v
[0:5])
2904 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2905 v
= ValueOf(&xa
).Elem().Slice(2, 5).Interface().([]int)
2907 t
.Errorf("len(xa.Slice(2, 5)) = %d", len(v
))
2910 t
.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v
))
2912 if !DeepEqual(v
[0:6], xa
[2:]) {
2913 t
.Errorf("xs.Slice(2, 5)[0:6] = %v", v
[0:6])
2916 vs
:= ValueOf(s
).Slice(3, 5).Interface().(string)
2918 t
.Errorf("s.Slice(3, 5) = %q; expected %q", vs
, s
[3:5])
2921 rv
:= ValueOf(&xs
).Elem()
2923 ptr2
:= rv
.Pointer()
2925 ptr3
:= rv
.Pointer()
2927 t
.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3
, ptr2
)
2931 func TestSlice3(t
*testing
.T
) {
2932 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2933 v
:= ValueOf(xs
).Slice3(3, 5, 7).Interface().([]int)
2935 t
.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v
))
2938 t
.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v
))
2940 if !DeepEqual(v
[0:4], xs
[3:7:7]) {
2941 t
.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v
[0:4])
2943 rv
:= ValueOf(&xs
).Elem()
2944 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2945 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2946 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2948 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2949 v
= ValueOf(&xa
).Elem().Slice3(2, 5, 6).Interface().([]int)
2951 t
.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v
))
2954 t
.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v
))
2956 if !DeepEqual(v
[0:4], xa
[2:6:6]) {
2957 t
.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v
[0:4])
2959 rv
= ValueOf(&xa
).Elem()
2960 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2961 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2962 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2965 rv
= ValueOf(&s
).Elem()
2966 shouldPanic(func() { rv
.Slice3(1, 2, 3) })
2968 rv
= ValueOf(&xs
).Elem()
2969 rv
= rv
.Slice3(3, 5, 7)
2970 ptr2
:= rv
.Pointer()
2971 rv
= rv
.Slice3(4, 4, 4)
2972 ptr3
:= rv
.Pointer()
2974 t
.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3
, ptr2
)
2978 func TestSetLenCap(t
*testing
.T
) {
2979 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2980 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2982 vs
:= ValueOf(&xs
).Elem()
2983 shouldPanic(func() { vs
.SetLen(10) })
2984 shouldPanic(func() { vs
.SetCap(10) })
2985 shouldPanic(func() { vs
.SetLen(-1) })
2986 shouldPanic(func() { vs
.SetCap(-1) })
2987 shouldPanic(func() { vs
.SetCap(6) }) // smaller than len
2989 if len(xs
) != 5 ||
cap(xs
) != 8 {
2990 t
.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs
), cap(xs
))
2993 if len(xs
) != 5 ||
cap(xs
) != 6 {
2994 t
.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs
), cap(xs
))
2997 if len(xs
) != 5 ||
cap(xs
) != 5 {
2998 t
.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs
), cap(xs
))
3000 shouldPanic(func() { vs
.SetCap(4) }) // smaller than len
3001 shouldPanic(func() { vs
.SetLen(6) }) // bigger than cap
3003 va
:= ValueOf(&xa
).Elem()
3004 shouldPanic(func() { va
.SetLen(8) })
3005 shouldPanic(func() { va
.SetCap(8) })
3008 func TestVariadic(t
*testing
.T
) {
3013 V(fmt
.Fprintf
).Call([]Value
{V(&b
), V("%s, %d world"), V("hello"), V(42)})
3014 if b
.String() != "hello, 42 world" {
3015 t
.Errorf("after Fprintf Call: %q != %q", b
.String(), "hello 42 world")
3019 V(fmt
.Fprintf
).CallSlice([]Value
{V(&b
), V("%s, %d world"), V([]interface{}{"hello", 42})})
3020 if b
.String() != "hello, 42 world" {
3021 t
.Errorf("after Fprintf CallSlice: %q != %q", b
.String(), "hello 42 world")
3025 func TestFuncArg(t
*testing
.T
) {
3026 f1
:= func(i
int, f
func(int) int) int { return f(i
) }
3027 f2
:= func(i
int) int { return i
+ 1 }
3028 r
:= ValueOf(f1
).Call([]Value
{ValueOf(100), ValueOf(f2
)})
3029 if r
[0].Int() != 101 {
3030 t
.Errorf("function returned %d, want 101", r
[0].Int())
3034 func TestStructArg(t
*testing
.T
) {
3035 type padded
struct {
3042 wantA
= padded
{"3", 4}
3045 f
:= func(a padded
, b
uint32) {
3048 ValueOf(f
).Call([]Value
{ValueOf(wantA
), ValueOf(wantB
)})
3049 if gotA
!= wantA || gotB
!= wantB
{
3050 t
.Errorf("function called with (%v, %v), want (%v, %v)", gotA
, gotB
, wantA
, wantB
)
3054 var tagGetTests
= []struct {
3059 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3060 {`protobuf:"PB(1,2)"`, `foo`, ``},
3061 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3062 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3063 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3064 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3065 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3068 func TestTagGet(t
*testing
.T
) {
3069 for _
, tt
:= range tagGetTests
{
3070 if v
:= tt
.Tag
.Get(tt
.Key
); v
!= tt
.Value
{
3071 t
.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt
.Tag
, tt
.Key
, v
, tt
.Value
)
3076 func TestBytes(t
*testing
.T
) {
3079 y
:= ValueOf(x
).Bytes()
3080 if !bytes
.Equal(x
, y
) {
3081 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
3084 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
3088 func TestSetBytes(t
*testing
.T
) {
3091 y
:= []byte{1, 2, 3, 4}
3092 ValueOf(&x
).Elem().SetBytes(y
)
3093 if !bytes
.Equal(x
, y
) {
3094 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
3097 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
3101 type Private
struct {
3107 func (p
*Private
) m() {
3110 type private
struct {
3118 func (p
*private
) P() {
3121 type Public
struct {
3127 func (p
*Public
) M() {
3130 func TestUnexported(t
*testing
.T
) {
3135 isValid(v
.Elem().Field(0))
3136 isValid(v
.Elem().Field(1))
3137 isValid(v
.Elem().Field(2))
3138 isValid(v
.Elem().FieldByName("X"))
3139 isValid(v
.Elem().FieldByName("Y"))
3140 isValid(v
.Elem().FieldByName("Z"))
3141 isValid(v
.Type().Method(0).Func
)
3142 m
, _
:= v
.Type().MethodByName("M")
3144 m
, _
= v
.Type().MethodByName("P")
3146 isNonNil(v
.Elem().Field(0).Interface())
3147 isNonNil(v
.Elem().Field(1).Interface())
3148 isNonNil(v
.Elem().Field(2).Field(2).Index(0))
3149 isNonNil(v
.Elem().FieldByName("X").Interface())
3150 isNonNil(v
.Elem().FieldByName("Y").Interface())
3151 isNonNil(v
.Elem().FieldByName("Z").Interface())
3152 isNonNil(v
.Elem().FieldByName("S").Index(0).Interface())
3153 isNonNil(v
.Type().Method(0).Func
.Interface())
3154 m
, _
= v
.Type().MethodByName("P")
3155 isNonNil(m
.Func
.Interface())
3159 isValid(v
.Elem().Field(0))
3160 isValid(v
.Elem().Field(1))
3161 isValid(v
.Elem().FieldByName("x"))
3162 isValid(v
.Elem().FieldByName("y"))
3163 shouldPanic(func() { v
.Elem().Field(0).Interface() })
3164 shouldPanic(func() { v
.Elem().Field(1).Interface() })
3165 shouldPanic(func() { v
.Elem().FieldByName("x").Interface() })
3166 shouldPanic(func() { v
.Elem().FieldByName("y").Interface() })
3167 shouldPanic(func() { v
.Type().Method(0) })
3170 func TestSetPanic(t
*testing
.T
) {
3171 ok
:= func(f
func()) { f() }
3173 clear
:= func(v Value
) { v
.Set(Zero(v
.Type())) }
3201 bad(func() { clear(v
.Field(0)) }) // .X
3202 bad(func() { clear(v
.Field(1)) }) // .t1
3203 bad(func() { clear(v
.Field(1).Field(0)) }) // .t1.Y
3204 bad(func() { clear(v
.Field(1).Field(1)) }) // .t1.t0
3205 bad(func() { clear(v
.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3206 bad(func() { clear(v
.Field(2)) }) // .T2
3207 bad(func() { clear(v
.Field(2).Field(0)) }) // .T2.Z
3208 bad(func() { clear(v
.Field(2).Field(1)) }) // .T2.namedT0
3209 bad(func() { clear(v
.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3210 bad(func() { clear(v
.Field(3)) }) // .NamedT1
3211 bad(func() { clear(v
.Field(3).Field(0)) }) // .NamedT1.Y
3212 bad(func() { clear(v
.Field(3).Field(1)) }) // .NamedT1.t0
3213 bad(func() { clear(v
.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3214 bad(func() { clear(v
.Field(4)) }) // .NamedT2
3215 bad(func() { clear(v
.Field(4).Field(0)) }) // .NamedT2.Z
3216 bad(func() { clear(v
.Field(4).Field(1)) }) // .NamedT2.namedT0
3217 bad(func() { clear(v
.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3218 bad(func() { clear(v
.Field(5)) }) // .namedT1
3219 bad(func() { clear(v
.Field(5).Field(0)) }) // .namedT1.Y
3220 bad(func() { clear(v
.Field(5).Field(1)) }) // .namedT1.t0
3221 bad(func() { clear(v
.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3222 bad(func() { clear(v
.Field(6)) }) // .namedT2
3223 bad(func() { clear(v
.Field(6).Field(0)) }) // .namedT2.Z
3224 bad(func() { clear(v
.Field(6).Field(1)) }) // .namedT2.namedT0
3225 bad(func() { clear(v
.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3228 v
= ValueOf(&T
{}).Elem()
3229 ok(func() { clear(v
.Field(0)) }) // .X
3230 bad(func() { clear(v
.Field(1)) }) // .t1
3231 ok(func() { clear(v
.Field(1).Field(0)) }) // .t1.Y
3232 bad(func() { clear(v
.Field(1).Field(1)) }) // .t1.t0
3233 ok(func() { clear(v
.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3234 ok(func() { clear(v
.Field(2)) }) // .T2
3235 ok(func() { clear(v
.Field(2).Field(0)) }) // .T2.Z
3236 bad(func() { clear(v
.Field(2).Field(1)) }) // .T2.namedT0
3237 bad(func() { clear(v
.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3238 ok(func() { clear(v
.Field(3)) }) // .NamedT1
3239 ok(func() { clear(v
.Field(3).Field(0)) }) // .NamedT1.Y
3240 bad(func() { clear(v
.Field(3).Field(1)) }) // .NamedT1.t0
3241 ok(func() { clear(v
.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3242 ok(func() { clear(v
.Field(4)) }) // .NamedT2
3243 ok(func() { clear(v
.Field(4).Field(0)) }) // .NamedT2.Z
3244 bad(func() { clear(v
.Field(4).Field(1)) }) // .NamedT2.namedT0
3245 bad(func() { clear(v
.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3246 bad(func() { clear(v
.Field(5)) }) // .namedT1
3247 bad(func() { clear(v
.Field(5).Field(0)) }) // .namedT1.Y
3248 bad(func() { clear(v
.Field(5).Field(1)) }) // .namedT1.t0
3249 bad(func() { clear(v
.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3250 bad(func() { clear(v
.Field(6)) }) // .namedT2
3251 bad(func() { clear(v
.Field(6).Field(0)) }) // .namedT2.Z
3252 bad(func() { clear(v
.Field(6).Field(1)) }) // .namedT2.namedT0
3253 bad(func() { clear(v
.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3258 func (t timp
) W() {}
3259 func (t timp
) Y() {}
3260 func (t timp
) w() {}
3261 func (t timp
) y() {}
3263 func TestCallPanic(t
*testing
.T
) {
3288 ok
:= func(f
func()) { f() }
3290 call
:= func(v Value
) { v
.Call(nil) }
3293 v
:= ValueOf(T
{i
, i
, i
, i
, T2
{i
, i
}, i
, i
, T2
{i
, i
}})
3294 ok(func() { call(v
.Field(0).Method(0)) }) // .t0.W
3295 bad(func() { call(v
.Field(0).Elem().Method(0)) }) // .t0.W
3296 bad(func() { call(v
.Field(0).Method(1)) }) // .t0.w
3297 bad(func() { call(v
.Field(0).Elem().Method(2)) }) // .t0.w
3298 ok(func() { call(v
.Field(1).Method(0)) }) // .T1.Y
3299 ok(func() { call(v
.Field(1).Elem().Method(0)) }) // .T1.Y
3300 bad(func() { call(v
.Field(1).Method(1)) }) // .T1.y
3301 bad(func() { call(v
.Field(1).Elem().Method(2)) }) // .T1.y
3303 ok(func() { call(v
.Field(2).Method(0)) }) // .NamedT0.W
3304 ok(func() { call(v
.Field(2).Elem().Method(0)) }) // .NamedT0.W
3305 bad(func() { call(v
.Field(2).Method(1)) }) // .NamedT0.w
3306 bad(func() { call(v
.Field(2).Elem().Method(2)) }) // .NamedT0.w
3308 ok(func() { call(v
.Field(3).Method(0)) }) // .NamedT1.Y
3309 ok(func() { call(v
.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3310 bad(func() { call(v
.Field(3).Method(1)) }) // .NamedT1.y
3311 bad(func() { call(v
.Field(3).Elem().Method(3)) }) // .NamedT1.y
3313 ok(func() { call(v
.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3314 ok(func() { call(v
.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3315 ok(func() { call(v
.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3316 bad(func() { call(v
.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3318 bad(func() { call(v
.Field(5).Method(0)) }) // .namedT0.W
3319 bad(func() { call(v
.Field(5).Elem().Method(0)) }) // .namedT0.W
3320 bad(func() { call(v
.Field(5).Method(1)) }) // .namedT0.w
3321 bad(func() { call(v
.Field(5).Elem().Method(2)) }) // .namedT0.w
3323 bad(func() { call(v
.Field(6).Method(0)) }) // .namedT1.Y
3324 bad(func() { call(v
.Field(6).Elem().Method(0)) }) // .namedT1.Y
3325 bad(func() { call(v
.Field(6).Method(0)) }) // .namedT1.y
3326 bad(func() { call(v
.Field(6).Elem().Method(0)) }) // .namedT1.y
3328 bad(func() { call(v
.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3329 bad(func() { call(v
.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3330 bad(func() { call(v
.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3331 bad(func() { call(v
.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3334 func shouldPanic(f
func()) {
3336 if recover() == nil {
3337 panic("did not panic")
3343 func isNonNil(x
interface{}) {
3345 panic("nil interface")
3349 func isValid(v Value
) {
3355 func TestAlias(t
*testing
.T
) {
3356 x
:= string("hello")
3357 v
:= ValueOf(&x
).Elem()
3358 oldvalue
:= v
.Interface()
3359 v
.SetString("world")
3360 newvalue
:= v
.Interface()
3362 if oldvalue
!= "hello" || newvalue
!= "world" {
3363 t
.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue
, newvalue
)
3369 func EmptyInterfaceV(x
interface{}) Value
{
3370 return ValueOf(&x
).Elem()
3373 func ReaderV(x io
.Reader
) Value
{
3374 return ValueOf(&x
).Elem()
3377 func ReadWriterV(x io
.ReadWriter
) Value
{
3378 return ValueOf(&x
).Elem()
3382 type MyStruct
struct {
3385 type MyString
string
3387 type MyRunes
[]int32
3391 var convertTests
= []struct {
3397 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3403 var numbers = []string{
3404 "int8", "uint8", "int16", "uint16",
3405 "int32", "uint32", "int64", "uint64",
3406 "int", "uint", "uintptr",
3407 "float32", "float64",
3411 // all pairs but in an unusual order,
3412 // to emit all the int8, uint8 cases
3413 // before n grows too big.
3415 for i, f := range numbers {
3416 for _, g := range numbers[i:] {
3417 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3420 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3427 {V(int8(1)), V(int8(1))},
3428 {V(int8(2)), V(uint8(2))},
3429 {V(uint8(3)), V(int8(3))},
3430 {V(int8(4)), V(int16(4))},
3431 {V(int16(5)), V(int8(5))},
3432 {V(int8(6)), V(uint16(6))},
3433 {V(uint16(7)), V(int8(7))},
3434 {V(int8(8)), V(int32(8))},
3435 {V(int32(9)), V(int8(9))},
3436 {V(int8(10)), V(uint32(10))},
3437 {V(uint32(11)), V(int8(11))},
3438 {V(int8(12)), V(int64(12))},
3439 {V(int64(13)), V(int8(13))},
3440 {V(int8(14)), V(uint64(14))},
3441 {V(uint64(15)), V(int8(15))},
3442 {V(int8(16)), V(int(16))},
3443 {V(int(17)), V(int8(17))},
3444 {V(int8(18)), V(uint(18))},
3445 {V(uint(19)), V(int8(19))},
3446 {V(int8(20)), V(uintptr(20))},
3447 {V(uintptr(21)), V(int8(21))},
3448 {V(int8(22)), V(float32(22))},
3449 {V(float32(23)), V(int8(23))},
3450 {V(int8(24)), V(float64(24))},
3451 {V(float64(25)), V(int8(25))},
3452 {V(uint8(26)), V(uint8(26))},
3453 {V(uint8(27)), V(int16(27))},
3454 {V(int16(28)), V(uint8(28))},
3455 {V(uint8(29)), V(uint16(29))},
3456 {V(uint16(30)), V(uint8(30))},
3457 {V(uint8(31)), V(int32(31))},
3458 {V(int32(32)), V(uint8(32))},
3459 {V(uint8(33)), V(uint32(33))},
3460 {V(uint32(34)), V(uint8(34))},
3461 {V(uint8(35)), V(int64(35))},
3462 {V(int64(36)), V(uint8(36))},
3463 {V(uint8(37)), V(uint64(37))},
3464 {V(uint64(38)), V(uint8(38))},
3465 {V(uint8(39)), V(int(39))},
3466 {V(int(40)), V(uint8(40))},
3467 {V(uint8(41)), V(uint(41))},
3468 {V(uint(42)), V(uint8(42))},
3469 {V(uint8(43)), V(uintptr(43))},
3470 {V(uintptr(44)), V(uint8(44))},
3471 {V(uint8(45)), V(float32(45))},
3472 {V(float32(46)), V(uint8(46))},
3473 {V(uint8(47)), V(float64(47))},
3474 {V(float64(48)), V(uint8(48))},
3475 {V(int16(49)), V(int16(49))},
3476 {V(int16(50)), V(uint16(50))},
3477 {V(uint16(51)), V(int16(51))},
3478 {V(int16(52)), V(int32(52))},
3479 {V(int32(53)), V(int16(53))},
3480 {V(int16(54)), V(uint32(54))},
3481 {V(uint32(55)), V(int16(55))},
3482 {V(int16(56)), V(int64(56))},
3483 {V(int64(57)), V(int16(57))},
3484 {V(int16(58)), V(uint64(58))},
3485 {V(uint64(59)), V(int16(59))},
3486 {V(int16(60)), V(int(60))},
3487 {V(int(61)), V(int16(61))},
3488 {V(int16(62)), V(uint(62))},
3489 {V(uint(63)), V(int16(63))},
3490 {V(int16(64)), V(uintptr(64))},
3491 {V(uintptr(65)), V(int16(65))},
3492 {V(int16(66)), V(float32(66))},
3493 {V(float32(67)), V(int16(67))},
3494 {V(int16(68)), V(float64(68))},
3495 {V(float64(69)), V(int16(69))},
3496 {V(uint16(70)), V(uint16(70))},
3497 {V(uint16(71)), V(int32(71))},
3498 {V(int32(72)), V(uint16(72))},
3499 {V(uint16(73)), V(uint32(73))},
3500 {V(uint32(74)), V(uint16(74))},
3501 {V(uint16(75)), V(int64(75))},
3502 {V(int64(76)), V(uint16(76))},
3503 {V(uint16(77)), V(uint64(77))},
3504 {V(uint64(78)), V(uint16(78))},
3505 {V(uint16(79)), V(int(79))},
3506 {V(int(80)), V(uint16(80))},
3507 {V(uint16(81)), V(uint(81))},
3508 {V(uint(82)), V(uint16(82))},
3509 {V(uint16(83)), V(uintptr(83))},
3510 {V(uintptr(84)), V(uint16(84))},
3511 {V(uint16(85)), V(float32(85))},
3512 {V(float32(86)), V(uint16(86))},
3513 {V(uint16(87)), V(float64(87))},
3514 {V(float64(88)), V(uint16(88))},
3515 {V(int32(89)), V(int32(89))},
3516 {V(int32(90)), V(uint32(90))},
3517 {V(uint32(91)), V(int32(91))},
3518 {V(int32(92)), V(int64(92))},
3519 {V(int64(93)), V(int32(93))},
3520 {V(int32(94)), V(uint64(94))},
3521 {V(uint64(95)), V(int32(95))},
3522 {V(int32(96)), V(int(96))},
3523 {V(int(97)), V(int32(97))},
3524 {V(int32(98)), V(uint(98))},
3525 {V(uint(99)), V(int32(99))},
3526 {V(int32(100)), V(uintptr(100))},
3527 {V(uintptr(101)), V(int32(101))},
3528 {V(int32(102)), V(float32(102))},
3529 {V(float32(103)), V(int32(103))},
3530 {V(int32(104)), V(float64(104))},
3531 {V(float64(105)), V(int32(105))},
3532 {V(uint32(106)), V(uint32(106))},
3533 {V(uint32(107)), V(int64(107))},
3534 {V(int64(108)), V(uint32(108))},
3535 {V(uint32(109)), V(uint64(109))},
3536 {V(uint64(110)), V(uint32(110))},
3537 {V(uint32(111)), V(int(111))},
3538 {V(int(112)), V(uint32(112))},
3539 {V(uint32(113)), V(uint(113))},
3540 {V(uint(114)), V(uint32(114))},
3541 {V(uint32(115)), V(uintptr(115))},
3542 {V(uintptr(116)), V(uint32(116))},
3543 {V(uint32(117)), V(float32(117))},
3544 {V(float32(118)), V(uint32(118))},
3545 {V(uint32(119)), V(float64(119))},
3546 {V(float64(120)), V(uint32(120))},
3547 {V(int64(121)), V(int64(121))},
3548 {V(int64(122)), V(uint64(122))},
3549 {V(uint64(123)), V(int64(123))},
3550 {V(int64(124)), V(int(124))},
3551 {V(int(125)), V(int64(125))},
3552 {V(int64(126)), V(uint(126))},
3553 {V(uint(127)), V(int64(127))},
3554 {V(int64(128)), V(uintptr(128))},
3555 {V(uintptr(129)), V(int64(129))},
3556 {V(int64(130)), V(float32(130))},
3557 {V(float32(131)), V(int64(131))},
3558 {V(int64(132)), V(float64(132))},
3559 {V(float64(133)), V(int64(133))},
3560 {V(uint64(134)), V(uint64(134))},
3561 {V(uint64(135)), V(int(135))},
3562 {V(int(136)), V(uint64(136))},
3563 {V(uint64(137)), V(uint(137))},
3564 {V(uint(138)), V(uint64(138))},
3565 {V(uint64(139)), V(uintptr(139))},
3566 {V(uintptr(140)), V(uint64(140))},
3567 {V(uint64(141)), V(float32(141))},
3568 {V(float32(142)), V(uint64(142))},
3569 {V(uint64(143)), V(float64(143))},
3570 {V(float64(144)), V(uint64(144))},
3571 {V(int(145)), V(int(145))},
3572 {V(int(146)), V(uint(146))},
3573 {V(uint(147)), V(int(147))},
3574 {V(int(148)), V(uintptr(148))},
3575 {V(uintptr(149)), V(int(149))},
3576 {V(int(150)), V(float32(150))},
3577 {V(float32(151)), V(int(151))},
3578 {V(int(152)), V(float64(152))},
3579 {V(float64(153)), V(int(153))},
3580 {V(uint(154)), V(uint(154))},
3581 {V(uint(155)), V(uintptr(155))},
3582 {V(uintptr(156)), V(uint(156))},
3583 {V(uint(157)), V(float32(157))},
3584 {V(float32(158)), V(uint(158))},
3585 {V(uint(159)), V(float64(159))},
3586 {V(float64(160)), V(uint(160))},
3587 {V(uintptr(161)), V(uintptr(161))},
3588 {V(uintptr(162)), V(float32(162))},
3589 {V(float32(163)), V(uintptr(163))},
3590 {V(uintptr(164)), V(float64(164))},
3591 {V(float64(165)), V(uintptr(165))},
3592 {V(float32(166)), V(float32(166))},
3593 {V(float32(167)), V(float64(167))},
3594 {V(float64(168)), V(float32(168))},
3595 {V(float64(169)), V(float64(169))},
3598 {V(float64(1.5)), V(int(1))},
3601 {V(complex64(1i
)), V(complex64(1i
))},
3602 {V(complex64(2i
)), V(complex128(2i
))},
3603 {V(complex128(3i
)), V(complex64(3i
))},
3604 {V(complex128(4i
)), V(complex128(4i
))},
3607 {V(string("hello")), V(string("hello"))},
3608 {V(string("bytes1")), V([]byte("bytes1"))},
3609 {V([]byte("bytes2")), V(string("bytes2"))},
3610 {V([]byte("bytes3")), V([]byte("bytes3"))},
3611 {V(string("runes♝")), V([]rune("runes♝"))},
3612 {V([]rune("runes♕")), V(string("runes♕"))},
3613 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3614 {V(int('a')), V(string("a"))},
3615 {V(int8('a')), V(string("a"))},
3616 {V(int16('a')), V(string("a"))},
3617 {V(int32('a')), V(string("a"))},
3618 {V(int64('a')), V(string("a"))},
3619 {V(uint('a')), V(string("a"))},
3620 {V(uint8('a')), V(string("a"))},
3621 {V(uint16('a')), V(string("a"))},
3622 {V(uint32('a')), V(string("a"))},
3623 {V(uint64('a')), V(string("a"))},
3624 {V(uintptr('a')), V(string("a"))},
3625 {V(int(-1)), V(string("\uFFFD"))},
3626 {V(int8(-2)), V(string("\uFFFD"))},
3627 {V(int16(-3)), V(string("\uFFFD"))},
3628 {V(int32(-4)), V(string("\uFFFD"))},
3629 {V(int64(-5)), V(string("\uFFFD"))},
3630 {V(uint(0x110001)), V(string("\uFFFD"))},
3631 {V(uint32(0x110002)), V(string("\uFFFD"))},
3632 {V(uint64(0x110003)), V(string("\uFFFD"))},
3633 {V(uintptr(0x110004)), V(string("\uFFFD"))},
3636 {V(MyString("hello")), V(string("hello"))},
3637 {V(string("hello")), V(MyString("hello"))},
3638 {V(string("hello")), V(string("hello"))},
3639 {V(MyString("hello")), V(MyString("hello"))},
3640 {V(MyString("bytes1")), V([]byte("bytes1"))},
3641 {V([]byte("bytes2")), V(MyString("bytes2"))},
3642 {V([]byte("bytes3")), V([]byte("bytes3"))},
3643 {V(MyString("runes♝")), V([]rune("runes♝"))},
3644 {V([]rune("runes♕")), V(MyString("runes♕"))},
3645 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3646 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3647 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3648 {V(int('a')), V(MyString("a"))},
3649 {V(int8('a')), V(MyString("a"))},
3650 {V(int16('a')), V(MyString("a"))},
3651 {V(int32('a')), V(MyString("a"))},
3652 {V(int64('a')), V(MyString("a"))},
3653 {V(uint('a')), V(MyString("a"))},
3654 {V(uint8('a')), V(MyString("a"))},
3655 {V(uint16('a')), V(MyString("a"))},
3656 {V(uint32('a')), V(MyString("a"))},
3657 {V(uint64('a')), V(MyString("a"))},
3658 {V(uintptr('a')), V(MyString("a"))},
3659 {V(int(-1)), V(MyString("\uFFFD"))},
3660 {V(int8(-2)), V(MyString("\uFFFD"))},
3661 {V(int16(-3)), V(MyString("\uFFFD"))},
3662 {V(int32(-4)), V(MyString("\uFFFD"))},
3663 {V(int64(-5)), V(MyString("\uFFFD"))},
3664 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3665 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3666 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3667 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3670 {V(string("bytes1")), V(MyBytes("bytes1"))},
3671 {V(MyBytes("bytes2")), V(string("bytes2"))},
3672 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3673 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3674 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3677 {V(string("runes♝")), V(MyRunes("runes♝"))},
3678 {V(MyRunes("runes♕")), V(string("runes♕"))},
3679 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3680 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3681 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3683 // named types and equal underlying types
3684 {V(new(int)), V(new(integer
))},
3685 {V(new(integer
)), V(new(int))},
3686 {V(Empty
{}), V(struct{}{})},
3687 {V(new(Empty
)), V(new(struct{}))},
3688 {V(struct{}{}), V(Empty
{})},
3689 {V(new(struct{})), V(new(Empty
))},
3690 {V(Empty
{}), V(Empty
{})},
3691 {V(MyBytes
{}), V([]byte{})},
3692 {V([]byte{}), V(MyBytes
{})},
3693 {V((func())(nil)), V(MyFunc(nil))},
3694 {V((MyFunc
)(nil)), V((func())(nil))},
3696 // structs with different tags
3709 {V(MyStruct
{}), V(struct {
3715 }{}), V(MyStruct
{})},
3717 {V(MyStruct
{}), V(struct {
3723 }{}), V(MyStruct
{})},
3725 // can convert *byte and *MyByte
3726 {V((*byte)(nil)), V((*MyByte
)(nil))},
3727 {V((*MyByte
)(nil)), V((*byte)(nil))},
3729 // cannot convert mismatched array sizes
3730 {V([2]byte{}), V([2]byte{})},
3731 {V([3]byte{}), V([3]byte{})},
3733 // cannot convert other instances
3734 {V((**byte)(nil)), V((**byte)(nil))},
3735 {V((**MyByte
)(nil)), V((**MyByte
)(nil))},
3736 {V((chan byte)(nil)), V((chan byte)(nil))},
3737 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3738 {V(([]byte)(nil)), V(([]byte)(nil))},
3739 {V(([]MyByte
)(nil)), V(([]MyByte
)(nil))},
3740 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3741 {V((map[int]MyByte
)(nil)), V((map[int]MyByte
)(nil))},
3742 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3743 {V((map[MyByte
]int)(nil)), V((map[MyByte
]int)(nil))},
3744 {V([2]byte{}), V([2]byte{})},
3745 {V([2]MyByte
{}), V([2]MyByte
{})},
3748 {V((***int)(nil)), V((***int)(nil))},
3749 {V((***byte)(nil)), V((***byte)(nil))},
3750 {V((***int32)(nil)), V((***int32)(nil))},
3751 {V((***int64)(nil)), V((***int64)(nil))},
3752 {V((chan int)(nil)), V((<-chan int)(nil))},
3753 {V((chan int)(nil)), V((chan<- int)(nil))},
3754 {V((chan string)(nil)), V((<-chan string)(nil))},
3755 {V((chan string)(nil)), V((chan<- string)(nil))},
3756 {V((chan byte)(nil)), V((chan byte)(nil))},
3757 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3758 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3759 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3760 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3761 {V([]uint(nil)), V([]uint(nil))},
3762 {V([]int(nil)), V([]int(nil))},
3763 {V(new(interface{})), V(new(interface{}))},
3764 {V(new(io
.Reader
)), V(new(io
.Reader
))},
3765 {V(new(io
.Writer
)), V(new(io
.Writer
))},
3768 {V(int(1)), EmptyInterfaceV(int(1))},
3769 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3770 {V(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3771 {ReadWriterV(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3772 {V(new(bytes
.Buffer
)), ReadWriterV(new(bytes
.Buffer
))},
3775 func TestConvert(t
*testing
.T
) {
3776 canConvert
:= map[[2]Type
]bool{}
3777 all
:= map[Type
]bool{}
3779 for _
, tt
:= range convertTests
{
3781 if !t1
.ConvertibleTo(t1
) {
3782 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t1
)
3787 if !t1
.ConvertibleTo(t2
) {
3788 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t2
)
3794 canConvert
[[2]Type
{t1
, t2
}] = true
3796 // vout1 represents the in value converted to the in type.
3798 vout1
:= v1
.Convert(t1
)
3799 out1
:= vout1
.Interface()
3800 if vout1
.Type() != tt
.in
.Type() ||
!DeepEqual(out1
, tt
.in
.Interface()) {
3801 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t1
, out1
, tt
.in
.Interface())
3804 // vout2 represents the in value converted to the out type.
3805 vout2
:= v1
.Convert(t2
)
3806 out2
:= vout2
.Interface()
3807 if vout2
.Type() != tt
.out
.Type() ||
!DeepEqual(out2
, tt
.out
.Interface()) {
3808 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out2
, tt
.out
.Interface())
3811 // vout3 represents a new value of the out type, set to vout2. This makes
3812 // sure the converted value vout2 is really usable as a regular value.
3813 vout3
:= New(t2
).Elem()
3815 out3
:= vout3
.Interface()
3816 if vout3
.Type() != tt
.out
.Type() ||
!DeepEqual(out3
, tt
.out
.Interface()) {
3817 t
.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out3
, tt
.out
.Interface())
3821 t
.Errorf("table entry %v is RO, should not be", v1
)
3824 t
.Errorf("self-conversion output %v is RO, should not be", vout1
)
3827 t
.Errorf("conversion output %v is RO, should not be", vout2
)
3830 t
.Errorf("set(conversion output) %v is RO, should not be", vout3
)
3832 if !IsRO(MakeRO(v1
).Convert(t1
)) {
3833 t
.Errorf("RO self-conversion output %v is not RO, should be", v1
)
3835 if !IsRO(MakeRO(v1
).Convert(t2
)) {
3836 t
.Errorf("RO conversion output %v is not RO, should be", v1
)
3840 // Assume that of all the types we saw during the tests,
3841 // if there wasn't an explicit entry for a conversion between
3842 // a pair of types, then it's not to be allowed. This checks for
3843 // things like 'int64' converting to '*int'.
3844 for t1
:= range all
{
3845 for t2
:= range all
{
3846 expectOK
:= t1
== t2 || canConvert
[[2]Type
{t1
, t2
}] || t2
.Kind() == Interface
&& t2
.NumMethod() == 0
3847 if ok
:= t1
.ConvertibleTo(t2
); ok
!= expectOK
{
3848 t
.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1
, t2
, ok
, expectOK
)
3854 type ComparableStruct
struct {
3858 type NonComparableStruct
struct {
3863 var comparableTests
= []struct {
3868 {TypeOf("hello"), true},
3869 {TypeOf(new(byte)), true},
3870 {TypeOf((func())(nil)), false},
3871 {TypeOf([]byte{}), false},
3872 {TypeOf(map[string]int{}), false},
3873 {TypeOf(make(chan int)), true},
3874 {TypeOf(1.5), true},
3875 {TypeOf(false), true},
3877 {TypeOf(ComparableStruct
{}), true},
3878 {TypeOf(NonComparableStruct
{}), false},
3879 {TypeOf([10]map[string]int{}), false},
3880 {TypeOf([10]string{}), true},
3881 {TypeOf(new(interface{})).Elem(), true},
3884 func TestComparable(t
*testing
.T
) {
3885 for _
, tt
:= range comparableTests
{
3886 if ok
:= tt
.typ
.Comparable(); ok
!= tt
.ok
{
3887 t
.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt
.typ
, ok
, tt
.ok
)
3892 func TestOverflow(t
*testing
.T
) {
3893 if ovf
:= V(float64(0)).OverflowFloat(1e300
); ovf
{
3894 t
.Errorf("%v wrongly overflows float64", 1e300
)
3897 maxFloat32
:= float64((1<<24 - 1) << (127 - 23))
3898 if ovf
:= V(float32(0)).OverflowFloat(maxFloat32
); ovf
{
3899 t
.Errorf("%v wrongly overflows float32", maxFloat32
)
3901 ovfFloat32
:= float64((1<<24-1)<<(127-23) + 1<<(127-52))
3902 if ovf
:= V(float32(0)).OverflowFloat(ovfFloat32
); !ovf
{
3903 t
.Errorf("%v should overflow float32", ovfFloat32
)
3905 if ovf
:= V(float32(0)).OverflowFloat(-ovfFloat32
); !ovf
{
3906 t
.Errorf("%v should overflow float32", -ovfFloat32
)
3909 maxInt32
:= int64(0x7fffffff)
3910 if ovf
:= V(int32(0)).OverflowInt(maxInt32
); ovf
{
3911 t
.Errorf("%v wrongly overflows int32", maxInt32
)
3913 if ovf
:= V(int32(0)).OverflowInt(-1 << 31); ovf
{
3914 t
.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3916 ovfInt32
:= int64(1 << 31)
3917 if ovf
:= V(int32(0)).OverflowInt(ovfInt32
); !ovf
{
3918 t
.Errorf("%v should overflow int32", ovfInt32
)
3921 maxUint32
:= uint64(0xffffffff)
3922 if ovf
:= V(uint32(0)).OverflowUint(maxUint32
); ovf
{
3923 t
.Errorf("%v wrongly overflows uint32", maxUint32
)
3925 ovfUint32
:= uint64(1 << 32)
3926 if ovf
:= V(uint32(0)).OverflowUint(ovfUint32
); !ovf
{
3927 t
.Errorf("%v should overflow uint32", ovfUint32
)
3931 func checkSameType(t
*testing
.T
, x Type
, y
interface{}) {
3932 if x
!= TypeOf(y
) ||
TypeOf(Zero(x
).Interface()) != TypeOf(y
) {
3933 t
.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x
), TypeOf(y
))
3937 func TestArrayOf(t
*testing
.T
) {
3938 // check construction and use of type not in binary
3941 value
func(i
int) interface{}
3947 value
: func(i
int) interface{} { type Tint
int; return Tint(i
) },
3953 value
: func(i
int) interface{} { type Tint
int; return Tint(i
) },
3955 want
: "[0 1 2 3 4 5 6 7 8 9]",
3959 value
: func(i
int) interface{} { type Tfloat
float64; return Tfloat(i
) },
3961 want
: "[0 1 2 3 4 5 6 7 8 9]",
3965 value
: func(i
int) interface{} { type Tstring
string; return Tstring(strconv
.Itoa(i
)) },
3967 want
: "[0 1 2 3 4 5 6 7 8 9]",
3971 value
: func(i
int) interface{} { type Tstruct
struct{ V
int }; return Tstruct
{i
} },
3973 want
: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
3977 value
: func(i
int) interface{} { type Tint
int; return []Tint
{Tint(i
)} },
3979 want
: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3983 value
: func(i
int) interface{} { type Tint
int; return [1]Tint
{Tint(i
)} },
3985 want
: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3989 value
: func(i
int) interface{} { type Tstruct
struct{ V
[1]int }; return Tstruct
{[1]int{i
}} },
3991 want
: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3995 value
: func(i
int) interface{} { type Tstruct
struct{ V
[]int }; return Tstruct
{[]int{i
}} },
3997 want
: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4001 value
: func(i
int) interface{} { type TstructUV
struct{ U
, V
int }; return TstructUV
{i
, i
} },
4003 want
: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4007 value
: func(i
int) interface{} {
4008 type TstructUV
struct {
4012 return TstructUV
{i
, float64(i
)}
4015 want
: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4019 for _
, table
:= range tests
{
4020 at
:= ArrayOf(table
.n
, TypeOf(table
.value(0)))
4022 vok
:= New(at
).Elem()
4023 vnot
:= New(at
).Elem()
4024 for i
:= 0; i
< v
.Len(); i
++ {
4025 v
.Index(i
).Set(ValueOf(table
.value(i
)))
4026 vok
.Index(i
).Set(ValueOf(table
.value(i
)))
4031 vnot
.Index(i
).Set(ValueOf(table
.value(j
))) // make it differ only by last element
4033 s
:= fmt
.Sprint(v
.Interface())
4034 if s
!= table
.want
{
4035 t
.Errorf("constructed array = %s, want %s", s
, table
.want
)
4038 if table
.comparable
!= at
.Comparable() {
4039 t
.Errorf("constructed array (%#v) is comparable=%v, want=%v", v
.Interface(), at
.Comparable(), table
.comparable
)
4041 if table
.comparable
{
4043 if DeepEqual(vnot
.Interface(), v
.Interface()) {
4045 "arrays (%#v) compare ok (but should not)",
4050 if !DeepEqual(vok
.Interface(), v
.Interface()) {
4052 "arrays (%#v) compare NOT-ok (but should)",
4059 // check that type already in binary is found
4061 checkSameType(t
, ArrayOf(5, TypeOf(T(1))), [5]T
{})
4064 func TestArrayOfGC(t
*testing
.T
) {
4066 tt
:= TypeOf(T(nil))
4069 for i
:= 0; i
< n
; i
++ {
4070 v
:= New(ArrayOf(n
, tt
)).Elem()
4071 for j
:= 0; j
< v
.Len(); j
++ {
4073 *p
= uintptr(i
*n
+ j
)
4074 v
.Index(j
).Set(ValueOf(p
).Convert(tt
))
4076 x
= append(x
, v
.Interface())
4080 for i
, xi
:= range x
{
4082 for j
:= 0; j
< v
.Len(); j
++ {
4083 k
:= v
.Index(j
).Elem().Interface()
4084 if k
!= uintptr(i
*n
+j
) {
4085 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
4091 func TestArrayOfAlg(t
*testing
.T
) {
4092 at
:= ArrayOf(6, TypeOf(byte(0)))
4093 v1
:= New(at
).Elem()
4094 v2
:= New(at
).Elem()
4095 if v1
.Interface() != v1
.Interface() {
4096 t
.Errorf("constructed array %v not equal to itself", v1
.Interface())
4098 v1
.Index(5).Set(ValueOf(byte(1)))
4099 if i1
, i2
:= v1
.Interface(), v2
.Interface(); i1
== i2
{
4100 t
.Errorf("constructed arrays %v and %v should not be equal", i1
, i2
)
4103 at
= ArrayOf(6, TypeOf([]int(nil)))
4105 shouldPanic(func() { _
= v1
.Interface() == v1
.Interface() })
4108 func TestArrayOfGenericAlg(t
*testing
.T
) {
4109 at1
:= ArrayOf(5, TypeOf(string("")))
4110 at
:= ArrayOf(6, at1
)
4111 v1
:= New(at
).Elem()
4112 v2
:= New(at
).Elem()
4113 if v1
.Interface() != v1
.Interface() {
4114 t
.Errorf("constructed array %v not equal to itself", v1
.Interface())
4117 v1
.Index(0).Index(0).Set(ValueOf("abc"))
4118 v2
.Index(0).Index(0).Set(ValueOf("efg"))
4119 if i1
, i2
:= v1
.Interface(), v2
.Interface(); i1
== i2
{
4120 t
.Errorf("constructed arrays %v and %v should not be equal", i1
, i2
)
4123 v1
.Index(0).Index(0).Set(ValueOf("abc"))
4124 v2
.Index(0).Index(0).Set(ValueOf((v1
.Index(0).Index(0).String() + " ")[:3]))
4125 if i1
, i2
:= v1
.Interface(), v2
.Interface(); i1
!= i2
{
4126 t
.Errorf("constructed arrays %v and %v should be equal", i1
, i2
)
4130 m
:= MakeMap(MapOf(at
, TypeOf(int(0))))
4131 m
.SetMapIndex(v1
, ValueOf(1))
4132 if i1
, i2
:= v1
.Interface(), v2
.Interface(); !m
.MapIndex(v2
).IsValid() {
4133 t
.Errorf("constructed arrays %v and %v have different hashes", i1
, i2
)
4137 func TestArrayOfDirectIface(t
*testing
.T
) {
4138 t
.Skip("skipping test because gccgo uses a different directiface value")
4141 i1
:= Zero(TypeOf(T
{})).Interface()
4142 v1
:= ValueOf(&i1
).Elem()
4143 p1
:= v1
.InterfaceData()[1]
4145 i2
:= Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4146 v2
:= ValueOf(&i2
).Elem()
4147 p2
:= v2
.InterfaceData()[1]
4150 t
.Errorf("got p1=%v. want=%v", p1
, nil)
4154 t
.Errorf("got p2=%v. want=%v", p2
, nil)
4159 i1
:= Zero(TypeOf(T
{})).Interface()
4160 v1
:= ValueOf(&i1
).Elem()
4161 p1
:= v1
.InterfaceData()[1]
4163 i2
:= Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4164 v2
:= ValueOf(&i2
).Elem()
4165 p2
:= v2
.InterfaceData()[1]
4168 t
.Errorf("got p1=%v. want=not-%v", p1
, nil)
4172 t
.Errorf("got p2=%v. want=not-%v", p2
, nil)
4177 func TestSliceOf(t
*testing
.T
) {
4178 // check construction and use of type not in binary
4180 st
:= SliceOf(TypeOf(T(1)))
4181 if got
, want
:= st
.String(), "[]reflect_test.T"; got
!= want
{
4182 t
.Errorf("SliceOf(T(1)).String()=%q, want %q", got
, want
)
4184 v
:= MakeSlice(st
, 10, 10)
4186 for i
:= 0; i
< v
.Len(); i
++ {
4187 v
.Index(i
).Set(ValueOf(T(i
)))
4190 s
:= fmt
.Sprint(v
.Interface())
4191 want
:= "[0 1 2 3 4 5 6 7 8 9]"
4193 t
.Errorf("constructed slice = %s, want %s", s
, want
)
4196 // check that type already in binary is found
4198 checkSameType(t
, SliceOf(TypeOf(T1(1))), []T1
{})
4201 func TestSliceOverflow(t
*testing
.T
) {
4202 // check that MakeSlice panics when size of slice overflows uint
4205 l
:= (1<<(unsafe
.Sizeof((*byte)(nil))*8)-1)/s
+ 1
4207 t
.Fatal("slice size does not overflow")
4210 st
:= SliceOf(TypeOf(x
))
4214 t
.Fatal("slice overflow does not panic")
4217 MakeSlice(st
, int(l
), int(l
))
4220 func TestSliceOfGC(t
*testing
.T
) {
4222 tt
:= TypeOf(T(nil))
4226 for i
:= 0; i
< n
; i
++ {
4227 v
:= MakeSlice(st
, n
, n
)
4228 for j
:= 0; j
< v
.Len(); j
++ {
4230 *p
= uintptr(i
*n
+ j
)
4231 v
.Index(j
).Set(ValueOf(p
).Convert(tt
))
4233 x
= append(x
, v
.Interface())
4237 for i
, xi
:= range x
{
4239 for j
:= 0; j
< v
.Len(); j
++ {
4240 k
:= v
.Index(j
).Elem().Interface()
4241 if k
!= uintptr(i
*n
+j
) {
4242 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
4248 func TestStructOfFieldName(t
*testing
.T
) {
4249 // invalid field name "1nvalid"
4250 shouldPanic(func() {
4251 StructOf([]StructField
{
4252 StructField
{Name
: "valid", Type
: TypeOf("")},
4253 StructField
{Name
: "1nvalid", Type
: TypeOf("")},
4257 // invalid field name "+"
4258 shouldPanic(func() {
4259 StructOf([]StructField
{
4260 StructField
{Name
: "val1d", Type
: TypeOf("")},
4261 StructField
{Name
: "+", Type
: TypeOf("")},
4266 shouldPanic(func() {
4267 StructOf([]StructField
{
4268 StructField
{Name
: "", Type
: TypeOf("")},
4272 // verify creation of a struct with valid struct fields
4273 validFields
:= []StructField
{
4288 validStruct
:= StructOf(validFields
)
4290 const structStr
= `struct { φ string; ValidName string; Val1dNam5 string }`
4291 if got
, want
:= validStruct
.String(), structStr
; got
!= want
{
4292 t
.Errorf("StructOf(validFields).String()=%q, want %q", got
, want
)
4296 func TestStructOf(t
*testing
.T
) {
4297 // check construction and use of type not in binary
4298 fields
:= []StructField
{
4307 Type
: TypeOf(byte(0)),
4311 Type
: TypeOf(uint64(0)),
4315 Type
: TypeOf([3]uint16{}),
4319 st
:= StructOf(fields
)
4322 v
.FieldByName("X").Set(ValueOf(byte(2)))
4323 v
.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
4326 s
:= fmt
.Sprint(v
.Interface())
4327 want
:= `{ 1 0 [0 0 0]}`
4329 t
.Errorf("constructed struct = %s, want %s", s
, want
)
4331 const stStr
= `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
4332 if got
, want
:= st
.String(), stStr
; got
!= want
{
4333 t
.Errorf("StructOf(fields).String()=%q, want %q", got
, want
)
4336 // check the size, alignment and field offsets
4337 stt
:= TypeOf(struct {
4343 if st
.Size() != stt
.Size() {
4344 t
.Errorf("constructed struct size = %v, want %v", st
.Size(), stt
.Size())
4346 if st
.Align() != stt
.Align() {
4347 t
.Errorf("constructed struct align = %v, want %v", st
.Align(), stt
.Align())
4349 if st
.FieldAlign() != stt
.FieldAlign() {
4350 t
.Errorf("constructed struct field align = %v, want %v", st
.FieldAlign(), stt
.FieldAlign())
4352 for i
:= 0; i
< st
.NumField(); i
++ {
4353 o1
:= st
.Field(i
).Offset
4354 o2
:= stt
.Field(i
).Offset
4356 t
.Errorf("constructed struct field %v offset = %v, want %v", i
, o1
, o2
)
4360 // Check size and alignment with a trailing zero-sized field.
4361 st
= StructOf([]StructField
{
4364 Type
: TypeOf(byte(0)),
4368 Type
: TypeOf([0]*byte{}),
4371 stt
= TypeOf(struct {
4375 // Broken with gccgo for now--gccgo does not pad structs yet.
4376 // if st.Size() != stt.Size() {
4377 // t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
4379 if st
.Align() != stt
.Align() {
4380 t
.Errorf("constructed zero-padded struct align = %v, want %v", st
.Align(), stt
.Align())
4382 if st
.FieldAlign() != stt
.FieldAlign() {
4383 t
.Errorf("constructed zero-padded struct field align = %v, want %v", st
.FieldAlign(), stt
.FieldAlign())
4385 for i
:= 0; i
< st
.NumField(); i
++ {
4386 o1
:= st
.Field(i
).Offset
4387 o2
:= stt
.Field(i
).Offset
4389 t
.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i
, o1
, o2
)
4393 // check duplicate names
4394 shouldPanic(func() {
4395 StructOf([]StructField
{
4396 StructField
{Name
: "string", Type
: TypeOf("")},
4397 StructField
{Name
: "string", Type
: TypeOf("")},
4400 shouldPanic(func() {
4401 StructOf([]StructField
{
4402 StructField
{Type
: TypeOf("")},
4403 StructField
{Name
: "string", Type
: TypeOf("")},
4406 shouldPanic(func() {
4407 StructOf([]StructField
{
4408 StructField
{Type
: TypeOf("")},
4409 StructField
{Type
: TypeOf("")},
4412 // check that type already in binary is found
4413 checkSameType(t
, StructOf(fields
[2:3]), struct{ Y
uint64 }{})
4416 func TestStructOfExportRules(t
*testing
.T
) {
4422 testPanic
:= func(i
int, mustPanic
bool, f
func()) {
4425 if err
== nil && mustPanic
{
4426 t
.Errorf("test-%d did not panic", i
)
4428 if err
!= nil && !mustPanic
{
4429 t
.Errorf("test-%d panicked: %v\n", i
, err
)
4441 field
: StructField
{Name
: "S1", Anonymous
: true, Type
: TypeOf(S1
{})},
4445 field
: StructField
{Name
: "S1", Anonymous
: true, Type
: TypeOf((*S1
)(nil))},
4449 field
: StructField
{Name
: "s2", Anonymous
: true, Type
: TypeOf(s2
{})},
4453 field
: StructField
{Name
: "s2", Anonymous
: true, Type
: TypeOf((*s2
)(nil))},
4457 field
: StructField
{Name
: "Name", Type
: nil, PkgPath
: ""},
4461 field
: StructField
{Name
: "", Type
: TypeOf(S1
{}), PkgPath
: ""},
4465 field
: StructField
{Name
: "S1", Anonymous
: true, Type
: TypeOf(S1
{}), PkgPath
: "other/pkg"},
4469 field
: StructField
{Name
: "S1", Anonymous
: true, Type
: TypeOf((*S1
)(nil)), PkgPath
: "other/pkg"},
4473 field
: StructField
{Name
: "s2", Anonymous
: true, Type
: TypeOf(s2
{}), PkgPath
: "other/pkg"},
4477 field
: StructField
{Name
: "s2", Anonymous
: true, Type
: TypeOf((*s2
)(nil)), PkgPath
: "other/pkg"},
4481 field
: StructField
{Name
: "s2", Type
: TypeOf(int(0)), PkgPath
: "other/pkg"},
4485 field
: StructField
{Name
: "s2", Type
: TypeOf(int(0)), PkgPath
: "other/pkg"},
4489 field
: StructField
{Name
: "S", Type
: TypeOf(S1
{})},
4494 field
: StructField
{Name
: "S", Type
: TypeOf((*S1
)(nil))},
4498 field
: StructField
{Name
: "S", Type
: TypeOf(s2
{})},
4502 field
: StructField
{Name
: "S", Type
: TypeOf((*s2
)(nil))},
4506 field
: StructField
{Name
: "s", Type
: TypeOf(S1
{})},
4510 field
: StructField
{Name
: "s", Type
: TypeOf((*S1
)(nil))},
4514 field
: StructField
{Name
: "s", Type
: TypeOf(s2
{})},
4518 field
: StructField
{Name
: "s", Type
: TypeOf((*s2
)(nil))},
4522 field
: StructField
{Name
: "s", Type
: TypeOf(S1
{}), PkgPath
: "other/pkg"},
4523 mustPanic
: true, // TODO(sbinet): creating a name with a package path
4526 field
: StructField
{Name
: "s", Type
: TypeOf((*S1
)(nil)), PkgPath
: "other/pkg"},
4527 mustPanic
: true, // TODO(sbinet): creating a name with a package path
4530 field
: StructField
{Name
: "s", Type
: TypeOf(s2
{}), PkgPath
: "other/pkg"},
4531 mustPanic
: true, // TODO(sbinet): creating a name with a package path
4534 field
: StructField
{Name
: "s", Type
: TypeOf((*s2
)(nil)), PkgPath
: "other/pkg"},
4535 mustPanic
: true, // TODO(sbinet): creating a name with a package path
4538 field
: StructField
{Name
: "", Type
: TypeOf(ΦType
{})},
4542 field
: StructField
{Name
: "", Type
: TypeOf(φType
{})},
4546 field
: StructField
{Name
: "Φ", Type
: TypeOf(0)},
4550 field
: StructField
{Name
: "φ", Type
: TypeOf(0)},
4555 for i
, test
:= range tests
{
4556 testPanic(i
, test
.mustPanic
, func() {
4557 typ
:= StructOf([]StructField
{test
.field
})
4559 t
.Errorf("test-%d: error creating struct type", i
)
4562 field
:= typ
.Field(0)
4565 panic("field.Name must not be empty")
4567 exported
:= isExported(n
)
4568 if exported
!= test
.exported
{
4569 t
.Errorf("test-%d: got exported=%v want exported=%v", i
, exported
, test
.exported
)
4575 // isExported reports whether name is an exported Go symbol
4576 // (that is, whether it begins with an upper-case letter).
4578 func isExported(name
string) bool {
4579 ch
, _
:= utf8
.DecodeRuneInString(name
)
4580 return unicode
.IsUpper(ch
)
4583 func TestStructOfGC(t
*testing
.T
) {
4585 tt
:= TypeOf(T(nil))
4586 fields
:= []StructField
{
4587 {Name
: "X", Type
: tt
},
4588 {Name
: "Y", Type
: tt
},
4590 st
:= StructOf(fields
)
4594 for i
:= 0; i
< n
; i
++ {
4596 for j
:= 0; j
< v
.NumField(); j
++ {
4598 *p
= uintptr(i
*n
+ j
)
4599 v
.Field(j
).Set(ValueOf(p
).Convert(tt
))
4601 x
= append(x
, v
.Interface())
4605 for i
, xi
:= range x
{
4607 for j
:= 0; j
< v
.NumField(); j
++ {
4608 k
:= v
.Field(j
).Elem().Interface()
4609 if k
!= uintptr(i
*n
+j
) {
4610 t
.Errorf("lost x[%d].%c = %d, want %d", i
, "XY"[j
], k
, i
*n
+j
)
4616 func TestStructOfAlg(t
*testing
.T
) {
4617 st
:= StructOf([]StructField
{{Name
: "X", Tag
: "x", Type
: TypeOf(int(0))}})
4618 v1
:= New(st
).Elem()
4619 v2
:= New(st
).Elem()
4620 if !DeepEqual(v1
.Interface(), v1
.Interface()) {
4621 t
.Errorf("constructed struct %v not equal to itself", v1
.Interface())
4623 v1
.FieldByName("X").Set(ValueOf(int(1)))
4624 if i1
, i2
:= v1
.Interface(), v2
.Interface(); DeepEqual(i1
, i2
) {
4625 t
.Errorf("constructed structs %v and %v should not be equal", i1
, i2
)
4628 st
= StructOf([]StructField
{{Name
: "X", Tag
: "x", Type
: TypeOf([]int(nil))}})
4630 shouldPanic(func() { _
= v1
.Interface() == v1
.Interface() })
4633 func TestStructOfGenericAlg(t
*testing
.T
) {
4634 st1
:= StructOf([]StructField
{
4635 {Name
: "X", Tag
: "x", Type
: TypeOf(int64(0))},
4636 {Name
: "Y", Type
: TypeOf(string(""))},
4638 st
:= StructOf([]StructField
{
4639 {Name
: "S0", Type
: st1
},
4640 {Name
: "S1", Type
: st1
},
4658 {Name
: "XX", Type
: TypeOf([0]int{})},
4659 {Name
: "YY", Type
: TypeOf("")},
4667 {Name
: "XX", Type
: TypeOf([0]int{})},
4668 {Name
: "YY", Type
: TypeOf("")},
4669 {Name
: "ZZ", Type
: TypeOf([2]int{})},
4677 {Name
: "XX", Type
: TypeOf([1]int{})},
4678 {Name
: "YY", Type
: TypeOf("")},
4686 {Name
: "XX", Type
: TypeOf([1]int{})},
4687 {Name
: "YY", Type
: TypeOf("")},
4688 {Name
: "ZZ", Type
: TypeOf([1]int{})},
4696 {Name
: "XX", Type
: TypeOf([2]int{})},
4697 {Name
: "YY", Type
: TypeOf("")},
4698 {Name
: "ZZ", Type
: TypeOf([2]int{})},
4706 {Name
: "XX", Type
: TypeOf(int64(0))},
4707 {Name
: "YY", Type
: TypeOf(byte(0))},
4708 {Name
: "ZZ", Type
: TypeOf("")},
4716 {Name
: "XX", Type
: TypeOf(int64(0))},
4717 {Name
: "YY", Type
: TypeOf(int64(0))},
4718 {Name
: "ZZ", Type
: TypeOf("")},
4719 {Name
: "AA", Type
: TypeOf([1]int64{})},
4726 for _
, table
:= range tests
{
4727 v1
:= New(table
.rt
).Elem()
4728 v2
:= New(table
.rt
).Elem()
4730 if !DeepEqual(v1
.Interface(), v1
.Interface()) {
4731 t
.Errorf("constructed struct %v not equal to itself", v1
.Interface())
4734 v1
.FieldByIndex(table
.idx
).Set(ValueOf("abc"))
4735 v2
.FieldByIndex(table
.idx
).Set(ValueOf("def"))
4736 if i1
, i2
:= v1
.Interface(), v2
.Interface(); DeepEqual(i1
, i2
) {
4737 t
.Errorf("constructed structs %v and %v should not be equal", i1
, i2
)
4741 v1
.FieldByIndex(table
.idx
).Set(ValueOf(abc
))
4742 val
:= "+" + abc
+ "-"
4743 v2
.FieldByIndex(table
.idx
).Set(ValueOf(val
[1:4]))
4744 if i1
, i2
:= v1
.Interface(), v2
.Interface(); !DeepEqual(i1
, i2
) {
4745 t
.Errorf("constructed structs %v and %v should be equal", i1
, i2
)
4749 m
:= MakeMap(MapOf(table
.rt
, TypeOf(int(0))))
4750 m
.SetMapIndex(v1
, ValueOf(1))
4751 if i1
, i2
:= v1
.Interface(), v2
.Interface(); !m
.MapIndex(v2
).IsValid() {
4752 t
.Errorf("constructed structs %#v and %#v have different hashes", i1
, i2
)
4755 v2
.FieldByIndex(table
.idx
).Set(ValueOf("abc"))
4756 if i1
, i2
:= v1
.Interface(), v2
.Interface(); !DeepEqual(i1
, i2
) {
4757 t
.Errorf("constructed structs %v and %v should be equal", i1
, i2
)
4760 if i1
, i2
:= v1
.Interface(), v2
.Interface(); !m
.MapIndex(v2
).IsValid() {
4761 t
.Errorf("constructed structs %v and %v have different hashes", i1
, i2
)
4767 gccgo does not use the same directiface settings as gc.
4769 func TestStructOfDirectIface(t *testing.T) {
4771 type T struct{ X [1]*byte }
4772 i1 := Zero(TypeOf(T{})).Interface()
4773 v1 := ValueOf(&i1).Elem()
4774 p1 := v1.InterfaceData()[1]
4776 i2 := Zero(StructOf([]StructField{
4779 Type: ArrayOf(1, TypeOf((*int8)(nil))),
4782 v2 := ValueOf(&i2).Elem()
4783 p2 := v2.InterfaceData()[1]
4786 t.Errorf("got p1=%v. want=%v", p1, nil)
4790 t.Errorf("got p2=%v. want=%v", p2, nil)
4794 type T struct{ X [0]*byte }
4795 i1 := Zero(TypeOf(T{})).Interface()
4796 v1 := ValueOf(&i1).Elem()
4797 p1 := v1.InterfaceData()[1]
4799 i2 := Zero(StructOf([]StructField{
4802 Type: ArrayOf(0, TypeOf((*int8)(nil))),
4805 v2 := ValueOf(&i2).Elem()
4806 p2 := v2.InterfaceData()[1]
4809 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4813 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4821 func (i StructI
) Get() int { return int(i
) }
4825 func (i
*StructIPtr
) Get() int { return int(*i
) }
4828 gccgo does not yet support StructOf with methods.
4830 func TestStructOfWithInterface(t *testing.T) {
4832 type Iface interface {
4843 typ: TypeOf(StructI(want)),
4844 val: ValueOf(StructI(want)),
4849 typ: PtrTo(TypeOf(StructI(want))),
4850 val: ValueOf(func() interface{} {
4858 typ: PtrTo(TypeOf(StructIPtr(want))),
4859 val: ValueOf(func() interface{} {
4860 v := StructIPtr(want)
4867 typ: TypeOf(StructIPtr(want)),
4868 val: ValueOf(StructIPtr(want)),
4872 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
4873 // val: ValueOf(StructI(want)),
4878 for i, table := range tests {
4879 for j := 0; j < 2; j++ {
4880 var fields []StructField
4882 fields = append(fields, StructField{
4885 Type: TypeOf(int(0)),
4888 fields = append(fields, StructField{
4895 // We currently do not correctly implement methods
4896 // for anonymous fields other than the first.
4897 // Therefore, for now, we expect those methods
4898 // to not exist. See issues 15924 and 20824.
4899 // When those issues are fixed, this test of panic
4900 // should be removed.
4901 if j == 1 && table.impl {
4904 if err := recover(); err == nil {
4905 t.Errorf("test-%d-%d did not panic", i, j)
4908 _ = StructOf(fields)
4913 rt := StructOf(fields)
4914 rv := New(rt).Elem()
4915 rv.Field(j).Set(table.val)
4917 if _, ok := rv.Interface().(Iface); ok != table.impl {
4919 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
4921 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
4930 v := rv.Interface().(Iface).Get()
4932 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
4935 fct := rv.MethodByName("Get")
4936 out := fct.Call(nil)
4937 if !DeepEqual(out[0].Interface(), want) {
4938 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
4945 func TestChanOf(t
*testing
.T
) {
4946 // check construction and use of type not in binary
4948 ct
:= ChanOf(BothDir
, TypeOf(T("")))
4949 v
:= MakeChan(ct
, 2)
4951 v
.Send(ValueOf(T("hello")))
4953 v
.Send(ValueOf(T("world")))
4960 if s1
!= "hello" || s2
!= "world" {
4961 t
.Errorf("constructed chan: have %q, %q, want %q, %q", s1
, s2
, "hello", "world")
4964 // check that type already in binary is found
4966 checkSameType(t
, ChanOf(BothDir
, TypeOf(T1(1))), (chan T1
)(nil))
4969 func TestChanOfDir(t
*testing
.T
) {
4970 // check construction and use of type not in binary
4972 crt
:= ChanOf(RecvDir
, TypeOf(T("")))
4973 cst
:= ChanOf(SendDir
, TypeOf(T("")))
4975 // check that type already in binary is found
4977 checkSameType(t
, ChanOf(RecvDir
, TypeOf(T1(1))), (<-chan T1
)(nil))
4978 checkSameType(t
, ChanOf(SendDir
, TypeOf(T1(1))), (chan<- T1
)(nil))
4980 // check String form of ChanDir
4981 if crt
.ChanDir().String() != "<-chan" {
4982 t
.Errorf("chan dir: have %q, want %q", crt
.ChanDir().String(), "<-chan")
4984 if cst
.ChanDir().String() != "chan<-" {
4985 t
.Errorf("chan dir: have %q, want %q", cst
.ChanDir().String(), "chan<-")
4989 func TestChanOfGC(t
*testing
.T
) {
4990 done
:= make(chan bool, 1)
4994 case <-time
.After(5 * time
.Second
):
4995 panic("deadlock in TestChanOfGC")
5004 tt
:= TypeOf(T(nil))
5005 ct
:= ChanOf(BothDir
, tt
)
5007 // NOTE: The garbage collector handles allocated channels specially,
5008 // so we have to save pointers to channels in x; the pointer code will
5009 // use the gc info in the newly constructed chan type.
5012 for i
:= 0; i
< n
; i
++ {
5013 v
:= MakeChan(ct
, n
)
5014 for j
:= 0; j
< n
; j
++ {
5016 *p
= uintptr(i
*n
+ j
)
5017 v
.Send(ValueOf(p
).Convert(tt
))
5021 x
= append(x
, pv
.Interface())
5025 for i
, xi
:= range x
{
5026 v
:= ValueOf(xi
).Elem()
5027 for j
:= 0; j
< n
; j
++ {
5029 k
:= pv
.Elem().Interface()
5030 if k
!= uintptr(i
*n
+j
) {
5031 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
5037 func TestMapOf(t
*testing
.T
) {
5038 // check construction and use of type not in binary
5042 v
:= MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5044 v
.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5047 s
:= fmt
.Sprint(v
.Interface())
5050 t
.Errorf("constructed map = %s, want %s", s
, want
)
5053 // check that type already in binary is found
5054 checkSameType(t
, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V
]K(nil))
5056 // check that invalid key type panics
5057 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5060 func TestMapOfGCKeys(t
*testing
.T
) {
5062 tt
:= TypeOf(T(nil))
5063 mt
:= MapOf(tt
, TypeOf(false))
5065 // NOTE: The garbage collector handles allocated maps specially,
5066 // so we have to save pointers to maps in x; the pointer code will
5067 // use the gc info in the newly constructed map type.
5070 for i
:= 0; i
< n
; i
++ {
5072 for j
:= 0; j
< n
; j
++ {
5074 *p
= uintptr(i
*n
+ j
)
5075 v
.SetMapIndex(ValueOf(p
).Convert(tt
), ValueOf(true))
5079 x
= append(x
, pv
.Interface())
5083 for i
, xi
:= range x
{
5084 v
:= ValueOf(xi
).Elem()
5086 for _
, kv
:= range v
.MapKeys() {
5087 out
= append(out
, int(kv
.Elem().Interface().(uintptr)))
5090 for j
, k
:= range out
{
5092 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
5098 func TestMapOfGCValues(t
*testing
.T
) {
5100 tt
:= TypeOf(T(nil))
5101 mt
:= MapOf(TypeOf(1), tt
)
5103 // NOTE: The garbage collector handles allocated maps specially,
5104 // so we have to save pointers to maps in x; the pointer code will
5105 // use the gc info in the newly constructed map type.
5108 for i
:= 0; i
< n
; i
++ {
5110 for j
:= 0; j
< n
; j
++ {
5112 *p
= uintptr(i
*n
+ j
)
5113 v
.SetMapIndex(ValueOf(j
), ValueOf(p
).Convert(tt
))
5117 x
= append(x
, pv
.Interface())
5121 for i
, xi
:= range x
{
5122 v
:= ValueOf(xi
).Elem()
5123 for j
:= 0; j
< n
; j
++ {
5124 k
:= v
.MapIndex(ValueOf(j
)).Elem().Interface().(uintptr)
5125 if k
!= uintptr(i
*n
+j
) {
5126 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
5132 func TestTypelinksSorted(t
*testing
.T
) {
5134 for i
, n
:= range TypeLinks() {
5136 t
.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last
, i
-1, n
, i
)
5142 func TestFuncOf(t
*testing
.T
) {
5143 // check construction and use of type not in binary
5147 fn
:= func(args
[]Value
) []Value
{
5149 t
.Errorf("args == %v, want exactly one arg", args
)
5150 } else if args
[0].Type() != TypeOf(K("")) {
5151 t
.Errorf("args[0] is type %v, want %v", args
[0].Type(), TypeOf(K("")))
5152 } else if args
[0].String() != "gopher" {
5153 t
.Errorf("args[0] = %q, want %q", args
[0].String(), "gopher")
5155 return []Value
{ValueOf(V(3.14))}
5157 v
:= MakeFunc(FuncOf([]Type
{TypeOf(K(""))}, []Type
{TypeOf(V(0))}, false), fn
)
5159 outs
:= v
.Call([]Value
{ValueOf(K("gopher"))})
5161 t
.Fatalf("v.Call returned %v, want exactly one result", outs
)
5162 } else if outs
[0].Type() != TypeOf(V(0)) {
5163 t
.Fatalf("c.Call[0] is type %v, want %v", outs
[0].Type(), TypeOf(V(0)))
5165 f
:= outs
[0].Float()
5167 t
.Errorf("constructed func returned %f, want %f", f
, 3.14)
5170 // check that types already in binary are found
5172 testCases
:= []struct {
5177 {in
: []Type
{TypeOf(T1(0))}, want
: (func(T1
))(nil)},
5178 {in
: []Type
{TypeOf(int(0))}, want
: (func(int))(nil)},
5179 {in
: []Type
{SliceOf(TypeOf(int(0)))}, variadic
: true, want
: (func(...int))(nil)},
5180 {in
: []Type
{TypeOf(int(0))}, out
: []Type
{TypeOf(false)}, want
: (func(int) bool)(nil)},
5181 {in
: []Type
{TypeOf(int(0))}, out
: []Type
{TypeOf(false), TypeOf("")}, want
: (func(int) (bool, string))(nil)},
5183 for _
, tt
:= range testCases
{
5184 checkSameType(t
, FuncOf(tt
.in
, tt
.out
, tt
.variadic
), tt
.want
)
5187 // check that variadic requires last element be a slice.
5188 FuncOf([]Type
{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5189 shouldPanic(func() { FuncOf([]Type
{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5190 shouldPanic(func() { FuncOf(nil, nil, true) })
5199 func BenchmarkFieldByName1(b
*testing
.B
) {
5201 b
.RunParallel(func(pb
*testing
.PB
) {
5208 func BenchmarkFieldByName2(b
*testing
.B
) {
5210 b
.RunParallel(func(pb
*testing
.PB
) {
5287 func TestEmbed(t
*testing
.T
) {
5289 f
, ok
:= typ
.FieldByName("X")
5291 t
.Fatalf(`FieldByName("X") should fail, returned %v`, f
.Index
)
5295 func BenchmarkFieldByName3(b
*testing
.B
) {
5297 b
.RunParallel(func(pb
*testing
.PB
) {
5309 func BenchmarkInterfaceBig(b
*testing
.B
) {
5311 b
.RunParallel(func(pb
*testing
.PB
) {
5319 func TestAllocsInterfaceBig(t
*testing
.T
) {
5320 if testing
.Short() {
5321 t
.Skip("skipping malloc count in short mode")
5324 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
5325 t
.Error("allocs:", allocs
)
5329 func BenchmarkInterfaceSmall(b
*testing
.B
) {
5330 v
:= ValueOf(int64(0))
5331 b
.RunParallel(func(pb
*testing
.PB
) {
5338 func TestAllocsInterfaceSmall(t
*testing
.T
) {
5339 if testing
.Short() {
5340 t
.Skip("skipping malloc count in short mode")
5342 v
:= ValueOf(int64(0))
5343 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
5344 t
.Error("allocs:", allocs
)
5348 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
5349 // The basic usage is:
5352 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
5355 // Each iteration of the loop returns a different set of results, until all
5356 // possible result sets have been explored. It is okay for different code paths
5357 // to make different method call sequences on x, but there must be no
5358 // other source of non-determinism in the call sequences.
5360 // When faced with a new decision, x chooses randomly. Future explorations
5361 // of that path will choose successive values for the result. Thus, stopping
5362 // the loop after a fixed number of iterations gives somewhat stochastic
5368 // v := make([]bool, x.Choose(4))
5369 // for i := range v {
5375 // prints (in some order):
5384 // [false false false]
5387 // [false false false false]
5389 // [true true true true]
5391 type exhaustive
struct {
5397 type choice
struct {
5403 func (x
*exhaustive
) Next() bool {
5405 x
.r
= rand
.New(rand
.NewSource(time
.Now().UnixNano()))
5412 for i
:= len(x
.last
) - 1; i
>= 0; i
-- {
5416 x
.last
= x
.last
[:i
+1]
5423 func (x
*exhaustive
) Choose(max
int) int {
5424 if x
.pos
>= len(x
.last
) {
5425 x
.last
= append(x
.last
, choice
{x
.r
.Intn(max
), 0, max
})
5430 panic("inconsistent use of exhaustive tester")
5432 return (c
.n
+ c
.off
) % max
5435 func (x
*exhaustive
) Maybe() bool {
5436 return x
.Choose(2) == 1
5439 func GCFunc(args
[]Value
) []Value
{
5444 func TestReflectFuncTraceback(t
*testing
.T
) {
5445 f
:= MakeFunc(TypeOf(func() {}), GCFunc
)
5449 func TestReflectMethodTraceback(t
*testing
.T
) {
5451 m
:= ValueOf(p
).MethodByName("GCMethod")
5452 i
:= ValueOf(m
.Interface()).Call([]Value
{ValueOf(5)})[0].Int()
5454 t
.Errorf("Call returned %d; want 8", i
)
5458 func TestBigZero(t
*testing
.T
) {
5459 const size
= 1 << 10
5461 z
:= Zero(ValueOf(v
).Type()).Interface().([size
]byte)
5462 for i
:= 0; i
< size
; i
++ {
5464 t
.Fatalf("Zero object not all zero, index %d", i
)
5469 func TestFieldByIndexNil(t
*testing
.T
) {
5478 v
.FieldByName("P") // should be fine
5481 if err
:= recover(); err
== nil {
5482 t
.Fatalf("no error")
5483 } else if !strings
.Contains(fmt
.Sprint(err
), "nil pointer to embedded struct") {
5484 t
.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err
)
5487 v
.FieldByName("F") // should panic
5489 t
.Fatalf("did not panic")
5493 // type Outer struct {
5497 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
5498 // The implementation is logically:
5499 // func (p *Outer) M() {
5502 // but since the only change here is the replacement of one pointer receiver with another,
5503 // the actual generated code overwrites the original receiver with the p.Inner pointer and
5504 // then jumps to the M method expecting the *Inner receiver.
5506 // During reflect.Value.Call, we create an argument frame and the associated data structures
5507 // to describe it to the garbage collector, populate the frame, call reflect.call to
5508 // run a function call using that frame, and then copy the results back out of the frame.
5509 // The reflect.call function does a memmove of the frame structure onto the
5510 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
5511 // the frame structure (to preserve the outputs).
5513 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
5514 // were for the full stack frame. However, in the case where the called function was
5515 // one of these wrappers, the rewritten receiver is almost certainly a different type
5516 // than the original receiver. This is not a problem on the stack, where we use the
5517 // program counter to determine the type information and understand that
5518 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
5519 // memory word is now an *Inner. But in the statically typed argument frame created
5520 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
5521 // off the stack into the frame will store an *Inner there, and then if a garbage collection
5522 // happens to scan that argument frame before it is discarded, it will scan the *Inner
5523 // memory as if it were an *Outer. If the two have different memory layouts, the
5524 // collection will interpret the memory incorrectly.
5526 // One such possible incorrect interpretation is to treat two arbitrary memory words
5527 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
5528 // an interface requires dereferencing the itab word, the misinterpretation will try to
5529 // deference Inner.P1, causing a crash during garbage collection.
5531 // This came up in a real program in issue 7725.
5544 func (pi
*Inner
) M() {
5545 // Clear references to pi so that the only way the
5546 // garbage collection will find the pointer is in the
5547 // argument frame, typed as a *Outer.
5550 // Set up an interface value that will cause a crash.
5551 // P1 = 1 is a non-zero, so the interface looks non-nil.
5552 // P2 = pi ensures that the data word points into the
5553 // allocated heap; if not the collection skips the interface
5554 // value as irrelevant, without dereferencing P1.
5556 pi
.P2
= uintptr(unsafe
.Pointer(pi
))
5559 func TestCallMethodJump(t
*testing
.T
) {
5560 // In reflect.Value.Call, trigger a garbage collection after reflect.call
5561 // returns but before the args frame has been discarded.
5562 // This is a little clumsy but makes the failure repeatable.
5565 p
:= &Outer
{Inner
: new(Inner
)}
5567 ValueOf(p
).Method(0).Call(nil)
5569 // Stop garbage collecting during reflect.call.
5573 func TestMakeFuncStackCopy(t
*testing
.T
) {
5574 target
:= func(in
[]Value
) []Value
{
5577 return []Value
{ValueOf(9)}
5580 var concrete
func(*int, int) int
5581 fn
:= MakeFunc(ValueOf(concrete
).Type(), target
)
5582 ValueOf(&concrete
).Elem().Set(fn
)
5583 x
:= concrete(nil, 7)
5585 t
.Errorf("have %#q want 9", x
)
5589 // use about n KB of stack
5590 func useStack(n
int) {
5594 var b
[1024]byte // makes frame about 1KB
5595 useStack(n
- 1 + int(b
[99]))
5602 func TestValueString(t
*testing
.T
) {
5603 rv
:= ValueOf(Impl
{})
5604 if rv
.String() != "<reflect_test.Impl Value>" {
5605 t
.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv
.String(), "<reflect_test.Impl Value>")
5608 method
:= rv
.Method(0)
5609 if method
.String() != "<func() Value>" {
5610 t
.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method
.String(), "<func() Value>")
5614 func TestInvalid(t
*testing
.T
) {
5615 // Used to have inconsistency between IsValid() and Kind() != Invalid.
5616 type T
struct{ v
interface{} }
5618 v
:= ValueOf(T
{}).Field(0)
5619 if v
.IsValid() != true || v
.Kind() != Interface
{
5620 t
.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v
.IsValid(), v
.Kind())
5623 if v
.IsValid() != false || v
.Kind() != Invalid
{
5624 t
.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v
.IsValid(), v
.Kind())
5629 func TestLargeGCProg(t
*testing
.T
) {
5630 fv
:= ValueOf(func([256]*byte) {})
5631 fv
.Call([]Value
{ValueOf([256]*byte{})})
5634 func fieldIndexRecover(t Type
, i
int) (recovered
interface{}) {
5636 recovered
= recover()
5644 func TestTypeFieldOutOfRangePanic(t
*testing
.T
) {
5645 typ
:= TypeOf(struct{ X
int }{10})
5646 testIndices
:= [...]struct {
5655 for i
, tt
:= range testIndices
{
5656 recoveredErr
:= fieldIndexRecover(typ
, tt
.i
)
5658 if recoveredErr
== nil {
5659 t
.Errorf("#%d: fieldIndex %d expected to panic", i
, tt
.i
)
5662 if recoveredErr
!= nil {
5663 t
.Errorf("#%d: got err=%v, expected no panic", i
, recoveredErr
)
5670 func TestCallGC(t
*testing
.T
) {
5671 f
:= func(a
, b
, c
, d
, e
string) {
5673 g
:= func(in
[]Value
) []Value
{
5677 typ
:= ValueOf(f
).Type()
5678 f2
:= MakeFunc(typ
, g
).Interface().(func(string, string, string, string, string))
5679 f2("four", "five5", "six666", "seven77", "eight888")
5682 // Issue 18635 (function version).
5683 func TestKeepFuncLive(t
*testing
.T
) {
5684 // Test that we keep makeFuncImpl live as long as it is
5685 // referenced on the stack.
5686 typ
:= TypeOf(func(i
int) {})
5687 var f
, g
func(in
[]Value
) []Value
5688 f
= func(in
[]Value
) []Value
{
5690 i
:= int(in
[0].Int())
5692 // We can't use Value.Call here because
5693 // runtime.call* will keep the makeFuncImpl
5694 // alive. However, by converting it to an
5695 // interface value and calling that,
5696 // reflect.callReflect is the only thing that
5697 // can keep the makeFuncImpl live.
5699 // Alternate between f and g so that if we do
5700 // reuse the memory prematurely it's more
5701 // likely to get obviously corrupted.
5702 MakeFunc(typ
, g
).Interface().(func(i
int))(i
- 1)
5706 g
= func(in
[]Value
) []Value
{
5708 i
:= int(in
[0].Int())
5709 MakeFunc(typ
, f
).Interface().(func(i
int))(i
)
5712 MakeFunc(typ
, f
).Call([]Value
{ValueOf(10)})
5715 type UnExportedFirst
int
5717 func (i UnExportedFirst
) Φ
Exported() {}
5718 func (i UnExportedFirst
) unexported() {}
5721 func TestMethodByNameUnExportedFirst(t
*testing
.T
) {
5723 if recover() != nil {
5724 t
.Errorf("should not panic")
5727 typ
:= TypeOf(UnExportedFirst(0))
5728 m
, _
:= typ
.MethodByName("ΦExported")
5729 if m
.Name
!= "ΦExported" {
5730 t
.Errorf("got %s, expected ΦExported", m
.Name
)
5734 // Issue 18635 (method version).
5735 type KeepMethodLive
struct{}
5737 func (k KeepMethodLive
) Method1(i
int) {
5740 ValueOf(k
).MethodByName("Method2").Interface().(func(i
int))(i
- 1)
5744 func (k KeepMethodLive
) Method2(i
int) {
5746 ValueOf(k
).MethodByName("Method1").Interface().(func(i
int))(i
)
5749 func TestKeepMethodLive(t
*testing
.T
) {
5750 // Test that we keep methodValue live as long as it is
5751 // referenced on the stack.
5752 KeepMethodLive
{}.Method1(10)
5755 // clobber tries to clobber unreachable memory.
5758 for i
:= 1; i
< 32; i
++ {
5759 for j
:= 0; j
< 10; j
++ {
5760 obj
:= make([]*byte, i
)
5767 type funcLayoutTest
struct {
5769 size
, argsize
, retOffset
uintptr
5770 stack
[]byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized)
5774 var funcLayoutTests
[]funcLayoutTest
5777 var argAlign
uintptr = PtrSize
5778 if runtime
.GOARCH
== "amd64p32" {
5779 argAlign
= 2 * PtrSize
5781 roundup
:= func(x
uintptr, a
uintptr) uintptr {
5782 return (x
+ a
- 1) / a
* a
5785 funcLayoutTests
= append(funcLayoutTests
,
5788 ValueOf(func(a
, b
string) string { return "" }).Type(),
5793 []byte{1, 0, 1, 0, 1},
5798 r
= []byte{0, 0, 0, 1}
5802 funcLayoutTests
= append(funcLayoutTests
,
5805 ValueOf(func(a
, b
, c
uint32, p
*byte, d
uint16) {}).Type(),
5806 roundup(roundup(3*4, PtrSize
)+PtrSize
+2, argAlign
),
5807 roundup(3*4, PtrSize
) + PtrSize
+ 2,
5808 roundup(roundup(3*4, PtrSize
)+PtrSize
+2, argAlign
),
5813 funcLayoutTests
= append(funcLayoutTests
,
5816 ValueOf(func(a
map[int]int, b
uintptr, c
interface{}) {}).Type(),
5828 funcLayoutTests
= append(funcLayoutTests
,
5831 ValueOf(func(a S
) {}).Type(),
5839 funcLayoutTests
= append(funcLayoutTests
,
5841 ValueOf((*byte)(nil)).Type(),
5842 ValueOf(func(a
uintptr, b
*int) {}).Type(),
5843 roundup(3*PtrSize
, argAlign
),
5845 roundup(3*PtrSize
, argAlign
),
5850 funcLayoutTests
= append(funcLayoutTests
,
5853 ValueOf(func(a
uintptr) {}).Type(),
5854 roundup(PtrSize
, argAlign
),
5856 roundup(PtrSize
, argAlign
),
5861 funcLayoutTests
= append(funcLayoutTests
,
5864 ValueOf(func() uintptr { return 0 }).Type(),
5872 funcLayoutTests
= append(funcLayoutTests
,
5874 ValueOf(uintptr(0)).Type(),
5875 ValueOf(func(a
uintptr) {}).Type(),
5881 // Note: this one is tricky, as the receiver is not a pointer. But we
5882 // pass the receiver by reference to the autogenerated pointer-receiver
5883 // version of the function.
5887 func TestFuncLayout(t
*testing
.T
) {
5888 t
.Skip("gccgo does not use funcLayout")
5889 for _
, lt
:= range funcLayoutTests
{
5890 typ
, argsize
, retOffset
, stack
, gc
, ptrs
:= FuncLayout(lt
.t
, lt
.rcvr
)
5891 if typ
.Size() != lt
.size
{
5892 t
.Errorf("funcLayout(%v, %v).size=%d, want %d", lt
.t
, lt
.rcvr
, typ
.Size(), lt
.size
)
5894 if argsize
!= lt
.argsize
{
5895 t
.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt
.t
, lt
.rcvr
, argsize
, lt
.argsize
)
5897 if retOffset
!= lt
.retOffset
{
5898 t
.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt
.t
, lt
.rcvr
, retOffset
, lt
.retOffset
)
5900 if !bytes
.Equal(stack
, lt
.stack
) {
5901 t
.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt
.t
, lt
.rcvr
, stack
, lt
.stack
)
5903 if !bytes
.Equal(gc
, lt
.gc
) {
5904 t
.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt
.t
, lt
.rcvr
, gc
, lt
.gc
)
5906 if ptrs
&& len(stack
) == 0 ||
!ptrs
&& len(stack
) > 0 {
5907 t
.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt
.t
, lt
.rcvr
, ptrs
, !ptrs
)
5912 func verifyGCBits(t
*testing
.T
, typ Type
, bits
[]byte) {
5913 heapBits
:= GCBits(New(typ
).Interface())
5914 if !bytes
.Equal(heapBits
, bits
) {
5915 t
.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ
, heapBits
, bits
)
5919 func verifyGCBitsSlice(t
*testing
.T
, typ Type
, cap int, bits
[]byte) {
5920 // Creating a slice causes the runtime to repeat a bitmap,
5921 // which exercises a different path from making the compiler
5922 // repeat a bitmap for a small array or executing a repeat in
5924 val
:= MakeSlice(typ
, 0, cap)
5925 data
:= NewAt(ArrayOf(cap, typ
), unsafe
.Pointer(val
.Pointer()))
5926 heapBits
:= GCBits(data
.Interface())
5927 // Repeat the bitmap for the slice size, trimming scalars in
5928 // the last element.
5929 bits
= rep(cap, bits
)
5930 for len(bits
) > 2 && bits
[len(bits
)-1] == 0 {
5931 bits
= bits
[:len(bits
)-1]
5933 if len(bits
) == 2 && bits
[0] == 0 && bits
[1] == 0 {
5936 if !bytes
.Equal(heapBits
, bits
) {
5937 t
.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ
, cap, heapBits
, bits
)
5941 func TestGCBits(t
*testing
.T
) {
5942 t
.Skip("gccgo does not use gcbits yet")
5944 verifyGCBits(t
, TypeOf((*byte)(nil)), []byte{1})
5946 // Building blocks for types seen by the compiler (like [2]Xscalar).
5947 // The compiler will create the type structures for the derived types,
5948 // including their GC metadata.
5949 type Xscalar
struct{ x
uintptr }
5950 type Xptr
struct{ x
*byte }
5951 type Xptrscalar
struct {
5955 type Xscalarptr
struct {
5959 type Xbigptrscalar
struct {
5964 var Tscalar
, Tint64
, Tptr
, Tscalarptr
, Tptrscalar
, Tbigptrscalar Type
5966 // Building blocks for types constructed by reflect.
5967 // This code is in a separate block so that code below
5968 // cannot accidentally refer to these.
5969 // The compiler must NOT see types derived from these
5970 // (for example, [2]Scalar must NOT appear in the program),
5971 // or else reflect will use it instead of having to construct one.
5972 // The goal is to test the construction.
5973 type Scalar
struct{ x
uintptr }
5974 type Ptr
struct{ x
*byte }
5975 type Ptrscalar
struct {
5979 type Scalarptr
struct {
5983 type Bigptrscalar
struct {
5988 Tscalar
= TypeOf(Scalar
{})
5989 Tint64
= TypeOf(Int64(0))
5990 Tptr
= TypeOf(Ptr
{})
5991 Tscalarptr
= TypeOf(Scalarptr
{})
5992 Tptrscalar
= TypeOf(Ptrscalar
{})
5993 Tbigptrscalar
= TypeOf(Bigptrscalar
{})
5998 verifyGCBits(t
, TypeOf(Xscalar
{}), empty
)
5999 verifyGCBits(t
, Tscalar
, empty
)
6000 verifyGCBits(t
, TypeOf(Xptr
{}), lit(1))
6001 verifyGCBits(t
, Tptr
, lit(1))
6002 verifyGCBits(t
, TypeOf(Xscalarptr
{}), lit(0, 1))
6003 verifyGCBits(t
, Tscalarptr
, lit(0, 1))
6004 verifyGCBits(t
, TypeOf(Xptrscalar
{}), lit(1))
6005 verifyGCBits(t
, Tptrscalar
, lit(1))
6007 verifyGCBits(t
, TypeOf([0]Xptr
{}), empty
)
6008 verifyGCBits(t
, ArrayOf(0, Tptr
), empty
)
6009 verifyGCBits(t
, TypeOf([1]Xptrscalar
{}), lit(1))
6010 verifyGCBits(t
, ArrayOf(1, Tptrscalar
), lit(1))
6011 verifyGCBits(t
, TypeOf([2]Xscalar
{}), empty
)
6012 verifyGCBits(t
, ArrayOf(2, Tscalar
), empty
)
6013 verifyGCBits(t
, TypeOf([10000]Xscalar
{}), empty
)
6014 verifyGCBits(t
, ArrayOf(10000, Tscalar
), empty
)
6015 verifyGCBits(t
, TypeOf([2]Xptr
{}), lit(1, 1))
6016 verifyGCBits(t
, ArrayOf(2, Tptr
), lit(1, 1))
6017 verifyGCBits(t
, TypeOf([10000]Xptr
{}), rep(10000, lit(1)))
6018 verifyGCBits(t
, ArrayOf(10000, Tptr
), rep(10000, lit(1)))
6019 verifyGCBits(t
, TypeOf([2]Xscalarptr
{}), lit(0, 1, 0, 1))
6020 verifyGCBits(t
, ArrayOf(2, Tscalarptr
), lit(0, 1, 0, 1))
6021 verifyGCBits(t
, TypeOf([10000]Xscalarptr
{}), rep(10000, lit(0, 1)))
6022 verifyGCBits(t
, ArrayOf(10000, Tscalarptr
), rep(10000, lit(0, 1)))
6023 verifyGCBits(t
, TypeOf([2]Xptrscalar
{}), lit(1, 0, 1))
6024 verifyGCBits(t
, ArrayOf(2, Tptrscalar
), lit(1, 0, 1))
6025 verifyGCBits(t
, TypeOf([10000]Xptrscalar
{}), rep(10000, lit(1, 0)))
6026 verifyGCBits(t
, ArrayOf(10000, Tptrscalar
), rep(10000, lit(1, 0)))
6027 verifyGCBits(t
, TypeOf([1][10000]Xptrscalar
{}), rep(10000, lit(1, 0)))
6028 verifyGCBits(t
, ArrayOf(1, ArrayOf(10000, Tptrscalar
)), rep(10000, lit(1, 0)))
6029 verifyGCBits(t
, TypeOf([2][10000]Xptrscalar
{}), rep(2*10000, lit(1, 0)))
6030 verifyGCBits(t
, ArrayOf(2, ArrayOf(10000, Tptrscalar
)), rep(2*10000, lit(1, 0)))
6031 verifyGCBits(t
, TypeOf([4]Xbigptrscalar
{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6032 verifyGCBits(t
, ArrayOf(4, Tbigptrscalar
), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6034 verifyGCBitsSlice(t
, TypeOf([]Xptr
{}), 0, empty
)
6035 verifyGCBitsSlice(t
, SliceOf(Tptr
), 0, empty
)
6036 verifyGCBitsSlice(t
, TypeOf([]Xptrscalar
{}), 1, lit(1))
6037 verifyGCBitsSlice(t
, SliceOf(Tptrscalar
), 1, lit(1))
6038 verifyGCBitsSlice(t
, TypeOf([]Xscalar
{}), 2, lit(0))
6039 verifyGCBitsSlice(t
, SliceOf(Tscalar
), 2, lit(0))
6040 verifyGCBitsSlice(t
, TypeOf([]Xscalar
{}), 10000, lit(0))
6041 verifyGCBitsSlice(t
, SliceOf(Tscalar
), 10000, lit(0))
6042 verifyGCBitsSlice(t
, TypeOf([]Xptr
{}), 2, lit(1))
6043 verifyGCBitsSlice(t
, SliceOf(Tptr
), 2, lit(1))
6044 verifyGCBitsSlice(t
, TypeOf([]Xptr
{}), 10000, lit(1))
6045 verifyGCBitsSlice(t
, SliceOf(Tptr
), 10000, lit(1))
6046 verifyGCBitsSlice(t
, TypeOf([]Xscalarptr
{}), 2, lit(0, 1))
6047 verifyGCBitsSlice(t
, SliceOf(Tscalarptr
), 2, lit(0, 1))
6048 verifyGCBitsSlice(t
, TypeOf([]Xscalarptr
{}), 10000, lit(0, 1))
6049 verifyGCBitsSlice(t
, SliceOf(Tscalarptr
), 10000, lit(0, 1))
6050 verifyGCBitsSlice(t
, TypeOf([]Xptrscalar
{}), 2, lit(1, 0))
6051 verifyGCBitsSlice(t
, SliceOf(Tptrscalar
), 2, lit(1, 0))
6052 verifyGCBitsSlice(t
, TypeOf([]Xptrscalar
{}), 10000, lit(1, 0))
6053 verifyGCBitsSlice(t
, SliceOf(Tptrscalar
), 10000, lit(1, 0))
6054 verifyGCBitsSlice(t
, TypeOf([][10000]Xptrscalar
{}), 1, rep(10000, lit(1, 0)))
6055 verifyGCBitsSlice(t
, SliceOf(ArrayOf(10000, Tptrscalar
)), 1, rep(10000, lit(1, 0)))
6056 verifyGCBitsSlice(t
, TypeOf([][10000]Xptrscalar
{}), 2, rep(10000, lit(1, 0)))
6057 verifyGCBitsSlice(t
, SliceOf(ArrayOf(10000, Tptrscalar
)), 2, rep(10000, lit(1, 0)))
6058 verifyGCBitsSlice(t
, TypeOf([]Xbigptrscalar
{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6059 verifyGCBitsSlice(t
, SliceOf(Tbigptrscalar
), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6061 verifyGCBits(t
, TypeOf((chan [100]Xscalar
)(nil)), lit(1))
6062 verifyGCBits(t
, ChanOf(BothDir
, ArrayOf(100, Tscalar
)), lit(1))
6064 verifyGCBits(t
, TypeOf((func([10000]Xscalarptr
))(nil)), lit(1))
6065 verifyGCBits(t
, FuncOf([]Type
{ArrayOf(10000, Tscalarptr
)}, nil, false), lit(1))
6067 verifyGCBits(t
, TypeOf((map[[10000]Xscalarptr
]Xscalar
)(nil)), lit(1))
6068 verifyGCBits(t
, MapOf(ArrayOf(10000, Tscalarptr
), Tscalar
), lit(1))
6070 verifyGCBits(t
, TypeOf((*[10000]Xscalar
)(nil)), lit(1))
6071 verifyGCBits(t
, PtrTo(ArrayOf(10000, Tscalar
)), lit(1))
6073 verifyGCBits(t
, TypeOf(([][10000]Xscalar
)(nil)), lit(1))
6074 verifyGCBits(t
, SliceOf(ArrayOf(10000, Tscalar
)), lit(1))
6076 hdr
:= make([]byte, 8/PtrSize
)
6078 verifyMapBucket
:= func(t
*testing
.T
, k
, e Type
, m
interface{}, want
[]byte) {
6079 verifyGCBits(t
, MapBucketOf(k
, e
), want
)
6080 verifyGCBits(t
, CachedBucketOf(TypeOf(m
)), want
)
6084 map[Xscalar
]Xptr(nil),
6085 join(hdr
, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6088 map[Xscalarptr
]Xptr(nil),
6089 join(hdr
, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6090 verifyMapBucket(t
, Tint64
, Tptr
,
6091 map[int64]Xptr(nil),
6092 join(hdr
, rep(8, rep(8/PtrSize
, lit(0))), rep(8, lit(1)), naclpad(), lit(1)))
6095 map[Xscalar
]Xscalar(nil),
6098 ArrayOf(2, Tscalarptr
), ArrayOf(3, Tptrscalar
),
6099 map[[2]Xscalarptr
][3]Xptrscalar(nil),
6100 join(hdr
, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6102 ArrayOf(64/PtrSize
, Tscalarptr
), ArrayOf(64/PtrSize
, Tptrscalar
),
6103 map[[64 / PtrSize
]Xscalarptr
][64 / PtrSize
]Xptrscalar(nil),
6104 join(hdr
, rep(8*64/PtrSize
, lit(0, 1)), rep(8*64/PtrSize
, lit(1, 0)), lit(1)))
6106 ArrayOf(64/PtrSize
+1, Tscalarptr
), ArrayOf(64/PtrSize
, Tptrscalar
),
6107 map[[64/PtrSize
+ 1]Xscalarptr
][64 / PtrSize
]Xptrscalar(nil),
6108 join(hdr
, rep(8, lit(1)), rep(8*64/PtrSize
, lit(1, 0)), lit(1)))
6110 ArrayOf(64/PtrSize
, Tscalarptr
), ArrayOf(64/PtrSize
+1, Tptrscalar
),
6111 map[[64 / PtrSize
]Xscalarptr
][64/PtrSize
+ 1]Xptrscalar(nil),
6112 join(hdr
, rep(8*64/PtrSize
, lit(0, 1)), rep(8, lit(1)), lit(1)))
6114 ArrayOf(64/PtrSize
+1, Tscalarptr
), ArrayOf(64/PtrSize
+1, Tptrscalar
),
6115 map[[64/PtrSize
+ 1]Xscalarptr
][64/PtrSize
+ 1]Xptrscalar(nil),
6116 join(hdr
, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6119 func naclpad() []byte {
6120 if runtime
.GOARCH
== "amd64p32" {
6126 func rep(n
int, b
[]byte) []byte { return bytes
.Repeat(b
, n
) }
6127 func join(b
...[]byte) []byte { return bytes
.Join(b
, nil) }
6128 func lit(x
...byte) []byte { return x
}
6130 func TestTypeOfTypeOf(t
*testing
.T
) {
6131 // Check that all the type constructors return concrete *rtype implementations.
6132 // It's difficult to test directly because the reflect package is only at arm's length.
6133 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6134 check
:= func(name
string, typ Type
) {
6135 if underlying
:= TypeOf(typ
).String(); underlying
!= "*reflect.rtype" {
6136 t
.Errorf("%v returned %v, not *reflect.rtype", name
, underlying
)
6140 type T
struct{ int }
6141 check("TypeOf", TypeOf(T
{}))
6143 check("ArrayOf", ArrayOf(10, TypeOf(T
{})))
6144 check("ChanOf", ChanOf(BothDir
, TypeOf(T
{})))
6145 check("FuncOf", FuncOf([]Type
{TypeOf(T
{})}, nil, false))
6146 check("MapOf", MapOf(TypeOf(T
{}), TypeOf(T
{})))
6147 check("PtrTo", PtrTo(TypeOf(T
{})))
6148 check("SliceOf", SliceOf(TypeOf(T
{})))
6151 type XM
struct{ _
bool }
6153 func (*XM
) String() string { return "" }
6155 func TestPtrToMethods(t
*testing
.T
) {
6157 yp
:= New(TypeOf(y
)).Interface()
6158 _
, ok
:= yp
.(fmt
.Stringer
)
6160 t
.Fatal("does not implement Stringer, but should")
6164 func TestMapAlloc(t
*testing
.T
) {
6165 m
:= ValueOf(make(map[int]int, 10))
6168 allocs
:= testing
.AllocsPerRun(100, func() {
6172 t
.Errorf("allocs per map assignment: want 0 got %f", allocs
)
6177 val
:= ValueOf(&tmp
).Elem()
6178 allocs
= testing
.AllocsPerRun(100, func() {
6179 mv
:= MakeMapWithSize(TypeOf(map[int]int{}), size
)
6180 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6181 for i
:= 0; i
< size
/2; i
++ {
6182 val
.SetInt(int64(i
))
6183 mv
.SetMapIndex(val
, val
)
6187 t
.Errorf("allocs per map assignment: want at most 10 got %f", allocs
)
6189 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
6190 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
6191 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
6194 func TestChanAlloc(t
*testing
.T
) {
6195 // Note: for a chan int, the return Value must be allocated, so we
6196 // use a chan *int instead.
6197 c
:= ValueOf(make(chan *int, 1))
6198 v
:= ValueOf(new(int))
6199 allocs
:= testing
.AllocsPerRun(100, func() {
6203 if allocs
< 0.5 || allocs
> 1.5 {
6204 t
.Errorf("allocs per chan send/recv: want 1 got %f", allocs
)
6206 // Note: there is one allocation in reflect.recv which seems to be
6207 // a limitation of escape analysis. If that is ever fixed the
6208 // allocs < 0.5 condition will trigger and this test should be fixed.
6211 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678
int
6213 type nameTest
struct {
6218 var nameTests
= []nameTest
{
6219 {(*int32)(nil), "int32"},
6222 {(*chan D1
)(nil), ""},
6223 {(*func() D1
)(nil), ""},
6224 {(*<-chan D1
)(nil), ""},
6225 {(*chan<- D1
)(nil), ""},
6226 {(*interface{})(nil), ""},
6230 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678
)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
6233 func TestNames(t
*testing
.T
) {
6234 for _
, test
:= range nameTests
{
6235 typ
:= TypeOf(test
.v
).Elem()
6236 if got
:= typ
.Name(); got
!= test
.want
{
6237 t
.Errorf("%v Name()=%q, want %q", typ
, got
, test
.want
)
6243 gccgo doesn't really record whether a type is exported.
6244 It's not in the reflect API anyhow.
6246 func TestExported(t *testing.T) {
6247 type ΦExported struct{}
6248 type φUnexported struct{}
6255 type exportTest struct {
6259 exportTests := []exportTest{
6263 {(*big)(nil), false},
6264 {(BigP)(nil), true},
6265 {(*BigP)(nil), true},
6266 {ΦExported{}, true},
6267 {φUnexported{}, false},
6274 for i, test := range exportTests {
6275 typ := TypeOf(test.v)
6276 if got := IsExported(typ); got != test.want {
6277 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
6288 func TestNameBytesAreAligned(t *testing.T) {
6289 typ := TypeOf(embed{})
6290 b := FirstMethodNameBytes(typ)
6291 v := uintptr(unsafe.Pointer(b))
6292 if v%unsafe.Alignof((*byte)(nil)) != 0 {
6293 t.Errorf("reflect.name.bytes pointer is not aligned: %x", v)
6298 func TestTypeStrings(t
*testing
.T
) {
6299 type stringTest
struct {
6303 stringTests
:= []stringTest
{
6304 {TypeOf(func(int) {}), "func(int)"},
6305 {FuncOf([]Type
{TypeOf(int(0))}, nil, false), "func(int)"},
6306 {TypeOf(XM
{}), "reflect_test.XM"},
6307 {TypeOf(new(XM
)), "*reflect_test.XM"},
6308 {TypeOf(new(XM
).String
), "func() string"},
6309 {TypeOf(new(XM
)).Method(0).Type
, "func(*reflect_test.XM) string"},
6310 {ChanOf(3, TypeOf(XM
{})), "chan reflect_test.XM"},
6311 {MapOf(TypeOf(int(0)), TypeOf(XM
{})), "map[int]reflect_test.XM"},
6312 {ArrayOf(3, TypeOf(XM
{})), "[3]reflect_test.XM"},
6313 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
6316 for i
, test
:= range stringTests
{
6317 if got
, want
:= test
.typ
.String(), test
.want
; got
!= want
{
6318 t
.Errorf("type %d String()=%q, want %q", i
, got
, want
)
6324 gccgo does not have resolveReflectName.
6326 func TestOffsetLock(t *testing.T) {
6327 var wg sync.WaitGroup
6328 for i := 0; i < 4; i++ {
6332 for j := 0; j < 50; j++ {
6333 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
6342 func BenchmarkNew(b
*testing
.B
) {
6344 b
.RunParallel(func(pb
*testing
.PB
) {
6351 func TestSwapper(t
*testing
.T
) {
6357 type pairPtr
struct {
6369 in
: []int{1, 20, 300},
6372 want
: []int{300, 20, 1},
6375 in
: []uintptr{1, 20, 300},
6378 want
: []uintptr{300, 20, 1},
6381 in
: []int16{1, 20, 300},
6384 want
: []int16{300, 20, 1},
6387 in
: []int8{1, 20, 100},
6390 want
: []int8{100, 20, 1},
6393 in
: []*I
{&a
, &b
, &c
},
6396 want
: []*I
{&c
, &b
, &a
},
6399 in
: []string{"eric", "sergey", "larry"},
6402 want
: []string{"larry", "sergey", "eric"},
6405 in
: []S
{"eric", "sergey", "larry"},
6408 want
: []S
{"larry", "sergey", "eric"},
6411 in
: []pair
{{1, 2}, {3, 4}, {5, 6}},
6414 want
: []pair
{{5, 6}, {3, 4}, {1, 2}},
6417 in
: []pairPtr
{{1, 2, &a
}, {3, 4, &b
}, {5, 6, &c
}},
6420 want
: []pairPtr
{{5, 6, &c
}, {3, 4, &b
}, {1, 2, &a
}},
6424 for i
, tt
:= range tests
{
6425 inStr
:= fmt
.Sprint(tt
.in
)
6426 Swapper(tt
.in
)(tt
.i
, tt
.j
)
6427 if !DeepEqual(tt
.in
, tt
.want
) {
6428 t
.Errorf("%d. swapping %v and %v of %v = %v; want %v", i
, tt
.i
, tt
.j
, inStr
, tt
.in
, tt
.want
)
6433 // TestUnaddressableField tests that the reflect package will not allow
6434 // a type from another package to be used as a named type with an
6435 // unexported field.
6437 // This ensures that unexported fields cannot be modified by other packages.
6438 func TestUnaddressableField(t
*testing
.T
) {
6439 var b Buffer
// type defined in reflect, a different package
6440 var localBuffer
struct {
6443 lv
:= ValueOf(&localBuffer
).Elem()
6445 shouldPanic(func() {
6454 type Talias1
struct {
6462 type Talias2
struct {
6467 func TestAliasNames(t
*testing
.T
) {
6468 t1
:= Talias1
{byte: 1, uint8: 2, int: 3, int32: 4, rune
: 5}
6469 out
:= fmt
.Sprintf("%#v", t1
)
6470 want
:= "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
6472 t
.Errorf("Talias1 print:\nhave: %s\nwant: %s", out
, want
)
6475 t2
:= Talias2
{Tint
: 1, Tint2
: 2}
6476 out
= fmt
.Sprintf("%#v", t2
)
6477 want
= "reflect_test.Talias2{Tint:1, Tint2:2}"
6479 t
.Errorf("Talias2 print:\nhave: %s\nwant: %s", out
, want
)
6483 func TestIssue22031(t
*testing
.T
) {
6484 type s
[]struct{ C
int }
6487 type t2
struct{ f s
}
6490 ValueOf(t1
{s
{{}}}).Field(0).Index(0).Field(0),
6491 ValueOf(t2
{s
{{}}}).Field(0).Index(0).Field(0),
6494 for i
, test
:= range tests
{
6496 t
.Errorf("%d: CanSet: got true, want false", i
)
6501 type NonExportedFirst
int
6503 func (i NonExportedFirst
) Φ
Exported() {}
6504 func (i NonExportedFirst
) nonexported() int { panic("wrong") }
6506 func TestIssue22073(t
*testing
.T
) {
6507 m
:= ValueOf(NonExportedFirst(0)).Method(0)
6509 if got
:= m
.Type().NumOut(); got
!= 0 {
6510 t
.Errorf("NumOut: got %v, want 0", got
)