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.
25 func TestBool(t
*testing
.T
) {
28 t
.Fatal("ValueOf(true).Bool() = false")
45 func isDigit(c
uint8) bool { return '0' <= c
&& c
<= '9' }
47 func assert(t
*testing
.T
, s
, want
string) {
49 t
.Errorf("have %#q want %#q", s
, want
)
53 func typestring(i
interface{}) string { return TypeOf(i
).String() }
55 var typeTests
= []pair
{
56 {struct{ x
int }{}, "int"},
57 {struct{ x
int8 }{}, "int8"},
58 {struct{ x
int16 }{}, "int16"},
59 {struct{ x
int32 }{}, "int32"},
60 {struct{ x
int64 }{}, "int64"},
61 {struct{ x
uint }{}, "uint"},
62 {struct{ x
uint8 }{}, "uint8"},
63 {struct{ x
uint16 }{}, "uint16"},
64 {struct{ x
uint32 }{}, "uint32"},
65 {struct{ x
uint64 }{}, "uint64"},
66 {struct{ x
float32 }{}, "float32"},
67 {struct{ x
float64 }{}, "float64"},
68 {struct{ x
int8 }{}, "int8"},
69 {struct{ x (**int8) }{}, "**int8"},
70 {struct{ x (**integer
) }{}, "**reflect_test.integer"},
71 {struct{ x ([32]int32) }{}, "[32]int32"},
72 {struct{ x ([]int8) }{}, "[]int8"},
73 {struct{ x (map[string]int32) }{}, "map[string]int32"},
74 {struct{ x (chan<- string) }{}, "chan<- string"},
81 "struct { c chan *int32; d float32 }",
83 {struct{ x (func(a
int8, b
int32)) }{}, "func(int8, int32)"},
86 c
func(chan *integer
, *int8)
89 "struct { c func(chan *reflect_test.integer, *int8) }",
97 "struct { a int8; b int32 }",
106 "struct { a int8; b int8; c int32 }",
116 "struct { a int8; b int8; c int8; d int32 }",
127 "struct { a int8; b int8; c int8; d int8; e int32 }",
139 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
143 a
int8 `reflect:"hi there"`
146 `struct { a int8 "reflect:\"hi there\"" }`,
150 a
int8 `reflect:"hi \x00there\t\n\"\\"`
153 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
160 "struct { f func(...int) }",
164 a(func(func(int) int) func(func(int)) int)
168 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
172 var valueTests
= []pair
{
183 {new(float32), "256.25"},
184 {new(float64), "512.125"},
185 {new(complex64
), "532.125+10i"},
186 {new(complex128
), "564.25+1i"},
187 {new(string), "stringy cheese"},
189 {new(*int8), "*int8(0)"},
190 {new(**int8), "**int8(0)"},
191 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
192 {new(**integer
), "**reflect_test.integer(0)"},
193 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
194 {new(chan<- string), "chan<- string"},
195 {new(func(a
int8, b
int32)), "func(int8, int32)(0)"},
200 "struct { c chan *int32; d float32 }{chan *int32, 0}",
202 {new(struct{ c
func(chan *integer
, *int8) }),
203 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
209 "struct { a int8; b int32 }{0, 0}",
216 "struct { a int8; b int8; c int32 }{0, 0, 0}",
220 func testType(t
*testing
.T
, i
int, typ Type
, want
string) {
223 t
.Errorf("#%d: have %#q, want %#q", i
, s
, want
)
227 func TestTypes(t
*testing
.T
) {
228 for i
, tt
:= range typeTests
{
229 testType(t
, i
, ValueOf(tt
.i
).Field(0).Type(), tt
.s
)
233 func TestSet(t
*testing
.T
) {
234 for i
, tt
:= range valueTests
{
263 v
.SetComplex(532.125 + 10i
)
265 v
.SetComplex(564.25 + 1i
)
267 v
.SetString("stringy cheese")
271 s
:= valueToString(v
)
273 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
278 func TestSetValue(t
*testing
.T
) {
279 for i
, tt
:= range valueTests
{
280 v
:= ValueOf(tt
.i
).Elem()
283 v
.Set(ValueOf(int(132)))
285 v
.Set(ValueOf(int8(8)))
287 v
.Set(ValueOf(int16(16)))
289 v
.Set(ValueOf(int32(32)))
291 v
.Set(ValueOf(int64(64)))
293 v
.Set(ValueOf(uint(132)))
295 v
.Set(ValueOf(uint8(8)))
297 v
.Set(ValueOf(uint16(16)))
299 v
.Set(ValueOf(uint32(32)))
301 v
.Set(ValueOf(uint64(64)))
303 v
.Set(ValueOf(float32(256.25)))
305 v
.Set(ValueOf(512.125))
307 v
.Set(ValueOf(complex64(532.125 + 10i
)))
309 v
.Set(ValueOf(complex128(564.25 + 1i
)))
311 v
.Set(ValueOf("stringy cheese"))
315 s
:= valueToString(v
)
317 t
.Errorf("#%d: have %#q, want %#q", i
, s
, tt
.s
)
324 var valueToStringTests
= []pair
{
329 {T
{123, 456.75, "hello", &_i
}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
330 {new(chan *T
), "*chan *reflect_test.T(&chan *reflect_test.T)"},
331 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
332 {&[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})"},
333 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
334 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
337 func TestValueToString(t
*testing
.T
) {
338 for i
, test
:= range valueToStringTests
{
339 s
:= valueToString(ValueOf(test
.i
))
341 t
.Errorf("#%d: have %#q, want %#q", i
, s
, test
.s
)
346 func TestArrayElemSet(t
*testing
.T
) {
347 v
:= ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
348 v
.Index(4).SetInt(123)
349 s
:= valueToString(v
)
350 const want
= "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
352 t
.Errorf("[10]int: have %#q want %#q", s
, want
)
355 v
= ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
356 v
.Index(4).SetInt(123)
358 const want1
= "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
360 t
.Errorf("[]int: have %#q want %#q", s
, want1
)
364 func TestPtrPointTo(t
*testing
.T
) {
368 vi
:= ValueOf(&i
).Elem()
369 vip
.Elem().Set(vi
.Addr())
371 t
.Errorf("got %d, want 1234", *ip
)
375 vp
:= ValueOf(&ip
).Elem()
376 vp
.Set(Zero(vp
.Type()))
378 t
.Errorf("got non-nil (%p), want nil", ip
)
382 func TestPtrSetNil(t
*testing
.T
) {
386 vip
.Elem().Set(Zero(vip
.Elem().Type()))
388 t
.Errorf("got non-nil (%d), want nil", *ip
)
392 func TestMapSetNil(t
*testing
.T
) {
393 m
:= make(map[string]int)
395 vm
.Elem().Set(Zero(vm
.Elem().Type()))
397 t
.Errorf("got non-nil (%p), want nil", m
)
401 func TestAll(t
*testing
.T
) {
402 testType(t
, 1, TypeOf((int8)(0)), "int8")
403 testType(t
, 2, TypeOf((*int8)(nil)).Elem(), "int8")
405 typ
:= TypeOf((*struct {
409 testType(t
, 3, typ
, "*struct { c chan *int32; d float32 }")
411 testType(t
, 4, etyp
, "struct { c chan *int32; d float32 }")
414 testType(t
, 5, f
.Type
, "chan *int32")
416 f
, present
:= styp
.FieldByName("d")
418 t
.Errorf("FieldByName says present field is absent")
420 testType(t
, 6, f
.Type
, "float32")
422 f
, present
= styp
.FieldByName("absent")
424 t
.Errorf("FieldByName says absent field is present")
427 typ
= TypeOf([32]int32{})
428 testType(t
, 7, typ
, "[32]int32")
429 testType(t
, 8, typ
.Elem(), "int32")
431 typ
= TypeOf((map[string]*int32)(nil))
432 testType(t
, 9, typ
, "map[string]*int32")
434 testType(t
, 10, mtyp
.Key(), "string")
435 testType(t
, 11, mtyp
.Elem(), "*int32")
437 typ
= TypeOf((chan<- string)(nil))
438 testType(t
, 12, typ
, "chan<- string")
439 testType(t
, 13, typ
.Elem(), "string")
441 // make sure tag strings are not part of element type
442 typ
= TypeOf(struct {
443 d
[]uint32 `reflect:"TAG"`
445 testType(t
, 14, typ
, "[]uint32")
448 func TestInterfaceGet(t
*testing
.T
) {
453 v1
:= ValueOf(&inter
)
454 v2
:= v1
.Elem().Field(0)
455 assert(t
, v2
.Type().String(), "interface {}")
458 assert(t
, v3
.Type().String(), "float64")
461 func TestInterfaceValue(t
*testing
.T
) {
466 v1
:= ValueOf(&inter
)
467 v2
:= v1
.Elem().Field(0)
468 assert(t
, v2
.Type().String(), "interface {}")
470 assert(t
, v3
.Type().String(), "float64")
473 if _
, ok
:= i3
.(float64); !ok
{
474 t
.Error("v2.Interface() did not return float64, got ", TypeOf(i3
))
478 func TestFunctionValue(t
*testing
.T
) {
479 var x
interface{} = func() {}
481 if fmt
.Sprint(v
.Interface()) != fmt
.Sprint(x
) {
482 t
.Fatalf("TestFunction returned wrong pointer")
484 assert(t
, v
.Type().String(), "func()")
487 var appendTests
= []struct {
490 {make([]int, 2, 4), []int{22}},
491 {make([]int, 2, 4), []int{22, 33, 44}},
494 func sameInts(x
, y
[]int) bool {
495 if len(x
) != len(y
) {
498 for i
, xx
:= range x
{
506 func TestAppend(t
*testing
.T
) {
507 for i
, test
:= range appendTests
{
508 origLen
, extraLen
:= len(test
.orig
), len(test
.extra
)
509 want
:= append(test
.orig
, test
.extra
...)
510 // Convert extra from []int to []Value.
511 e0
:= make([]Value
, len(test
.extra
))
512 for j
, e
:= range test
.extra
{
515 // Convert extra from []int to *SliceValue.
516 e1
:= ValueOf(test
.extra
)
518 a0
:= ValueOf(test
.orig
)
519 have0
:= Append(a0
, e0
...).Interface().([]int)
520 if !sameInts(have0
, want
) {
521 t
.Errorf("Append #%d: have %v, want %v (%p %p)", i
, have0
, want
, test
.orig
, have0
)
523 // Check that the orig and extra slices were not modified.
524 if len(test
.orig
) != origLen
{
525 t
.Errorf("Append #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
527 if len(test
.extra
) != extraLen
{
528 t
.Errorf("Append #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
531 a1
:= ValueOf(test
.orig
)
532 have1
:= AppendSlice(a1
, e1
).Interface().([]int)
533 if !sameInts(have1
, want
) {
534 t
.Errorf("AppendSlice #%d: have %v, want %v", i
, have1
, want
)
536 // Check that the orig and extra slices were not modified.
537 if len(test
.orig
) != origLen
{
538 t
.Errorf("AppendSlice #%d origLen: have %v, want %v", i
, len(test
.orig
), origLen
)
540 if len(test
.extra
) != extraLen
{
541 t
.Errorf("AppendSlice #%d extraLen: have %v, want %v", i
, len(test
.extra
), extraLen
)
546 func TestCopy(t
*testing
.T
) {
547 a
:= []int{1, 2, 3, 4, 10, 9, 8, 7}
548 b
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
549 c
:= []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
550 for i
:= 0; i
< len(b
); i
++ {
552 t
.Fatalf("b != c before test")
557 aa
:= ValueOf(&a1
).Elem()
558 ab
:= ValueOf(&b1
).Elem()
559 for tocopy
:= 1; tocopy
<= 7; tocopy
++ {
563 for i
:= 0; i
< tocopy
; i
++ {
565 t
.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
566 tocopy
, i
, a
[i
], i
, b
[i
])
569 for i
:= tocopy
; i
< len(b
); i
++ {
572 t
.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
573 tocopy
, i
, a
[i
], i
, b
[i
], i
, c
[i
])
575 t
.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
576 tocopy
, i
, b
[i
], i
, c
[i
])
579 t
.Logf("tocopy=%d elem %d is okay\n", tocopy
, i
)
585 func TestCopyArray(t
*testing
.T
) {
586 a
:= [8]int{1, 2, 3, 4, 10, 9, 8, 7}
587 b
:= [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
589 aa
:= ValueOf(&a
).Elem()
590 ab
:= ValueOf(&b
).Elem()
592 for i
:= 0; i
< len(a
); i
++ {
594 t
.Errorf("(i) a[%d]=%d, b[%d]=%d", i
, a
[i
], i
, b
[i
])
597 for i
:= len(a
); i
< len(b
); i
++ {
599 t
.Errorf("(ii) b[%d]=%d, c[%d]=%d", i
, b
[i
], i
, c
[i
])
601 t
.Logf("elem %d is okay\n", i
)
606 func TestBigUnnamedStruct(t
*testing
.T
) {
607 b
:= struct{ a
, b
, c
, d
int64 }{1, 2, 3, 4}
609 b1
:= v
.Interface().(struct {
612 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d
{
613 t
.Errorf("ValueOf(%v).Interface().(*Big) = %v", b
, b1
)
621 func TestBigStruct(t
*testing
.T
) {
622 b
:= big
{1, 2, 3, 4, 5}
624 b1
:= v
.Interface().(big
)
625 if b1
.a
!= b
.a || b1
.b
!= b
.b || b1
.c
!= b
.c || b1
.d
!= b
.d || b1
.e
!= b
.e
{
626 t
.Errorf("ValueOf(%v).Interface().(big) = %v", b
, b1
)
637 type DeepEqualTest
struct {
642 // Simple functions for DeepEqual tests.
646 fn3
= func() { fn1() } // Not nil.
649 var deepEqualTests
= []DeepEqualTest
{
653 {int32(1), int32(1), true},
655 {float32(0.5), float32(0.5), true},
656 {"hello", "hello", true},
657 {make([]int, 10), make([]int, 10), true},
658 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
659 {Basic
{1, 0.5}, Basic
{1, 0.5}, true},
660 {error(nil), error(nil), true},
661 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
666 {int32(1), int32(2), false},
668 {float32(0.5), float32(0.6), false},
669 {"hello", "hey", false},
670 {make([]int, 10), make([]int, 11), false},
671 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
672 {Basic
{1, 0.5}, Basic
{1, 0.6}, false},
673 {Basic
{1, 0}, Basic
{2, 0}, false},
674 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
675 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
676 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
677 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
682 {[][]int{{1}}, [][]int{{2}}, false},
684 // Nil vs empty: not the same.
685 {[]int{}, []int(nil), false},
686 {[]int{}, []int{}, true},
687 {[]int(nil), []int(nil), true},
688 {map[int]int{}, map[int]int(nil), false},
689 {map[int]int{}, map[int]int{}, true},
690 {map[int]int(nil), map[int]int(nil), true},
694 {int32(1), int64(1), false},
695 {0.5, "hello", false},
696 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
697 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
698 {Basic
{1, 0.5}, NotBasic
{1, 0.5}, false},
699 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
702 func TestDeepEqual(t
*testing
.T
) {
703 for _
, test
:= range deepEqualTests
{
704 if r
:= DeepEqual(test
.a
, test
.b
); r
!= test
.eq
{
705 t
.Errorf("DeepEqual(%v, %v) = %v, want %v", test
.a
, test
.b
, r
, test
.eq
)
710 func TestTypeOf(t
*testing
.T
) {
711 // Special case for nil
712 if typ
:= TypeOf(nil); typ
!= nil {
713 t
.Errorf("expected nil type for nil value; got %v", typ
)
715 for _
, test
:= range deepEqualTests
{
720 typ
:= TypeOf(test
.a
)
722 t
.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test
.a
, typ
, test
.a
, v
.Type())
727 type Recursive
struct {
732 func TestDeepEqualRecursiveStruct(t
*testing
.T
) {
733 a
, b
:= new(Recursive
), new(Recursive
)
734 *a
= Recursive
{12, a
}
735 *b
= Recursive
{12, b
}
736 if !DeepEqual(a
, b
) {
737 t
.Error("DeepEqual(recursive same) = false, want true")
741 type _Complex
struct {
745 d
map[float64]float64
748 func TestDeepEqualComplexStruct(t
*testing
.T
) {
749 m
:= make(map[float64]float64)
750 stra
, strb
:= "hello", "hello"
751 a
, b
:= new(_Complex
), new(_Complex
)
752 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
753 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
754 if !DeepEqual(a
, b
) {
755 t
.Error("DeepEqual(complex same) = false, want true")
759 func TestDeepEqualComplexStructInequality(t
*testing
.T
) {
760 m
:= make(map[float64]float64)
761 stra
, strb
:= "hello", "helloo" // Difference is here
762 a
, b
:= new(_Complex
), new(_Complex
)
763 *a
= _Complex
{5, [3]*_Complex
{a
, b
, a
}, &stra
, m
}
764 *b
= _Complex
{5, [3]*_Complex
{b
, a
, a
}, &strb
, m
}
766 t
.Error("DeepEqual(complex different) = true, want false")
774 func TestDeepEqualUnexportedMap(t
*testing
.T
) {
775 // Check that DeepEqual can look at unexported fields.
776 x1
:= UnexpT
{map[int]int{1: 2}}
777 x2
:= UnexpT
{map[int]int{1: 2}}
778 if !DeepEqual(&x1
, &x2
) {
779 t
.Error("DeepEqual(x1, x2) = false, want true")
782 y1
:= UnexpT
{map[int]int{2: 3}}
783 if DeepEqual(&x1
, &y1
) {
784 t
.Error("DeepEqual(x1, y1) = true, want false")
788 func check2ndField(x
interface{}, offs
uintptr, t
*testing
.T
) {
790 f
:= s
.Type().Field(1)
791 if f
.Offset
!= offs
{
792 t
.Error("mismatched offsets in structure alignment:", f
.Offset
, offs
)
796 // Check that structure alignment & offsets viewed through reflect agree with those
797 // from the compiler itself.
798 func TestAlignment(t
*testing
.T
) {
799 type T1inner
struct {
806 type T2inner
struct {
814 x
:= T1
{T1inner
{2}, 17}
815 check2ndField(x
, uintptr(unsafe
.Pointer(&x
.f
))-uintptr(unsafe
.Pointer(&x
)), t
)
817 x1
:= T2
{T2inner
{2, 3}, 17}
818 check2ndField(x1
, uintptr(unsafe
.Pointer(&x1
.f
))-uintptr(unsafe
.Pointer(&x1
)), t
)
821 func Nil(a
interface{}, t
*testing
.T
) {
822 n
:= ValueOf(a
).Field(0)
824 t
.Errorf("%v should be nil", a
)
828 func NotNil(a
interface{}, t
*testing
.T
) {
829 n
:= ValueOf(a
).Field(0)
831 t
.Errorf("value of type %v should not be nil", ValueOf(a
).Type().String())
835 func TestIsNil(t
*testing
.T
) {
836 // These implement IsNil.
837 // Wrap in extra struct to hide interface type.
838 doNil
:= []interface{}{
840 struct{ x
interface{} }{},
841 struct{ x
map[string]int }{},
842 struct{ x
func() bool }{},
843 struct{ x
chan int }{},
844 struct{ x
[]string }{},
846 for _
, ts
:= range doNil
{
847 ty
:= TypeOf(ts
).Field(0).Type
849 v
.IsNil() // panics if not okay to call
852 // Check the implementations
864 si
.x
= make([]int, 10)
871 ci
.x
= make(chan int)
878 mi
.x
= make(map[int]int)
896 func TestInterfaceExtraction(t
*testing
.T
) {
902 v
:= Indirect(ValueOf(&s
)).Field(0).Interface()
903 if v
!= s
.W
.(interface{}) {
904 t
.Error("Interface() on interface: ", v
, s
.W
)
908 func TestNilPtrValueSub(t
*testing
.T
) {
910 if pv
:= ValueOf(pi
); pv
.Elem().IsValid() {
911 t
.Error("ValueOf((*int)(nil)).Elem().IsValid()")
915 func TestMap(t
*testing
.T
) {
916 m
:= map[string]int{"a": 1, "b": 2}
918 if n
:= mv
.Len(); n
!= len(m
) {
919 t
.Errorf("Len = %d, want %d", n
, len(m
))
922 newmap
:= MakeMap(mv
.Type())
923 for k
, v
:= range m
{
924 // Check that returned Keys match keys in range.
925 // These aren't required to be in the same order.
927 for _
, kv
:= range keys
{
928 if kv
.String() == k
{
934 t
.Errorf("Missing key %q", k
)
937 // Check that value lookup is correct.
938 vv
:= mv
.MapIndex(ValueOf(k
))
939 if vi
:= vv
.Int(); vi
!= int64(v
) {
940 t
.Errorf("Key %q: have value %d, want %d", k
, vi
, v
)
943 // Copy into new map.
944 newmap
.SetMapIndex(ValueOf(k
), ValueOf(v
))
946 vv
:= mv
.MapIndex(ValueOf("not-present"))
948 t
.Errorf("Invalid key: got non-nil value %s", valueToString(vv
))
951 newm
:= newmap
.Interface().(map[string]int)
952 if len(newm
) != len(m
) {
953 t
.Errorf("length after copy: newm=%d, m=%d", len(newm
), len(m
))
956 for k
, v
:= range newm
{
959 t
.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k
, v
, k
, mv
, ok
)
963 newmap
.SetMapIndex(ValueOf("a"), Value
{})
966 t
.Errorf("newm[\"a\"] = %d after delete", v
)
969 mv
= ValueOf(&m
).Elem()
970 mv
.Set(Zero(mv
.Type()))
972 t
.Errorf("mv.Set(nil) failed")
976 func TestNilMap(t
*testing
.T
) {
981 t
.Errorf(">0 keys for nil map: %v", keys
)
984 // Check that value for missing key is zero.
985 x
:= mv
.MapIndex(ValueOf("hello"))
986 if x
.Kind() != Invalid
{
987 t
.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x
)
990 // Check big value too.
991 var mbig
map[string][10 << 20]byte
992 x
= ValueOf(mbig
).MapIndex(ValueOf("hello"))
993 if x
.Kind() != Invalid
{
994 t
.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x
)
997 // Test that deletes from a nil map succeed.
998 mv
.SetMapIndex(ValueOf("hi"), Value
{})
1001 func TestChan(t
*testing
.T
) {
1002 for loop
:= 0; loop
< 2; loop
++ {
1006 // check both ways to allocate channels
1009 c
= make(chan int, 1)
1012 cv
= MakeChan(TypeOf(c
), 1)
1013 c
= cv
.Interface().(chan int)
1018 if i
:= <-c
; i
!= 2 {
1019 t
.Errorf("reflect Send 2, native recv %d", i
)
1024 if i
, ok
:= cv
.Recv(); i
.Int() != 3 ||
!ok
{
1025 t
.Errorf("native send 3, reflect Recv %d, %t", i
.Int(), ok
)
1029 val
, ok
:= cv
.TryRecv()
1030 if val
.IsValid() || ok
{
1031 t
.Errorf("TryRecv on empty chan: %s, %t", valueToString(val
), ok
)
1036 val
, ok
= cv
.TryRecv()
1038 t
.Errorf("TryRecv on ready chan got nil")
1039 } else if i
:= val
.Int(); i
!= 4 ||
!ok
{
1040 t
.Errorf("native send 4, TryRecv %d, %t", i
, ok
)
1045 ok
= cv
.TrySend(ValueOf(5))
1048 t
.Errorf("TrySend on full chan succeeded: value %d", i
)
1052 ok
= cv
.TrySend(ValueOf(6))
1054 t
.Errorf("TrySend on empty chan failed")
1056 if i
= <-c
; i
!= 6 {
1057 t
.Errorf("TrySend 6, recv %d", i
)
1064 if i
, ok
:= cv
.Recv(); i
.Int() != 123 ||
!ok
{
1065 t
.Errorf("send 123 then close; Recv %d, %t", i
.Int(), ok
)
1067 if i
, ok
:= cv
.Recv(); i
.Int() != 0 || ok
{
1068 t
.Errorf("after close Recv %d, %t", i
.Int(), ok
)
1072 // check creation of unbuffered channel
1074 cv
:= MakeChan(TypeOf(c
), 0)
1075 c
= cv
.Interface().(chan int)
1076 if cv
.TrySend(ValueOf(7)) {
1077 t
.Errorf("TrySend on sync chan succeeded")
1079 if v
, ok
:= cv
.TryRecv(); v
.IsValid() || ok
{
1080 t
.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v
.IsValid(), ok
)
1084 cv
= MakeChan(TypeOf(c
), 10)
1085 c
= cv
.Interface().(chan int)
1086 for i
:= 0; i
< 3; i
++ {
1089 if l
, m
:= cv
.Len(), cv
.Cap(); l
!= len(c
) || m
!= cap(c
) {
1090 t
.Errorf("Len/Cap = %d/%d want %d/%d", l
, m
, len(c
), cap(c
))
1094 // caseInfo describes a single case in a select test.
1095 type caseInfo
struct {
1104 var allselect
= flag
.Bool("allselect", false, "exhaustive select test")
1106 func TestSelect(t
*testing
.T
) {
1107 selectWatch
.once
.Do(func() { go selectWatcher() })
1111 newop
:= func(n
int, cap int) (ch
, val Value
) {
1114 c
:= make(chan int, cap)
1118 c
:= make(chan string, cap)
1120 val
= ValueOf(fmt
.Sprint(n
))
1125 for n
:= 0; x
.Next(); n
++ {
1126 if testing
.Short() && n
>= 1000 {
1129 if n
>= 100000 && !*allselect
{
1132 if n%100000
== 0 && testing
.Verbose() {
1133 println("TestSelect", n
)
1135 var cases
[]SelectCase
1140 ch
, val
:= newop(len(cases
), 1)
1141 cases
= append(cases
, SelectCase
{
1146 info
= append(info
, caseInfo
{desc
: "ready send", canSelect
: true})
1151 ch
, val
:= newop(len(cases
), 1)
1153 cases
= append(cases
, SelectCase
{
1157 info
= append(info
, caseInfo
{desc
: "ready recv", canSelect
: true, recv
: val
})
1162 ch
, val
:= newop(len(cases
), 0)
1163 cases
= append(cases
, SelectCase
{
1170 f
:= func() { ch
.Recv() }
1171 info
= append(info
, caseInfo
{desc
: "blocking send", helper
: f
})
1173 info
= append(info
, caseInfo
{desc
: "blocking send"})
1179 ch
, val
:= newop(len(cases
), 0)
1180 cases
= append(cases
, SelectCase
{
1186 f
:= func() { ch
.Send(val
) }
1187 info
= append(info
, caseInfo
{desc
: "blocking recv", recv
: val
, helper
: f
})
1189 info
= append(info
, caseInfo
{desc
: "blocking recv"})
1195 // Maybe include value to send.
1200 cases
= append(cases
, SelectCase
{
1204 info
= append(info
, caseInfo
{desc
: "zero Chan send"})
1207 // Zero Chan receive.
1209 cases
= append(cases
, SelectCase
{
1212 info
= append(info
, caseInfo
{desc
: "zero Chan recv"})
1217 cases
= append(cases
, SelectCase
{
1219 Chan
: ValueOf((chan int)(nil)),
1222 info
= append(info
, caseInfo
{desc
: "nil Chan send"})
1227 cases
= append(cases
, SelectCase
{
1229 Chan
: ValueOf((chan int)(nil)),
1231 info
= append(info
, caseInfo
{desc
: "nil Chan recv"})
1234 // closed Chan send.
1236 ch
:= make(chan int)
1238 cases
= append(cases
, SelectCase
{
1243 info
= append(info
, caseInfo
{desc
: "closed Chan send", canSelect
: true, panic: true})
1246 // closed Chan recv.
1248 ch
, val
:= newop(len(cases
), 0)
1250 val
= Zero(val
.Type())
1251 cases
= append(cases
, SelectCase
{
1255 info
= append(info
, caseInfo
{desc
: "closed Chan recv", canSelect
: true, closed: true, recv
: val
})
1258 var helper
func() // goroutine to help the select complete
1260 // Add default? Must be last case here, but will permute.
1261 // Add the default if the select would otherwise
1262 // block forever, and maybe add it anyway.
1268 for i
, c
:= range info
{
1276 } else if c
.helper
!= nil {
1278 helpers
= append(helpers
, i
)
1281 if !canProceed || x
.Maybe() {
1282 cases
= append(cases
, SelectCase
{
1285 info
= append(info
, caseInfo
{desc
: "default", canSelect
: canBlock
})
1287 } else if canBlock
{
1288 // Select needs to communicate with another goroutine.
1289 cas
:= &info
[helpers
[x
.Choose(len(helpers
))]]
1291 cas
.canSelect
= true
1295 // Permute cases and case info.
1296 // Doing too much here makes the exhaustive loop
1297 // too exhausting, so just do two swaps.
1298 for loop
:= 0; loop
< 2; loop
++ {
1299 i
:= x
.Choose(len(cases
))
1300 j
:= x
.Choose(len(cases
))
1301 cases
[i
], cases
[j
] = cases
[j
], cases
[i
]
1302 info
[i
], info
[j
] = info
[j
], info
[i
]
1306 // We wait before kicking off a goroutine to satisfy a blocked select.
1307 // The pause needs to be big enough to let the select block before
1308 // we run the helper, but if we lose that race once in a while it's okay: the
1309 // select will just proceed immediately. Not a big deal.
1310 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1311 pause
:= 10 * time
.Microsecond
1312 if testing
.Short() {
1313 pause
= 100 * time
.Microsecond
1315 time
.AfterFunc(pause
, helper
)
1319 i
, recv
, recvOK
, panicErr
:= runSelect(cases
, info
)
1320 if panicErr
!= nil && !canPanic
{
1321 t
.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info
), panicErr
)
1323 if panicErr
== nil && canPanic
&& numCanSelect
== 1 {
1324 t
.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info
), i
)
1326 if panicErr
!= nil {
1334 recvStr
= fmt
.Sprintf(", received %v, %v", recv
.Interface(), recvOK
)
1336 t
.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info
), i
, recvStr
)
1340 t
.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info
), i
)
1344 if cases
[i
].Dir
== SelectRecv
{
1345 if !recv
.IsValid() {
1346 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, cas
.recv
.Interface(), !cas
.closed)
1348 if !cas
.recv
.IsValid() {
1349 t
.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info
), i
)
1351 if recv
.Interface() != cas
.recv
.Interface() || recvOK
!= !cas
.closed {
1352 if recv
.Interface() == cas
.recv
.Interface() && recvOK
== !cas
.closed {
1353 t
.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info
), i
, recv
.Interface(), recvOK
, recv
.Interface())
1355 t
.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info
), i
, recv
.Interface(), recvOK
, cas
.recv
.Interface(), !cas
.closed)
1358 if recv
.IsValid() || recvOK
{
1359 t
.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info
), i
, recv
, recvOK
, Value
{}, false)
1365 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1366 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1367 // an error describing the select and panics the entire test binary.
1368 var selectWatch
struct {
1375 func selectWatcher() {
1377 time
.Sleep(1 * time
.Second
)
1379 if selectWatch
.info
!= nil && time
.Since(selectWatch
.now
) > 1*time
.Second
{
1380 fmt
.Fprintf(os
.Stderr
, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch
.info
))
1381 panic("select stuck")
1383 selectWatch
.Unlock()
1387 // runSelect runs a single select test.
1388 // It returns the values returned by Select but also returns
1389 // a panic value if the Select panics.
1390 func runSelect(cases
[]SelectCase
, info
[]caseInfo
) (chosen
int, recv Value
, recvOK
bool, panicErr
interface{}) {
1392 panicErr
= recover()
1395 selectWatch
.info
= nil
1396 selectWatch
.Unlock()
1400 selectWatch
.now
= time
.Now()
1401 selectWatch
.info
= info
1402 selectWatch
.Unlock()
1404 chosen
, recv
, recvOK
= Select(cases
)
1408 // fmtSelect formats the information about a single select test.
1409 func fmtSelect(info
[]caseInfo
) string {
1410 var buf bytes
.Buffer
1411 fmt
.Fprintf(&buf
, "\nselect {\n")
1412 for i
, cas
:= range info
{
1413 fmt
.Fprintf(&buf
, "%d: %s", i
, cas
.desc
)
1414 if cas
.recv
.IsValid() {
1415 fmt
.Fprintf(&buf
, " val=%#v", cas
.recv
.Interface())
1418 fmt
.Fprintf(&buf
, " canselect")
1421 fmt
.Fprintf(&buf
, " panic")
1423 fmt
.Fprintf(&buf
, "\n")
1425 fmt
.Fprintf(&buf
, "}")
1431 // Difficult test for function call because of
1432 // implicit padding between arguments.
1433 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) {
1434 return b
, c
, d
, e
, f
, g
, h
1437 func TestFunc(t
*testing
.T
) {
1438 ret
:= ValueOf(dummy
).Call([]Value
{
1442 ValueOf(two
{40, 50}),
1444 ValueOf(float32(70)),
1448 t
.Fatalf("Call returned %d values, want 7", len(ret
))
1451 i
:= byte(ret
[0].Uint())
1452 j
:= int(ret
[1].Int())
1453 k
:= byte(ret
[2].Uint())
1454 l
:= ret
[3].Interface().(two
)
1455 m
:= byte(ret
[4].Uint())
1456 n
:= float32(ret
[5].Float())
1457 o
:= byte(ret
[6].Uint())
1459 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1460 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
)
1464 type emptyStruct
struct{}
1466 type nonEmptyStruct
struct {
1470 func returnEmpty() emptyStruct
{
1471 return emptyStruct
{}
1474 func takesEmpty(e emptyStruct
) {
1477 func returnNonEmpty(i
int) nonEmptyStruct
{
1478 return nonEmptyStruct
{member
: i
}
1481 func takesNonEmpty(n nonEmptyStruct
) int {
1485 func TestCallWithStruct(t
*testing
.T
) {
1486 r
:= ValueOf(returnEmpty
).Call(nil)
1487 if len(r
) != 1 || r
[0].Type() != TypeOf(emptyStruct
{}) {
1488 t
.Errorf("returning empty struct returned %#v instead", r
)
1490 r
= ValueOf(takesEmpty
).Call([]Value
{ValueOf(emptyStruct
{})})
1492 t
.Errorf("takesEmpty returned values: %#v", r
)
1494 r
= ValueOf(returnNonEmpty
).Call([]Value
{ValueOf(42)})
1495 if len(r
) != 1 || r
[0].Type() != TypeOf(nonEmptyStruct
{}) || r
[0].Field(0).Int() != 42 {
1496 t
.Errorf("returnNonEmpty returned %#v", r
)
1498 r
= ValueOf(takesNonEmpty
).Call([]Value
{ValueOf(nonEmptyStruct
{member
: 42})})
1499 if len(r
) != 1 || r
[0].Type() != TypeOf(1) || r
[0].Int() != 42 {
1500 t
.Errorf("takesNonEmpty returned %#v", r
)
1504 func TestMakeFunc(t
*testing
.T
) {
1506 fv
:= MakeFunc(TypeOf(f
), func(in
[]Value
) []Value
{ return in
})
1507 ValueOf(&f
).Elem().Set(fv
)
1509 // Call g with small arguments so that there is
1510 // something predictable (and different from the
1511 // correct results) in those positions on the stack.
1513 g(1, 2, 3, two
{4, 5}, 6, 7, 8)
1515 // Call constructed function f.
1516 i
, j
, k
, l
, m
, n
, o
:= f(10, 20, 30, two
{40, 50}, 60, 70, 80)
1517 if i
!= 10 || j
!= 20 || k
!= 30 || l
!= (two
{40, 50}) || m
!= 60 || n
!= 70 || o
!= 80 {
1518 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
)
1522 func TestMakeFuncInterface(t
*testing
.T
) {
1523 fn
:= func(i
int) int { return i
}
1524 incr
:= func(in
[]Value
) []Value
{
1525 return []Value
{ValueOf(int(in
[0].Int() + 1))}
1527 fv
:= MakeFunc(TypeOf(fn
), incr
)
1528 ValueOf(&fn
).Elem().Set(fv
)
1529 if r
:= fn(2); r
!= 3 {
1530 t
.Errorf("Call returned %d, want 3", r
)
1532 if r
:= fv
.Call([]Value
{ValueOf(14)})[0].Int(); r
!= 15 {
1533 t
.Errorf("Call returned %d, want 15", r
)
1535 if r
:= fv
.Interface().(func(int) int)(26); r
!= 27 {
1536 t
.Errorf("Call returned %d, want 27", r
)
1540 func TestMakeFuncVariadic(t
*testing
.T
) {
1541 // Test that variadic arguments are packed into a slice and passed as last arg
1542 fn
:= func(_
int, is
...int) []int { return nil }
1543 fv
:= MakeFunc(TypeOf(fn
), func(in
[]Value
) []Value
{ return in
[1:2] })
1544 ValueOf(&fn
).Elem().Set(fv
)
1547 if r
[0] != 2 || r
[1] != 3 {
1548 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1551 r
= fn(1, []int{2, 3}...)
1552 if r
[0] != 2 || r
[1] != 3 {
1553 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1556 r
= fv
.Call([]Value
{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1557 if r
[0] != 2 || r
[1] != 3 {
1558 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1561 r
= fv
.CallSlice([]Value
{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1562 if r
[0] != 2 || r
[1] != 3 {
1563 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1566 f
:= fv
.Interface().(func(int, ...int) []int)
1569 if r
[0] != 2 || r
[1] != 3 {
1570 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1572 r
= f(1, []int{2, 3}...)
1573 if r
[0] != 2 || r
[1] != 3 {
1574 t
.Errorf("Call returned [%v, %v]; want 2, 3", r
[0], r
[1])
1582 // This will be index 0.
1583 func (p Point
) AnotherMethod(scale
int) int {
1587 // This will be index 1.
1588 func (p Point
) Dist(scale
int) int {
1589 //println("Point.Dist", p.x, p.y, scale)
1590 return p
.x
*p
.x
*scale
+ p
.y
*p
.y
*scale
1593 // This will be index 2.
1594 func (p Point
) GCMethod(k
int) int {
1599 // This will be index 3.
1600 func (p Point
) TotalDist(points
...Point
) int {
1602 for _
, q
:= range points
{
1605 tot
+= dx
*dx
+ dy
*dy
// Should call Sqrt, but it's just a test.
1611 func TestMethod(t
*testing
.T
) {
1612 // Non-curried method of type.
1614 i
:= TypeOf(p
).Method(1).Func
.Call([]Value
{ValueOf(p
), ValueOf(10)})[0].Int()
1616 t
.Errorf("Type Method returned %d; want 250", i
)
1619 m
, ok
:= TypeOf(p
).MethodByName("Dist")
1621 t
.Fatalf("method by name failed")
1623 i
= m
.Func
.Call([]Value
{ValueOf(p
), ValueOf(11)})[0].Int()
1625 t
.Errorf("Type MethodByName returned %d; want 275", i
)
1628 i
= TypeOf(&p
).Method(1).Func
.Call([]Value
{ValueOf(&p
), ValueOf(12)})[0].Int()
1630 t
.Errorf("Pointer Type Method returned %d; want 300", i
)
1633 m
, ok
= TypeOf(&p
).MethodByName("Dist")
1635 t
.Fatalf("ptr method by name failed")
1637 i
= m
.Func
.Call([]Value
{ValueOf(&p
), ValueOf(13)})[0].Int()
1639 t
.Errorf("Pointer Type MethodByName returned %d; want 325", i
)
1642 // Curried method of value.
1643 tfunc
:= TypeOf((func(int) int)(nil))
1644 v
:= ValueOf(p
).Method(1)
1645 if tt
:= v
.Type(); tt
!= tfunc
{
1646 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1648 i
= v
.Call([]Value
{ValueOf(14)})[0].Int()
1650 t
.Errorf("Value Method returned %d; want 350", i
)
1652 v
= ValueOf(p
).MethodByName("Dist")
1653 if tt
:= v
.Type(); tt
!= tfunc
{
1654 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
1656 i
= v
.Call([]Value
{ValueOf(15)})[0].Int()
1658 t
.Errorf("Value MethodByName returned %d; want 375", i
)
1661 // Curried method of pointer.
1662 v
= ValueOf(&p
).Method(1)
1663 if tt
:= v
.Type(); tt
!= tfunc
{
1664 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1666 i
= v
.Call([]Value
{ValueOf(16)})[0].Int()
1668 t
.Errorf("Pointer Value Method returned %d; want 400", i
)
1670 v
= ValueOf(&p
).MethodByName("Dist")
1671 if tt
:= v
.Type(); tt
!= tfunc
{
1672 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1674 i
= v
.Call([]Value
{ValueOf(17)})[0].Int()
1676 t
.Errorf("Pointer Value MethodByName returned %d; want 425", i
)
1679 // Curried method of interface value.
1680 // Have to wrap interface value in a struct to get at it.
1681 // Passing it to ValueOf directly would
1682 // access the underlying Point, not the interface.
1686 pv
:= ValueOf(&x
).Elem()
1688 if tt
:= v
.Type(); tt
!= tfunc
{
1689 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
1691 i
= v
.Call([]Value
{ValueOf(18)})[0].Int()
1693 t
.Errorf("Interface Method returned %d; want 450", i
)
1695 v
= pv
.MethodByName("Dist")
1696 if tt
:= v
.Type(); tt
!= tfunc
{
1697 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
1699 i
= v
.Call([]Value
{ValueOf(19)})[0].Int()
1701 t
.Errorf("Interface MethodByName returned %d; want 475", i
)
1705 func TestMethodValue(t
*testing
.T
) {
1709 // Curried method of value.
1710 tfunc
:= TypeOf((func(int) int)(nil))
1711 v
:= ValueOf(p
).Method(1)
1712 if tt
:= v
.Type(); tt
!= tfunc
{
1713 t
.Errorf("Value Method Type is %s; want %s", tt
, tfunc
)
1715 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(10)})[0].Int()
1717 t
.Errorf("Value Method returned %d; want 250", i
)
1719 v
= ValueOf(p
).MethodByName("Dist")
1720 if tt
:= v
.Type(); tt
!= tfunc
{
1721 t
.Errorf("Value MethodByName Type is %s; want %s", tt
, tfunc
)
1723 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(11)})[0].Int()
1725 t
.Errorf("Value MethodByName returned %d; want 275", i
)
1728 // Curried method of pointer.
1729 v
= ValueOf(&p
).Method(1)
1730 if tt
:= v
.Type(); tt
!= tfunc
{
1731 t
.Errorf("Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1733 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(12)})[0].Int()
1735 t
.Errorf("Pointer Value Method returned %d; want 300", i
)
1737 v
= ValueOf(&p
).MethodByName("Dist")
1738 if tt
:= v
.Type(); tt
!= tfunc
{
1739 t
.Errorf("Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1741 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(13)})[0].Int()
1743 t
.Errorf("Pointer Value MethodByName returned %d; want 325", i
)
1746 // Curried method of pointer to pointer.
1748 v
= ValueOf(&pp
).Elem().Method(1)
1749 if tt
:= v
.Type(); tt
!= tfunc
{
1750 t
.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt
, tfunc
)
1752 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(14)})[0].Int()
1754 t
.Errorf("Pointer Pointer Value Method returned %d; want 350", i
)
1756 v
= ValueOf(&pp
).Elem().MethodByName("Dist")
1757 if tt
:= v
.Type(); tt
!= tfunc
{
1758 t
.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt
, tfunc
)
1760 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(15)})[0].Int()
1762 t
.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i
)
1765 // Curried method of interface value.
1766 // Have to wrap interface value in a struct to get at it.
1767 // Passing it to ValueOf directly would
1768 // access the underlying Point, not the interface.
1774 pv
:= ValueOf(s
).Field(0)
1776 if tt
:= v
.Type(); tt
!= tfunc
{
1777 t
.Errorf("Interface Method Type is %s; want %s", tt
, tfunc
)
1779 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(16)})[0].Int()
1781 t
.Errorf("Interface Method returned %d; want 400", i
)
1783 v
= pv
.MethodByName("Dist")
1784 if tt
:= v
.Type(); tt
!= tfunc
{
1785 t
.Errorf("Interface MethodByName Type is %s; want %s", tt
, tfunc
)
1787 i
= ValueOf(v
.Interface()).Call([]Value
{ValueOf(17)})[0].Int()
1789 t
.Errorf("Interface MethodByName returned %d; want 425", i
)
1793 func TestVariadicMethodValue(t
*testing
.T
) {
1795 points
:= []Point
{{20, 21}, {22, 23}, {24, 25}}
1796 want
:= int64(p
.TotalDist(points
[0], points
[1], points
[2]))
1798 // Curried method of value.
1799 tfunc
:= TypeOf((func(...Point
) int)(nil))
1800 v
:= ValueOf(p
).Method(3)
1801 if tt
:= v
.Type(); tt
!= tfunc
{
1802 t
.Errorf("Variadic Method Type is %s; want %s", tt
, tfunc
)
1804 i
:= ValueOf(v
.Interface()).Call([]Value
{ValueOf(points
[0]), ValueOf(points
[1]), ValueOf(points
[2])})[0].Int()
1806 t
.Errorf("Variadic Method returned %d; want %d", i
, want
)
1808 i
= ValueOf(v
.Interface()).CallSlice([]Value
{ValueOf(points
)})[0].Int()
1810 t
.Errorf("Variadic Method CallSlice returned %d; want %d", i
, want
)
1813 f
:= v
.Interface().(func(...Point
) int)
1814 i
= int64(f(points
[0], points
[1], points
[2]))
1816 t
.Errorf("Variadic Method Interface returned %d; want %d", i
, want
)
1818 i
= int64(f(points
...))
1820 t
.Errorf("Variadic Method Interface Slice returned %d; want %d", i
, want
)
1824 // Reflect version of $GOROOT/test/method5.go
1826 // Concrete types implementing M method.
1827 // Smaller than a word, word-sized, larger than a word.
1828 // Value and pointer receivers.
1830 type Tinter
interface {
1831 M(int, byte) (byte, int)
1836 func (v Tsmallv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1840 func (p
*Tsmallp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1844 func (v Twordv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1848 func (p
*Twordp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1850 type Tbigv
[2]uintptr
1852 func (v Tbigv
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
1854 type Tbigp
[2]uintptr
1856 func (p
*Tbigp
) M(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
1858 // Again, with an unexported method.
1862 func (v tsmallv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1866 func (p
*tsmallp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1870 func (v twordv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
) }
1874 func (p
*twordp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(*p
) }
1876 type tbigv
[2]uintptr
1878 func (v tbigv
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(v
[0]) + int(v
[1]) }
1880 type tbigp
[2]uintptr
1882 func (p
*tbigp
) m(x
int, b
byte) (byte, int) { return b
, x
+ int(p
[0]) + int(p
[1]) }
1884 type tinter
interface {
1885 m(int, byte) (byte, int)
1888 // Embedding via pointer.
1905 func (t4 Tm4
) M(x
int, b
byte) (byte, int) { return b
, x
+ 40 }
1907 func TestMethod5(t
*testing
.T
) {
1908 CheckF
:= func(name
string, f
func(int, byte) (byte, int), inc
int) {
1910 if b
!= 99 || x
!= 1000+inc
{
1911 t
.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
1915 CheckV
:= func(name
string, i Value
, inc
int) {
1916 bx
:= i
.Method(0).Call([]Value
{ValueOf(1000), ValueOf(byte(99))})
1917 b
:= bx
[0].Interface()
1918 x
:= bx
[1].Interface()
1919 if b
!= byte(99) || x
!= 1000+inc
{
1920 t
.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name
, b
, x
, 1000+inc
)
1923 CheckF(name
+".M", i
.Method(0).Interface().(func(int, byte) (byte, int)), inc
)
1926 var TinterType
= TypeOf(new(Tinter
)).Elem()
1927 var tinterType
= TypeOf(new(tinter
)).Elem()
1929 CheckI
:= func(name
string, i
interface{}, inc
int) {
1931 CheckV(name
, v
, inc
)
1932 CheckV("(i="+name
+")", v
.Convert(TinterType
), inc
)
1937 CheckI("&sv", &sv
, 1)
1940 CheckI("&sp", &sp
, 2)
1944 CheckI("&wv", &wv
, 3)
1947 CheckI("&wp", &wp
, 4)
1949 bv
:= Tbigv([2]uintptr{5, 6})
1950 CheckI("bv", bv
, 11)
1951 CheckI("&bv", &bv
, 11)
1953 bp
:= Tbigp([2]uintptr{7, 8})
1954 CheckI("&bp", &bp
, 15)
1960 CheckI("t4", t4
, 40)
1961 CheckI("&t4", &t4
, 40)
1962 CheckI("t3", t3
, 40)
1963 CheckI("&t3", &t3
, 40)
1964 CheckI("t2", t2
, 40)
1965 CheckI("&t2", &t2
, 40)
1966 CheckI("t1", t1
, 40)
1967 CheckI("&t1", &t1
, 40)
1969 methodShouldPanic
:= func(name
string, i
interface{}) {
1972 shouldPanic(func() { m
.Call([]Value
{ValueOf(1000), ValueOf(byte(99))}) })
1973 shouldPanic(func() { m
.Interface() })
1975 v
= v
.Convert(tinterType
)
1977 shouldPanic(func() { m
.Call([]Value
{ValueOf(1000), ValueOf(byte(99))}) })
1978 shouldPanic(func() { m
.Interface() })
1982 methodShouldPanic("_sv", _sv
)
1983 methodShouldPanic("&_sv", &_sv
)
1986 methodShouldPanic("&_sp", &_sp
)
1989 methodShouldPanic("_wv", _wv
)
1990 methodShouldPanic("&_wv", &_wv
)
1993 methodShouldPanic("&_wp", &_wp
)
1995 _bv
:= tbigv([2]uintptr{5, 6})
1996 methodShouldPanic("_bv", _bv
)
1997 methodShouldPanic("&_bv", &_bv
)
1999 _bp
:= tbigp([2]uintptr{7, 8})
2000 methodShouldPanic("&_bp", &_bp
)
2003 vnil
:= ValueOf(&tnil
).Elem()
2004 shouldPanic(func() { vnil
.Method(0) })
2007 func TestInterfaceSet(t
*testing
.T
) {
2016 sv
:= ValueOf(&s
).Elem()
2017 sv
.Field(0).Set(ValueOf(p
))
2018 if q
:= s
.I
.(*Point
); q
!= p
{
2019 t
.Errorf("i: have %p want %p", q
, p
)
2024 if q
:= s
.P
.(*Point
); q
!= p
{
2025 t
.Errorf("i: have %p want %p", q
, p
)
2028 i
:= pv
.Method(0).Call([]Value
{ValueOf(10)})[0].Int()
2030 t
.Errorf("Interface Method returned %d; want 250", i
)
2039 func TestAnonymousFields(t
*testing
.T
) {
2040 var field StructField
2044 if field
, ok
= type1
.FieldByName("int"); !ok
{
2045 t
.Fatal("no field 'int'")
2047 if field
.Index
[0] != 1 {
2048 t
.Error("field index should be 1; is", field
.Index
)
2102 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2124 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2143 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2157 var fieldTests
= []FTest
{
2158 {struct{}{}, "", nil, 0},
2159 {struct{}{}, "Foo", nil, 0},
2160 {S0
{A
: 'a'}, "A", []int{0}, 'a'},
2161 {S0
{}, "D", nil, 0},
2162 {S1
{S0
: S0
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2163 {S1
{B
: 'b'}, "B", []int{0}, 'b'},
2164 {S1
{}, "S0", []int{1}, 0},
2165 {S1
{S0
: S0
{C
: 'c'}}, "C", []int{1, 2}, 'c'},
2166 {S2
{A
: 'a'}, "A", []int{0}, 'a'},
2167 {S2
{}, "S1", []int{1}, 0},
2168 {S2
{S1
: &S1
{B
: 'b'}}, "B", []int{1, 0}, 'b'},
2169 {S2
{S1
: &S1
{S0
: S0
{C
: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2170 {S2
{}, "D", nil, 0},
2171 {S3
{}, "S1", nil, 0},
2172 {S3
{S2
: S2
{A
: 'a'}}, "A", []int{1, 0}, 'a'},
2173 {S3
{}, "B", nil, 0},
2174 {S3
{D
: 'd'}, "D", []int{2}, 0},
2175 {S3
{E
: 'e'}, "E", []int{3}, 'e'},
2176 {S4
{A
: 'a'}, "A", []int{1}, 'a'},
2177 {S4
{}, "B", nil, 0},
2178 {S5
{}, "X", nil, 0},
2179 {S5
{}, "Y", []int{2, 0, 1}, 0},
2180 {S10
{}, "X", nil, 0},
2181 {S10
{}, "Y", []int{2, 0, 0, 1}, 0},
2182 {S14
{}, "X", nil, 0},
2185 func TestFieldByIndex(t
*testing
.T
) {
2186 for _
, test
:= range fieldTests
{
2188 f
:= s
.FieldByIndex(test
.index
)
2190 if test
.index
!= nil {
2191 if f
.Name
!= test
.name
{
2192 t
.Errorf("%s.%s found; want %s", s
.Name(), f
.Name
, test
.name
)
2195 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2197 } else if len(test
.index
) > 0 {
2198 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2201 if test
.value
!= 0 {
2202 v
:= ValueOf(test
.s
).FieldByIndex(test
.index
)
2204 if x
, ok
:= v
.Interface().(int); ok
{
2205 if x
!= test
.value
{
2206 t
.Errorf("%s%v is %d; want %d", s
.Name(), test
.index
, x
, test
.value
)
2209 t
.Errorf("%s%v value not an int", s
.Name(), test
.index
)
2212 t
.Errorf("%s%v value not found", s
.Name(), test
.index
)
2218 func TestFieldByName(t
*testing
.T
) {
2219 for _
, test
:= range fieldTests
{
2221 f
, found
:= s
.FieldByName(test
.name
)
2223 if test
.index
!= nil {
2224 // Verify field depth and index.
2225 if len(f
.Index
) != len(test
.index
) {
2226 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
)
2228 for i
, x
:= range f
.Index
{
2229 if x
!= test
.index
[i
] {
2230 t
.Errorf("%s.%s.Index[%d] is %d; want %d", s
.Name(), test
.name
, i
, x
, test
.index
[i
])
2235 t
.Errorf("%s.%s found", s
.Name(), f
.Name
)
2237 } else if len(test
.index
) > 0 {
2238 t
.Errorf("%s.%s not found", s
.Name(), test
.name
)
2241 if test
.value
!= 0 {
2242 v
:= ValueOf(test
.s
).FieldByName(test
.name
)
2244 if x
, ok
:= v
.Interface().(int); ok
{
2245 if x
!= test
.value
{
2246 t
.Errorf("%s.%s is %d; want %d", s
.Name(), test
.name
, x
, test
.value
)
2249 t
.Errorf("%s.%s value not an int", s
.Name(), test
.name
)
2252 t
.Errorf("%s.%s value not found", s
.Name(), test
.name
)
2258 func TestImportPath(t
*testing
.T
) {
2263 {TypeOf(&base64
.Encoding
{}).Elem(), "encoding/base64"},
2264 {TypeOf(int(0)), ""},
2265 {TypeOf(int8(0)), ""},
2266 {TypeOf(int16(0)), ""},
2267 {TypeOf(int32(0)), ""},
2268 {TypeOf(int64(0)), ""},
2269 {TypeOf(uint(0)), ""},
2270 {TypeOf(uint8(0)), ""},
2271 {TypeOf(uint16(0)), ""},
2272 {TypeOf(uint32(0)), ""},
2273 {TypeOf(uint64(0)), ""},
2274 {TypeOf(uintptr(0)), ""},
2275 {TypeOf(float32(0)), ""},
2276 {TypeOf(float64(0)), ""},
2277 {TypeOf(complex64(0)), ""},
2278 {TypeOf(complex128(0)), ""},
2279 {TypeOf(byte(0)), ""},
2280 {TypeOf(rune(0)), ""},
2281 {TypeOf([]byte(nil)), ""},
2282 {TypeOf([]rune(nil)), ""},
2283 {TypeOf(string("")), ""},
2284 {TypeOf((*interface{})(nil)).Elem(), ""},
2285 {TypeOf((*byte)(nil)), ""},
2286 {TypeOf((*rune
)(nil)), ""},
2287 {TypeOf((*int64)(nil)), ""},
2288 {TypeOf(map[string]int{}), ""},
2289 {TypeOf((*error
)(nil)).Elem(), ""},
2291 for _
, test
:= range tests
{
2292 if path
:= test
.t
.PkgPath(); path
!= test
.path
{
2293 t
.Errorf("%v.PkgPath() = %q, want %q", test
.t
, path
, test
.path
)
2298 func TestVariadicType(t
*testing
.T
) {
2299 // Test example from Type documentation.
2300 var f
func(x
int, y
...float64)
2302 if typ
.NumIn() == 2 && typ
.In(0) == TypeOf(int(0)) {
2304 if sl
.Kind() == Slice
{
2305 if sl
.Elem() == TypeOf(0.0) {
2313 t
.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2314 s
:= fmt
.Sprintf("have NumIn() = %d", typ
.NumIn())
2315 for i
:= 0; i
< typ
.NumIn(); i
++ {
2316 s
+= fmt
.Sprintf(", In(%d) = %s", i
, typ
.In(i
))
2330 func (*inner
) m() {}
2331 func (*outer
) m() {}
2333 func TestNestedMethods(t
*testing
.T
) {
2334 t
.Skip("fails on gccgo due to function wrappers")
2335 typ
:= TypeOf((*outer
)(nil))
2336 if typ
.NumMethod() != 1 || typ
.Method(0).Func
.Pointer() != ValueOf((*outer
).m
).Pointer() {
2337 t
.Errorf("Wrong method table for outer: (m=%p)", (*outer
).m
)
2338 for i
:= 0; i
< typ
.NumMethod(); i
++ {
2340 t
.Errorf("\t%d: %s %#x\n", i
, m
.Name
, m
.Func
.Pointer())
2345 type InnerInt
struct {
2349 type OuterInt
struct {
2354 func (i
*InnerInt
) M() int {
2358 func TestEmbeddedMethods(t
*testing
.T
) {
2359 /* This part of the test fails on gccgo due to function wrappers.
2360 typ := TypeOf((*OuterInt)(nil))
2361 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2362 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2363 for i := 0; i < typ.NumMethod(); i++ {
2365 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2371 if v
:= ValueOf(i
).Method(0).Call(nil)[0].Int(); v
!= 3 {
2372 t
.Errorf("i.M() = %d, want 3", v
)
2375 o
:= &OuterInt
{1, InnerInt
{2}}
2376 if v
:= ValueOf(o
).Method(0).Call(nil)[0].Int(); v
!= 2 {
2377 t
.Errorf("i.M() = %d, want 2", v
)
2381 if v
:= f(o
); v
!= 2 {
2382 t
.Errorf("f(o) = %d, want 2", v
)
2386 func TestPtrTo(t
*testing
.T
) {
2390 for i
= 0; i
< 100; i
++ {
2393 for i
= 0; i
< 100; i
++ {
2396 if typ
!= TypeOf(i
) {
2397 t
.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ
, TypeOf(i
))
2401 func TestPtrToGC(t
*testing
.T
) {
2403 tt
:= TypeOf(T(nil))
2407 for i
:= 0; i
< n
; i
++ {
2412 v
.Elem().Set(ValueOf(p
).Convert(pt
))
2413 x
= append(x
, v
.Interface())
2417 for i
, xi
:= range x
{
2418 k
:= ValueOf(xi
).Elem().Elem().Elem().Interface().(uintptr)
2419 if k
!= uintptr(i
) {
2420 t
.Errorf("lost x[%d] = %d, want %d", i
, k
, i
)
2425 func TestAddr(t
*testing
.T
) {
2437 t
.Errorf("Addr.Elem.Set failed to set value")
2440 // Again but take address of the ValueOf value.
2441 // Exercises generation of PtrTypes not present in the binary.
2443 v
= ValueOf(&q
).Elem()
2452 t
.Errorf("Addr.Elem.Set failed to set value")
2455 // Starting without pointer we should get changed value
2458 v
= ValueOf(&qq
).Elem()
2464 if p
.X
!= 3 { // should be unchanged from last time
2465 t
.Errorf("somehow value Set changed original p")
2467 p
= v0
.Interface().(struct {
2471 t
.Errorf("Addr.Elem.Set valued to set value in top value")
2474 // Verify that taking the address of a type gives us a pointer
2475 // which we can convert back using the usual interface
2480 ps
:= ValueOf(&s
).Elem().Field(0).Addr().Interface()
2481 *(ps
.(**bool)) = new(bool)
2483 t
.Errorf("Addr.Interface direct assignment failed")
2487 /* gccgo does do allocations here.
2489 func noAlloc(t *testing.T, n int, f func(int)) {
2490 if testing.Short() {
2491 t.Skip("skipping malloc count in short mode")
2493 if runtime.GOMAXPROCS(0) > 1 {
2494 t.Skip("skipping; GOMAXPROCS>1")
2497 allocs := testing.AllocsPerRun(n, func() {
2502 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2506 func TestAllocations(t *testing.T) {
2507 noAlloc(t, 100, func(j int) {
2511 // We can uncomment this when compiler escape analysis
2512 // is good enough to see that the integer assigned to i
2513 // does not escape and therefore need not be allocated.
2517 // if int(v.Int()) != 42+j {
2518 // panic("wrong int")
2521 i = func(j int) int { return j }
2523 if v.Interface().(func(int) int)(j) != j {
2524 panic("wrong result")
2531 func TestSmallNegativeInt(t
*testing
.T
) {
2535 t
.Errorf("int16(-1).Int() returned %v", v
.Int())
2539 func TestIndex(t
*testing
.T
) {
2540 xs
:= []byte{1, 2, 3, 4, 5, 6, 7, 8}
2541 v
:= ValueOf(xs
).Index(3).Interface().(byte)
2543 t
.Errorf("xs.Index(3) = %v; expected %v", v
, xs
[3])
2545 xa
:= [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2546 v
= ValueOf(xa
).Index(2).Interface().(byte)
2548 t
.Errorf("xa.Index(2) = %v; expected %v", v
, xa
[2])
2551 v
= ValueOf(s
).Index(3).Interface().(byte)
2553 t
.Errorf("s.Index(3) = %v; expected %v", v
, s
[3])
2557 func TestSlice(t
*testing
.T
) {
2558 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2559 v
:= ValueOf(xs
).Slice(3, 5).Interface().([]int)
2561 t
.Errorf("len(xs.Slice(3, 5)) = %d", len(v
))
2564 t
.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v
))
2566 if !DeepEqual(v
[0:5], xs
[3:]) {
2567 t
.Errorf("xs.Slice(3, 5)[0:5] = %v", v
[0:5])
2569 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2570 v
= ValueOf(&xa
).Elem().Slice(2, 5).Interface().([]int)
2572 t
.Errorf("len(xa.Slice(2, 5)) = %d", len(v
))
2575 t
.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v
))
2577 if !DeepEqual(v
[0:6], xa
[2:]) {
2578 t
.Errorf("xs.Slice(2, 5)[0:6] = %v", v
[0:6])
2581 vs
:= ValueOf(s
).Slice(3, 5).Interface().(string)
2583 t
.Errorf("s.Slice(3, 5) = %q; expected %q", vs
, s
[3:5])
2586 rv
:= ValueOf(&xs
).Elem()
2588 ptr2
:= rv
.Pointer()
2590 ptr3
:= rv
.Pointer()
2592 t
.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3
, ptr2
)
2596 func TestSlice3(t
*testing
.T
) {
2597 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2598 v
:= ValueOf(xs
).Slice3(3, 5, 7).Interface().([]int)
2600 t
.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v
))
2603 t
.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v
))
2605 if !DeepEqual(v
[0:4], xs
[3:7:7]) {
2606 t
.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v
[0:4])
2608 rv
:= ValueOf(&xs
).Elem()
2609 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2610 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2611 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2613 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2614 v
= ValueOf(&xa
).Elem().Slice3(2, 5, 6).Interface().([]int)
2616 t
.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v
))
2619 t
.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v
))
2621 if !DeepEqual(v
[0:4], xa
[2:6:6]) {
2622 t
.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v
[0:4])
2624 rv
= ValueOf(&xa
).Elem()
2625 shouldPanic(func() { rv
.Slice3(1, 2, 1) })
2626 shouldPanic(func() { rv
.Slice3(1, 1, 11) })
2627 shouldPanic(func() { rv
.Slice3(2, 2, 1) })
2630 rv
= ValueOf(&s
).Elem()
2631 shouldPanic(func() { rv
.Slice3(1, 2, 3) })
2633 rv
= ValueOf(&xs
).Elem()
2634 rv
= rv
.Slice3(3, 5, 7)
2635 ptr2
:= rv
.Pointer()
2636 rv
= rv
.Slice3(4, 4, 4)
2637 ptr3
:= rv
.Pointer()
2639 t
.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3
, ptr2
)
2643 func TestSetLenCap(t
*testing
.T
) {
2644 xs
:= []int{1, 2, 3, 4, 5, 6, 7, 8}
2645 xa
:= [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2647 vs
:= ValueOf(&xs
).Elem()
2648 shouldPanic(func() { vs
.SetLen(10) })
2649 shouldPanic(func() { vs
.SetCap(10) })
2650 shouldPanic(func() { vs
.SetLen(-1) })
2651 shouldPanic(func() { vs
.SetCap(-1) })
2652 shouldPanic(func() { vs
.SetCap(6) }) // smaller than len
2654 if len(xs
) != 5 ||
cap(xs
) != 8 {
2655 t
.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs
), cap(xs
))
2658 if len(xs
) != 5 ||
cap(xs
) != 6 {
2659 t
.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs
), cap(xs
))
2662 if len(xs
) != 5 ||
cap(xs
) != 5 {
2663 t
.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs
), cap(xs
))
2665 shouldPanic(func() { vs
.SetCap(4) }) // smaller than len
2666 shouldPanic(func() { vs
.SetLen(6) }) // bigger than cap
2668 va
:= ValueOf(&xa
).Elem()
2669 shouldPanic(func() { va
.SetLen(8) })
2670 shouldPanic(func() { va
.SetCap(8) })
2673 func TestVariadic(t
*testing
.T
) {
2678 V(fmt
.Fprintf
).Call([]Value
{V(&b
), V("%s, %d world"), V("hello"), V(42)})
2679 if b
.String() != "hello, 42 world" {
2680 t
.Errorf("after Fprintf Call: %q != %q", b
.String(), "hello 42 world")
2684 V(fmt
.Fprintf
).CallSlice([]Value
{V(&b
), V("%s, %d world"), V([]interface{}{"hello", 42})})
2685 if b
.String() != "hello, 42 world" {
2686 t
.Errorf("after Fprintf CallSlice: %q != %q", b
.String(), "hello 42 world")
2690 func TestFuncArg(t
*testing
.T
) {
2691 f1
:= func(i
int, f
func(int) int) int { return f(i
) }
2692 f2
:= func(i
int) int { return i
+ 1 }
2693 r
:= ValueOf(f1
).Call([]Value
{ValueOf(100), ValueOf(f2
)})
2694 if r
[0].Int() != 101 {
2695 t
.Errorf("function returned %d, want 101", r
[0].Int())
2699 func TestStructArg(t
*testing
.T
) {
2700 type padded
struct {
2707 wantA
= padded
{"3", 4}
2710 f
:= func(a padded
, b
uint32) {
2713 ValueOf(f
).Call([]Value
{ValueOf(wantA
), ValueOf(wantB
)})
2714 if gotA
!= wantA || gotB
!= wantB
{
2715 t
.Errorf("function called with (%v, %v), want (%v, %v)", gotA
, gotB
, wantA
, wantB
)
2719 var tagGetTests
= []struct {
2724 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2725 {`protobuf:"PB(1,2)"`, `foo`, ``},
2726 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2727 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2728 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2731 func TestTagGet(t
*testing
.T
) {
2732 for _
, tt
:= range tagGetTests
{
2733 if v
:= tt
.Tag
.Get(tt
.Key
); v
!= tt
.Value
{
2734 t
.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt
.Tag
, tt
.Key
, v
, tt
.Value
)
2739 func TestBytes(t
*testing
.T
) {
2742 y
:= ValueOf(x
).Bytes()
2743 if !bytes
.Equal(x
, y
) {
2744 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
2747 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
2751 func TestSetBytes(t
*testing
.T
) {
2754 y
:= []byte{1, 2, 3, 4}
2755 ValueOf(&x
).Elem().SetBytes(y
)
2756 if !bytes
.Equal(x
, y
) {
2757 t
.Fatalf("ValueOf(%v).Bytes() = %v", x
, y
)
2760 t
.Errorf("ValueOf(%p).Bytes() = %p", &x
[0], &y
[0])
2764 type Private
struct {
2769 func (p
*Private
) m() {
2772 type Public
struct {
2777 func (p
*Public
) M() {
2780 func TestUnexported(t
*testing
.T
) {
2783 isValid(v
.Elem().Field(0))
2784 isValid(v
.Elem().Field(1))
2785 isValid(v
.Elem().FieldByName("X"))
2786 isValid(v
.Elem().FieldByName("Y"))
2787 isValid(v
.Type().Method(0).Func
)
2788 isNonNil(v
.Elem().Field(0).Interface())
2789 isNonNil(v
.Elem().Field(1).Interface())
2790 isNonNil(v
.Elem().FieldByName("X").Interface())
2791 isNonNil(v
.Elem().FieldByName("Y").Interface())
2792 isNonNil(v
.Type().Method(0).Func
.Interface())
2796 isValid(v
.Elem().Field(0))
2797 isValid(v
.Elem().Field(1))
2798 isValid(v
.Elem().FieldByName("x"))
2799 isValid(v
.Elem().FieldByName("y"))
2800 isValid(v
.Type().Method(0).Func
)
2801 shouldPanic(func() { v
.Elem().Field(0).Interface() })
2802 shouldPanic(func() { v
.Elem().Field(1).Interface() })
2803 shouldPanic(func() { v
.Elem().FieldByName("x").Interface() })
2804 shouldPanic(func() { v
.Elem().FieldByName("y").Interface() })
2805 shouldPanic(func() { v
.Type().Method(0).Func
.Interface() })
2808 func shouldPanic(f
func()) {
2810 if recover() == nil {
2811 panic("did not panic")
2817 func isNonNil(x
interface{}) {
2819 panic("nil interface")
2823 func isValid(v Value
) {
2829 func TestAlias(t
*testing
.T
) {
2830 x
:= string("hello")
2831 v
:= ValueOf(&x
).Elem()
2832 oldvalue
:= v
.Interface()
2833 v
.SetString("world")
2834 newvalue
:= v
.Interface()
2836 if oldvalue
!= "hello" || newvalue
!= "world" {
2837 t
.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue
, newvalue
)
2843 func EmptyInterfaceV(x
interface{}) Value
{
2844 return ValueOf(&x
).Elem()
2847 func ReaderV(x io
.Reader
) Value
{
2848 return ValueOf(&x
).Elem()
2851 func ReadWriterV(x io
.ReadWriter
) Value
{
2852 return ValueOf(&x
).Elem()
2856 type MyString
string
2858 type MyRunes
[]int32
2862 var convertTests
= []struct {
2868 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2874 var numbers = []string{
2875 "int8", "uint8", "int16", "uint16",
2876 "int32", "uint32", "int64", "uint64",
2877 "int", "uint", "uintptr",
2878 "float32", "float64",
2882 // all pairs but in an unusual order,
2883 // to emit all the int8, uint8 cases
2884 // before n grows too big.
2886 for i, f := range numbers {
2887 for _, g := range numbers[i:] {
2888 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2891 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2898 {V(int8(1)), V(int8(1))},
2899 {V(int8(2)), V(uint8(2))},
2900 {V(uint8(3)), V(int8(3))},
2901 {V(int8(4)), V(int16(4))},
2902 {V(int16(5)), V(int8(5))},
2903 {V(int8(6)), V(uint16(6))},
2904 {V(uint16(7)), V(int8(7))},
2905 {V(int8(8)), V(int32(8))},
2906 {V(int32(9)), V(int8(9))},
2907 {V(int8(10)), V(uint32(10))},
2908 {V(uint32(11)), V(int8(11))},
2909 {V(int8(12)), V(int64(12))},
2910 {V(int64(13)), V(int8(13))},
2911 {V(int8(14)), V(uint64(14))},
2912 {V(uint64(15)), V(int8(15))},
2913 {V(int8(16)), V(int(16))},
2914 {V(int(17)), V(int8(17))},
2915 {V(int8(18)), V(uint(18))},
2916 {V(uint(19)), V(int8(19))},
2917 {V(int8(20)), V(uintptr(20))},
2918 {V(uintptr(21)), V(int8(21))},
2919 {V(int8(22)), V(float32(22))},
2920 {V(float32(23)), V(int8(23))},
2921 {V(int8(24)), V(float64(24))},
2922 {V(float64(25)), V(int8(25))},
2923 {V(uint8(26)), V(uint8(26))},
2924 {V(uint8(27)), V(int16(27))},
2925 {V(int16(28)), V(uint8(28))},
2926 {V(uint8(29)), V(uint16(29))},
2927 {V(uint16(30)), V(uint8(30))},
2928 {V(uint8(31)), V(int32(31))},
2929 {V(int32(32)), V(uint8(32))},
2930 {V(uint8(33)), V(uint32(33))},
2931 {V(uint32(34)), V(uint8(34))},
2932 {V(uint8(35)), V(int64(35))},
2933 {V(int64(36)), V(uint8(36))},
2934 {V(uint8(37)), V(uint64(37))},
2935 {V(uint64(38)), V(uint8(38))},
2936 {V(uint8(39)), V(int(39))},
2937 {V(int(40)), V(uint8(40))},
2938 {V(uint8(41)), V(uint(41))},
2939 {V(uint(42)), V(uint8(42))},
2940 {V(uint8(43)), V(uintptr(43))},
2941 {V(uintptr(44)), V(uint8(44))},
2942 {V(uint8(45)), V(float32(45))},
2943 {V(float32(46)), V(uint8(46))},
2944 {V(uint8(47)), V(float64(47))},
2945 {V(float64(48)), V(uint8(48))},
2946 {V(int16(49)), V(int16(49))},
2947 {V(int16(50)), V(uint16(50))},
2948 {V(uint16(51)), V(int16(51))},
2949 {V(int16(52)), V(int32(52))},
2950 {V(int32(53)), V(int16(53))},
2951 {V(int16(54)), V(uint32(54))},
2952 {V(uint32(55)), V(int16(55))},
2953 {V(int16(56)), V(int64(56))},
2954 {V(int64(57)), V(int16(57))},
2955 {V(int16(58)), V(uint64(58))},
2956 {V(uint64(59)), V(int16(59))},
2957 {V(int16(60)), V(int(60))},
2958 {V(int(61)), V(int16(61))},
2959 {V(int16(62)), V(uint(62))},
2960 {V(uint(63)), V(int16(63))},
2961 {V(int16(64)), V(uintptr(64))},
2962 {V(uintptr(65)), V(int16(65))},
2963 {V(int16(66)), V(float32(66))},
2964 {V(float32(67)), V(int16(67))},
2965 {V(int16(68)), V(float64(68))},
2966 {V(float64(69)), V(int16(69))},
2967 {V(uint16(70)), V(uint16(70))},
2968 {V(uint16(71)), V(int32(71))},
2969 {V(int32(72)), V(uint16(72))},
2970 {V(uint16(73)), V(uint32(73))},
2971 {V(uint32(74)), V(uint16(74))},
2972 {V(uint16(75)), V(int64(75))},
2973 {V(int64(76)), V(uint16(76))},
2974 {V(uint16(77)), V(uint64(77))},
2975 {V(uint64(78)), V(uint16(78))},
2976 {V(uint16(79)), V(int(79))},
2977 {V(int(80)), V(uint16(80))},
2978 {V(uint16(81)), V(uint(81))},
2979 {V(uint(82)), V(uint16(82))},
2980 {V(uint16(83)), V(uintptr(83))},
2981 {V(uintptr(84)), V(uint16(84))},
2982 {V(uint16(85)), V(float32(85))},
2983 {V(float32(86)), V(uint16(86))},
2984 {V(uint16(87)), V(float64(87))},
2985 {V(float64(88)), V(uint16(88))},
2986 {V(int32(89)), V(int32(89))},
2987 {V(int32(90)), V(uint32(90))},
2988 {V(uint32(91)), V(int32(91))},
2989 {V(int32(92)), V(int64(92))},
2990 {V(int64(93)), V(int32(93))},
2991 {V(int32(94)), V(uint64(94))},
2992 {V(uint64(95)), V(int32(95))},
2993 {V(int32(96)), V(int(96))},
2994 {V(int(97)), V(int32(97))},
2995 {V(int32(98)), V(uint(98))},
2996 {V(uint(99)), V(int32(99))},
2997 {V(int32(100)), V(uintptr(100))},
2998 {V(uintptr(101)), V(int32(101))},
2999 {V(int32(102)), V(float32(102))},
3000 {V(float32(103)), V(int32(103))},
3001 {V(int32(104)), V(float64(104))},
3002 {V(float64(105)), V(int32(105))},
3003 {V(uint32(106)), V(uint32(106))},
3004 {V(uint32(107)), V(int64(107))},
3005 {V(int64(108)), V(uint32(108))},
3006 {V(uint32(109)), V(uint64(109))},
3007 {V(uint64(110)), V(uint32(110))},
3008 {V(uint32(111)), V(int(111))},
3009 {V(int(112)), V(uint32(112))},
3010 {V(uint32(113)), V(uint(113))},
3011 {V(uint(114)), V(uint32(114))},
3012 {V(uint32(115)), V(uintptr(115))},
3013 {V(uintptr(116)), V(uint32(116))},
3014 {V(uint32(117)), V(float32(117))},
3015 {V(float32(118)), V(uint32(118))},
3016 {V(uint32(119)), V(float64(119))},
3017 {V(float64(120)), V(uint32(120))},
3018 {V(int64(121)), V(int64(121))},
3019 {V(int64(122)), V(uint64(122))},
3020 {V(uint64(123)), V(int64(123))},
3021 {V(int64(124)), V(int(124))},
3022 {V(int(125)), V(int64(125))},
3023 {V(int64(126)), V(uint(126))},
3024 {V(uint(127)), V(int64(127))},
3025 {V(int64(128)), V(uintptr(128))},
3026 {V(uintptr(129)), V(int64(129))},
3027 {V(int64(130)), V(float32(130))},
3028 {V(float32(131)), V(int64(131))},
3029 {V(int64(132)), V(float64(132))},
3030 {V(float64(133)), V(int64(133))},
3031 {V(uint64(134)), V(uint64(134))},
3032 {V(uint64(135)), V(int(135))},
3033 {V(int(136)), V(uint64(136))},
3034 {V(uint64(137)), V(uint(137))},
3035 {V(uint(138)), V(uint64(138))},
3036 {V(uint64(139)), V(uintptr(139))},
3037 {V(uintptr(140)), V(uint64(140))},
3038 {V(uint64(141)), V(float32(141))},
3039 {V(float32(142)), V(uint64(142))},
3040 {V(uint64(143)), V(float64(143))},
3041 {V(float64(144)), V(uint64(144))},
3042 {V(int(145)), V(int(145))},
3043 {V(int(146)), V(uint(146))},
3044 {V(uint(147)), V(int(147))},
3045 {V(int(148)), V(uintptr(148))},
3046 {V(uintptr(149)), V(int(149))},
3047 {V(int(150)), V(float32(150))},
3048 {V(float32(151)), V(int(151))},
3049 {V(int(152)), V(float64(152))},
3050 {V(float64(153)), V(int(153))},
3051 {V(uint(154)), V(uint(154))},
3052 {V(uint(155)), V(uintptr(155))},
3053 {V(uintptr(156)), V(uint(156))},
3054 {V(uint(157)), V(float32(157))},
3055 {V(float32(158)), V(uint(158))},
3056 {V(uint(159)), V(float64(159))},
3057 {V(float64(160)), V(uint(160))},
3058 {V(uintptr(161)), V(uintptr(161))},
3059 {V(uintptr(162)), V(float32(162))},
3060 {V(float32(163)), V(uintptr(163))},
3061 {V(uintptr(164)), V(float64(164))},
3062 {V(float64(165)), V(uintptr(165))},
3063 {V(float32(166)), V(float32(166))},
3064 {V(float32(167)), V(float64(167))},
3065 {V(float64(168)), V(float32(168))},
3066 {V(float64(169)), V(float64(169))},
3069 {V(float64(1.5)), V(int(1))},
3072 {V(complex64(1i
)), V(complex64(1i
))},
3073 {V(complex64(2i
)), V(complex128(2i
))},
3074 {V(complex128(3i
)), V(complex64(3i
))},
3075 {V(complex128(4i
)), V(complex128(4i
))},
3078 {V(string("hello")), V(string("hello"))},
3079 {V(string("bytes1")), V([]byte("bytes1"))},
3080 {V([]byte("bytes2")), V(string("bytes2"))},
3081 {V([]byte("bytes3")), V([]byte("bytes3"))},
3082 {V(string("runes♝")), V([]rune("runes♝"))},
3083 {V([]rune("runes♕")), V(string("runes♕"))},
3084 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3085 {V(int('a')), V(string("a"))},
3086 {V(int8('a')), V(string("a"))},
3087 {V(int16('a')), V(string("a"))},
3088 {V(int32('a')), V(string("a"))},
3089 {V(int64('a')), V(string("a"))},
3090 {V(uint('a')), V(string("a"))},
3091 {V(uint8('a')), V(string("a"))},
3092 {V(uint16('a')), V(string("a"))},
3093 {V(uint32('a')), V(string("a"))},
3094 {V(uint64('a')), V(string("a"))},
3095 {V(uintptr('a')), V(string("a"))},
3096 {V(int(-1)), V(string("\uFFFD"))},
3097 {V(int8(-2)), V(string("\uFFFD"))},
3098 {V(int16(-3)), V(string("\uFFFD"))},
3099 {V(int32(-4)), V(string("\uFFFD"))},
3100 {V(int64(-5)), V(string("\uFFFD"))},
3101 {V(uint(0x110001)), V(string("\uFFFD"))},
3102 {V(uint32(0x110002)), V(string("\uFFFD"))},
3103 {V(uint64(0x110003)), V(string("\uFFFD"))},
3104 {V(uintptr(0x110004)), V(string("\uFFFD"))},
3107 {V(MyString("hello")), V(string("hello"))},
3108 {V(string("hello")), V(MyString("hello"))},
3109 {V(string("hello")), V(string("hello"))},
3110 {V(MyString("hello")), V(MyString("hello"))},
3111 {V(MyString("bytes1")), V([]byte("bytes1"))},
3112 {V([]byte("bytes2")), V(MyString("bytes2"))},
3113 {V([]byte("bytes3")), V([]byte("bytes3"))},
3114 {V(MyString("runes♝")), V([]rune("runes♝"))},
3115 {V([]rune("runes♕")), V(MyString("runes♕"))},
3116 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3117 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3118 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3119 {V(int('a')), V(MyString("a"))},
3120 {V(int8('a')), V(MyString("a"))},
3121 {V(int16('a')), V(MyString("a"))},
3122 {V(int32('a')), V(MyString("a"))},
3123 {V(int64('a')), V(MyString("a"))},
3124 {V(uint('a')), V(MyString("a"))},
3125 {V(uint8('a')), V(MyString("a"))},
3126 {V(uint16('a')), V(MyString("a"))},
3127 {V(uint32('a')), V(MyString("a"))},
3128 {V(uint64('a')), V(MyString("a"))},
3129 {V(uintptr('a')), V(MyString("a"))},
3130 {V(int(-1)), V(MyString("\uFFFD"))},
3131 {V(int8(-2)), V(MyString("\uFFFD"))},
3132 {V(int16(-3)), V(MyString("\uFFFD"))},
3133 {V(int32(-4)), V(MyString("\uFFFD"))},
3134 {V(int64(-5)), V(MyString("\uFFFD"))},
3135 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3136 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3137 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3138 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3141 {V(string("bytes1")), V(MyBytes("bytes1"))},
3142 {V(MyBytes("bytes2")), V(string("bytes2"))},
3143 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3144 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3145 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3148 {V(string("runes♝")), V(MyRunes("runes♝"))},
3149 {V(MyRunes("runes♕")), V(string("runes♕"))},
3150 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3151 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3152 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3154 // named types and equal underlying types
3155 {V(new(int)), V(new(integer
))},
3156 {V(new(integer
)), V(new(int))},
3157 {V(Empty
{}), V(struct{}{})},
3158 {V(new(Empty
)), V(new(struct{}))},
3159 {V(struct{}{}), V(Empty
{})},
3160 {V(new(struct{})), V(new(Empty
))},
3161 {V(Empty
{}), V(Empty
{})},
3162 {V(MyBytes
{}), V([]byte{})},
3163 {V([]byte{}), V(MyBytes
{})},
3164 {V((func())(nil)), V(MyFunc(nil))},
3165 {V((MyFunc
)(nil)), V((func())(nil))},
3167 // can convert *byte and *MyByte
3168 {V((*byte)(nil)), V((*MyByte
)(nil))},
3169 {V((*MyByte
)(nil)), V((*byte)(nil))},
3171 // cannot convert mismatched array sizes
3172 {V([2]byte{}), V([2]byte{})},
3173 {V([3]byte{}), V([3]byte{})},
3175 // cannot convert other instances
3176 {V((**byte)(nil)), V((**byte)(nil))},
3177 {V((**MyByte
)(nil)), V((**MyByte
)(nil))},
3178 {V((chan byte)(nil)), V((chan byte)(nil))},
3179 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3180 {V(([]byte)(nil)), V(([]byte)(nil))},
3181 {V(([]MyByte
)(nil)), V(([]MyByte
)(nil))},
3182 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3183 {V((map[int]MyByte
)(nil)), V((map[int]MyByte
)(nil))},
3184 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3185 {V((map[MyByte
]int)(nil)), V((map[MyByte
]int)(nil))},
3186 {V([2]byte{}), V([2]byte{})},
3187 {V([2]MyByte
{}), V([2]MyByte
{})},
3190 {V((***int)(nil)), V((***int)(nil))},
3191 {V((***byte)(nil)), V((***byte)(nil))},
3192 {V((***int32)(nil)), V((***int32)(nil))},
3193 {V((***int64)(nil)), V((***int64)(nil))},
3194 {V((chan int)(nil)), V((<-chan int)(nil))},
3195 {V((chan int)(nil)), V((chan<- int)(nil))},
3196 {V((chan string)(nil)), V((<-chan string)(nil))},
3197 {V((chan string)(nil)), V((chan<- string)(nil))},
3198 {V((chan byte)(nil)), V((chan byte)(nil))},
3199 {V((chan MyByte
)(nil)), V((chan MyByte
)(nil))},
3200 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3201 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3202 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3203 {V([]uint(nil)), V([]uint(nil))},
3204 {V([]int(nil)), V([]int(nil))},
3205 {V(new(interface{})), V(new(interface{}))},
3206 {V(new(io
.Reader
)), V(new(io
.Reader
))},
3207 {V(new(io
.Writer
)), V(new(io
.Writer
))},
3210 {V(int(1)), EmptyInterfaceV(int(1))},
3211 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3212 {V(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3213 {ReadWriterV(new(bytes
.Buffer
)), ReaderV(new(bytes
.Buffer
))},
3214 {V(new(bytes
.Buffer
)), ReadWriterV(new(bytes
.Buffer
))},
3217 func TestConvert(t
*testing
.T
) {
3218 canConvert
:= map[[2]Type
]bool{}
3219 all
:= map[Type
]bool{}
3221 for _
, tt
:= range convertTests
{
3223 if !t1
.ConvertibleTo(t1
) {
3224 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t1
)
3229 if !t1
.ConvertibleTo(t2
) {
3230 t
.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1
, t2
)
3236 canConvert
[[2]Type
{t1
, t2
}] = true
3238 // vout1 represents the in value converted to the in type.
3240 vout1
:= v1
.Convert(t1
)
3241 out1
:= vout1
.Interface()
3242 if vout1
.Type() != tt
.in
.Type() ||
!DeepEqual(out1
, tt
.in
.Interface()) {
3243 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t1
, out1
, tt
.in
.Interface())
3246 // vout2 represents the in value converted to the out type.
3247 vout2
:= v1
.Convert(t2
)
3248 out2
:= vout2
.Interface()
3249 if vout2
.Type() != tt
.out
.Type() ||
!DeepEqual(out2
, tt
.out
.Interface()) {
3250 t
.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out2
, tt
.out
.Interface())
3253 // vout3 represents a new value of the out type, set to vout2. This makes
3254 // sure the converted value vout2 is really usable as a regular value.
3255 vout3
:= New(t2
).Elem()
3257 out3
:= vout3
.Interface()
3258 if vout3
.Type() != tt
.out
.Type() ||
!DeepEqual(out3
, tt
.out
.Interface()) {
3259 t
.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt
.in
.Interface(), t2
, out3
, tt
.out
.Interface())
3263 t
.Errorf("table entry %v is RO, should not be", v1
)
3266 t
.Errorf("self-conversion output %v is RO, should not be", vout1
)
3269 t
.Errorf("conversion output %v is RO, should not be", vout2
)
3272 t
.Errorf("set(conversion output) %v is RO, should not be", vout3
)
3274 if !IsRO(MakeRO(v1
).Convert(t1
)) {
3275 t
.Errorf("RO self-conversion output %v is not RO, should be", v1
)
3277 if !IsRO(MakeRO(v1
).Convert(t2
)) {
3278 t
.Errorf("RO conversion output %v is not RO, should be", v1
)
3282 // Assume that of all the types we saw during the tests,
3283 // if there wasn't an explicit entry for a conversion between
3284 // a pair of types, then it's not to be allowed. This checks for
3285 // things like 'int64' converting to '*int'.
3286 for t1
:= range all
{
3287 for t2
:= range all
{
3288 expectOK
:= t1
== t2 || canConvert
[[2]Type
{t1
, t2
}] || t2
.Kind() == Interface
&& t2
.NumMethod() == 0
3289 if ok
:= t1
.ConvertibleTo(t2
); ok
!= expectOK
{
3290 t
.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1
, t2
, ok
, expectOK
)
3296 type ComparableStruct
struct {
3300 type NonComparableStruct
struct {
3305 var comparableTests
= []struct {
3310 {TypeOf("hello"), true},
3311 {TypeOf(new(byte)), true},
3312 {TypeOf((func())(nil)), false},
3313 {TypeOf([]byte{}), false},
3314 {TypeOf(map[string]int{}), false},
3315 {TypeOf(make(chan int)), true},
3316 {TypeOf(1.5), true},
3317 {TypeOf(false), true},
3319 {TypeOf(ComparableStruct
{}), true},
3320 {TypeOf(NonComparableStruct
{}), false},
3321 {TypeOf([10]map[string]int{}), false},
3322 {TypeOf([10]string{}), true},
3323 {TypeOf(new(interface{})).Elem(), true},
3326 func TestComparable(t
*testing
.T
) {
3327 for _
, tt
:= range comparableTests
{
3328 if ok
:= tt
.typ
.Comparable(); ok
!= tt
.ok
{
3329 t
.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt
.typ
, ok
, tt
.ok
)
3334 func TestOverflow(t
*testing
.T
) {
3335 if ovf
:= V(float64(0)).OverflowFloat(1e300
); ovf
{
3336 t
.Errorf("%v wrongly overflows float64", 1e300
)
3339 maxFloat32
:= float64((1<<24 - 1) << (127 - 23))
3340 if ovf
:= V(float32(0)).OverflowFloat(maxFloat32
); ovf
{
3341 t
.Errorf("%v wrongly overflows float32", maxFloat32
)
3343 ovfFloat32
:= float64((1<<24-1)<<(127-23) + 1<<(127-52))
3344 if ovf
:= V(float32(0)).OverflowFloat(ovfFloat32
); !ovf
{
3345 t
.Errorf("%v should overflow float32", ovfFloat32
)
3347 if ovf
:= V(float32(0)).OverflowFloat(-ovfFloat32
); !ovf
{
3348 t
.Errorf("%v should overflow float32", -ovfFloat32
)
3351 maxInt32
:= int64(0x7fffffff)
3352 if ovf
:= V(int32(0)).OverflowInt(maxInt32
); ovf
{
3353 t
.Errorf("%v wrongly overflows int32", maxInt32
)
3355 if ovf
:= V(int32(0)).OverflowInt(-1 << 31); ovf
{
3356 t
.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3358 ovfInt32
:= int64(1 << 31)
3359 if ovf
:= V(int32(0)).OverflowInt(ovfInt32
); !ovf
{
3360 t
.Errorf("%v should overflow int32", ovfInt32
)
3363 maxUint32
:= uint64(0xffffffff)
3364 if ovf
:= V(uint32(0)).OverflowUint(maxUint32
); ovf
{
3365 t
.Errorf("%v wrongly overflows uint32", maxUint32
)
3367 ovfUint32
:= uint64(1 << 32)
3368 if ovf
:= V(uint32(0)).OverflowUint(ovfUint32
); !ovf
{
3369 t
.Errorf("%v should overflow uint32", ovfUint32
)
3373 func checkSameType(t
*testing
.T
, x
, y
interface{}) {
3374 if TypeOf(x
) != TypeOf(y
) {
3375 t
.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x
), TypeOf(y
))
3379 func TestArrayOf(t
*testing
.T
) {
3380 // TODO(rsc): Finish ArrayOf and enable-test.
3381 t
.Skip("ArrayOf is not finished (and not exported)")
3383 // check construction and use of type not in binary
3385 at
:= ArrayOf(10, TypeOf(T(1)))
3387 for i
:= 0; i
< v
.Len(); i
++ {
3388 v
.Index(i
).Set(ValueOf(T(i
)))
3390 s
:= fmt
.Sprint(v
.Interface())
3391 want
:= "[0 1 2 3 4 5 6 7 8 9]"
3393 t
.Errorf("constructed array = %s, want %s", s
, want
)
3396 // check that type already in binary is found
3397 checkSameType(t
, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T
{})
3400 func TestSliceOf(t
*testing
.T
) {
3401 // check construction and use of type not in binary
3403 st
:= SliceOf(TypeOf(T(1)))
3404 v
:= MakeSlice(st
, 10, 10)
3406 for i
:= 0; i
< v
.Len(); i
++ {
3407 v
.Index(i
).Set(ValueOf(T(i
)))
3410 s
:= fmt
.Sprint(v
.Interface())
3411 want
:= "[0 1 2 3 4 5 6 7 8 9]"
3413 t
.Errorf("constructed slice = %s, want %s", s
, want
)
3416 // check that type already in binary is found
3418 checkSameType(t
, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1
{})
3421 func TestSliceOverflow(t
*testing
.T
) {
3422 // check that MakeSlice panics when size of slice overflows uint
3425 l
:= (1<<(unsafe
.Sizeof((*byte)(nil))*8)-1)/s
+ 1
3427 t
.Fatal("slice size does not overflow")
3430 st
:= SliceOf(TypeOf(x
))
3434 t
.Fatal("slice overflow does not panic")
3437 MakeSlice(st
, int(l
), int(l
))
3440 func TestSliceOfGC(t
*testing
.T
) {
3442 tt
:= TypeOf(T(nil))
3446 for i
:= 0; i
< n
; i
++ {
3447 v
:= MakeSlice(st
, n
, n
)
3448 for j
:= 0; j
< v
.Len(); j
++ {
3450 *p
= uintptr(i
*n
+ j
)
3451 v
.Index(j
).Set(ValueOf(p
).Convert(tt
))
3453 x
= append(x
, v
.Interface())
3457 for i
, xi
:= range x
{
3459 for j
:= 0; j
< v
.Len(); j
++ {
3460 k
:= v
.Index(j
).Elem().Interface()
3461 if k
!= uintptr(i
*n
+j
) {
3462 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3468 func TestChanOf(t
*testing
.T
) {
3469 // check construction and use of type not in binary
3471 ct
:= ChanOf(BothDir
, TypeOf(T("")))
3472 v
:= MakeChan(ct
, 2)
3474 v
.Send(ValueOf(T("hello")))
3476 v
.Send(ValueOf(T("world")))
3483 if s1
!= "hello" || s2
!= "world" {
3484 t
.Errorf("constructed chan: have %q, %q, want %q, %q", s1
, s2
, "hello", "world")
3487 // check that type already in binary is found
3489 checkSameType(t
, Zero(ChanOf(BothDir
, TypeOf(T1(1)))).Interface(), (chan T1
)(nil))
3492 func TestChanOfGC(t
*testing
.T
) {
3493 done
:= make(chan bool, 1)
3497 case <-time
.After(5 * time
.Second
):
3498 panic("deadlock in TestChanOfGC")
3507 tt
:= TypeOf(T(nil))
3508 ct
:= ChanOf(BothDir
, tt
)
3510 // NOTE: The garbage collector handles allocated channels specially,
3511 // so we have to save pointers to channels in x; the pointer code will
3512 // use the gc info in the newly constructed chan type.
3515 for i
:= 0; i
< n
; i
++ {
3516 v
:= MakeChan(ct
, n
)
3517 for j
:= 0; j
< n
; j
++ {
3519 *p
= uintptr(i
*n
+ j
)
3520 v
.Send(ValueOf(p
).Convert(tt
))
3524 x
= append(x
, pv
.Interface())
3528 for i
, xi
:= range x
{
3529 v
:= ValueOf(xi
).Elem()
3530 for j
:= 0; j
< n
; j
++ {
3532 k
:= pv
.Elem().Interface()
3533 if k
!= uintptr(i
*n
+j
) {
3534 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3540 func TestMapOf(t
*testing
.T
) {
3541 // check construction and use of type not in binary
3545 v
:= MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
3547 v
.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
3550 s
:= fmt
.Sprint(v
.Interface())
3553 t
.Errorf("constructed map = %s, want %s", s
, want
)
3556 // check that type already in binary is found
3557 checkSameType(t
, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V
]K(nil))
3559 // check that invalid key type panics
3560 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3563 func TestMapOfGCKeys(t
*testing
.T
) {
3565 tt
:= TypeOf(T(nil))
3566 mt
:= MapOf(tt
, TypeOf(false))
3568 // NOTE: The garbage collector handles allocated maps specially,
3569 // so we have to save pointers to maps in x; the pointer code will
3570 // use the gc info in the newly constructed map type.
3573 for i
:= 0; i
< n
; i
++ {
3575 for j
:= 0; j
< n
; j
++ {
3577 *p
= uintptr(i
*n
+ j
)
3578 v
.SetMapIndex(ValueOf(p
).Convert(tt
), ValueOf(true))
3582 x
= append(x
, pv
.Interface())
3586 for i
, xi
:= range x
{
3587 v
:= ValueOf(xi
).Elem()
3589 for _
, kv
:= range v
.MapKeys() {
3590 out
= append(out
, int(kv
.Elem().Interface().(uintptr)))
3593 for j
, k
:= range out
{
3595 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3601 func TestMapOfGCValues(t
*testing
.T
) {
3603 tt
:= TypeOf(T(nil))
3604 mt
:= MapOf(TypeOf(1), tt
)
3606 // NOTE: The garbage collector handles allocated maps specially,
3607 // so we have to save pointers to maps in x; the pointer code will
3608 // use the gc info in the newly constructed map type.
3611 for i
:= 0; i
< n
; i
++ {
3613 for j
:= 0; j
< n
; j
++ {
3615 *p
= uintptr(i
*n
+ j
)
3616 v
.SetMapIndex(ValueOf(j
), ValueOf(p
).Convert(tt
))
3620 x
= append(x
, pv
.Interface())
3624 for i
, xi
:= range x
{
3625 v
:= ValueOf(xi
).Elem()
3626 for j
:= 0; j
< n
; j
++ {
3627 k
:= v
.MapIndex(ValueOf(j
)).Elem().Interface().(uintptr)
3628 if k
!= uintptr(i
*n
+j
) {
3629 t
.Errorf("lost x[%d][%d] = %d, want %d", i
, j
, k
, i
*n
+j
)
3641 func BenchmarkFieldByName1(b
*testing
.B
) {
3643 for i
:= 0; i
< b
.N
; i
++ {
3648 func BenchmarkFieldByName2(b
*testing
.B
) {
3650 for i
:= 0; i
< b
.N
; i
++ {
3725 func TestEmbed(t
*testing
.T
) {
3727 f
, ok
:= typ
.FieldByName("X")
3729 t
.Fatalf(`FieldByName("X") should fail, returned %v`, f
.Index
)
3733 func BenchmarkFieldByName3(b
*testing
.B
) {
3735 for i
:= 0; i
< b
.N
; i
++ {
3745 func BenchmarkInterfaceBig(b
*testing
.B
) {
3747 for i
:= 0; i
< b
.N
; i
++ {
3753 func TestAllocsInterfaceBig(t
*testing
.T
) {
3754 if testing
.Short() {
3755 t
.Skip("skipping malloc count in short mode")
3758 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
3759 t
.Error("allocs:", allocs
)
3763 func BenchmarkInterfaceSmall(b
*testing
.B
) {
3764 v
:= ValueOf(int64(0))
3765 for i
:= 0; i
< b
.N
; i
++ {
3770 func TestAllocsInterfaceSmall(t
*testing
.T
) {
3771 if testing
.Short() {
3772 t
.Skip("skipping malloc count in short mode")
3774 v
:= ValueOf(int64(0))
3775 if allocs
:= testing
.AllocsPerRun(100, func() { v
.Interface() }); allocs
> 0 {
3776 t
.Error("allocs:", allocs
)
3780 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
3781 // The basic usage is:
3784 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
3787 // Each iteration of the loop returns a different set of results, until all
3788 // possible result sets have been explored. It is okay for different code paths
3789 // to make different method call sequences on x, but there must be no
3790 // other source of non-determinism in the call sequences.
3792 // When faced with a new decision, x chooses randomly. Future explorations
3793 // of that path will choose successive values for the result. Thus, stopping
3794 // the loop after a fixed number of iterations gives somewhat stochastic
3800 // v := make([]bool, x.Choose(4))
3801 // for i := range v {
3807 // prints (in some order):
3816 // [false false false]
3819 // [false false false false]
3821 // [true true true true]
3823 type exhaustive
struct {
3829 type choice
struct {
3835 func (x
*exhaustive
) Next() bool {
3837 x
.r
= rand
.New(rand
.NewSource(time
.Now().UnixNano()))
3844 for i
:= len(x
.last
) - 1; i
>= 0; i
-- {
3848 x
.last
= x
.last
[:i
+1]
3855 func (x
*exhaustive
) Choose(max
int) int {
3856 if x
.pos
>= len(x
.last
) {
3857 x
.last
= append(x
.last
, choice
{x
.r
.Intn(max
), 0, max
})
3862 panic("inconsistent use of exhaustive tester")
3864 return (c
.n
+ c
.off
) % max
3867 func (x
*exhaustive
) Maybe() bool {
3868 return x
.Choose(2) == 1
3871 func GCFunc(args
[]Value
) []Value
{
3876 func TestReflectFuncTraceback(t
*testing
.T
) {
3877 f
:= MakeFunc(TypeOf(func() {}), GCFunc
)
3881 func TestReflectMethodTraceback(t
*testing
.T
) {
3883 m
:= ValueOf(p
).MethodByName("GCMethod")
3884 i
:= ValueOf(m
.Interface()).Call([]Value
{ValueOf(5)})[0].Int()
3886 t
.Errorf("Call returned %d; want 8", i
)
3890 func TestBigZero(t
*testing
.T
) {
3891 const size
= 1 << 10
3893 z
:= Zero(ValueOf(v
).Type()).Interface().([size
]byte)
3894 for i
:= 0; i
< size
; i
++ {
3896 t
.Fatalf("Zero object not all zero, index %d", i
)
3901 func TestFieldByIndexNil(t
*testing
.T
) {
3910 v
.FieldByName("P") // should be fine
3913 if err
:= recover(); err
== nil {
3914 t
.Fatalf("no error")
3915 } else if !strings
.Contains(fmt
.Sprint(err
), "nil pointer to embedded struct") {
3916 t
.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err
)
3919 v
.FieldByName("F") // should panic
3921 t
.Fatalf("did not panic")
3925 // type Outer struct {
3929 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
3930 // The implementation is logically:
3931 // func (p *Outer) M() {
3934 // but since the only change here is the replacement of one pointer receiver with another,
3935 // the actual generated code overwrites the original receiver with the p.Inner pointer and
3936 // then jumps to the M method expecting the *Inner receiver.
3938 // During reflect.Value.Call, we create an argument frame and the associated data structures
3939 // to describe it to the garbage collector, populate the frame, call reflect.call to
3940 // run a function call using that frame, and then copy the results back out of the frame.
3941 // The reflect.call function does a memmove of the frame structure onto the
3942 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
3943 // the frame structure (to preserve the outputs).
3945 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
3946 // were for the full stack frame. However, in the case where the called function was
3947 // one of these wrappers, the rewritten receiver is almost certainly a different type
3948 // than the original receiver. This is not a problem on the stack, where we use the
3949 // program counter to determine the type information and understand that
3950 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
3951 // memory word is now an *Inner. But in the statically typed argument frame created
3952 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
3953 // off the stack into the frame will store an *Inner there, and then if a garbage collection
3954 // happens to scan that argument frame before it is discarded, it will scan the *Inner
3955 // memory as if it were an *Outer. If the two have different memory layouts, the
3956 // collection will intepret the memory incorrectly.
3958 // One such possible incorrect interpretation is to treat two arbitrary memory words
3959 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
3960 // an interface requires dereferencing the itab word, the misinterpretation will try to
3961 // deference Inner.P1, causing a crash during garbage collection.
3963 // This came up in a real program in issue 7725.
3976 func (pi
*Inner
) M() {
3977 // Clear references to pi so that the only way the
3978 // garbage collection will find the pointer is in the
3979 // argument frame, typed as a *Outer.
3982 // Set up an interface value that will cause a crash.
3983 // P1 = 1 is a non-zero, so the interface looks non-nil.
3984 // P2 = pi ensures that the data word points into the
3985 // allocated heap; if not the collection skips the interface
3986 // value as irrelevant, without dereferencing P1.
3988 pi
.P2
= uintptr(unsafe
.Pointer(pi
))
3991 func TestCallMethodJump(t
*testing
.T
) {
3992 // In reflect.Value.Call, trigger a garbage collection after reflect.call
3993 // returns but before the args frame has been discarded.
3994 // This is a little clumsy but makes the failure repeatable.
3997 p
:= &Outer
{Inner
: new(Inner
)}
3999 ValueOf(p
).Method(0).Call(nil)
4001 // Stop garbage collecting during reflect.call.
4005 func TestMakeFuncStackCopy(t
*testing
.T
) {
4006 target
:= func(in
[]Value
) []Value
{
4009 return []Value
{ValueOf(9)}
4012 var concrete
func(*int, int) int
4013 fn
:= MakeFunc(ValueOf(concrete
).Type(), target
)
4014 ValueOf(&concrete
).Elem().Set(fn
)
4015 x
:= concrete(nil, 7)
4017 t
.Errorf("have %#q want 9", x
)
4021 // use about n KB of stack
4022 func useStack(n
int) {
4026 var b
[1024]byte // makes frame about 1KB
4027 useStack(n
- 1 + int(b
[99]))
4034 func TestValueString(t
*testing
.T
) {
4035 rv
:= ValueOf(Impl
{})
4036 if rv
.String() != "<reflect_test.Impl Value>" {
4037 t
.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv
.String(), "<reflect_test.Impl Value>")
4040 method
:= rv
.Method(0)
4041 if method
.String() != "<func() Value>" {
4042 t
.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method
.String(), "<func() Value>")
4046 func TestInvalid(t
*testing
.T
) {
4047 // Used to have inconsistency between IsValid() and Kind() != Invalid.
4048 type T
struct{ v
interface{} }
4050 v
:= ValueOf(T
{}).Field(0)
4051 if v
.IsValid() != true || v
.Kind() != Interface
{
4052 t
.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v
.IsValid(), v
.Kind())
4055 if v
.IsValid() != false || v
.Kind() != Invalid
{
4056 t
.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v
.IsValid(), v
.Kind())
4061 func TestLargeGCProg(t
*testing
.T
) {
4062 fv
:= ValueOf(func([256]*byte) {})
4063 fv
.Call([]Value
{ValueOf([256]*byte{})})
4067 func TestCallGC(t
*testing
.T
) {
4068 f
:= func(a
, b
, c
, d
, e
string) {
4070 g
:= func(in
[]Value
) []Value
{
4074 typ
:= ValueOf(f
).Type()
4075 f2
:= MakeFunc(typ
, g
).Interface().(func(string, string, string, string, string))
4076 f2("four", "five5", "six666", "seven77", "eight888")
4079 type funcLayoutTest
struct {
4081 argsize
, retOffset
uintptr
4085 var funcLayoutTests
[]funcLayoutTest
4088 var argAlign
= PtrSize
4089 if runtime
.GOARCH
== "amd64p32" {
4090 argAlign
= 2 * PtrSize
4092 roundup
:= func(x
uintptr, a
uintptr) uintptr {
4093 return (x
+ a
- 1) / a
* a
4096 funcLayoutTests
= append(funcLayoutTests
,
4099 ValueOf(func(a
, b
string) string { return "" }).Type(),
4102 []byte{BitsPointer
, BitsScalar
, BitsPointer
},
4107 r
= []byte{BitsScalar
, BitsScalar
, BitsScalar
, BitsPointer
}
4109 r
= []byte{BitsScalar
, BitsScalar
, BitsPointer
}
4111 funcLayoutTests
= append(funcLayoutTests
,
4114 ValueOf(func(a
, b
, c
uint32, p
*byte, d
uint16) {}).Type(),
4115 roundup(3*4, PtrSize
) + PtrSize
+ 2,
4116 roundup(roundup(3*4, PtrSize
)+PtrSize
+2, argAlign
),
4120 funcLayoutTests
= append(funcLayoutTests
,
4123 ValueOf(func(a
map[int]int, b
uintptr, c
interface{}) {}).Type(),
4126 []byte{BitsPointer
, BitsScalar
, BitsPointer
, BitsPointer
},
4133 funcLayoutTests
= append(funcLayoutTests
,
4136 ValueOf(func(a S
) {}).Type(),
4139 []byte{BitsScalar
, BitsScalar
, BitsPointer
, BitsPointer
},
4142 funcLayoutTests
= append(funcLayoutTests
,
4144 ValueOf((*byte)(nil)).Type(),
4145 ValueOf(func(a
uintptr, b
*int) {}).Type(),
4147 roundup(3*PtrSize
, argAlign
),
4148 []byte{BitsPointer
, BitsScalar
, BitsPointer
},
4152 func TestFuncLayout(t
*testing
.T
) {
4153 t
.Skip("gccgo does not use funcLayout")
4154 for _
, lt
:= range funcLayoutTests
{
4155 _
, argsize
, retOffset
, stack
:= FuncLayout(lt
.t
, lt
.rcvr
)
4156 if argsize
!= lt
.argsize
{
4157 t
.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt
.t
, lt
.rcvr
, argsize
, lt
.argsize
)
4159 if retOffset
!= lt
.retOffset
{
4160 t
.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt
.t
, lt
.rcvr
, retOffset
, lt
.retOffset
)
4162 if !bytes
.Equal(stack
, lt
.stack
) {
4163 t
.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt
.t
, lt
.rcvr
, stack
, lt
.stack
)