reflect: fix StructOf hash and string
[official-gcc.git] / libgo / go / reflect / all_test.go
blob96b57ef2cdaa375d4a9446f03f296ba573a85166
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.
5 package reflect_test
7 import (
8 "bytes"
9 "encoding/base64"
10 "flag"
11 "fmt"
12 "io"
13 "math"
14 "math/rand"
15 "os"
16 . "reflect"
17 "runtime"
18 "sort"
19 "strconv"
20 "strings"
21 "sync"
22 "sync/atomic"
23 "testing"
24 "time"
25 "unicode"
26 "unicode/utf8"
27 "unsafe"
30 var sink interface{}
32 func TestBool(t *testing.T) {
33 v := ValueOf(true)
34 if v.Bool() != true {
35 t.Fatal("ValueOf(true).Bool() = false")
39 type integer int
40 type T struct {
41 a int
42 b float64
43 c string
44 d *int
47 type pair struct {
48 i interface{}
49 s string
52 func assert(t *testing.T, s, want string) {
53 if s != want {
54 t.Errorf("have %#q want %#q", s, want)
58 var typeTests = []pair{
59 {struct{ x int }{}, "int"},
60 {struct{ x int8 }{}, "int8"},
61 {struct{ x int16 }{}, "int16"},
62 {struct{ x int32 }{}, "int32"},
63 {struct{ x int64 }{}, "int64"},
64 {struct{ x uint }{}, "uint"},
65 {struct{ x uint8 }{}, "uint8"},
66 {struct{ x uint16 }{}, "uint16"},
67 {struct{ x uint32 }{}, "uint32"},
68 {struct{ x uint64 }{}, "uint64"},
69 {struct{ x float32 }{}, "float32"},
70 {struct{ x float64 }{}, "float64"},
71 {struct{ x int8 }{}, "int8"},
72 {struct{ x (**int8) }{}, "**int8"},
73 {struct{ x (**integer) }{}, "**reflect_test.integer"},
74 {struct{ x ([32]int32) }{}, "[32]int32"},
75 {struct{ x ([]int8) }{}, "[]int8"},
76 {struct{ x (map[string]int32) }{}, "map[string]int32"},
77 {struct{ x (chan<- string) }{}, "chan<- string"},
78 {struct {
79 x struct {
80 c chan *int32
81 d float32
83 }{},
84 "struct { c chan *int32; d float32 }",
86 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
87 {struct {
88 x struct {
89 c func(chan *integer, *int8)
91 }{},
92 "struct { c func(chan *reflect_test.integer, *int8) }",
94 {struct {
95 x struct {
96 a int8
97 b int32
99 }{},
100 "struct { a int8; b int32 }",
102 {struct {
103 x struct {
104 a int8
105 b int8
106 c int32
108 }{},
109 "struct { a int8; b int8; c int32 }",
111 {struct {
112 x struct {
113 a int8
114 b int8
115 c int8
116 d int32
118 }{},
119 "struct { a int8; b int8; c int8; d int32 }",
121 {struct {
122 x struct {
123 a int8
124 b int8
125 c int8
126 d int8
127 e int32
129 }{},
130 "struct { a int8; b int8; c int8; d int8; e int32 }",
132 {struct {
133 x struct {
134 a int8
135 b int8
136 c int8
137 d int8
138 e int8
139 f int32
141 }{},
142 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
144 {struct {
145 x struct {
146 a int8 `reflect:"hi there"`
148 }{},
149 `struct { a int8 "reflect:\"hi there\"" }`,
151 {struct {
152 x struct {
153 a int8 `reflect:"hi \x00there\t\n\"\\"`
155 }{},
156 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
158 {struct {
159 x struct {
160 f func(args ...int)
162 }{},
163 "struct { f func(...int) }",
165 {struct {
166 x (interface {
167 a(func(func(int) int) func(func(int)) int)
170 }{},
171 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
173 {struct {
174 x struct {
175 int32
176 int64
178 }{},
179 "struct { int32; int64 }",
183 var valueTests = []pair{
184 {new(int), "132"},
185 {new(int8), "8"},
186 {new(int16), "16"},
187 {new(int32), "32"},
188 {new(int64), "64"},
189 {new(uint), "132"},
190 {new(uint8), "8"},
191 {new(uint16), "16"},
192 {new(uint32), "32"},
193 {new(uint64), "64"},
194 {new(float32), "256.25"},
195 {new(float64), "512.125"},
196 {new(complex64), "532.125+10i"},
197 {new(complex128), "564.25+1i"},
198 {new(string), "stringy cheese"},
199 {new(bool), "true"},
200 {new(*int8), "*int8(0)"},
201 {new(**int8), "**int8(0)"},
202 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
203 {new(**integer), "**reflect_test.integer(0)"},
204 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
205 {new(chan<- string), "chan<- string"},
206 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
207 {new(struct {
208 c chan *int32
209 d float32
211 "struct { c chan *int32; d float32 }{chan *int32, 0}",
213 {new(struct{ c func(chan *integer, *int8) }),
214 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
216 {new(struct {
217 a int8
218 b int32
220 "struct { a int8; b int32 }{0, 0}",
222 {new(struct {
223 a int8
224 b int8
225 c int32
227 "struct { a int8; b int8; c int32 }{0, 0, 0}",
231 func testType(t *testing.T, i int, typ Type, want string) {
232 s := typ.String()
233 if s != want {
234 t.Errorf("#%d: have %#q, want %#q", i, s, want)
238 func TestTypes(t *testing.T) {
239 for i, tt := range typeTests {
240 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
244 func TestSet(t *testing.T) {
245 for i, tt := range valueTests {
246 v := ValueOf(tt.i)
247 v = v.Elem()
248 switch v.Kind() {
249 case Int:
250 v.SetInt(132)
251 case Int8:
252 v.SetInt(8)
253 case Int16:
254 v.SetInt(16)
255 case Int32:
256 v.SetInt(32)
257 case Int64:
258 v.SetInt(64)
259 case Uint:
260 v.SetUint(132)
261 case Uint8:
262 v.SetUint(8)
263 case Uint16:
264 v.SetUint(16)
265 case Uint32:
266 v.SetUint(32)
267 case Uint64:
268 v.SetUint(64)
269 case Float32:
270 v.SetFloat(256.25)
271 case Float64:
272 v.SetFloat(512.125)
273 case Complex64:
274 v.SetComplex(532.125 + 10i)
275 case Complex128:
276 v.SetComplex(564.25 + 1i)
277 case String:
278 v.SetString("stringy cheese")
279 case Bool:
280 v.SetBool(true)
282 s := valueToString(v)
283 if s != tt.s {
284 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
289 func TestSetValue(t *testing.T) {
290 for i, tt := range valueTests {
291 v := ValueOf(tt.i).Elem()
292 switch v.Kind() {
293 case Int:
294 v.Set(ValueOf(int(132)))
295 case Int8:
296 v.Set(ValueOf(int8(8)))
297 case Int16:
298 v.Set(ValueOf(int16(16)))
299 case Int32:
300 v.Set(ValueOf(int32(32)))
301 case Int64:
302 v.Set(ValueOf(int64(64)))
303 case Uint:
304 v.Set(ValueOf(uint(132)))
305 case Uint8:
306 v.Set(ValueOf(uint8(8)))
307 case Uint16:
308 v.Set(ValueOf(uint16(16)))
309 case Uint32:
310 v.Set(ValueOf(uint32(32)))
311 case Uint64:
312 v.Set(ValueOf(uint64(64)))
313 case Float32:
314 v.Set(ValueOf(float32(256.25)))
315 case Float64:
316 v.Set(ValueOf(512.125))
317 case Complex64:
318 v.Set(ValueOf(complex64(532.125 + 10i)))
319 case Complex128:
320 v.Set(ValueOf(complex128(564.25 + 1i)))
321 case String:
322 v.Set(ValueOf("stringy cheese"))
323 case Bool:
324 v.Set(ValueOf(true))
326 s := valueToString(v)
327 if s != tt.s {
328 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
333 func TestCanSetField(t *testing.T) {
334 type embed struct{ x, X int }
335 type Embed struct{ x, X int }
336 type S1 struct {
337 embed
338 x, X int
340 type S2 struct {
341 *embed
342 x, X int
344 type S3 struct {
345 Embed
346 x, X int
348 type S4 struct {
349 *Embed
350 x, X int
353 type testCase struct {
354 index []int
355 canSet bool
357 tests := []struct {
358 val Value
359 cases []testCase
361 val: ValueOf(&S1{}),
362 cases: []testCase{
363 {[]int{0}, false},
364 {[]int{0, 0}, false},
365 {[]int{0, 1}, true},
366 {[]int{1}, false},
367 {[]int{2}, true},
369 }, {
370 val: ValueOf(&S2{embed: &embed{}}),
371 cases: []testCase{
372 {[]int{0}, false},
373 {[]int{0, 0}, false},
374 {[]int{0, 1}, true},
375 {[]int{1}, false},
376 {[]int{2}, true},
378 }, {
379 val: ValueOf(&S3{}),
380 cases: []testCase{
381 {[]int{0}, true},
382 {[]int{0, 0}, false},
383 {[]int{0, 1}, true},
384 {[]int{1}, false},
385 {[]int{2}, true},
387 }, {
388 val: ValueOf(&S4{Embed: &Embed{}}),
389 cases: []testCase{
390 {[]int{0}, true},
391 {[]int{0, 0}, false},
392 {[]int{0, 1}, true},
393 {[]int{1}, false},
394 {[]int{2}, true},
398 for _, tt := range tests {
399 t.Run(tt.val.Type().Name(), func(t *testing.T) {
400 for _, tc := range tt.cases {
401 f := tt.val
402 for _, i := range tc.index {
403 if f.Kind() == Ptr {
404 f = f.Elem()
406 f = f.Field(i)
408 if got := f.CanSet(); got != tc.canSet {
409 t.Errorf("CanSet() = %v, want %v", got, tc.canSet)
416 var _i = 7
418 var valueToStringTests = []pair{
419 {123, "123"},
420 {123.5, "123.5"},
421 {byte(123), "123"},
422 {"abc", "abc"},
423 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
424 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
425 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
426 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
427 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
428 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
431 func TestValueToString(t *testing.T) {
432 for i, test := range valueToStringTests {
433 s := valueToString(ValueOf(test.i))
434 if s != test.s {
435 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
440 func TestArrayElemSet(t *testing.T) {
441 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
442 v.Index(4).SetInt(123)
443 s := valueToString(v)
444 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
445 if s != want {
446 t.Errorf("[10]int: have %#q want %#q", s, want)
449 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
450 v.Index(4).SetInt(123)
451 s = valueToString(v)
452 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
453 if s != want1 {
454 t.Errorf("[]int: have %#q want %#q", s, want1)
458 func TestPtrPointTo(t *testing.T) {
459 var ip *int32
460 var i int32 = 1234
461 vip := ValueOf(&ip)
462 vi := ValueOf(&i).Elem()
463 vip.Elem().Set(vi.Addr())
464 if *ip != 1234 {
465 t.Errorf("got %d, want 1234", *ip)
468 ip = nil
469 vp := ValueOf(&ip).Elem()
470 vp.Set(Zero(vp.Type()))
471 if ip != nil {
472 t.Errorf("got non-nil (%p), want nil", ip)
476 func TestPtrSetNil(t *testing.T) {
477 var i int32 = 1234
478 ip := &i
479 vip := ValueOf(&ip)
480 vip.Elem().Set(Zero(vip.Elem().Type()))
481 if ip != nil {
482 t.Errorf("got non-nil (%d), want nil", *ip)
486 func TestMapSetNil(t *testing.T) {
487 m := make(map[string]int)
488 vm := ValueOf(&m)
489 vm.Elem().Set(Zero(vm.Elem().Type()))
490 if m != nil {
491 t.Errorf("got non-nil (%p), want nil", m)
495 func TestAll(t *testing.T) {
496 testType(t, 1, TypeOf((int8)(0)), "int8")
497 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
499 typ := TypeOf((*struct {
500 c chan *int32
501 d float32
502 })(nil))
503 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
504 etyp := typ.Elem()
505 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
506 styp := etyp
507 f := styp.Field(0)
508 testType(t, 5, f.Type, "chan *int32")
510 f, present := styp.FieldByName("d")
511 if !present {
512 t.Errorf("FieldByName says present field is absent")
514 testType(t, 6, f.Type, "float32")
516 f, present = styp.FieldByName("absent")
517 if present {
518 t.Errorf("FieldByName says absent field is present")
521 typ = TypeOf([32]int32{})
522 testType(t, 7, typ, "[32]int32")
523 testType(t, 8, typ.Elem(), "int32")
525 typ = TypeOf((map[string]*int32)(nil))
526 testType(t, 9, typ, "map[string]*int32")
527 mtyp := typ
528 testType(t, 10, mtyp.Key(), "string")
529 testType(t, 11, mtyp.Elem(), "*int32")
531 typ = TypeOf((chan<- string)(nil))
532 testType(t, 12, typ, "chan<- string")
533 testType(t, 13, typ.Elem(), "string")
535 // make sure tag strings are not part of element type
536 typ = TypeOf(struct {
537 d []uint32 `reflect:"TAG"`
538 }{}).Field(0).Type
539 testType(t, 14, typ, "[]uint32")
542 func TestInterfaceGet(t *testing.T) {
543 var inter struct {
544 E interface{}
546 inter.E = 123.456
547 v1 := ValueOf(&inter)
548 v2 := v1.Elem().Field(0)
549 assert(t, v2.Type().String(), "interface {}")
550 i2 := v2.Interface()
551 v3 := ValueOf(i2)
552 assert(t, v3.Type().String(), "float64")
555 func TestInterfaceValue(t *testing.T) {
556 var inter struct {
557 E interface{}
559 inter.E = 123.456
560 v1 := ValueOf(&inter)
561 v2 := v1.Elem().Field(0)
562 assert(t, v2.Type().String(), "interface {}")
563 v3 := v2.Elem()
564 assert(t, v3.Type().String(), "float64")
566 i3 := v2.Interface()
567 if _, ok := i3.(float64); !ok {
568 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
572 func TestFunctionValue(t *testing.T) {
573 var x interface{} = func() {}
574 v := ValueOf(x)
575 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
576 t.Fatalf("TestFunction returned wrong pointer")
578 assert(t, v.Type().String(), "func()")
581 var appendTests = []struct {
582 orig, extra []int
584 {make([]int, 2, 4), []int{22}},
585 {make([]int, 2, 4), []int{22, 33, 44}},
588 func sameInts(x, y []int) bool {
589 if len(x) != len(y) {
590 return false
592 for i, xx := range x {
593 if xx != y[i] {
594 return false
597 return true
600 func TestAppend(t *testing.T) {
601 for i, test := range appendTests {
602 origLen, extraLen := len(test.orig), len(test.extra)
603 want := append(test.orig, test.extra...)
604 // Convert extra from []int to []Value.
605 e0 := make([]Value, len(test.extra))
606 for j, e := range test.extra {
607 e0[j] = ValueOf(e)
609 // Convert extra from []int to *SliceValue.
610 e1 := ValueOf(test.extra)
611 // Test Append.
612 a0 := ValueOf(test.orig)
613 have0 := Append(a0, e0...).Interface().([]int)
614 if !sameInts(have0, want) {
615 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
617 // Check that the orig and extra slices were not modified.
618 if len(test.orig) != origLen {
619 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
621 if len(test.extra) != extraLen {
622 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
624 // Test AppendSlice.
625 a1 := ValueOf(test.orig)
626 have1 := AppendSlice(a1, e1).Interface().([]int)
627 if !sameInts(have1, want) {
628 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
630 // Check that the orig and extra slices were not modified.
631 if len(test.orig) != origLen {
632 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
634 if len(test.extra) != extraLen {
635 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
640 func TestCopy(t *testing.T) {
641 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
642 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
643 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
644 for i := 0; i < len(b); i++ {
645 if b[i] != c[i] {
646 t.Fatalf("b != c before test")
649 a1 := a
650 b1 := b
651 aa := ValueOf(&a1).Elem()
652 ab := ValueOf(&b1).Elem()
653 for tocopy := 1; tocopy <= 7; tocopy++ {
654 aa.SetLen(tocopy)
655 Copy(ab, aa)
656 aa.SetLen(8)
657 for i := 0; i < tocopy; i++ {
658 if a[i] != b[i] {
659 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
660 tocopy, i, a[i], i, b[i])
663 for i := tocopy; i < len(b); i++ {
664 if b[i] != c[i] {
665 if i < len(a) {
666 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
667 tocopy, i, a[i], i, b[i], i, c[i])
668 } else {
669 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
670 tocopy, i, b[i], i, c[i])
672 } else {
673 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
679 func TestCopyString(t *testing.T) {
680 t.Run("Slice", func(t *testing.T) {
681 s := bytes.Repeat([]byte{'_'}, 8)
682 val := ValueOf(s)
684 n := Copy(val, ValueOf(""))
685 if expecting := []byte("________"); n != 0 || !bytes.Equal(s, expecting) {
686 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s, expecting)
689 n = Copy(val, ValueOf("hello"))
690 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s, expecting) {
691 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s, expecting)
694 n = Copy(val, ValueOf("helloworld"))
695 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s, expecting) {
696 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s, expecting)
699 t.Run("Array", func(t *testing.T) {
700 s := [...]byte{'_', '_', '_', '_', '_', '_', '_', '_'}
701 val := ValueOf(&s).Elem()
703 n := Copy(val, ValueOf(""))
704 if expecting := []byte("________"); n != 0 || !bytes.Equal(s[:], expecting) {
705 t.Errorf("got n = %d, s = %s, expecting n = 0, s = %s", n, s[:], expecting)
708 n = Copy(val, ValueOf("hello"))
709 if expecting := []byte("hello___"); n != 5 || !bytes.Equal(s[:], expecting) {
710 t.Errorf("got n = %d, s = %s, expecting n = 5, s = %s", n, s[:], expecting)
713 n = Copy(val, ValueOf("helloworld"))
714 if expecting := []byte("hellowor"); n != 8 || !bytes.Equal(s[:], expecting) {
715 t.Errorf("got n = %d, s = %s, expecting n = 8, s = %s", n, s[:], expecting)
720 func TestCopyArray(t *testing.T) {
721 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
722 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
723 c := b
724 aa := ValueOf(&a).Elem()
725 ab := ValueOf(&b).Elem()
726 Copy(ab, aa)
727 for i := 0; i < len(a); i++ {
728 if a[i] != b[i] {
729 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
732 for i := len(a); i < len(b); i++ {
733 if b[i] != c[i] {
734 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
735 } else {
736 t.Logf("elem %d is okay\n", i)
741 func TestBigUnnamedStruct(t *testing.T) {
742 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
743 v := ValueOf(b)
744 b1 := v.Interface().(struct {
745 a, b, c, d int64
747 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
748 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
752 type big struct {
753 a, b, c, d, e int64
756 func TestBigStruct(t *testing.T) {
757 b := big{1, 2, 3, 4, 5}
758 v := ValueOf(b)
759 b1 := v.Interface().(big)
760 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
761 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
765 type Basic struct {
766 x int
767 y float32
770 type NotBasic Basic
772 type DeepEqualTest struct {
773 a, b interface{}
774 eq bool
777 // Simple functions for DeepEqual tests.
778 var (
779 fn1 func() // nil.
780 fn2 func() // nil.
781 fn3 = func() { fn1() } // Not nil.
784 type self struct{}
786 type Loop *Loop
787 type Loopy interface{}
789 var loop1, loop2 Loop
790 var loopy1, loopy2 Loopy
792 func init() {
793 loop1 = &loop2
794 loop2 = &loop1
796 loopy1 = &loopy2
797 loopy2 = &loopy1
800 var deepEqualTests = []DeepEqualTest{
801 // Equalities
802 {nil, nil, true},
803 {1, 1, true},
804 {int32(1), int32(1), true},
805 {0.5, 0.5, true},
806 {float32(0.5), float32(0.5), true},
807 {"hello", "hello", true},
808 {make([]int, 10), make([]int, 10), true},
809 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
810 {Basic{1, 0.5}, Basic{1, 0.5}, true},
811 {error(nil), error(nil), true},
812 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
813 {fn1, fn2, true},
815 // Inequalities
816 {1, 2, false},
817 {int32(1), int32(2), false},
818 {0.5, 0.6, false},
819 {float32(0.5), float32(0.6), false},
820 {"hello", "hey", false},
821 {make([]int, 10), make([]int, 11), false},
822 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
823 {Basic{1, 0.5}, Basic{1, 0.6}, false},
824 {Basic{1, 0}, Basic{2, 0}, false},
825 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
826 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
827 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
828 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
829 {nil, 1, false},
830 {1, nil, false},
831 {fn1, fn3, false},
832 {fn3, fn3, false},
833 {[][]int{{1}}, [][]int{{2}}, false},
834 {math.NaN(), math.NaN(), false},
835 {&[1]float64{math.NaN()}, &[1]float64{math.NaN()}, false},
836 {&[1]float64{math.NaN()}, self{}, true},
837 {[]float64{math.NaN()}, []float64{math.NaN()}, false},
838 {[]float64{math.NaN()}, self{}, true},
839 {map[float64]float64{math.NaN(): 1}, map[float64]float64{1: 2}, false},
840 {map[float64]float64{math.NaN(): 1}, self{}, true},
842 // Nil vs empty: not the same.
843 {[]int{}, []int(nil), false},
844 {[]int{}, []int{}, true},
845 {[]int(nil), []int(nil), true},
846 {map[int]int{}, map[int]int(nil), false},
847 {map[int]int{}, map[int]int{}, true},
848 {map[int]int(nil), map[int]int(nil), true},
850 // Mismatched types
851 {1, 1.0, false},
852 {int32(1), int64(1), false},
853 {0.5, "hello", false},
854 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
855 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
856 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
857 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
859 // Possible loops.
860 {&loop1, &loop1, true},
861 {&loop1, &loop2, true},
862 {&loopy1, &loopy1, true},
863 {&loopy1, &loopy2, true},
866 func TestDeepEqual(t *testing.T) {
867 for _, test := range deepEqualTests {
868 if test.b == (self{}) {
869 test.b = test.a
871 if r := DeepEqual(test.a, test.b); r != test.eq {
872 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
877 func TestTypeOf(t *testing.T) {
878 // Special case for nil
879 if typ := TypeOf(nil); typ != nil {
880 t.Errorf("expected nil type for nil value; got %v", typ)
882 for _, test := range deepEqualTests {
883 v := ValueOf(test.a)
884 if !v.IsValid() {
885 continue
887 typ := TypeOf(test.a)
888 if typ != v.Type() {
889 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
894 type Recursive struct {
895 x int
896 r *Recursive
899 func TestDeepEqualRecursiveStruct(t *testing.T) {
900 a, b := new(Recursive), new(Recursive)
901 *a = Recursive{12, a}
902 *b = Recursive{12, b}
903 if !DeepEqual(a, b) {
904 t.Error("DeepEqual(recursive same) = false, want true")
908 type _Complex struct {
909 a int
910 b [3]*_Complex
911 c *string
912 d map[float64]float64
915 func TestDeepEqualComplexStruct(t *testing.T) {
916 m := make(map[float64]float64)
917 stra, strb := "hello", "hello"
918 a, b := new(_Complex), new(_Complex)
919 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
920 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
921 if !DeepEqual(a, b) {
922 t.Error("DeepEqual(complex same) = false, want true")
926 func TestDeepEqualComplexStructInequality(t *testing.T) {
927 m := make(map[float64]float64)
928 stra, strb := "hello", "helloo" // Difference is here
929 a, b := new(_Complex), new(_Complex)
930 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
931 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
932 if DeepEqual(a, b) {
933 t.Error("DeepEqual(complex different) = true, want false")
937 type UnexpT struct {
938 m map[int]int
941 func TestDeepEqualUnexportedMap(t *testing.T) {
942 // Check that DeepEqual can look at unexported fields.
943 x1 := UnexpT{map[int]int{1: 2}}
944 x2 := UnexpT{map[int]int{1: 2}}
945 if !DeepEqual(&x1, &x2) {
946 t.Error("DeepEqual(x1, x2) = false, want true")
949 y1 := UnexpT{map[int]int{2: 3}}
950 if DeepEqual(&x1, &y1) {
951 t.Error("DeepEqual(x1, y1) = true, want false")
955 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
956 s := ValueOf(x)
957 f := s.Type().Field(1)
958 if f.Offset != offs {
959 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
963 // Check that structure alignment & offsets viewed through reflect agree with those
964 // from the compiler itself.
965 func TestAlignment(t *testing.T) {
966 type T1inner struct {
967 a int
969 type T1 struct {
970 T1inner
971 f int
973 type T2inner struct {
974 a, b int
976 type T2 struct {
977 T2inner
978 f int
981 x := T1{T1inner{2}, 17}
982 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
984 x1 := T2{T2inner{2, 3}, 17}
985 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
988 func Nil(a interface{}, t *testing.T) {
989 n := ValueOf(a).Field(0)
990 if !n.IsNil() {
991 t.Errorf("%v should be nil", a)
995 func NotNil(a interface{}, t *testing.T) {
996 n := ValueOf(a).Field(0)
997 if n.IsNil() {
998 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
1002 func TestIsNil(t *testing.T) {
1003 // These implement IsNil.
1004 // Wrap in extra struct to hide interface type.
1005 doNil := []interface{}{
1006 struct{ x *int }{},
1007 struct{ x interface{} }{},
1008 struct{ x map[string]int }{},
1009 struct{ x func() bool }{},
1010 struct{ x chan int }{},
1011 struct{ x []string }{},
1013 for _, ts := range doNil {
1014 ty := TypeOf(ts).Field(0).Type
1015 v := Zero(ty)
1016 v.IsNil() // panics if not okay to call
1019 // Check the implementations
1020 var pi struct {
1021 x *int
1023 Nil(pi, t)
1024 pi.x = new(int)
1025 NotNil(pi, t)
1027 var si struct {
1028 x []int
1030 Nil(si, t)
1031 si.x = make([]int, 10)
1032 NotNil(si, t)
1034 var ci struct {
1035 x chan int
1037 Nil(ci, t)
1038 ci.x = make(chan int)
1039 NotNil(ci, t)
1041 var mi struct {
1042 x map[int]int
1044 Nil(mi, t)
1045 mi.x = make(map[int]int)
1046 NotNil(mi, t)
1048 var ii struct {
1049 x interface{}
1051 Nil(ii, t)
1052 ii.x = 2
1053 NotNil(ii, t)
1055 var fi struct {
1056 x func(t *testing.T)
1058 Nil(fi, t)
1059 fi.x = TestIsNil
1060 NotNil(fi, t)
1063 func TestInterfaceExtraction(t *testing.T) {
1064 var s struct {
1065 W io.Writer
1068 s.W = os.Stdout
1069 v := Indirect(ValueOf(&s)).Field(0).Interface()
1070 if v != s.W.(interface{}) {
1071 t.Error("Interface() on interface: ", v, s.W)
1075 func TestNilPtrValueSub(t *testing.T) {
1076 var pi *int
1077 if pv := ValueOf(pi); pv.Elem().IsValid() {
1078 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
1082 func TestMap(t *testing.T) {
1083 m := map[string]int{"a": 1, "b": 2}
1084 mv := ValueOf(m)
1085 if n := mv.Len(); n != len(m) {
1086 t.Errorf("Len = %d, want %d", n, len(m))
1088 keys := mv.MapKeys()
1089 newmap := MakeMap(mv.Type())
1090 for k, v := range m {
1091 // Check that returned Keys match keys in range.
1092 // These aren't required to be in the same order.
1093 seen := false
1094 for _, kv := range keys {
1095 if kv.String() == k {
1096 seen = true
1097 break
1100 if !seen {
1101 t.Errorf("Missing key %q", k)
1104 // Check that value lookup is correct.
1105 vv := mv.MapIndex(ValueOf(k))
1106 if vi := vv.Int(); vi != int64(v) {
1107 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
1110 // Copy into new map.
1111 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
1113 vv := mv.MapIndex(ValueOf("not-present"))
1114 if vv.IsValid() {
1115 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
1118 newm := newmap.Interface().(map[string]int)
1119 if len(newm) != len(m) {
1120 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
1123 for k, v := range newm {
1124 mv, ok := m[k]
1125 if mv != v {
1126 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
1130 newmap.SetMapIndex(ValueOf("a"), Value{})
1131 v, ok := newm["a"]
1132 if ok {
1133 t.Errorf("newm[\"a\"] = %d after delete", v)
1136 mv = ValueOf(&m).Elem()
1137 mv.Set(Zero(mv.Type()))
1138 if m != nil {
1139 t.Errorf("mv.Set(nil) failed")
1143 func TestNilMap(t *testing.T) {
1144 var m map[string]int
1145 mv := ValueOf(m)
1146 keys := mv.MapKeys()
1147 if len(keys) != 0 {
1148 t.Errorf(">0 keys for nil map: %v", keys)
1151 // Check that value for missing key is zero.
1152 x := mv.MapIndex(ValueOf("hello"))
1153 if x.Kind() != Invalid {
1154 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1157 // Check big value too.
1158 var mbig map[string][10 << 20]byte
1159 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
1160 if x.Kind() != Invalid {
1161 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
1164 // Test that deletes from a nil map succeed.
1165 mv.SetMapIndex(ValueOf("hi"), Value{})
1168 func TestChan(t *testing.T) {
1169 for loop := 0; loop < 2; loop++ {
1170 var c chan int
1171 var cv Value
1173 // check both ways to allocate channels
1174 switch loop {
1175 case 1:
1176 c = make(chan int, 1)
1177 cv = ValueOf(c)
1178 case 0:
1179 cv = MakeChan(TypeOf(c), 1)
1180 c = cv.Interface().(chan int)
1183 // Send
1184 cv.Send(ValueOf(2))
1185 if i := <-c; i != 2 {
1186 t.Errorf("reflect Send 2, native recv %d", i)
1189 // Recv
1190 c <- 3
1191 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1192 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1195 // TryRecv fail
1196 val, ok := cv.TryRecv()
1197 if val.IsValid() || ok {
1198 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1201 // TryRecv success
1202 c <- 4
1203 val, ok = cv.TryRecv()
1204 if !val.IsValid() {
1205 t.Errorf("TryRecv on ready chan got nil")
1206 } else if i := val.Int(); i != 4 || !ok {
1207 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1210 // TrySend fail
1211 c <- 100
1212 ok = cv.TrySend(ValueOf(5))
1213 i := <-c
1214 if ok {
1215 t.Errorf("TrySend on full chan succeeded: value %d", i)
1218 // TrySend success
1219 ok = cv.TrySend(ValueOf(6))
1220 if !ok {
1221 t.Errorf("TrySend on empty chan failed")
1222 select {
1223 case x := <-c:
1224 t.Errorf("TrySend failed but it did send %d", x)
1225 default:
1227 } else {
1228 if i = <-c; i != 6 {
1229 t.Errorf("TrySend 6, recv %d", i)
1233 // Close
1234 c <- 123
1235 cv.Close()
1236 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1237 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1239 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1240 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1244 // check creation of unbuffered channel
1245 var c chan int
1246 cv := MakeChan(TypeOf(c), 0)
1247 c = cv.Interface().(chan int)
1248 if cv.TrySend(ValueOf(7)) {
1249 t.Errorf("TrySend on sync chan succeeded")
1251 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1252 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1255 // len/cap
1256 cv = MakeChan(TypeOf(c), 10)
1257 c = cv.Interface().(chan int)
1258 for i := 0; i < 3; i++ {
1259 c <- i
1261 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1262 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1266 // caseInfo describes a single case in a select test.
1267 type caseInfo struct {
1268 desc string
1269 canSelect bool
1270 recv Value
1271 closed bool
1272 helper func()
1273 panic bool
1276 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1278 func TestSelect(t *testing.T) {
1279 selectWatch.once.Do(func() { go selectWatcher() })
1281 var x exhaustive
1282 nch := 0
1283 newop := func(n int, cap int) (ch, val Value) {
1284 nch++
1285 if nch%101%2 == 1 {
1286 c := make(chan int, cap)
1287 ch = ValueOf(c)
1288 val = ValueOf(n)
1289 } else {
1290 c := make(chan string, cap)
1291 ch = ValueOf(c)
1292 val = ValueOf(fmt.Sprint(n))
1294 return
1297 for n := 0; x.Next(); n++ {
1298 if testing.Short() && n >= 1000 {
1299 break
1301 if n >= 100000 && !*allselect {
1302 break
1304 if n%100000 == 0 && testing.Verbose() {
1305 println("TestSelect", n)
1307 var cases []SelectCase
1308 var info []caseInfo
1310 // Ready send.
1311 if x.Maybe() {
1312 ch, val := newop(len(cases), 1)
1313 cases = append(cases, SelectCase{
1314 Dir: SelectSend,
1315 Chan: ch,
1316 Send: val,
1318 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1321 // Ready recv.
1322 if x.Maybe() {
1323 ch, val := newop(len(cases), 1)
1324 ch.Send(val)
1325 cases = append(cases, SelectCase{
1326 Dir: SelectRecv,
1327 Chan: ch,
1329 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1332 // Blocking send.
1333 if x.Maybe() {
1334 ch, val := newop(len(cases), 0)
1335 cases = append(cases, SelectCase{
1336 Dir: SelectSend,
1337 Chan: ch,
1338 Send: val,
1340 // Let it execute?
1341 if x.Maybe() {
1342 f := func() { ch.Recv() }
1343 info = append(info, caseInfo{desc: "blocking send", helper: f})
1344 } else {
1345 info = append(info, caseInfo{desc: "blocking send"})
1349 // Blocking recv.
1350 if x.Maybe() {
1351 ch, val := newop(len(cases), 0)
1352 cases = append(cases, SelectCase{
1353 Dir: SelectRecv,
1354 Chan: ch,
1356 // Let it execute?
1357 if x.Maybe() {
1358 f := func() { ch.Send(val) }
1359 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1360 } else {
1361 info = append(info, caseInfo{desc: "blocking recv"})
1365 // Zero Chan send.
1366 if x.Maybe() {
1367 // Maybe include value to send.
1368 var val Value
1369 if x.Maybe() {
1370 val = ValueOf(100)
1372 cases = append(cases, SelectCase{
1373 Dir: SelectSend,
1374 Send: val,
1376 info = append(info, caseInfo{desc: "zero Chan send"})
1379 // Zero Chan receive.
1380 if x.Maybe() {
1381 cases = append(cases, SelectCase{
1382 Dir: SelectRecv,
1384 info = append(info, caseInfo{desc: "zero Chan recv"})
1387 // nil Chan send.
1388 if x.Maybe() {
1389 cases = append(cases, SelectCase{
1390 Dir: SelectSend,
1391 Chan: ValueOf((chan int)(nil)),
1392 Send: ValueOf(101),
1394 info = append(info, caseInfo{desc: "nil Chan send"})
1397 // nil Chan recv.
1398 if x.Maybe() {
1399 cases = append(cases, SelectCase{
1400 Dir: SelectRecv,
1401 Chan: ValueOf((chan int)(nil)),
1403 info = append(info, caseInfo{desc: "nil Chan recv"})
1406 // closed Chan send.
1407 if x.Maybe() {
1408 ch := make(chan int)
1409 close(ch)
1410 cases = append(cases, SelectCase{
1411 Dir: SelectSend,
1412 Chan: ValueOf(ch),
1413 Send: ValueOf(101),
1415 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1418 // closed Chan recv.
1419 if x.Maybe() {
1420 ch, val := newop(len(cases), 0)
1421 ch.Close()
1422 val = Zero(val.Type())
1423 cases = append(cases, SelectCase{
1424 Dir: SelectRecv,
1425 Chan: ch,
1427 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1430 var helper func() // goroutine to help the select complete
1432 // Add default? Must be last case here, but will permute.
1433 // Add the default if the select would otherwise
1434 // block forever, and maybe add it anyway.
1435 numCanSelect := 0
1436 canProceed := false
1437 canBlock := true
1438 canPanic := false
1439 helpers := []int{}
1440 for i, c := range info {
1441 if c.canSelect {
1442 canProceed = true
1443 canBlock = false
1444 numCanSelect++
1445 if c.panic {
1446 canPanic = true
1448 } else if c.helper != nil {
1449 canProceed = true
1450 helpers = append(helpers, i)
1453 if !canProceed || x.Maybe() {
1454 cases = append(cases, SelectCase{
1455 Dir: SelectDefault,
1457 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1458 numCanSelect++
1459 } else if canBlock {
1460 // Select needs to communicate with another goroutine.
1461 cas := &info[helpers[x.Choose(len(helpers))]]
1462 helper = cas.helper
1463 cas.canSelect = true
1464 numCanSelect++
1467 // Permute cases and case info.
1468 // Doing too much here makes the exhaustive loop
1469 // too exhausting, so just do two swaps.
1470 for loop := 0; loop < 2; loop++ {
1471 i := x.Choose(len(cases))
1472 j := x.Choose(len(cases))
1473 cases[i], cases[j] = cases[j], cases[i]
1474 info[i], info[j] = info[j], info[i]
1477 if helper != nil {
1478 // We wait before kicking off a goroutine to satisfy a blocked select.
1479 // The pause needs to be big enough to let the select block before
1480 // we run the helper, but if we lose that race once in a while it's okay: the
1481 // select will just proceed immediately. Not a big deal.
1482 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1483 pause := 10 * time.Microsecond
1484 if testing.Short() {
1485 pause = 100 * time.Microsecond
1487 time.AfterFunc(pause, helper)
1490 // Run select.
1491 i, recv, recvOK, panicErr := runSelect(cases, info)
1492 if panicErr != nil && !canPanic {
1493 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1495 if panicErr == nil && canPanic && numCanSelect == 1 {
1496 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1498 if panicErr != nil {
1499 continue
1502 cas := info[i]
1503 if !cas.canSelect {
1504 recvStr := ""
1505 if recv.IsValid() {
1506 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1508 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1509 continue
1511 if cas.panic {
1512 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1513 continue
1516 if cases[i].Dir == SelectRecv {
1517 if !recv.IsValid() {
1518 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1520 if !cas.recv.IsValid() {
1521 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1523 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1524 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1525 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1527 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1529 } else {
1530 if recv.IsValid() || recvOK {
1531 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1537 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1538 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1539 // an error describing the select and panics the entire test binary.
1540 var selectWatch struct {
1541 sync.Mutex
1542 once sync.Once
1543 now time.Time
1544 info []caseInfo
1547 func selectWatcher() {
1548 for {
1549 time.Sleep(1 * time.Second)
1550 selectWatch.Lock()
1551 if selectWatch.info != nil && time.Since(selectWatch.now) > 10*time.Second {
1552 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1553 panic("select stuck")
1555 selectWatch.Unlock()
1559 // runSelect runs a single select test.
1560 // It returns the values returned by Select but also returns
1561 // a panic value if the Select panics.
1562 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1563 defer func() {
1564 panicErr = recover()
1566 selectWatch.Lock()
1567 selectWatch.info = nil
1568 selectWatch.Unlock()
1571 selectWatch.Lock()
1572 selectWatch.now = time.Now()
1573 selectWatch.info = info
1574 selectWatch.Unlock()
1576 chosen, recv, recvOK = Select(cases)
1577 return
1580 // fmtSelect formats the information about a single select test.
1581 func fmtSelect(info []caseInfo) string {
1582 var buf bytes.Buffer
1583 fmt.Fprintf(&buf, "\nselect {\n")
1584 for i, cas := range info {
1585 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1586 if cas.recv.IsValid() {
1587 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1589 if cas.canSelect {
1590 fmt.Fprintf(&buf, " canselect")
1592 if cas.panic {
1593 fmt.Fprintf(&buf, " panic")
1595 fmt.Fprintf(&buf, "\n")
1597 fmt.Fprintf(&buf, "}")
1598 return buf.String()
1601 type two [2]uintptr
1603 // Difficult test for function call because of
1604 // implicit padding between arguments.
1605 func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
1606 return b, c, d, e, f, g, h
1609 func TestFunc(t *testing.T) {
1610 ret := ValueOf(dummy).Call([]Value{
1611 ValueOf(byte(10)),
1612 ValueOf(20),
1613 ValueOf(byte(30)),
1614 ValueOf(two{40, 50}),
1615 ValueOf(byte(60)),
1616 ValueOf(float32(70)),
1617 ValueOf(byte(80)),
1619 if len(ret) != 7 {
1620 t.Fatalf("Call returned %d values, want 7", len(ret))
1623 i := byte(ret[0].Uint())
1624 j := int(ret[1].Int())
1625 k := byte(ret[2].Uint())
1626 l := ret[3].Interface().(two)
1627 m := byte(ret[4].Uint())
1628 n := float32(ret[5].Float())
1629 o := byte(ret[6].Uint())
1631 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1632 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1635 for i, v := range ret {
1636 if v.CanAddr() {
1637 t.Errorf("result %d is addressable", i)
1642 func TestCallConvert(t *testing.T) {
1643 v := ValueOf(new(io.ReadWriter)).Elem()
1644 f := ValueOf(func(r io.Reader) io.Reader { return r })
1645 out := f.Call([]Value{v})
1646 if len(out) != 1 || out[0].Type() != TypeOf(new(io.Reader)).Elem() || !out[0].IsNil() {
1647 t.Errorf("expected [nil], got %v", out)
1651 type emptyStruct struct{}
1653 type nonEmptyStruct struct {
1654 member int
1657 func returnEmpty() emptyStruct {
1658 return emptyStruct{}
1661 func takesEmpty(e emptyStruct) {
1664 func returnNonEmpty(i int) nonEmptyStruct {
1665 return nonEmptyStruct{member: i}
1668 func takesNonEmpty(n nonEmptyStruct) int {
1669 return n.member
1672 func TestCallWithStruct(t *testing.T) {
1673 r := ValueOf(returnEmpty).Call(nil)
1674 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1675 t.Errorf("returning empty struct returned %#v instead", r)
1677 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1678 if len(r) != 0 {
1679 t.Errorf("takesEmpty returned values: %#v", r)
1681 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1682 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1683 t.Errorf("returnNonEmpty returned %#v", r)
1685 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1686 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1687 t.Errorf("takesNonEmpty returned %#v", r)
1691 func TestCallReturnsEmpty(t *testing.T) {
1692 if runtime.Compiler == "gccgo" {
1693 t.Skip("skipping on gccgo: imprecise stack can keep i live")
1695 // Issue 21717: past-the-end pointer write in Call with
1696 // nonzero-sized frame and zero-sized return value.
1697 runtime.GC()
1698 var finalized uint32
1699 f := func() (emptyStruct, *int) {
1700 i := new(int)
1701 runtime.SetFinalizer(i, func(*int) { atomic.StoreUint32(&finalized, 1) })
1702 return emptyStruct{}, i
1704 v := ValueOf(f).Call(nil)[0] // out[0] should not alias out[1]'s memory, so the finalizer should run.
1705 timeout := time.After(5 * time.Second)
1706 for atomic.LoadUint32(&finalized) == 0 {
1707 select {
1708 case <-timeout:
1709 t.Fatal("finalizer did not run")
1710 default:
1712 runtime.Gosched()
1713 runtime.GC()
1715 runtime.KeepAlive(v)
1718 func BenchmarkCall(b *testing.B) {
1719 fv := ValueOf(func(a, b string) {})
1720 b.ReportAllocs()
1721 b.RunParallel(func(pb *testing.PB) {
1722 args := []Value{ValueOf("a"), ValueOf("b")}
1723 for pb.Next() {
1724 fv.Call(args)
1729 func BenchmarkCallArgCopy(b *testing.B) {
1730 byteArray := func(n int) Value {
1731 return Zero(ArrayOf(n, TypeOf(byte(0))))
1733 sizes := [...]struct {
1734 fv Value
1735 arg Value
1737 {ValueOf(func(a [128]byte) {}), byteArray(128)},
1738 {ValueOf(func(a [256]byte) {}), byteArray(256)},
1739 {ValueOf(func(a [1024]byte) {}), byteArray(1024)},
1740 {ValueOf(func(a [4096]byte) {}), byteArray(4096)},
1741 {ValueOf(func(a [65536]byte) {}), byteArray(65536)},
1743 for _, size := range sizes {
1744 bench := func(b *testing.B) {
1745 args := []Value{size.arg}
1746 b.SetBytes(int64(size.arg.Len()))
1747 b.ResetTimer()
1748 b.RunParallel(func(pb *testing.PB) {
1749 for pb.Next() {
1750 size.fv.Call(args)
1754 name := fmt.Sprintf("size=%v", size.arg.Len())
1755 b.Run(name, bench)
1759 func TestMakeFunc(t *testing.T) {
1760 f := dummy
1761 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1762 ValueOf(&f).Elem().Set(fv)
1764 // Call g with small arguments so that there is
1765 // something predictable (and different from the
1766 // correct results) in those positions on the stack.
1767 g := dummy
1768 g(1, 2, 3, two{4, 5}, 6, 7, 8)
1770 // Call constructed function f.
1771 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1772 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1773 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1777 func TestMakeFuncInterface(t *testing.T) {
1778 fn := func(i int) int { return i }
1779 incr := func(in []Value) []Value {
1780 return []Value{ValueOf(int(in[0].Int() + 1))}
1782 fv := MakeFunc(TypeOf(fn), incr)
1783 ValueOf(&fn).Elem().Set(fv)
1784 if r := fn(2); r != 3 {
1785 t.Errorf("Call returned %d, want 3", r)
1787 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1788 t.Errorf("Call returned %d, want 15", r)
1790 if r := fv.Interface().(func(int) int)(26); r != 27 {
1791 t.Errorf("Call returned %d, want 27", r)
1795 func TestMakeFuncVariadic(t *testing.T) {
1796 // Test that variadic arguments are packed into a slice and passed as last arg
1797 fn := func(_ int, is ...int) []int { return nil }
1798 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
1799 ValueOf(&fn).Elem().Set(fv)
1801 r := fn(1, 2, 3)
1802 if r[0] != 2 || r[1] != 3 {
1803 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1806 r = fn(1, []int{2, 3}...)
1807 if r[0] != 2 || r[1] != 3 {
1808 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1811 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
1812 if r[0] != 2 || r[1] != 3 {
1813 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1816 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1817 if r[0] != 2 || r[1] != 3 {
1818 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1821 f := fv.Interface().(func(int, ...int) []int)
1823 r = f(1, 2, 3)
1824 if r[0] != 2 || r[1] != 3 {
1825 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1827 r = f(1, []int{2, 3}...)
1828 if r[0] != 2 || r[1] != 3 {
1829 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1833 type Point struct {
1834 x, y int
1837 // This will be index 0.
1838 func (p Point) AnotherMethod(scale int) int {
1839 return -1
1842 // This will be index 1.
1843 func (p Point) Dist(scale int) int {
1844 //println("Point.Dist", p.x, p.y, scale)
1845 return p.x*p.x*scale + p.y*p.y*scale
1848 // This will be index 2.
1849 func (p Point) GCMethod(k int) int {
1850 runtime.GC()
1851 return k + p.x
1854 // This will be index 3.
1855 func (p Point) NoArgs() {
1856 // Exercise no-argument/no-result paths.
1859 // This will be index 4.
1860 func (p Point) TotalDist(points ...Point) int {
1861 tot := 0
1862 for _, q := range points {
1863 dx := q.x - p.x
1864 dy := q.y - p.y
1865 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
1868 return tot
1871 func TestMethod(t *testing.T) {
1872 // Non-curried method of type.
1873 p := Point{3, 4}
1874 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1875 if i != 250 {
1876 t.Errorf("Type Method returned %d; want 250", i)
1879 m, ok := TypeOf(p).MethodByName("Dist")
1880 if !ok {
1881 t.Fatalf("method by name failed")
1883 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1884 if i != 275 {
1885 t.Errorf("Type MethodByName returned %d; want 275", i)
1888 m, ok = TypeOf(p).MethodByName("NoArgs")
1889 if !ok {
1890 t.Fatalf("method by name failed")
1892 n := len(m.Func.Call([]Value{ValueOf(p)}))
1893 if n != 0 {
1894 t.Errorf("NoArgs returned %d values; want 0", n)
1897 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1898 if i != 300 {
1899 t.Errorf("Pointer Type Method returned %d; want 300", i)
1902 m, ok = TypeOf(&p).MethodByName("Dist")
1903 if !ok {
1904 t.Fatalf("ptr method by name failed")
1906 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1907 if i != 325 {
1908 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
1911 m, ok = TypeOf(&p).MethodByName("NoArgs")
1912 if !ok {
1913 t.Fatalf("method by name failed")
1915 n = len(m.Func.Call([]Value{ValueOf(&p)}))
1916 if n != 0 {
1917 t.Errorf("NoArgs returned %d values; want 0", n)
1920 // Curried method of value.
1921 tfunc := TypeOf((func(int) int)(nil))
1922 v := ValueOf(p).Method(1)
1923 if tt := v.Type(); tt != tfunc {
1924 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1926 i = v.Call([]Value{ValueOf(14)})[0].Int()
1927 if i != 350 {
1928 t.Errorf("Value Method returned %d; want 350", i)
1930 v = ValueOf(p).MethodByName("Dist")
1931 if tt := v.Type(); tt != tfunc {
1932 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1934 i = v.Call([]Value{ValueOf(15)})[0].Int()
1935 if i != 375 {
1936 t.Errorf("Value MethodByName returned %d; want 375", i)
1938 v = ValueOf(p).MethodByName("NoArgs")
1939 v.Call(nil)
1941 // Curried method of pointer.
1942 v = ValueOf(&p).Method(1)
1943 if tt := v.Type(); tt != tfunc {
1944 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1946 i = v.Call([]Value{ValueOf(16)})[0].Int()
1947 if i != 400 {
1948 t.Errorf("Pointer Value Method returned %d; want 400", i)
1950 v = ValueOf(&p).MethodByName("Dist")
1951 if tt := v.Type(); tt != tfunc {
1952 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1954 i = v.Call([]Value{ValueOf(17)})[0].Int()
1955 if i != 425 {
1956 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1958 v = ValueOf(&p).MethodByName("NoArgs")
1959 v.Call(nil)
1961 // Curried method of interface value.
1962 // Have to wrap interface value in a struct to get at it.
1963 // Passing it to ValueOf directly would
1964 // access the underlying Point, not the interface.
1965 var x interface {
1966 Dist(int) int
1967 } = p
1968 pv := ValueOf(&x).Elem()
1969 v = pv.Method(0)
1970 if tt := v.Type(); tt != tfunc {
1971 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1973 i = v.Call([]Value{ValueOf(18)})[0].Int()
1974 if i != 450 {
1975 t.Errorf("Interface Method returned %d; want 450", i)
1977 v = pv.MethodByName("Dist")
1978 if tt := v.Type(); tt != tfunc {
1979 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1981 i = v.Call([]Value{ValueOf(19)})[0].Int()
1982 if i != 475 {
1983 t.Errorf("Interface MethodByName returned %d; want 475", i)
1987 func TestMethodValue(t *testing.T) {
1988 p := Point{3, 4}
1989 var i int64
1991 // Curried method of value.
1992 tfunc := TypeOf((func(int) int)(nil))
1993 v := ValueOf(p).Method(1)
1994 if tt := v.Type(); tt != tfunc {
1995 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1997 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1998 if i != 250 {
1999 t.Errorf("Value Method returned %d; want 250", i)
2001 v = ValueOf(p).MethodByName("Dist")
2002 if tt := v.Type(); tt != tfunc {
2003 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
2005 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
2006 if i != 275 {
2007 t.Errorf("Value MethodByName returned %d; want 275", i)
2009 v = ValueOf(p).MethodByName("NoArgs")
2010 ValueOf(v.Interface()).Call(nil)
2011 v.Interface().(func())()
2013 // Curried method of pointer.
2014 v = ValueOf(&p).Method(1)
2015 if tt := v.Type(); tt != tfunc {
2016 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
2018 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
2019 if i != 300 {
2020 t.Errorf("Pointer Value Method returned %d; want 300", i)
2022 v = ValueOf(&p).MethodByName("Dist")
2023 if tt := v.Type(); tt != tfunc {
2024 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2026 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
2027 if i != 325 {
2028 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
2030 v = ValueOf(&p).MethodByName("NoArgs")
2031 ValueOf(v.Interface()).Call(nil)
2032 v.Interface().(func())()
2034 // Curried method of pointer to pointer.
2035 pp := &p
2036 v = ValueOf(&pp).Elem().Method(1)
2037 if tt := v.Type(); tt != tfunc {
2038 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
2040 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
2041 if i != 350 {
2042 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
2044 v = ValueOf(&pp).Elem().MethodByName("Dist")
2045 if tt := v.Type(); tt != tfunc {
2046 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
2048 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
2049 if i != 375 {
2050 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
2053 // Curried method of interface value.
2054 // Have to wrap interface value in a struct to get at it.
2055 // Passing it to ValueOf directly would
2056 // access the underlying Point, not the interface.
2057 var s = struct {
2058 X interface {
2059 Dist(int) int
2061 }{p}
2062 pv := ValueOf(s).Field(0)
2063 v = pv.Method(0)
2064 if tt := v.Type(); tt != tfunc {
2065 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
2067 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
2068 if i != 400 {
2069 t.Errorf("Interface Method returned %d; want 400", i)
2071 v = pv.MethodByName("Dist")
2072 if tt := v.Type(); tt != tfunc {
2073 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
2075 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
2076 if i != 425 {
2077 t.Errorf("Interface MethodByName returned %d; want 425", i)
2081 func TestVariadicMethodValue(t *testing.T) {
2082 p := Point{3, 4}
2083 points := []Point{{20, 21}, {22, 23}, {24, 25}}
2084 want := int64(p.TotalDist(points[0], points[1], points[2]))
2086 // Curried method of value.
2087 tfunc := TypeOf((func(...Point) int)(nil))
2088 v := ValueOf(p).Method(4)
2089 if tt := v.Type(); tt != tfunc {
2090 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
2092 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
2093 if i != want {
2094 t.Errorf("Variadic Method returned %d; want %d", i, want)
2096 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
2097 if i != want {
2098 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
2101 f := v.Interface().(func(...Point) int)
2102 i = int64(f(points[0], points[1], points[2]))
2103 if i != want {
2104 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
2106 i = int64(f(points...))
2107 if i != want {
2108 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
2112 // Reflect version of $GOROOT/test/method5.go
2114 // Concrete types implementing M method.
2115 // Smaller than a word, word-sized, larger than a word.
2116 // Value and pointer receivers.
2118 type Tinter interface {
2119 M(int, byte) (byte, int)
2122 type Tsmallv byte
2124 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2126 type Tsmallp byte
2128 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2130 type Twordv uintptr
2132 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
2134 type Twordp uintptr
2136 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
2138 type Tbigv [2]uintptr
2140 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
2142 type Tbigp [2]uintptr
2144 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
2146 type tinter interface {
2147 m(int, byte) (byte, int)
2150 // Embedding via pointer.
2152 type Tm1 struct {
2156 type Tm2 struct {
2157 *Tm3
2160 type Tm3 struct {
2161 *Tm4
2164 type Tm4 struct {
2167 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
2169 func TestMethod5(t *testing.T) {
2170 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
2171 b, x := f(1000, 99)
2172 if b != 99 || x != 1000+inc {
2173 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2177 CheckV := func(name string, i Value, inc int) {
2178 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
2179 b := bx[0].Interface()
2180 x := bx[1].Interface()
2181 if b != byte(99) || x != 1000+inc {
2182 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
2185 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
2188 var TinterType = TypeOf(new(Tinter)).Elem()
2190 CheckI := func(name string, i interface{}, inc int) {
2191 v := ValueOf(i)
2192 CheckV(name, v, inc)
2193 CheckV("(i="+name+")", v.Convert(TinterType), inc)
2196 sv := Tsmallv(1)
2197 CheckI("sv", sv, 1)
2198 CheckI("&sv", &sv, 1)
2200 sp := Tsmallp(2)
2201 CheckI("&sp", &sp, 2)
2203 wv := Twordv(3)
2204 CheckI("wv", wv, 3)
2205 CheckI("&wv", &wv, 3)
2207 wp := Twordp(4)
2208 CheckI("&wp", &wp, 4)
2210 bv := Tbigv([2]uintptr{5, 6})
2211 CheckI("bv", bv, 11)
2212 CheckI("&bv", &bv, 11)
2214 bp := Tbigp([2]uintptr{7, 8})
2215 CheckI("&bp", &bp, 15)
2217 t4 := Tm4{}
2218 t3 := Tm3{&t4}
2219 t2 := Tm2{&t3}
2220 t1 := Tm1{t2}
2221 CheckI("t4", t4, 40)
2222 CheckI("&t4", &t4, 40)
2223 CheckI("t3", t3, 40)
2224 CheckI("&t3", &t3, 40)
2225 CheckI("t2", t2, 40)
2226 CheckI("&t2", &t2, 40)
2227 CheckI("t1", t1, 40)
2228 CheckI("&t1", &t1, 40)
2230 var tnil Tinter
2231 vnil := ValueOf(&tnil).Elem()
2232 shouldPanic(func() { vnil.Method(0) })
2235 func TestInterfaceSet(t *testing.T) {
2236 p := &Point{3, 4}
2238 var s struct {
2239 I interface{}
2240 P interface {
2241 Dist(int) int
2244 sv := ValueOf(&s).Elem()
2245 sv.Field(0).Set(ValueOf(p))
2246 if q := s.I.(*Point); q != p {
2247 t.Errorf("i: have %p want %p", q, p)
2250 pv := sv.Field(1)
2251 pv.Set(ValueOf(p))
2252 if q := s.P.(*Point); q != p {
2253 t.Errorf("i: have %p want %p", q, p)
2256 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
2257 if i != 250 {
2258 t.Errorf("Interface Method returned %d; want 250", i)
2262 type T1 struct {
2263 a string
2267 func TestAnonymousFields(t *testing.T) {
2268 var field StructField
2269 var ok bool
2270 var t1 T1
2271 type1 := TypeOf(t1)
2272 if field, ok = type1.FieldByName("int"); !ok {
2273 t.Fatal("no field 'int'")
2275 if field.Index[0] != 1 {
2276 t.Error("field index should be 1; is", field.Index)
2280 type FTest struct {
2281 s interface{}
2282 name string
2283 index []int
2284 value int
2287 type D1 struct {
2288 d int
2290 type D2 struct {
2291 d int
2294 type S0 struct {
2295 A, B, C int
2300 type S1 struct {
2301 B int
2305 type S2 struct {
2306 A int
2310 type S1x struct {
2314 type S1y struct {
2318 type S3 struct {
2321 D, E int
2322 *S1y
2325 type S4 struct {
2327 A int
2330 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2331 type S5 struct {
2337 type S6 struct {
2338 X int
2341 type S7 S6
2343 type S8 struct {
2347 type S9 struct {
2348 X int
2349 Y int
2352 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2353 type S10 struct {
2359 type S11 struct {
2363 type S12 struct {
2367 type S13 struct {
2371 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2372 type S14 struct {
2377 type S15 struct {
2381 type S16 struct {
2385 var fieldTests = []FTest{
2386 {struct{}{}, "", nil, 0},
2387 {struct{}{}, "Foo", nil, 0},
2388 {S0{A: 'a'}, "A", []int{0}, 'a'},
2389 {S0{}, "D", nil, 0},
2390 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2391 {S1{B: 'b'}, "B", []int{0}, 'b'},
2392 {S1{}, "S0", []int{1}, 0},
2393 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2394 {S2{A: 'a'}, "A", []int{0}, 'a'},
2395 {S2{}, "S1", []int{1}, 0},
2396 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2397 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2398 {S2{}, "D", nil, 0},
2399 {S3{}, "S1", nil, 0},
2400 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2401 {S3{}, "B", nil, 0},
2402 {S3{D: 'd'}, "D", []int{2}, 0},
2403 {S3{E: 'e'}, "E", []int{3}, 'e'},
2404 {S4{A: 'a'}, "A", []int{1}, 'a'},
2405 {S4{}, "B", nil, 0},
2406 {S5{}, "X", nil, 0},
2407 {S5{}, "Y", []int{2, 0, 1}, 0},
2408 {S10{}, "X", nil, 0},
2409 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2410 {S14{}, "X", nil, 0},
2413 func TestFieldByIndex(t *testing.T) {
2414 for _, test := range fieldTests {
2415 s := TypeOf(test.s)
2416 f := s.FieldByIndex(test.index)
2417 if f.Name != "" {
2418 if test.index != nil {
2419 if f.Name != test.name {
2420 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2422 } else {
2423 t.Errorf("%s.%s found", s.Name(), f.Name)
2425 } else if len(test.index) > 0 {
2426 t.Errorf("%s.%s not found", s.Name(), test.name)
2429 if test.value != 0 {
2430 v := ValueOf(test.s).FieldByIndex(test.index)
2431 if v.IsValid() {
2432 if x, ok := v.Interface().(int); ok {
2433 if x != test.value {
2434 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2436 } else {
2437 t.Errorf("%s%v value not an int", s.Name(), test.index)
2439 } else {
2440 t.Errorf("%s%v value not found", s.Name(), test.index)
2446 func TestFieldByName(t *testing.T) {
2447 for _, test := range fieldTests {
2448 s := TypeOf(test.s)
2449 f, found := s.FieldByName(test.name)
2450 if found {
2451 if test.index != nil {
2452 // Verify field depth and index.
2453 if len(f.Index) != len(test.index) {
2454 t.Errorf("%s.%s depth %d; want %d: %v vs %v", s.Name(), test.name, len(f.Index), len(test.index), f.Index, test.index)
2455 } else {
2456 for i, x := range f.Index {
2457 if x != test.index[i] {
2458 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2462 } else {
2463 t.Errorf("%s.%s found", s.Name(), f.Name)
2465 } else if len(test.index) > 0 {
2466 t.Errorf("%s.%s not found", s.Name(), test.name)
2469 if test.value != 0 {
2470 v := ValueOf(test.s).FieldByName(test.name)
2471 if v.IsValid() {
2472 if x, ok := v.Interface().(int); ok {
2473 if x != test.value {
2474 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2476 } else {
2477 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2479 } else {
2480 t.Errorf("%s.%s value not found", s.Name(), test.name)
2486 func TestImportPath(t *testing.T) {
2487 tests := []struct {
2488 t Type
2489 path string
2491 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2492 {TypeOf(int(0)), ""},
2493 {TypeOf(int8(0)), ""},
2494 {TypeOf(int16(0)), ""},
2495 {TypeOf(int32(0)), ""},
2496 {TypeOf(int64(0)), ""},
2497 {TypeOf(uint(0)), ""},
2498 {TypeOf(uint8(0)), ""},
2499 {TypeOf(uint16(0)), ""},
2500 {TypeOf(uint32(0)), ""},
2501 {TypeOf(uint64(0)), ""},
2502 {TypeOf(uintptr(0)), ""},
2503 {TypeOf(float32(0)), ""},
2504 {TypeOf(float64(0)), ""},
2505 {TypeOf(complex64(0)), ""},
2506 {TypeOf(complex128(0)), ""},
2507 {TypeOf(byte(0)), ""},
2508 {TypeOf(rune(0)), ""},
2509 {TypeOf([]byte(nil)), ""},
2510 {TypeOf([]rune(nil)), ""},
2511 {TypeOf(string("")), ""},
2512 {TypeOf((*interface{})(nil)).Elem(), ""},
2513 {TypeOf((*byte)(nil)), ""},
2514 {TypeOf((*rune)(nil)), ""},
2515 {TypeOf((*int64)(nil)), ""},
2516 {TypeOf(map[string]int{}), ""},
2517 {TypeOf((*error)(nil)).Elem(), ""},
2518 {TypeOf((*Point)(nil)), ""},
2519 {TypeOf((*Point)(nil)).Elem(), "reflect_test"},
2521 for _, test := range tests {
2522 if path := test.t.PkgPath(); path != test.path {
2523 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2528 func TestFieldPkgPath(t *testing.T) {
2529 type x int
2530 typ := TypeOf(struct {
2531 Exported string
2532 unexported string
2533 OtherPkgFields
2534 int // issue 21702
2535 *x // issue 21122
2536 }{})
2538 type pkgpathTest struct {
2539 index []int
2540 pkgPath string
2541 anonymous bool
2544 checkPkgPath := func(name string, s []pkgpathTest) {
2545 for _, test := range s {
2546 f := typ.FieldByIndex(test.index)
2547 if got, want := f.PkgPath, test.pkgPath; got != want {
2548 t.Errorf("%s: Field(%d).PkgPath = %q, want %q", name, test.index, got, want)
2550 if got, want := f.Anonymous, test.anonymous; got != want {
2551 t.Errorf("%s: Field(%d).Anonymous = %v, want %v", name, test.index, got, want)
2556 checkPkgPath("testStruct", []pkgpathTest{
2557 {[]int{0}, "", false}, // Exported
2558 {[]int{1}, "reflect_test", false}, // unexported
2559 {[]int{2}, "", true}, // OtherPkgFields
2560 {[]int{2, 0}, "", false}, // OtherExported
2561 {[]int{2, 1}, "reflect", false}, // otherUnexported
2562 {[]int{3}, "reflect_test", true}, // int
2563 {[]int{4}, "reflect_test", true}, // *x
2566 type localOtherPkgFields OtherPkgFields
2567 typ = TypeOf(localOtherPkgFields{})
2568 checkPkgPath("localOtherPkgFields", []pkgpathTest{
2569 {[]int{0}, "", false}, // OtherExported
2570 {[]int{1}, "reflect", false}, // otherUnexported
2574 func TestVariadicType(t *testing.T) {
2575 // Test example from Type documentation.
2576 var f func(x int, y ...float64)
2577 typ := TypeOf(f)
2578 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2579 sl := typ.In(1)
2580 if sl.Kind() == Slice {
2581 if sl.Elem() == TypeOf(0.0) {
2582 // ok
2583 return
2588 // Failed
2589 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2590 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2591 for i := 0; i < typ.NumIn(); i++ {
2592 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2594 t.Error(s)
2597 type inner struct {
2598 x int
2601 type outer struct {
2602 y int
2603 inner
2606 func (*inner) M() {}
2607 func (*outer) M() {}
2609 func TestNestedMethods(t *testing.T) {
2610 t.Skip("fails on gccgo due to function wrappers")
2611 typ := TypeOf((*outer)(nil))
2612 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).M).Pointer() {
2613 t.Errorf("Wrong method table for outer: (M=%p)", (*outer).M)
2614 for i := 0; i < typ.NumMethod(); i++ {
2615 m := typ.Method(i)
2616 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2621 type unexp struct{}
2623 func (*unexp) f() (int32, int8) { return 7, 7 }
2624 func (*unexp) g() (int64, int8) { return 8, 8 }
2626 type unexpI interface {
2627 f() (int32, int8)
2630 var unexpi unexpI = new(unexp)
2632 func TestUnexportedMethods(t *testing.T) {
2633 typ := TypeOf(unexpi)
2635 if got := typ.NumMethod(); got != 0 {
2636 t.Errorf("NumMethod=%d, want 0 satisfied methods", got)
2640 type InnerInt struct {
2641 X int
2644 type OuterInt struct {
2645 Y int
2646 InnerInt
2649 func (i *InnerInt) M() int {
2650 return i.X
2653 func TestEmbeddedMethods(t *testing.T) {
2654 /* This part of the test fails on gccgo due to function wrappers.
2655 typ := TypeOf((*OuterInt)(nil))
2656 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2657 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2658 for i := 0; i < typ.NumMethod(); i++ {
2659 m := typ.Method(i)
2660 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2665 i := &InnerInt{3}
2666 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
2667 t.Errorf("i.M() = %d, want 3", v)
2670 o := &OuterInt{1, InnerInt{2}}
2671 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
2672 t.Errorf("i.M() = %d, want 2", v)
2675 f := (*OuterInt).M
2676 if v := f(o); v != 2 {
2677 t.Errorf("f(o) = %d, want 2", v)
2681 type FuncDDD func(...interface{}) error
2683 func (f FuncDDD) M() {}
2685 func TestNumMethodOnDDD(t *testing.T) {
2686 rv := ValueOf((FuncDDD)(nil))
2687 if n := rv.NumMethod(); n != 1 {
2688 t.Fatalf("NumMethod()=%d, want 1", n)
2692 func TestPtrTo(t *testing.T) {
2693 // This block of code means that the ptrToThis field of the
2694 // reflect data for *unsafe.Pointer is non zero, see
2695 // https://golang.org/issue/19003
2696 var x unsafe.Pointer
2697 var y = &x
2698 var z = &y
2700 var i int
2702 typ := TypeOf(z)
2703 for i = 0; i < 100; i++ {
2704 typ = PtrTo(typ)
2706 for i = 0; i < 100; i++ {
2707 typ = typ.Elem()
2709 if typ != TypeOf(z) {
2710 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(z))
2714 func TestPtrToGC(t *testing.T) {
2715 type T *uintptr
2716 tt := TypeOf(T(nil))
2717 pt := PtrTo(tt)
2718 const n = 100
2719 var x []interface{}
2720 for i := 0; i < n; i++ {
2721 v := New(pt)
2722 p := new(*uintptr)
2723 *p = new(uintptr)
2724 **p = uintptr(i)
2725 v.Elem().Set(ValueOf(p).Convert(pt))
2726 x = append(x, v.Interface())
2728 runtime.GC()
2730 for i, xi := range x {
2731 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2732 if k != uintptr(i) {
2733 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2738 func BenchmarkPtrTo(b *testing.B) {
2739 // Construct a type with a zero ptrToThis.
2740 type T struct{ int }
2741 t := SliceOf(TypeOf(T{}))
2742 ptrToThis := ValueOf(t).Elem().FieldByName("ptrToThis")
2743 if !ptrToThis.IsValid() {
2744 b.Fatalf("%v has no ptrToThis field; was it removed from rtype?", t)
2746 if ptrToThis.Int() != 0 {
2747 b.Fatalf("%v.ptrToThis unexpectedly nonzero", t)
2749 b.ResetTimer()
2751 // Now benchmark calling PtrTo on it: we'll have to hit the ptrMap cache on
2752 // every call.
2753 b.RunParallel(func(pb *testing.PB) {
2754 for pb.Next() {
2755 PtrTo(t)
2760 func TestAddr(t *testing.T) {
2761 var p struct {
2762 X, Y int
2765 v := ValueOf(&p)
2766 v = v.Elem()
2767 v = v.Addr()
2768 v = v.Elem()
2769 v = v.Field(0)
2770 v.SetInt(2)
2771 if p.X != 2 {
2772 t.Errorf("Addr.Elem.Set failed to set value")
2775 // Again but take address of the ValueOf value.
2776 // Exercises generation of PtrTypes not present in the binary.
2777 q := &p
2778 v = ValueOf(&q).Elem()
2779 v = v.Addr()
2780 v = v.Elem()
2781 v = v.Elem()
2782 v = v.Addr()
2783 v = v.Elem()
2784 v = v.Field(0)
2785 v.SetInt(3)
2786 if p.X != 3 {
2787 t.Errorf("Addr.Elem.Set failed to set value")
2790 // Starting without pointer we should get changed value
2791 // in interface.
2792 qq := p
2793 v = ValueOf(&qq).Elem()
2794 v0 := v
2795 v = v.Addr()
2796 v = v.Elem()
2797 v = v.Field(0)
2798 v.SetInt(4)
2799 if p.X != 3 { // should be unchanged from last time
2800 t.Errorf("somehow value Set changed original p")
2802 p = v0.Interface().(struct {
2803 X, Y int
2805 if p.X != 4 {
2806 t.Errorf("Addr.Elem.Set valued to set value in top value")
2809 // Verify that taking the address of a type gives us a pointer
2810 // which we can convert back using the usual interface
2811 // notation.
2812 var s struct {
2813 B *bool
2815 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2816 *(ps.(**bool)) = new(bool)
2817 if s.B == nil {
2818 t.Errorf("Addr.Interface direct assignment failed")
2822 /* gccgo does do allocations here.
2824 func noAlloc(t *testing.T, n int, f func(int)) {
2825 if testing.Short() {
2826 t.Skip("skipping malloc count in short mode")
2828 if runtime.GOMAXPROCS(0) > 1 {
2829 t.Skip("skipping; GOMAXPROCS>1")
2831 i := -1
2832 allocs := testing.AllocsPerRun(n, func() {
2833 f(i)
2836 if allocs > 0 {
2837 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2841 func TestAllocations(t *testing.T) {
2842 noAlloc(t, 100, func(j int) {
2843 var i interface{}
2844 var v Value
2846 // We can uncomment this when compiler escape analysis
2847 // is good enough to see that the integer assigned to i
2848 // does not escape and therefore need not be allocated.
2850 // i = 42 + j
2851 // v = ValueOf(i)
2852 // if int(v.Int()) != 42+j {
2853 // panic("wrong int")
2854 // }
2856 i = func(j int) int { return j }
2857 v = ValueOf(i)
2858 if v.Interface().(func(int) int)(j) != j {
2859 panic("wrong result")
2866 func TestSmallNegativeInt(t *testing.T) {
2867 i := int16(-1)
2868 v := ValueOf(i)
2869 if v.Int() != -1 {
2870 t.Errorf("int16(-1).Int() returned %v", v.Int())
2874 func TestIndex(t *testing.T) {
2875 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2876 v := ValueOf(xs).Index(3).Interface().(byte)
2877 if v != xs[3] {
2878 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2880 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2881 v = ValueOf(xa).Index(2).Interface().(byte)
2882 if v != xa[2] {
2883 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2885 s := "0123456789"
2886 v = ValueOf(s).Index(3).Interface().(byte)
2887 if v != s[3] {
2888 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2892 func TestSlice(t *testing.T) {
2893 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2894 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
2895 if len(v) != 2 {
2896 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2898 if cap(v) != 5 {
2899 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2901 if !DeepEqual(v[0:5], xs[3:]) {
2902 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
2904 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2905 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
2906 if len(v) != 3 {
2907 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2909 if cap(v) != 6 {
2910 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2912 if !DeepEqual(v[0:6], xa[2:]) {
2913 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
2915 s := "0123456789"
2916 vs := ValueOf(s).Slice(3, 5).Interface().(string)
2917 if vs != s[3:5] {
2918 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2921 rv := ValueOf(&xs).Elem()
2922 rv = rv.Slice(3, 4)
2923 ptr2 := rv.Pointer()
2924 rv = rv.Slice(5, 5)
2925 ptr3 := rv.Pointer()
2926 if ptr3 != ptr2 {
2927 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
2931 func TestSlice3(t *testing.T) {
2932 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2933 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
2934 if len(v) != 2 {
2935 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
2937 if cap(v) != 4 {
2938 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
2940 if !DeepEqual(v[0:4], xs[3:7:7]) {
2941 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
2943 rv := ValueOf(&xs).Elem()
2944 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2945 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2946 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2948 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2949 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
2950 if len(v) != 3 {
2951 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
2953 if cap(v) != 4 {
2954 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
2956 if !DeepEqual(v[0:4], xa[2:6:6]) {
2957 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
2959 rv = ValueOf(&xa).Elem()
2960 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2961 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2962 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2964 s := "hello world"
2965 rv = ValueOf(&s).Elem()
2966 shouldPanic(func() { rv.Slice3(1, 2, 3) })
2968 rv = ValueOf(&xs).Elem()
2969 rv = rv.Slice3(3, 5, 7)
2970 ptr2 := rv.Pointer()
2971 rv = rv.Slice3(4, 4, 4)
2972 ptr3 := rv.Pointer()
2973 if ptr3 != ptr2 {
2974 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
2978 func TestSetLenCap(t *testing.T) {
2979 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2980 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2982 vs := ValueOf(&xs).Elem()
2983 shouldPanic(func() { vs.SetLen(10) })
2984 shouldPanic(func() { vs.SetCap(10) })
2985 shouldPanic(func() { vs.SetLen(-1) })
2986 shouldPanic(func() { vs.SetCap(-1) })
2987 shouldPanic(func() { vs.SetCap(6) }) // smaller than len
2988 vs.SetLen(5)
2989 if len(xs) != 5 || cap(xs) != 8 {
2990 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
2992 vs.SetCap(6)
2993 if len(xs) != 5 || cap(xs) != 6 {
2994 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
2996 vs.SetCap(5)
2997 if len(xs) != 5 || cap(xs) != 5 {
2998 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
3000 shouldPanic(func() { vs.SetCap(4) }) // smaller than len
3001 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
3003 va := ValueOf(&xa).Elem()
3004 shouldPanic(func() { va.SetLen(8) })
3005 shouldPanic(func() { va.SetCap(8) })
3008 func TestVariadic(t *testing.T) {
3009 var b bytes.Buffer
3010 V := ValueOf
3012 b.Reset()
3013 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
3014 if b.String() != "hello, 42 world" {
3015 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
3018 b.Reset()
3019 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
3020 if b.String() != "hello, 42 world" {
3021 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
3025 func TestFuncArg(t *testing.T) {
3026 f1 := func(i int, f func(int) int) int { return f(i) }
3027 f2 := func(i int) int { return i + 1 }
3028 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
3029 if r[0].Int() != 101 {
3030 t.Errorf("function returned %d, want 101", r[0].Int())
3034 func TestStructArg(t *testing.T) {
3035 type padded struct {
3036 B string
3037 C int32
3039 var (
3040 gotA padded
3041 gotB uint32
3042 wantA = padded{"3", 4}
3043 wantB = uint32(5)
3045 f := func(a padded, b uint32) {
3046 gotA, gotB = a, b
3048 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
3049 if gotA != wantA || gotB != wantB {
3050 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
3054 var tagGetTests = []struct {
3055 Tag StructTag
3056 Key string
3057 Value string
3059 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
3060 {`protobuf:"PB(1,2)"`, `foo`, ``},
3061 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
3062 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
3063 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
3064 {`k0:"values contain spaces" k1:"and\ttabs"`, "k0", "values contain spaces"},
3065 {`k0:"values contain spaces" k1:"and\ttabs"`, "k1", "and\ttabs"},
3068 func TestTagGet(t *testing.T) {
3069 for _, tt := range tagGetTests {
3070 if v := tt.Tag.Get(tt.Key); v != tt.Value {
3071 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
3076 func TestBytes(t *testing.T) {
3077 type B []byte
3078 x := B{1, 2, 3, 4}
3079 y := ValueOf(x).Bytes()
3080 if !bytes.Equal(x, y) {
3081 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3083 if &x[0] != &y[0] {
3084 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3088 func TestSetBytes(t *testing.T) {
3089 type B []byte
3090 var x B
3091 y := []byte{1, 2, 3, 4}
3092 ValueOf(&x).Elem().SetBytes(y)
3093 if !bytes.Equal(x, y) {
3094 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
3096 if &x[0] != &y[0] {
3097 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
3101 type Private struct {
3102 x int
3103 y **int
3104 Z int
3107 func (p *Private) m() {
3110 type private struct {
3111 Z int
3112 z int
3113 S string
3114 A [1]Private
3115 T []Private
3118 func (p *private) P() {
3121 type Public struct {
3122 X int
3123 Y **int
3124 private
3127 func (p *Public) M() {
3130 func TestUnexported(t *testing.T) {
3131 var pub Public
3132 pub.S = "S"
3133 pub.T = pub.A[:]
3134 v := ValueOf(&pub)
3135 isValid(v.Elem().Field(0))
3136 isValid(v.Elem().Field(1))
3137 isValid(v.Elem().Field(2))
3138 isValid(v.Elem().FieldByName("X"))
3139 isValid(v.Elem().FieldByName("Y"))
3140 isValid(v.Elem().FieldByName("Z"))
3141 isValid(v.Type().Method(0).Func)
3142 m, _ := v.Type().MethodByName("M")
3143 isValid(m.Func)
3144 m, _ = v.Type().MethodByName("P")
3145 isValid(m.Func)
3146 isNonNil(v.Elem().Field(0).Interface())
3147 isNonNil(v.Elem().Field(1).Interface())
3148 isNonNil(v.Elem().Field(2).Field(2).Index(0))
3149 isNonNil(v.Elem().FieldByName("X").Interface())
3150 isNonNil(v.Elem().FieldByName("Y").Interface())
3151 isNonNil(v.Elem().FieldByName("Z").Interface())
3152 isNonNil(v.Elem().FieldByName("S").Index(0).Interface())
3153 isNonNil(v.Type().Method(0).Func.Interface())
3154 m, _ = v.Type().MethodByName("P")
3155 isNonNil(m.Func.Interface())
3157 var priv Private
3158 v = ValueOf(&priv)
3159 isValid(v.Elem().Field(0))
3160 isValid(v.Elem().Field(1))
3161 isValid(v.Elem().FieldByName("x"))
3162 isValid(v.Elem().FieldByName("y"))
3163 shouldPanic(func() { v.Elem().Field(0).Interface() })
3164 shouldPanic(func() { v.Elem().Field(1).Interface() })
3165 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
3166 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
3167 shouldPanic(func() { v.Type().Method(0) })
3170 func TestSetPanic(t *testing.T) {
3171 ok := func(f func()) { f() }
3172 bad := shouldPanic
3173 clear := func(v Value) { v.Set(Zero(v.Type())) }
3175 type t0 struct {
3176 W int
3179 type t1 struct {
3180 Y int
3184 type T2 struct {
3185 Z int
3186 namedT0 t0
3189 type T struct {
3190 X int
3193 NamedT1 t1
3194 NamedT2 T2
3195 namedT1 t1
3196 namedT2 T2
3199 // not addressable
3200 v := ValueOf(T{})
3201 bad(func() { clear(v.Field(0)) }) // .X
3202 bad(func() { clear(v.Field(1)) }) // .t1
3203 bad(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3204 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3205 bad(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3206 bad(func() { clear(v.Field(2)) }) // .T2
3207 bad(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3208 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3209 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3210 bad(func() { clear(v.Field(3)) }) // .NamedT1
3211 bad(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3212 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3213 bad(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3214 bad(func() { clear(v.Field(4)) }) // .NamedT2
3215 bad(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3216 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3217 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3218 bad(func() { clear(v.Field(5)) }) // .namedT1
3219 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3220 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3221 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3222 bad(func() { clear(v.Field(6)) }) // .namedT2
3223 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3224 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3225 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3227 // addressable
3228 v = ValueOf(&T{}).Elem()
3229 ok(func() { clear(v.Field(0)) }) // .X
3230 bad(func() { clear(v.Field(1)) }) // .t1
3231 ok(func() { clear(v.Field(1).Field(0)) }) // .t1.Y
3232 bad(func() { clear(v.Field(1).Field(1)) }) // .t1.t0
3233 ok(func() { clear(v.Field(1).Field(1).Field(0)) }) // .t1.t0.W
3234 ok(func() { clear(v.Field(2)) }) // .T2
3235 ok(func() { clear(v.Field(2).Field(0)) }) // .T2.Z
3236 bad(func() { clear(v.Field(2).Field(1)) }) // .T2.namedT0
3237 bad(func() { clear(v.Field(2).Field(1).Field(0)) }) // .T2.namedT0.W
3238 ok(func() { clear(v.Field(3)) }) // .NamedT1
3239 ok(func() { clear(v.Field(3).Field(0)) }) // .NamedT1.Y
3240 bad(func() { clear(v.Field(3).Field(1)) }) // .NamedT1.t0
3241 ok(func() { clear(v.Field(3).Field(1).Field(0)) }) // .NamedT1.t0.W
3242 ok(func() { clear(v.Field(4)) }) // .NamedT2
3243 ok(func() { clear(v.Field(4).Field(0)) }) // .NamedT2.Z
3244 bad(func() { clear(v.Field(4).Field(1)) }) // .NamedT2.namedT0
3245 bad(func() { clear(v.Field(4).Field(1).Field(0)) }) // .NamedT2.namedT0.W
3246 bad(func() { clear(v.Field(5)) }) // .namedT1
3247 bad(func() { clear(v.Field(5).Field(0)) }) // .namedT1.Y
3248 bad(func() { clear(v.Field(5).Field(1)) }) // .namedT1.t0
3249 bad(func() { clear(v.Field(5).Field(1).Field(0)) }) // .namedT1.t0.W
3250 bad(func() { clear(v.Field(6)) }) // .namedT2
3251 bad(func() { clear(v.Field(6).Field(0)) }) // .namedT2.Z
3252 bad(func() { clear(v.Field(6).Field(1)) }) // .namedT2.namedT0
3253 bad(func() { clear(v.Field(6).Field(1).Field(0)) }) // .namedT2.namedT0.W
3256 type timp int
3258 func (t timp) W() {}
3259 func (t timp) Y() {}
3260 func (t timp) w() {}
3261 func (t timp) y() {}
3263 func TestCallPanic(t *testing.T) {
3264 type t0 interface {
3268 type T1 interface {
3272 type T2 struct {
3276 type T struct {
3277 t0 // 0
3278 T1 // 1
3280 NamedT0 t0 // 2
3281 NamedT1 T1 // 3
3282 NamedT2 T2 // 4
3284 namedT0 t0 // 5
3285 namedT1 T1 // 6
3286 namedT2 T2 // 7
3288 ok := func(f func()) { f() }
3289 bad := shouldPanic
3290 call := func(v Value) { v.Call(nil) }
3292 i := timp(0)
3293 v := ValueOf(T{i, i, i, i, T2{i, i}, i, i, T2{i, i}})
3294 ok(func() { call(v.Field(0).Method(0)) }) // .t0.W
3295 bad(func() { call(v.Field(0).Elem().Method(0)) }) // .t0.W
3296 bad(func() { call(v.Field(0).Method(1)) }) // .t0.w
3297 bad(func() { call(v.Field(0).Elem().Method(2)) }) // .t0.w
3298 ok(func() { call(v.Field(1).Method(0)) }) // .T1.Y
3299 ok(func() { call(v.Field(1).Elem().Method(0)) }) // .T1.Y
3300 bad(func() { call(v.Field(1).Method(1)) }) // .T1.y
3301 bad(func() { call(v.Field(1).Elem().Method(2)) }) // .T1.y
3303 ok(func() { call(v.Field(2).Method(0)) }) // .NamedT0.W
3304 ok(func() { call(v.Field(2).Elem().Method(0)) }) // .NamedT0.W
3305 bad(func() { call(v.Field(2).Method(1)) }) // .NamedT0.w
3306 bad(func() { call(v.Field(2).Elem().Method(2)) }) // .NamedT0.w
3308 ok(func() { call(v.Field(3).Method(0)) }) // .NamedT1.Y
3309 ok(func() { call(v.Field(3).Elem().Method(0)) }) // .NamedT1.Y
3310 bad(func() { call(v.Field(3).Method(1)) }) // .NamedT1.y
3311 bad(func() { call(v.Field(3).Elem().Method(3)) }) // .NamedT1.y
3313 ok(func() { call(v.Field(4).Field(0).Method(0)) }) // .NamedT2.T1.Y
3314 ok(func() { call(v.Field(4).Field(0).Elem().Method(0)) }) // .NamedT2.T1.W
3315 ok(func() { call(v.Field(4).Field(1).Method(0)) }) // .NamedT2.t0.W
3316 bad(func() { call(v.Field(4).Field(1).Elem().Method(0)) }) // .NamedT2.t0.W
3318 bad(func() { call(v.Field(5).Method(0)) }) // .namedT0.W
3319 bad(func() { call(v.Field(5).Elem().Method(0)) }) // .namedT0.W
3320 bad(func() { call(v.Field(5).Method(1)) }) // .namedT0.w
3321 bad(func() { call(v.Field(5).Elem().Method(2)) }) // .namedT0.w
3323 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.Y
3324 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.Y
3325 bad(func() { call(v.Field(6).Method(0)) }) // .namedT1.y
3326 bad(func() { call(v.Field(6).Elem().Method(0)) }) // .namedT1.y
3328 bad(func() { call(v.Field(7).Field(0).Method(0)) }) // .namedT2.T1.Y
3329 bad(func() { call(v.Field(7).Field(0).Elem().Method(0)) }) // .namedT2.T1.W
3330 bad(func() { call(v.Field(7).Field(1).Method(0)) }) // .namedT2.t0.W
3331 bad(func() { call(v.Field(7).Field(1).Elem().Method(0)) }) // .namedT2.t0.W
3334 func shouldPanic(f func()) {
3335 defer func() {
3336 if recover() == nil {
3337 panic("did not panic")
3343 func isNonNil(x interface{}) {
3344 if x == nil {
3345 panic("nil interface")
3349 func isValid(v Value) {
3350 if !v.IsValid() {
3351 panic("zero Value")
3355 func TestAlias(t *testing.T) {
3356 x := string("hello")
3357 v := ValueOf(&x).Elem()
3358 oldvalue := v.Interface()
3359 v.SetString("world")
3360 newvalue := v.Interface()
3362 if oldvalue != "hello" || newvalue != "world" {
3363 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
3367 var V = ValueOf
3369 func EmptyInterfaceV(x interface{}) Value {
3370 return ValueOf(&x).Elem()
3373 func ReaderV(x io.Reader) Value {
3374 return ValueOf(&x).Elem()
3377 func ReadWriterV(x io.ReadWriter) Value {
3378 return ValueOf(&x).Elem()
3381 type Empty struct{}
3382 type MyStruct struct {
3383 x int `some:"tag"`
3385 type MyString string
3386 type MyBytes []byte
3387 type MyRunes []int32
3388 type MyFunc func()
3389 type MyByte byte
3391 var convertTests = []struct {
3392 in Value
3393 out Value
3395 // numbers
3397 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
3399 package main
3401 import "fmt"
3403 var numbers = []string{
3404 "int8", "uint8", "int16", "uint16",
3405 "int32", "uint32", "int64", "uint64",
3406 "int", "uint", "uintptr",
3407 "float32", "float64",
3410 func main() {
3411 // all pairs but in an unusual order,
3412 // to emit all the int8, uint8 cases
3413 // before n grows too big.
3414 n := 1
3415 for i, f := range numbers {
3416 for _, g := range numbers[i:] {
3417 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
3419 if f != g {
3420 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
3427 {V(int8(1)), V(int8(1))},
3428 {V(int8(2)), V(uint8(2))},
3429 {V(uint8(3)), V(int8(3))},
3430 {V(int8(4)), V(int16(4))},
3431 {V(int16(5)), V(int8(5))},
3432 {V(int8(6)), V(uint16(6))},
3433 {V(uint16(7)), V(int8(7))},
3434 {V(int8(8)), V(int32(8))},
3435 {V(int32(9)), V(int8(9))},
3436 {V(int8(10)), V(uint32(10))},
3437 {V(uint32(11)), V(int8(11))},
3438 {V(int8(12)), V(int64(12))},
3439 {V(int64(13)), V(int8(13))},
3440 {V(int8(14)), V(uint64(14))},
3441 {V(uint64(15)), V(int8(15))},
3442 {V(int8(16)), V(int(16))},
3443 {V(int(17)), V(int8(17))},
3444 {V(int8(18)), V(uint(18))},
3445 {V(uint(19)), V(int8(19))},
3446 {V(int8(20)), V(uintptr(20))},
3447 {V(uintptr(21)), V(int8(21))},
3448 {V(int8(22)), V(float32(22))},
3449 {V(float32(23)), V(int8(23))},
3450 {V(int8(24)), V(float64(24))},
3451 {V(float64(25)), V(int8(25))},
3452 {V(uint8(26)), V(uint8(26))},
3453 {V(uint8(27)), V(int16(27))},
3454 {V(int16(28)), V(uint8(28))},
3455 {V(uint8(29)), V(uint16(29))},
3456 {V(uint16(30)), V(uint8(30))},
3457 {V(uint8(31)), V(int32(31))},
3458 {V(int32(32)), V(uint8(32))},
3459 {V(uint8(33)), V(uint32(33))},
3460 {V(uint32(34)), V(uint8(34))},
3461 {V(uint8(35)), V(int64(35))},
3462 {V(int64(36)), V(uint8(36))},
3463 {V(uint8(37)), V(uint64(37))},
3464 {V(uint64(38)), V(uint8(38))},
3465 {V(uint8(39)), V(int(39))},
3466 {V(int(40)), V(uint8(40))},
3467 {V(uint8(41)), V(uint(41))},
3468 {V(uint(42)), V(uint8(42))},
3469 {V(uint8(43)), V(uintptr(43))},
3470 {V(uintptr(44)), V(uint8(44))},
3471 {V(uint8(45)), V(float32(45))},
3472 {V(float32(46)), V(uint8(46))},
3473 {V(uint8(47)), V(float64(47))},
3474 {V(float64(48)), V(uint8(48))},
3475 {V(int16(49)), V(int16(49))},
3476 {V(int16(50)), V(uint16(50))},
3477 {V(uint16(51)), V(int16(51))},
3478 {V(int16(52)), V(int32(52))},
3479 {V(int32(53)), V(int16(53))},
3480 {V(int16(54)), V(uint32(54))},
3481 {V(uint32(55)), V(int16(55))},
3482 {V(int16(56)), V(int64(56))},
3483 {V(int64(57)), V(int16(57))},
3484 {V(int16(58)), V(uint64(58))},
3485 {V(uint64(59)), V(int16(59))},
3486 {V(int16(60)), V(int(60))},
3487 {V(int(61)), V(int16(61))},
3488 {V(int16(62)), V(uint(62))},
3489 {V(uint(63)), V(int16(63))},
3490 {V(int16(64)), V(uintptr(64))},
3491 {V(uintptr(65)), V(int16(65))},
3492 {V(int16(66)), V(float32(66))},
3493 {V(float32(67)), V(int16(67))},
3494 {V(int16(68)), V(float64(68))},
3495 {V(float64(69)), V(int16(69))},
3496 {V(uint16(70)), V(uint16(70))},
3497 {V(uint16(71)), V(int32(71))},
3498 {V(int32(72)), V(uint16(72))},
3499 {V(uint16(73)), V(uint32(73))},
3500 {V(uint32(74)), V(uint16(74))},
3501 {V(uint16(75)), V(int64(75))},
3502 {V(int64(76)), V(uint16(76))},
3503 {V(uint16(77)), V(uint64(77))},
3504 {V(uint64(78)), V(uint16(78))},
3505 {V(uint16(79)), V(int(79))},
3506 {V(int(80)), V(uint16(80))},
3507 {V(uint16(81)), V(uint(81))},
3508 {V(uint(82)), V(uint16(82))},
3509 {V(uint16(83)), V(uintptr(83))},
3510 {V(uintptr(84)), V(uint16(84))},
3511 {V(uint16(85)), V(float32(85))},
3512 {V(float32(86)), V(uint16(86))},
3513 {V(uint16(87)), V(float64(87))},
3514 {V(float64(88)), V(uint16(88))},
3515 {V(int32(89)), V(int32(89))},
3516 {V(int32(90)), V(uint32(90))},
3517 {V(uint32(91)), V(int32(91))},
3518 {V(int32(92)), V(int64(92))},
3519 {V(int64(93)), V(int32(93))},
3520 {V(int32(94)), V(uint64(94))},
3521 {V(uint64(95)), V(int32(95))},
3522 {V(int32(96)), V(int(96))},
3523 {V(int(97)), V(int32(97))},
3524 {V(int32(98)), V(uint(98))},
3525 {V(uint(99)), V(int32(99))},
3526 {V(int32(100)), V(uintptr(100))},
3527 {V(uintptr(101)), V(int32(101))},
3528 {V(int32(102)), V(float32(102))},
3529 {V(float32(103)), V(int32(103))},
3530 {V(int32(104)), V(float64(104))},
3531 {V(float64(105)), V(int32(105))},
3532 {V(uint32(106)), V(uint32(106))},
3533 {V(uint32(107)), V(int64(107))},
3534 {V(int64(108)), V(uint32(108))},
3535 {V(uint32(109)), V(uint64(109))},
3536 {V(uint64(110)), V(uint32(110))},
3537 {V(uint32(111)), V(int(111))},
3538 {V(int(112)), V(uint32(112))},
3539 {V(uint32(113)), V(uint(113))},
3540 {V(uint(114)), V(uint32(114))},
3541 {V(uint32(115)), V(uintptr(115))},
3542 {V(uintptr(116)), V(uint32(116))},
3543 {V(uint32(117)), V(float32(117))},
3544 {V(float32(118)), V(uint32(118))},
3545 {V(uint32(119)), V(float64(119))},
3546 {V(float64(120)), V(uint32(120))},
3547 {V(int64(121)), V(int64(121))},
3548 {V(int64(122)), V(uint64(122))},
3549 {V(uint64(123)), V(int64(123))},
3550 {V(int64(124)), V(int(124))},
3551 {V(int(125)), V(int64(125))},
3552 {V(int64(126)), V(uint(126))},
3553 {V(uint(127)), V(int64(127))},
3554 {V(int64(128)), V(uintptr(128))},
3555 {V(uintptr(129)), V(int64(129))},
3556 {V(int64(130)), V(float32(130))},
3557 {V(float32(131)), V(int64(131))},
3558 {V(int64(132)), V(float64(132))},
3559 {V(float64(133)), V(int64(133))},
3560 {V(uint64(134)), V(uint64(134))},
3561 {V(uint64(135)), V(int(135))},
3562 {V(int(136)), V(uint64(136))},
3563 {V(uint64(137)), V(uint(137))},
3564 {V(uint(138)), V(uint64(138))},
3565 {V(uint64(139)), V(uintptr(139))},
3566 {V(uintptr(140)), V(uint64(140))},
3567 {V(uint64(141)), V(float32(141))},
3568 {V(float32(142)), V(uint64(142))},
3569 {V(uint64(143)), V(float64(143))},
3570 {V(float64(144)), V(uint64(144))},
3571 {V(int(145)), V(int(145))},
3572 {V(int(146)), V(uint(146))},
3573 {V(uint(147)), V(int(147))},
3574 {V(int(148)), V(uintptr(148))},
3575 {V(uintptr(149)), V(int(149))},
3576 {V(int(150)), V(float32(150))},
3577 {V(float32(151)), V(int(151))},
3578 {V(int(152)), V(float64(152))},
3579 {V(float64(153)), V(int(153))},
3580 {V(uint(154)), V(uint(154))},
3581 {V(uint(155)), V(uintptr(155))},
3582 {V(uintptr(156)), V(uint(156))},
3583 {V(uint(157)), V(float32(157))},
3584 {V(float32(158)), V(uint(158))},
3585 {V(uint(159)), V(float64(159))},
3586 {V(float64(160)), V(uint(160))},
3587 {V(uintptr(161)), V(uintptr(161))},
3588 {V(uintptr(162)), V(float32(162))},
3589 {V(float32(163)), V(uintptr(163))},
3590 {V(uintptr(164)), V(float64(164))},
3591 {V(float64(165)), V(uintptr(165))},
3592 {V(float32(166)), V(float32(166))},
3593 {V(float32(167)), V(float64(167))},
3594 {V(float64(168)), V(float32(168))},
3595 {V(float64(169)), V(float64(169))},
3597 // truncation
3598 {V(float64(1.5)), V(int(1))},
3600 // complex
3601 {V(complex64(1i)), V(complex64(1i))},
3602 {V(complex64(2i)), V(complex128(2i))},
3603 {V(complex128(3i)), V(complex64(3i))},
3604 {V(complex128(4i)), V(complex128(4i))},
3606 // string
3607 {V(string("hello")), V(string("hello"))},
3608 {V(string("bytes1")), V([]byte("bytes1"))},
3609 {V([]byte("bytes2")), V(string("bytes2"))},
3610 {V([]byte("bytes3")), V([]byte("bytes3"))},
3611 {V(string("runes♝")), V([]rune("runes♝"))},
3612 {V([]rune("runes♕")), V(string("runes♕"))},
3613 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3614 {V(int('a')), V(string("a"))},
3615 {V(int8('a')), V(string("a"))},
3616 {V(int16('a')), V(string("a"))},
3617 {V(int32('a')), V(string("a"))},
3618 {V(int64('a')), V(string("a"))},
3619 {V(uint('a')), V(string("a"))},
3620 {V(uint8('a')), V(string("a"))},
3621 {V(uint16('a')), V(string("a"))},
3622 {V(uint32('a')), V(string("a"))},
3623 {V(uint64('a')), V(string("a"))},
3624 {V(uintptr('a')), V(string("a"))},
3625 {V(int(-1)), V(string("\uFFFD"))},
3626 {V(int8(-2)), V(string("\uFFFD"))},
3627 {V(int16(-3)), V(string("\uFFFD"))},
3628 {V(int32(-4)), V(string("\uFFFD"))},
3629 {V(int64(-5)), V(string("\uFFFD"))},
3630 {V(uint(0x110001)), V(string("\uFFFD"))},
3631 {V(uint32(0x110002)), V(string("\uFFFD"))},
3632 {V(uint64(0x110003)), V(string("\uFFFD"))},
3633 {V(uintptr(0x110004)), V(string("\uFFFD"))},
3635 // named string
3636 {V(MyString("hello")), V(string("hello"))},
3637 {V(string("hello")), V(MyString("hello"))},
3638 {V(string("hello")), V(string("hello"))},
3639 {V(MyString("hello")), V(MyString("hello"))},
3640 {V(MyString("bytes1")), V([]byte("bytes1"))},
3641 {V([]byte("bytes2")), V(MyString("bytes2"))},
3642 {V([]byte("bytes3")), V([]byte("bytes3"))},
3643 {V(MyString("runes♝")), V([]rune("runes♝"))},
3644 {V([]rune("runes♕")), V(MyString("runes♕"))},
3645 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3646 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3647 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3648 {V(int('a')), V(MyString("a"))},
3649 {V(int8('a')), V(MyString("a"))},
3650 {V(int16('a')), V(MyString("a"))},
3651 {V(int32('a')), V(MyString("a"))},
3652 {V(int64('a')), V(MyString("a"))},
3653 {V(uint('a')), V(MyString("a"))},
3654 {V(uint8('a')), V(MyString("a"))},
3655 {V(uint16('a')), V(MyString("a"))},
3656 {V(uint32('a')), V(MyString("a"))},
3657 {V(uint64('a')), V(MyString("a"))},
3658 {V(uintptr('a')), V(MyString("a"))},
3659 {V(int(-1)), V(MyString("\uFFFD"))},
3660 {V(int8(-2)), V(MyString("\uFFFD"))},
3661 {V(int16(-3)), V(MyString("\uFFFD"))},
3662 {V(int32(-4)), V(MyString("\uFFFD"))},
3663 {V(int64(-5)), V(MyString("\uFFFD"))},
3664 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3665 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3666 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3667 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3669 // named []byte
3670 {V(string("bytes1")), V(MyBytes("bytes1"))},
3671 {V(MyBytes("bytes2")), V(string("bytes2"))},
3672 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3673 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3674 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3676 // named []rune
3677 {V(string("runes♝")), V(MyRunes("runes♝"))},
3678 {V(MyRunes("runes♕")), V(string("runes♕"))},
3679 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3680 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3681 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3683 // named types and equal underlying types
3684 {V(new(int)), V(new(integer))},
3685 {V(new(integer)), V(new(int))},
3686 {V(Empty{}), V(struct{}{})},
3687 {V(new(Empty)), V(new(struct{}))},
3688 {V(struct{}{}), V(Empty{})},
3689 {V(new(struct{})), V(new(Empty))},
3690 {V(Empty{}), V(Empty{})},
3691 {V(MyBytes{}), V([]byte{})},
3692 {V([]byte{}), V(MyBytes{})},
3693 {V((func())(nil)), V(MyFunc(nil))},
3694 {V((MyFunc)(nil)), V((func())(nil))},
3696 // structs with different tags
3697 {V(struct {
3698 x int `some:"foo"`
3699 }{}), V(struct {
3700 x int `some:"bar"`
3701 }{})},
3703 {V(struct {
3704 x int `some:"bar"`
3705 }{}), V(struct {
3706 x int `some:"foo"`
3707 }{})},
3709 {V(MyStruct{}), V(struct {
3710 x int `some:"foo"`
3711 }{})},
3713 {V(struct {
3714 x int `some:"foo"`
3715 }{}), V(MyStruct{})},
3717 {V(MyStruct{}), V(struct {
3718 x int `some:"bar"`
3719 }{})},
3721 {V(struct {
3722 x int `some:"bar"`
3723 }{}), V(MyStruct{})},
3725 // can convert *byte and *MyByte
3726 {V((*byte)(nil)), V((*MyByte)(nil))},
3727 {V((*MyByte)(nil)), V((*byte)(nil))},
3729 // cannot convert mismatched array sizes
3730 {V([2]byte{}), V([2]byte{})},
3731 {V([3]byte{}), V([3]byte{})},
3733 // cannot convert other instances
3734 {V((**byte)(nil)), V((**byte)(nil))},
3735 {V((**MyByte)(nil)), V((**MyByte)(nil))},
3736 {V((chan byte)(nil)), V((chan byte)(nil))},
3737 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3738 {V(([]byte)(nil)), V(([]byte)(nil))},
3739 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
3740 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3741 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
3742 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3743 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
3744 {V([2]byte{}), V([2]byte{})},
3745 {V([2]MyByte{}), V([2]MyByte{})},
3747 // other
3748 {V((***int)(nil)), V((***int)(nil))},
3749 {V((***byte)(nil)), V((***byte)(nil))},
3750 {V((***int32)(nil)), V((***int32)(nil))},
3751 {V((***int64)(nil)), V((***int64)(nil))},
3752 {V((chan int)(nil)), V((<-chan int)(nil))},
3753 {V((chan int)(nil)), V((chan<- int)(nil))},
3754 {V((chan string)(nil)), V((<-chan string)(nil))},
3755 {V((chan string)(nil)), V((chan<- string)(nil))},
3756 {V((chan byte)(nil)), V((chan byte)(nil))},
3757 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3758 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3759 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3760 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3761 {V([]uint(nil)), V([]uint(nil))},
3762 {V([]int(nil)), V([]int(nil))},
3763 {V(new(interface{})), V(new(interface{}))},
3764 {V(new(io.Reader)), V(new(io.Reader))},
3765 {V(new(io.Writer)), V(new(io.Writer))},
3767 // interfaces
3768 {V(int(1)), EmptyInterfaceV(int(1))},
3769 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3770 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3771 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3772 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
3775 func TestConvert(t *testing.T) {
3776 canConvert := map[[2]Type]bool{}
3777 all := map[Type]bool{}
3779 for _, tt := range convertTests {
3780 t1 := tt.in.Type()
3781 if !t1.ConvertibleTo(t1) {
3782 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
3783 continue
3786 t2 := tt.out.Type()
3787 if !t1.ConvertibleTo(t2) {
3788 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
3789 continue
3792 all[t1] = true
3793 all[t2] = true
3794 canConvert[[2]Type{t1, t2}] = true
3796 // vout1 represents the in value converted to the in type.
3797 v1 := tt.in
3798 vout1 := v1.Convert(t1)
3799 out1 := vout1.Interface()
3800 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
3801 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
3804 // vout2 represents the in value converted to the out type.
3805 vout2 := v1.Convert(t2)
3806 out2 := vout2.Interface()
3807 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
3808 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
3811 // vout3 represents a new value of the out type, set to vout2. This makes
3812 // sure the converted value vout2 is really usable as a regular value.
3813 vout3 := New(t2).Elem()
3814 vout3.Set(vout2)
3815 out3 := vout3.Interface()
3816 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
3817 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
3820 if IsRO(v1) {
3821 t.Errorf("table entry %v is RO, should not be", v1)
3823 if IsRO(vout1) {
3824 t.Errorf("self-conversion output %v is RO, should not be", vout1)
3826 if IsRO(vout2) {
3827 t.Errorf("conversion output %v is RO, should not be", vout2)
3829 if IsRO(vout3) {
3830 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
3832 if !IsRO(MakeRO(v1).Convert(t1)) {
3833 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3835 if !IsRO(MakeRO(v1).Convert(t2)) {
3836 t.Errorf("RO conversion output %v is not RO, should be", v1)
3840 // Assume that of all the types we saw during the tests,
3841 // if there wasn't an explicit entry for a conversion between
3842 // a pair of types, then it's not to be allowed. This checks for
3843 // things like 'int64' converting to '*int'.
3844 for t1 := range all {
3845 for t2 := range all {
3846 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3847 if ok := t1.ConvertibleTo(t2); ok != expectOK {
3848 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3854 type ComparableStruct struct {
3855 X int
3858 type NonComparableStruct struct {
3859 X int
3860 Y map[string]int
3863 var comparableTests = []struct {
3864 typ Type
3865 ok bool
3867 {TypeOf(1), true},
3868 {TypeOf("hello"), true},
3869 {TypeOf(new(byte)), true},
3870 {TypeOf((func())(nil)), false},
3871 {TypeOf([]byte{}), false},
3872 {TypeOf(map[string]int{}), false},
3873 {TypeOf(make(chan int)), true},
3874 {TypeOf(1.5), true},
3875 {TypeOf(false), true},
3876 {TypeOf(1i), true},
3877 {TypeOf(ComparableStruct{}), true},
3878 {TypeOf(NonComparableStruct{}), false},
3879 {TypeOf([10]map[string]int{}), false},
3880 {TypeOf([10]string{}), true},
3881 {TypeOf(new(interface{})).Elem(), true},
3884 func TestComparable(t *testing.T) {
3885 for _, tt := range comparableTests {
3886 if ok := tt.typ.Comparable(); ok != tt.ok {
3887 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
3892 func TestOverflow(t *testing.T) {
3893 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3894 t.Errorf("%v wrongly overflows float64", 1e300)
3897 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3898 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3899 t.Errorf("%v wrongly overflows float32", maxFloat32)
3901 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3902 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3903 t.Errorf("%v should overflow float32", ovfFloat32)
3905 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3906 t.Errorf("%v should overflow float32", -ovfFloat32)
3909 maxInt32 := int64(0x7fffffff)
3910 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3911 t.Errorf("%v wrongly overflows int32", maxInt32)
3913 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3914 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3916 ovfInt32 := int64(1 << 31)
3917 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3918 t.Errorf("%v should overflow int32", ovfInt32)
3921 maxUint32 := uint64(0xffffffff)
3922 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3923 t.Errorf("%v wrongly overflows uint32", maxUint32)
3925 ovfUint32 := uint64(1 << 32)
3926 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3927 t.Errorf("%v should overflow uint32", ovfUint32)
3931 func checkSameType(t *testing.T, x Type, y interface{}) {
3932 if x != TypeOf(y) || TypeOf(Zero(x).Interface()) != TypeOf(y) {
3933 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3937 func TestArrayOf(t *testing.T) {
3938 // check construction and use of type not in binary
3939 tests := []struct {
3940 n int
3941 value func(i int) interface{}
3942 comparable bool
3943 want string
3946 n: 0,
3947 value: func(i int) interface{} { type Tint int; return Tint(i) },
3948 comparable: true,
3949 want: "[]",
3952 n: 10,
3953 value: func(i int) interface{} { type Tint int; return Tint(i) },
3954 comparable: true,
3955 want: "[0 1 2 3 4 5 6 7 8 9]",
3958 n: 10,
3959 value: func(i int) interface{} { type Tfloat float64; return Tfloat(i) },
3960 comparable: true,
3961 want: "[0 1 2 3 4 5 6 7 8 9]",
3964 n: 10,
3965 value: func(i int) interface{} { type Tstring string; return Tstring(strconv.Itoa(i)) },
3966 comparable: true,
3967 want: "[0 1 2 3 4 5 6 7 8 9]",
3970 n: 10,
3971 value: func(i int) interface{} { type Tstruct struct{ V int }; return Tstruct{i} },
3972 comparable: true,
3973 want: "[{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}]",
3976 n: 10,
3977 value: func(i int) interface{} { type Tint int; return []Tint{Tint(i)} },
3978 comparable: false,
3979 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3982 n: 10,
3983 value: func(i int) interface{} { type Tint int; return [1]Tint{Tint(i)} },
3984 comparable: true,
3985 want: "[[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]]",
3988 n: 10,
3989 value: func(i int) interface{} { type Tstruct struct{ V [1]int }; return Tstruct{[1]int{i}} },
3990 comparable: true,
3991 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
3994 n: 10,
3995 value: func(i int) interface{} { type Tstruct struct{ V []int }; return Tstruct{[]int{i}} },
3996 comparable: false,
3997 want: "[{[0]} {[1]} {[2]} {[3]} {[4]} {[5]} {[6]} {[7]} {[8]} {[9]}]",
4000 n: 10,
4001 value: func(i int) interface{} { type TstructUV struct{ U, V int }; return TstructUV{i, i} },
4002 comparable: true,
4003 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4006 n: 10,
4007 value: func(i int) interface{} {
4008 type TstructUV struct {
4009 U int
4010 V float64
4012 return TstructUV{i, float64(i)}
4014 comparable: true,
4015 want: "[{0 0} {1 1} {2 2} {3 3} {4 4} {5 5} {6 6} {7 7} {8 8} {9 9}]",
4019 for _, table := range tests {
4020 at := ArrayOf(table.n, TypeOf(table.value(0)))
4021 v := New(at).Elem()
4022 vok := New(at).Elem()
4023 vnot := New(at).Elem()
4024 for i := 0; i < v.Len(); i++ {
4025 v.Index(i).Set(ValueOf(table.value(i)))
4026 vok.Index(i).Set(ValueOf(table.value(i)))
4027 j := i
4028 if i+1 == v.Len() {
4029 j = i + 1
4031 vnot.Index(i).Set(ValueOf(table.value(j))) // make it differ only by last element
4033 s := fmt.Sprint(v.Interface())
4034 if s != table.want {
4035 t.Errorf("constructed array = %s, want %s", s, table.want)
4038 if table.comparable != at.Comparable() {
4039 t.Errorf("constructed array (%#v) is comparable=%v, want=%v", v.Interface(), at.Comparable(), table.comparable)
4041 if table.comparable {
4042 if table.n > 0 {
4043 if DeepEqual(vnot.Interface(), v.Interface()) {
4044 t.Errorf(
4045 "arrays (%#v) compare ok (but should not)",
4046 v.Interface(),
4050 if !DeepEqual(vok.Interface(), v.Interface()) {
4051 t.Errorf(
4052 "arrays (%#v) compare NOT-ok (but should)",
4053 v.Interface(),
4059 // check that type already in binary is found
4060 type T int
4061 checkSameType(t, ArrayOf(5, TypeOf(T(1))), [5]T{})
4064 func TestArrayOfGC(t *testing.T) {
4065 type T *uintptr
4066 tt := TypeOf(T(nil))
4067 const n = 100
4068 var x []interface{}
4069 for i := 0; i < n; i++ {
4070 v := New(ArrayOf(n, tt)).Elem()
4071 for j := 0; j < v.Len(); j++ {
4072 p := new(uintptr)
4073 *p = uintptr(i*n + j)
4074 v.Index(j).Set(ValueOf(p).Convert(tt))
4076 x = append(x, v.Interface())
4078 runtime.GC()
4080 for i, xi := range x {
4081 v := ValueOf(xi)
4082 for j := 0; j < v.Len(); j++ {
4083 k := v.Index(j).Elem().Interface()
4084 if k != uintptr(i*n+j) {
4085 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4091 func TestArrayOfAlg(t *testing.T) {
4092 at := ArrayOf(6, TypeOf(byte(0)))
4093 v1 := New(at).Elem()
4094 v2 := New(at).Elem()
4095 if v1.Interface() != v1.Interface() {
4096 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4098 v1.Index(5).Set(ValueOf(byte(1)))
4099 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4100 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4103 at = ArrayOf(6, TypeOf([]int(nil)))
4104 v1 = New(at).Elem()
4105 shouldPanic(func() { _ = v1.Interface() == v1.Interface() })
4108 func TestArrayOfGenericAlg(t *testing.T) {
4109 at1 := ArrayOf(5, TypeOf(string("")))
4110 at := ArrayOf(6, at1)
4111 v1 := New(at).Elem()
4112 v2 := New(at).Elem()
4113 if v1.Interface() != v1.Interface() {
4114 t.Errorf("constructed array %v not equal to itself", v1.Interface())
4117 v1.Index(0).Index(0).Set(ValueOf("abc"))
4118 v2.Index(0).Index(0).Set(ValueOf("efg"))
4119 if i1, i2 := v1.Interface(), v2.Interface(); i1 == i2 {
4120 t.Errorf("constructed arrays %v and %v should not be equal", i1, i2)
4123 v1.Index(0).Index(0).Set(ValueOf("abc"))
4124 v2.Index(0).Index(0).Set(ValueOf((v1.Index(0).Index(0).String() + " ")[:3]))
4125 if i1, i2 := v1.Interface(), v2.Interface(); i1 != i2 {
4126 t.Errorf("constructed arrays %v and %v should be equal", i1, i2)
4129 // Test hash
4130 m := MakeMap(MapOf(at, TypeOf(int(0))))
4131 m.SetMapIndex(v1, ValueOf(1))
4132 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4133 t.Errorf("constructed arrays %v and %v have different hashes", i1, i2)
4137 func TestArrayOfDirectIface(t *testing.T) {
4138 t.Skip("skipping test because gccgo uses a different directiface value")
4140 type T [1]*byte
4141 i1 := Zero(TypeOf(T{})).Interface()
4142 v1 := ValueOf(&i1).Elem()
4143 p1 := v1.InterfaceData()[1]
4145 i2 := Zero(ArrayOf(1, PtrTo(TypeOf(int8(0))))).Interface()
4146 v2 := ValueOf(&i2).Elem()
4147 p2 := v2.InterfaceData()[1]
4149 if p1 != 0 {
4150 t.Errorf("got p1=%v. want=%v", p1, nil)
4153 if p2 != 0 {
4154 t.Errorf("got p2=%v. want=%v", p2, nil)
4158 type T [0]*byte
4159 i1 := Zero(TypeOf(T{})).Interface()
4160 v1 := ValueOf(&i1).Elem()
4161 p1 := v1.InterfaceData()[1]
4163 i2 := Zero(ArrayOf(0, PtrTo(TypeOf(int8(0))))).Interface()
4164 v2 := ValueOf(&i2).Elem()
4165 p2 := v2.InterfaceData()[1]
4167 if p1 == 0 {
4168 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4171 if p2 == 0 {
4172 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4177 func TestSliceOf(t *testing.T) {
4178 // check construction and use of type not in binary
4179 type T int
4180 st := SliceOf(TypeOf(T(1)))
4181 if got, want := st.String(), "[]reflect_test.T"; got != want {
4182 t.Errorf("SliceOf(T(1)).String()=%q, want %q", got, want)
4184 v := MakeSlice(st, 10, 10)
4185 runtime.GC()
4186 for i := 0; i < v.Len(); i++ {
4187 v.Index(i).Set(ValueOf(T(i)))
4188 runtime.GC()
4190 s := fmt.Sprint(v.Interface())
4191 want := "[0 1 2 3 4 5 6 7 8 9]"
4192 if s != want {
4193 t.Errorf("constructed slice = %s, want %s", s, want)
4196 // check that type already in binary is found
4197 type T1 int
4198 checkSameType(t, SliceOf(TypeOf(T1(1))), []T1{})
4201 func TestSliceOverflow(t *testing.T) {
4202 // check that MakeSlice panics when size of slice overflows uint
4203 const S = 1e6
4204 s := uint(S)
4205 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
4206 if l*s >= s {
4207 t.Fatal("slice size does not overflow")
4209 var x [S]byte
4210 st := SliceOf(TypeOf(x))
4211 defer func() {
4212 err := recover()
4213 if err == nil {
4214 t.Fatal("slice overflow does not panic")
4217 MakeSlice(st, int(l), int(l))
4220 func TestSliceOfGC(t *testing.T) {
4221 type T *uintptr
4222 tt := TypeOf(T(nil))
4223 st := SliceOf(tt)
4224 const n = 100
4225 var x []interface{}
4226 for i := 0; i < n; i++ {
4227 v := MakeSlice(st, n, n)
4228 for j := 0; j < v.Len(); j++ {
4229 p := new(uintptr)
4230 *p = uintptr(i*n + j)
4231 v.Index(j).Set(ValueOf(p).Convert(tt))
4233 x = append(x, v.Interface())
4235 runtime.GC()
4237 for i, xi := range x {
4238 v := ValueOf(xi)
4239 for j := 0; j < v.Len(); j++ {
4240 k := v.Index(j).Elem().Interface()
4241 if k != uintptr(i*n+j) {
4242 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
4248 func TestStructOfFieldName(t *testing.T) {
4249 // invalid field name "1nvalid"
4250 shouldPanic(func() {
4251 StructOf([]StructField{
4252 StructField{Name: "valid", Type: TypeOf("")},
4253 StructField{Name: "1nvalid", Type: TypeOf("")},
4257 // invalid field name "+"
4258 shouldPanic(func() {
4259 StructOf([]StructField{
4260 StructField{Name: "val1d", Type: TypeOf("")},
4261 StructField{Name: "+", Type: TypeOf("")},
4265 // no field name
4266 shouldPanic(func() {
4267 StructOf([]StructField{
4268 StructField{Name: "", Type: TypeOf("")},
4272 // verify creation of a struct with valid struct fields
4273 validFields := []StructField{
4274 StructField{
4275 Name: "φ",
4276 Type: TypeOf(""),
4278 StructField{
4279 Name: "ValidName",
4280 Type: TypeOf(""),
4282 StructField{
4283 Name: "Val1dNam5",
4284 Type: TypeOf(""),
4288 validStruct := StructOf(validFields)
4290 const structStr = `struct { φ string; ValidName string; Val1dNam5 string }`
4291 if got, want := validStruct.String(), structStr; got != want {
4292 t.Errorf("StructOf(validFields).String()=%q, want %q", got, want)
4296 func TestStructOf(t *testing.T) {
4297 // check construction and use of type not in binary
4298 fields := []StructField{
4299 StructField{
4300 Name: "S",
4301 Tag: "s",
4302 Type: TypeOf(""),
4304 StructField{
4305 Name: "X",
4306 Tag: "x",
4307 Type: TypeOf(byte(0)),
4309 StructField{
4310 Name: "Y",
4311 Type: TypeOf(uint64(0)),
4313 StructField{
4314 Name: "Z",
4315 Type: TypeOf([3]uint16{}),
4319 st := StructOf(fields)
4320 v := New(st).Elem()
4321 runtime.GC()
4322 v.FieldByName("X").Set(ValueOf(byte(2)))
4323 v.FieldByIndex([]int{1}).Set(ValueOf(byte(1)))
4324 runtime.GC()
4326 s := fmt.Sprint(v.Interface())
4327 want := `{ 1 0 [0 0 0]}`
4328 if s != want {
4329 t.Errorf("constructed struct = %s, want %s", s, want)
4331 const stStr = `struct { S string "s"; X uint8 "x"; Y uint64; Z [3]uint16 }`
4332 if got, want := st.String(), stStr; got != want {
4333 t.Errorf("StructOf(fields).String()=%q, want %q", got, want)
4336 // check the size, alignment and field offsets
4337 stt := TypeOf(struct {
4338 String string
4339 X byte
4340 Y uint64
4341 Z [3]uint16
4342 }{})
4343 if st.Size() != stt.Size() {
4344 t.Errorf("constructed struct size = %v, want %v", st.Size(), stt.Size())
4346 if st.Align() != stt.Align() {
4347 t.Errorf("constructed struct align = %v, want %v", st.Align(), stt.Align())
4349 if st.FieldAlign() != stt.FieldAlign() {
4350 t.Errorf("constructed struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4352 for i := 0; i < st.NumField(); i++ {
4353 o1 := st.Field(i).Offset
4354 o2 := stt.Field(i).Offset
4355 if o1 != o2 {
4356 t.Errorf("constructed struct field %v offset = %v, want %v", i, o1, o2)
4360 // Check size and alignment with a trailing zero-sized field.
4361 st = StructOf([]StructField{
4363 Name: "F1",
4364 Type: TypeOf(byte(0)),
4367 Name: "F2",
4368 Type: TypeOf([0]*byte{}),
4371 stt = TypeOf(struct {
4372 G1 byte
4373 G2 [0]*byte
4374 }{})
4375 // Broken with gccgo for now--gccgo does not pad structs yet.
4376 // if st.Size() != stt.Size() {
4377 // t.Errorf("constructed zero-padded struct size = %v, want %v", st.Size(), stt.Size())
4378 // }
4379 if st.Align() != stt.Align() {
4380 t.Errorf("constructed zero-padded struct align = %v, want %v", st.Align(), stt.Align())
4382 if st.FieldAlign() != stt.FieldAlign() {
4383 t.Errorf("constructed zero-padded struct field align = %v, want %v", st.FieldAlign(), stt.FieldAlign())
4385 for i := 0; i < st.NumField(); i++ {
4386 o1 := st.Field(i).Offset
4387 o2 := stt.Field(i).Offset
4388 if o1 != o2 {
4389 t.Errorf("constructed zero-padded struct field %v offset = %v, want %v", i, o1, o2)
4393 // check duplicate names
4394 shouldPanic(func() {
4395 StructOf([]StructField{
4396 StructField{Name: "string", Type: TypeOf("")},
4397 StructField{Name: "string", Type: TypeOf("")},
4400 shouldPanic(func() {
4401 StructOf([]StructField{
4402 StructField{Type: TypeOf("")},
4403 StructField{Name: "string", Type: TypeOf("")},
4406 shouldPanic(func() {
4407 StructOf([]StructField{
4408 StructField{Type: TypeOf("")},
4409 StructField{Type: TypeOf("")},
4412 // check that type already in binary is found
4413 checkSameType(t, StructOf(fields[2:3]), struct{ Y uint64 }{})
4415 // gccgo used to fail this test.
4416 type structFieldType interface{}
4417 checkSameType(t,
4418 StructOf([]StructField{
4419 StructField{
4420 Name: "F",
4421 Type: TypeOf((*structFieldType)(nil)).Elem(),
4424 struct{ F structFieldType }{})
4427 func TestStructOfExportRules(t *testing.T) {
4428 type S1 struct{}
4429 type s2 struct{}
4430 type ΦType struct{}
4431 type φType struct{}
4433 testPanic := func(i int, mustPanic bool, f func()) {
4434 defer func() {
4435 err := recover()
4436 if err == nil && mustPanic {
4437 t.Errorf("test-%d did not panic", i)
4439 if err != nil && !mustPanic {
4440 t.Errorf("test-%d panicked: %v\n", i, err)
4446 tests := []struct {
4447 field StructField
4448 mustPanic bool
4449 exported bool
4452 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{})},
4453 exported: true,
4456 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil))},
4457 exported: true,
4460 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{})},
4461 mustPanic: true,
4464 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil))},
4465 mustPanic: true,
4468 field: StructField{Name: "Name", Type: nil, PkgPath: ""},
4469 mustPanic: true,
4472 field: StructField{Name: "", Type: TypeOf(S1{}), PkgPath: ""},
4473 mustPanic: true,
4476 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf(S1{}), PkgPath: "other/pkg"},
4477 mustPanic: true,
4480 field: StructField{Name: "S1", Anonymous: true, Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
4481 mustPanic: true,
4484 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf(s2{}), PkgPath: "other/pkg"},
4485 mustPanic: true,
4488 field: StructField{Name: "s2", Anonymous: true, Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
4489 mustPanic: true,
4492 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
4493 mustPanic: true,
4496 field: StructField{Name: "s2", Type: TypeOf(int(0)), PkgPath: "other/pkg"},
4497 mustPanic: true,
4500 field: StructField{Name: "S", Type: TypeOf(S1{})},
4501 mustPanic: false,
4502 exported: true,
4505 field: StructField{Name: "S", Type: TypeOf((*S1)(nil))},
4506 exported: true,
4509 field: StructField{Name: "S", Type: TypeOf(s2{})},
4510 exported: true,
4513 field: StructField{Name: "S", Type: TypeOf((*s2)(nil))},
4514 exported: true,
4517 field: StructField{Name: "s", Type: TypeOf(S1{})},
4518 mustPanic: true,
4521 field: StructField{Name: "s", Type: TypeOf((*S1)(nil))},
4522 mustPanic: true,
4525 field: StructField{Name: "s", Type: TypeOf(s2{})},
4526 mustPanic: true,
4529 field: StructField{Name: "s", Type: TypeOf((*s2)(nil))},
4530 mustPanic: true,
4533 field: StructField{Name: "s", Type: TypeOf(S1{}), PkgPath: "other/pkg"},
4534 mustPanic: true, // TODO(sbinet): creating a name with a package path
4537 field: StructField{Name: "s", Type: TypeOf((*S1)(nil)), PkgPath: "other/pkg"},
4538 mustPanic: true, // TODO(sbinet): creating a name with a package path
4541 field: StructField{Name: "s", Type: TypeOf(s2{}), PkgPath: "other/pkg"},
4542 mustPanic: true, // TODO(sbinet): creating a name with a package path
4545 field: StructField{Name: "s", Type: TypeOf((*s2)(nil)), PkgPath: "other/pkg"},
4546 mustPanic: true, // TODO(sbinet): creating a name with a package path
4549 field: StructField{Name: "", Type: TypeOf(ΦType{})},
4550 mustPanic: true,
4553 field: StructField{Name: "", Type: TypeOf(φType{})},
4554 mustPanic: true,
4557 field: StructField{Name: "Φ", Type: TypeOf(0)},
4558 exported: true,
4561 field: StructField{Name: "φ", Type: TypeOf(0)},
4562 exported: false,
4566 for i, test := range tests {
4567 testPanic(i, test.mustPanic, func() {
4568 typ := StructOf([]StructField{test.field})
4569 if typ == nil {
4570 t.Errorf("test-%d: error creating struct type", i)
4571 return
4573 field := typ.Field(0)
4574 n := field.Name
4575 if n == "" {
4576 panic("field.Name must not be empty")
4578 exported := isExported(n)
4579 if exported != test.exported {
4580 t.Errorf("test-%d: got exported=%v want exported=%v", i, exported, test.exported)
4586 // isExported reports whether name is an exported Go symbol
4587 // (that is, whether it begins with an upper-case letter).
4589 func isExported(name string) bool {
4590 ch, _ := utf8.DecodeRuneInString(name)
4591 return unicode.IsUpper(ch)
4594 func TestStructOfGC(t *testing.T) {
4595 type T *uintptr
4596 tt := TypeOf(T(nil))
4597 fields := []StructField{
4598 {Name: "X", Type: tt},
4599 {Name: "Y", Type: tt},
4601 st := StructOf(fields)
4603 const n = 10000
4604 var x []interface{}
4605 for i := 0; i < n; i++ {
4606 v := New(st).Elem()
4607 for j := 0; j < v.NumField(); j++ {
4608 p := new(uintptr)
4609 *p = uintptr(i*n + j)
4610 v.Field(j).Set(ValueOf(p).Convert(tt))
4612 x = append(x, v.Interface())
4614 runtime.GC()
4616 for i, xi := range x {
4617 v := ValueOf(xi)
4618 for j := 0; j < v.NumField(); j++ {
4619 k := v.Field(j).Elem().Interface()
4620 if k != uintptr(i*n+j) {
4621 t.Errorf("lost x[%d].%c = %d, want %d", i, "XY"[j], k, i*n+j)
4627 func TestStructOfAlg(t *testing.T) {
4628 st := StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf(int(0))}})
4629 v1 := New(st).Elem()
4630 v2 := New(st).Elem()
4631 if !DeepEqual(v1.Interface(), v1.Interface()) {
4632 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
4634 v1.FieldByName("X").Set(ValueOf(int(1)))
4635 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
4636 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
4639 st = StructOf([]StructField{{Name: "X", Tag: "x", Type: TypeOf([]int(nil))}})
4640 v1 = New(st).Elem()
4641 shouldPanic(func() { _ = v1.Interface() == v1.Interface() })
4644 func TestStructOfGenericAlg(t *testing.T) {
4645 st1 := StructOf([]StructField{
4646 {Name: "X", Tag: "x", Type: TypeOf(int64(0))},
4647 {Name: "Y", Type: TypeOf(string(""))},
4649 st := StructOf([]StructField{
4650 {Name: "S0", Type: st1},
4651 {Name: "S1", Type: st1},
4654 tests := []struct {
4655 rt Type
4656 idx []int
4659 rt: st,
4660 idx: []int{0, 1},
4663 rt: st1,
4664 idx: []int{1},
4667 rt: StructOf(
4668 []StructField{
4669 {Name: "XX", Type: TypeOf([0]int{})},
4670 {Name: "YY", Type: TypeOf("")},
4673 idx: []int{1},
4676 rt: StructOf(
4677 []StructField{
4678 {Name: "XX", Type: TypeOf([0]int{})},
4679 {Name: "YY", Type: TypeOf("")},
4680 {Name: "ZZ", Type: TypeOf([2]int{})},
4683 idx: []int{1},
4686 rt: StructOf(
4687 []StructField{
4688 {Name: "XX", Type: TypeOf([1]int{})},
4689 {Name: "YY", Type: TypeOf("")},
4692 idx: []int{1},
4695 rt: StructOf(
4696 []StructField{
4697 {Name: "XX", Type: TypeOf([1]int{})},
4698 {Name: "YY", Type: TypeOf("")},
4699 {Name: "ZZ", Type: TypeOf([1]int{})},
4702 idx: []int{1},
4705 rt: StructOf(
4706 []StructField{
4707 {Name: "XX", Type: TypeOf([2]int{})},
4708 {Name: "YY", Type: TypeOf("")},
4709 {Name: "ZZ", Type: TypeOf([2]int{})},
4712 idx: []int{1},
4715 rt: StructOf(
4716 []StructField{
4717 {Name: "XX", Type: TypeOf(int64(0))},
4718 {Name: "YY", Type: TypeOf(byte(0))},
4719 {Name: "ZZ", Type: TypeOf("")},
4722 idx: []int{2},
4725 rt: StructOf(
4726 []StructField{
4727 {Name: "XX", Type: TypeOf(int64(0))},
4728 {Name: "YY", Type: TypeOf(int64(0))},
4729 {Name: "ZZ", Type: TypeOf("")},
4730 {Name: "AA", Type: TypeOf([1]int64{})},
4733 idx: []int{2},
4737 for _, table := range tests {
4738 v1 := New(table.rt).Elem()
4739 v2 := New(table.rt).Elem()
4741 if !DeepEqual(v1.Interface(), v1.Interface()) {
4742 t.Errorf("constructed struct %v not equal to itself", v1.Interface())
4745 v1.FieldByIndex(table.idx).Set(ValueOf("abc"))
4746 v2.FieldByIndex(table.idx).Set(ValueOf("def"))
4747 if i1, i2 := v1.Interface(), v2.Interface(); DeepEqual(i1, i2) {
4748 t.Errorf("constructed structs %v and %v should not be equal", i1, i2)
4751 abc := "abc"
4752 v1.FieldByIndex(table.idx).Set(ValueOf(abc))
4753 val := "+" + abc + "-"
4754 v2.FieldByIndex(table.idx).Set(ValueOf(val[1:4]))
4755 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
4756 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
4759 // Test hash
4760 m := MakeMap(MapOf(table.rt, TypeOf(int(0))))
4761 m.SetMapIndex(v1, ValueOf(1))
4762 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4763 t.Errorf("constructed structs %#v and %#v have different hashes", i1, i2)
4766 v2.FieldByIndex(table.idx).Set(ValueOf("abc"))
4767 if i1, i2 := v1.Interface(), v2.Interface(); !DeepEqual(i1, i2) {
4768 t.Errorf("constructed structs %v and %v should be equal", i1, i2)
4771 if i1, i2 := v1.Interface(), v2.Interface(); !m.MapIndex(v2).IsValid() {
4772 t.Errorf("constructed structs %v and %v have different hashes", i1, i2)
4778 gccgo does not use the same directiface settings as gc.
4780 func TestStructOfDirectIface(t *testing.T) {
4782 type T struct{ X [1]*byte }
4783 i1 := Zero(TypeOf(T{})).Interface()
4784 v1 := ValueOf(&i1).Elem()
4785 p1 := v1.InterfaceData()[1]
4787 i2 := Zero(StructOf([]StructField{
4789 Name: "X",
4790 Type: ArrayOf(1, TypeOf((*int8)(nil))),
4792 })).Interface()
4793 v2 := ValueOf(&i2).Elem()
4794 p2 := v2.InterfaceData()[1]
4796 if p1 != 0 {
4797 t.Errorf("got p1=%v. want=%v", p1, nil)
4800 if p2 != 0 {
4801 t.Errorf("got p2=%v. want=%v", p2, nil)
4805 type T struct{ X [0]*byte }
4806 i1 := Zero(TypeOf(T{})).Interface()
4807 v1 := ValueOf(&i1).Elem()
4808 p1 := v1.InterfaceData()[1]
4810 i2 := Zero(StructOf([]StructField{
4812 Name: "X",
4813 Type: ArrayOf(0, TypeOf((*int8)(nil))),
4815 })).Interface()
4816 v2 := ValueOf(&i2).Elem()
4817 p2 := v2.InterfaceData()[1]
4819 if p1 == 0 {
4820 t.Errorf("got p1=%v. want=not-%v", p1, nil)
4823 if p2 == 0 {
4824 t.Errorf("got p2=%v. want=not-%v", p2, nil)
4830 type StructI int
4832 func (i StructI) Get() int { return int(i) }
4834 type StructIPtr int
4836 func (i *StructIPtr) Get() int { return int(*i) }
4839 gccgo does not yet support StructOf with methods.
4841 func TestStructOfWithInterface(t *testing.T) {
4842 const want = 42
4843 type Iface interface {
4844 Get() int
4846 tests := []struct {
4847 name string
4848 typ Type
4849 val Value
4850 impl bool
4853 name: "StructI",
4854 typ: TypeOf(StructI(want)),
4855 val: ValueOf(StructI(want)),
4856 impl: true,
4859 name: "StructI",
4860 typ: PtrTo(TypeOf(StructI(want))),
4861 val: ValueOf(func() interface{} {
4862 v := StructI(want)
4863 return &v
4864 }()),
4865 impl: true,
4868 name: "StructIPtr",
4869 typ: PtrTo(TypeOf(StructIPtr(want))),
4870 val: ValueOf(func() interface{} {
4871 v := StructIPtr(want)
4872 return &v
4873 }()),
4874 impl: true,
4877 name: "StructIPtr",
4878 typ: TypeOf(StructIPtr(want)),
4879 val: ValueOf(StructIPtr(want)),
4880 impl: false,
4882 // {
4883 // typ: TypeOf((*Iface)(nil)).Elem(), // FIXME(sbinet): fix method.ifn/tfn
4884 // val: ValueOf(StructI(want)),
4885 // impl: true,
4886 // },
4889 for i, table := range tests {
4890 for j := 0; j < 2; j++ {
4891 var fields []StructField
4892 if j == 1 {
4893 fields = append(fields, StructField{
4894 Name: "Dummy",
4895 PkgPath: "",
4896 Type: TypeOf(int(0)),
4899 fields = append(fields, StructField{
4900 Name: table.name,
4901 Anonymous: true,
4902 PkgPath: "",
4903 Type: table.typ,
4906 // We currently do not correctly implement methods
4907 // for anonymous fields other than the first.
4908 // Therefore, for now, we expect those methods
4909 // to not exist. See issues 15924 and 20824.
4910 // When those issues are fixed, this test of panic
4911 // should be removed.
4912 if j == 1 && table.impl {
4913 func() {
4914 defer func() {
4915 if err := recover(); err == nil {
4916 t.Errorf("test-%d-%d did not panic", i, j)
4919 _ = StructOf(fields)
4921 continue
4924 rt := StructOf(fields)
4925 rv := New(rt).Elem()
4926 rv.Field(j).Set(table.val)
4928 if _, ok := rv.Interface().(Iface); ok != table.impl {
4929 if table.impl {
4930 t.Errorf("test-%d-%d: type=%v fails to implement Iface.\n", i, j, table.typ)
4931 } else {
4932 t.Errorf("test-%d-%d: type=%v should NOT implement Iface\n", i, j, table.typ)
4934 continue
4937 if !table.impl {
4938 continue
4941 v := rv.Interface().(Iface).Get()
4942 if v != want {
4943 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, v, want)
4946 fct := rv.MethodByName("Get")
4947 out := fct.Call(nil)
4948 if !DeepEqual(out[0].Interface(), want) {
4949 t.Errorf("test-%d-%d: x.Get()=%v. want=%v\n", i, j, out[0].Interface(), want)
4956 func TestChanOf(t *testing.T) {
4957 // check construction and use of type not in binary
4958 type T string
4959 ct := ChanOf(BothDir, TypeOf(T("")))
4960 v := MakeChan(ct, 2)
4961 runtime.GC()
4962 v.Send(ValueOf(T("hello")))
4963 runtime.GC()
4964 v.Send(ValueOf(T("world")))
4965 runtime.GC()
4967 sv1, _ := v.Recv()
4968 sv2, _ := v.Recv()
4969 s1 := sv1.String()
4970 s2 := sv2.String()
4971 if s1 != "hello" || s2 != "world" {
4972 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
4975 // check that type already in binary is found
4976 type T1 int
4977 checkSameType(t, ChanOf(BothDir, TypeOf(T1(1))), (chan T1)(nil))
4980 func TestChanOfDir(t *testing.T) {
4981 // check construction and use of type not in binary
4982 type T string
4983 crt := ChanOf(RecvDir, TypeOf(T("")))
4984 cst := ChanOf(SendDir, TypeOf(T("")))
4986 // check that type already in binary is found
4987 type T1 int
4988 checkSameType(t, ChanOf(RecvDir, TypeOf(T1(1))), (<-chan T1)(nil))
4989 checkSameType(t, ChanOf(SendDir, TypeOf(T1(1))), (chan<- T1)(nil))
4991 // check String form of ChanDir
4992 if crt.ChanDir().String() != "<-chan" {
4993 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
4995 if cst.ChanDir().String() != "chan<-" {
4996 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
5000 func TestChanOfGC(t *testing.T) {
5001 done := make(chan bool, 1)
5002 go func() {
5003 select {
5004 case <-done:
5005 case <-time.After(5 * time.Second):
5006 panic("deadlock in TestChanOfGC")
5010 defer func() {
5011 done <- true
5014 type T *uintptr
5015 tt := TypeOf(T(nil))
5016 ct := ChanOf(BothDir, tt)
5018 // NOTE: The garbage collector handles allocated channels specially,
5019 // so we have to save pointers to channels in x; the pointer code will
5020 // use the gc info in the newly constructed chan type.
5021 const n = 100
5022 var x []interface{}
5023 for i := 0; i < n; i++ {
5024 v := MakeChan(ct, n)
5025 for j := 0; j < n; j++ {
5026 p := new(uintptr)
5027 *p = uintptr(i*n + j)
5028 v.Send(ValueOf(p).Convert(tt))
5030 pv := New(ct)
5031 pv.Elem().Set(v)
5032 x = append(x, pv.Interface())
5034 runtime.GC()
5036 for i, xi := range x {
5037 v := ValueOf(xi).Elem()
5038 for j := 0; j < n; j++ {
5039 pv, _ := v.Recv()
5040 k := pv.Elem().Interface()
5041 if k != uintptr(i*n+j) {
5042 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5048 func TestMapOf(t *testing.T) {
5049 // check construction and use of type not in binary
5050 type K string
5051 type V float64
5053 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
5054 runtime.GC()
5055 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
5056 runtime.GC()
5058 s := fmt.Sprint(v.Interface())
5059 want := "map[a:1]"
5060 if s != want {
5061 t.Errorf("constructed map = %s, want %s", s, want)
5064 // check that type already in binary is found
5065 checkSameType(t, MapOf(TypeOf(V(0)), TypeOf(K(""))), map[V]K(nil))
5067 // check that invalid key type panics
5068 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
5071 func TestMapOfGCKeys(t *testing.T) {
5072 type T *uintptr
5073 tt := TypeOf(T(nil))
5074 mt := MapOf(tt, TypeOf(false))
5076 // NOTE: The garbage collector handles allocated maps specially,
5077 // so we have to save pointers to maps in x; the pointer code will
5078 // use the gc info in the newly constructed map type.
5079 const n = 100
5080 var x []interface{}
5081 for i := 0; i < n; i++ {
5082 v := MakeMap(mt)
5083 for j := 0; j < n; j++ {
5084 p := new(uintptr)
5085 *p = uintptr(i*n + j)
5086 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
5088 pv := New(mt)
5089 pv.Elem().Set(v)
5090 x = append(x, pv.Interface())
5092 runtime.GC()
5094 for i, xi := range x {
5095 v := ValueOf(xi).Elem()
5096 var out []int
5097 for _, kv := range v.MapKeys() {
5098 out = append(out, int(kv.Elem().Interface().(uintptr)))
5100 sort.Ints(out)
5101 for j, k := range out {
5102 if k != i*n+j {
5103 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5109 func TestMapOfGCValues(t *testing.T) {
5110 type T *uintptr
5111 tt := TypeOf(T(nil))
5112 mt := MapOf(TypeOf(1), tt)
5114 // NOTE: The garbage collector handles allocated maps specially,
5115 // so we have to save pointers to maps in x; the pointer code will
5116 // use the gc info in the newly constructed map type.
5117 const n = 100
5118 var x []interface{}
5119 for i := 0; i < n; i++ {
5120 v := MakeMap(mt)
5121 for j := 0; j < n; j++ {
5122 p := new(uintptr)
5123 *p = uintptr(i*n + j)
5124 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
5126 pv := New(mt)
5127 pv.Elem().Set(v)
5128 x = append(x, pv.Interface())
5130 runtime.GC()
5132 for i, xi := range x {
5133 v := ValueOf(xi).Elem()
5134 for j := 0; j < n; j++ {
5135 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
5136 if k != uintptr(i*n+j) {
5137 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
5143 func TestTypelinksSorted(t *testing.T) {
5144 var last string
5145 for i, n := range TypeLinks() {
5146 if n < last {
5147 t.Errorf("typelinks not sorted: %q [%d] > %q [%d]", last, i-1, n, i)
5149 last = n
5153 func TestFuncOf(t *testing.T) {
5154 // check construction and use of type not in binary
5155 type K string
5156 type V float64
5158 fn := func(args []Value) []Value {
5159 if len(args) != 1 {
5160 t.Errorf("args == %v, want exactly one arg", args)
5161 } else if args[0].Type() != TypeOf(K("")) {
5162 t.Errorf("args[0] is type %v, want %v", args[0].Type(), TypeOf(K("")))
5163 } else if args[0].String() != "gopher" {
5164 t.Errorf("args[0] = %q, want %q", args[0].String(), "gopher")
5166 return []Value{ValueOf(V(3.14))}
5168 v := MakeFunc(FuncOf([]Type{TypeOf(K(""))}, []Type{TypeOf(V(0))}, false), fn)
5170 outs := v.Call([]Value{ValueOf(K("gopher"))})
5171 if len(outs) != 1 {
5172 t.Fatalf("v.Call returned %v, want exactly one result", outs)
5173 } else if outs[0].Type() != TypeOf(V(0)) {
5174 t.Fatalf("c.Call[0] is type %v, want %v", outs[0].Type(), TypeOf(V(0)))
5176 f := outs[0].Float()
5177 if f != 3.14 {
5178 t.Errorf("constructed func returned %f, want %f", f, 3.14)
5181 // check that types already in binary are found
5182 type T1 int
5183 testCases := []struct {
5184 in, out []Type
5185 variadic bool
5186 want interface{}
5188 {in: []Type{TypeOf(T1(0))}, want: (func(T1))(nil)},
5189 {in: []Type{TypeOf(int(0))}, want: (func(int))(nil)},
5190 {in: []Type{SliceOf(TypeOf(int(0)))}, variadic: true, want: (func(...int))(nil)},
5191 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false)}, want: (func(int) bool)(nil)},
5192 {in: []Type{TypeOf(int(0))}, out: []Type{TypeOf(false), TypeOf("")}, want: (func(int) (bool, string))(nil)},
5194 for _, tt := range testCases {
5195 checkSameType(t, FuncOf(tt.in, tt.out, tt.variadic), tt.want)
5198 // check that variadic requires last element be a slice.
5199 FuncOf([]Type{TypeOf(1), TypeOf(""), SliceOf(TypeOf(false))}, nil, true)
5200 shouldPanic(func() { FuncOf([]Type{TypeOf(0), TypeOf(""), TypeOf(false)}, nil, true) })
5201 shouldPanic(func() { FuncOf(nil, nil, true) })
5204 type B1 struct {
5205 X int
5206 Y int
5207 Z int
5210 func BenchmarkFieldByName1(b *testing.B) {
5211 t := TypeOf(B1{})
5212 b.RunParallel(func(pb *testing.PB) {
5213 for pb.Next() {
5214 t.FieldByName("Z")
5219 func BenchmarkFieldByName2(b *testing.B) {
5220 t := TypeOf(S3{})
5221 b.RunParallel(func(pb *testing.PB) {
5222 for pb.Next() {
5223 t.FieldByName("B")
5228 type R0 struct {
5235 type R1 struct {
5242 type R2 R1
5243 type R3 R1
5244 type R4 R1
5246 type R5 struct {
5248 *R10
5249 *R11
5250 *R12
5253 type R6 R5
5254 type R7 R5
5255 type R8 R5
5257 type R9 struct {
5258 *R13
5259 *R14
5260 *R15
5261 *R16
5264 type R10 R9
5265 type R11 R9
5266 type R12 R9
5268 type R13 struct {
5269 *R17
5270 *R18
5271 *R19
5272 *R20
5275 type R14 R13
5276 type R15 R13
5277 type R16 R13
5279 type R17 struct {
5280 *R21
5281 *R22
5282 *R23
5283 *R24
5286 type R18 R17
5287 type R19 R17
5288 type R20 R17
5290 type R21 struct {
5291 X int
5294 type R22 R21
5295 type R23 R21
5296 type R24 R21
5298 func TestEmbed(t *testing.T) {
5299 typ := TypeOf(R0{})
5300 f, ok := typ.FieldByName("X")
5301 if ok {
5302 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
5306 func BenchmarkFieldByName3(b *testing.B) {
5307 t := TypeOf(R0{})
5308 b.RunParallel(func(pb *testing.PB) {
5309 for pb.Next() {
5310 t.FieldByName("X")
5315 type S struct {
5316 i1 int64
5317 i2 int64
5320 func BenchmarkInterfaceBig(b *testing.B) {
5321 v := ValueOf(S{})
5322 b.RunParallel(func(pb *testing.PB) {
5323 for pb.Next() {
5324 v.Interface()
5327 b.StopTimer()
5330 func TestAllocsInterfaceBig(t *testing.T) {
5331 if testing.Short() {
5332 t.Skip("skipping malloc count in short mode")
5334 v := ValueOf(S{})
5335 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
5336 t.Error("allocs:", allocs)
5340 func BenchmarkInterfaceSmall(b *testing.B) {
5341 v := ValueOf(int64(0))
5342 b.RunParallel(func(pb *testing.PB) {
5343 for pb.Next() {
5344 v.Interface()
5349 func TestAllocsInterfaceSmall(t *testing.T) {
5350 if testing.Short() {
5351 t.Skip("skipping malloc count in short mode")
5353 v := ValueOf(int64(0))
5354 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
5355 t.Error("allocs:", allocs)
5359 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
5360 // The basic usage is:
5362 // for x.Next() {
5363 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
5364 // }
5366 // Each iteration of the loop returns a different set of results, until all
5367 // possible result sets have been explored. It is okay for different code paths
5368 // to make different method call sequences on x, but there must be no
5369 // other source of non-determinism in the call sequences.
5371 // When faced with a new decision, x chooses randomly. Future explorations
5372 // of that path will choose successive values for the result. Thus, stopping
5373 // the loop after a fixed number of iterations gives somewhat stochastic
5374 // testing.
5376 // Example:
5378 // for x.Next() {
5379 // v := make([]bool, x.Choose(4))
5380 // for i := range v {
5381 // v[i] = x.Maybe()
5382 // }
5383 // fmt.Println(v)
5384 // }
5386 // prints (in some order):
5388 // []
5389 // [false]
5390 // [true]
5391 // [false false]
5392 // [false true]
5393 // ...
5394 // [true true]
5395 // [false false false]
5396 // ...
5397 // [true true true]
5398 // [false false false false]
5399 // ...
5400 // [true true true true]
5402 type exhaustive struct {
5403 r *rand.Rand
5404 pos int
5405 last []choice
5408 type choice struct {
5409 off int
5410 n int
5411 max int
5414 func (x *exhaustive) Next() bool {
5415 if x.r == nil {
5416 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
5418 x.pos = 0
5419 if x.last == nil {
5420 x.last = []choice{}
5421 return true
5423 for i := len(x.last) - 1; i >= 0; i-- {
5424 c := &x.last[i]
5425 if c.n+1 < c.max {
5426 c.n++
5427 x.last = x.last[:i+1]
5428 return true
5431 return false
5434 func (x *exhaustive) Choose(max int) int {
5435 if x.pos >= len(x.last) {
5436 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
5438 c := &x.last[x.pos]
5439 x.pos++
5440 if c.max != max {
5441 panic("inconsistent use of exhaustive tester")
5443 return (c.n + c.off) % max
5446 func (x *exhaustive) Maybe() bool {
5447 return x.Choose(2) == 1
5450 func GCFunc(args []Value) []Value {
5451 runtime.GC()
5452 return []Value{}
5455 func TestReflectFuncTraceback(t *testing.T) {
5456 f := MakeFunc(TypeOf(func() {}), GCFunc)
5457 f.Call([]Value{})
5460 func TestReflectMethodTraceback(t *testing.T) {
5461 p := Point{3, 4}
5462 m := ValueOf(p).MethodByName("GCMethod")
5463 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
5464 if i != 8 {
5465 t.Errorf("Call returned %d; want 8", i)
5469 func TestBigZero(t *testing.T) {
5470 const size = 1 << 10
5471 var v [size]byte
5472 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
5473 for i := 0; i < size; i++ {
5474 if z[i] != 0 {
5475 t.Fatalf("Zero object not all zero, index %d", i)
5480 func TestFieldByIndexNil(t *testing.T) {
5481 type P struct {
5482 F int
5484 type T struct {
5487 v := ValueOf(T{})
5489 v.FieldByName("P") // should be fine
5491 defer func() {
5492 if err := recover(); err == nil {
5493 t.Fatalf("no error")
5494 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
5495 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
5498 v.FieldByName("F") // should panic
5500 t.Fatalf("did not panic")
5503 // Given
5504 // type Outer struct {
5505 // *Inner
5506 // ...
5507 // }
5508 // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
5509 // The implementation is logically:
5510 // func (p *Outer) M() {
5511 // (p.Inner).M()
5512 // }
5513 // but since the only change here is the replacement of one pointer receiver with another,
5514 // the actual generated code overwrites the original receiver with the p.Inner pointer and
5515 // then jumps to the M method expecting the *Inner receiver.
5517 // During reflect.Value.Call, we create an argument frame and the associated data structures
5518 // to describe it to the garbage collector, populate the frame, call reflect.call to
5519 // run a function call using that frame, and then copy the results back out of the frame.
5520 // The reflect.call function does a memmove of the frame structure onto the
5521 // stack (to set up the inputs), runs the call, and the memmoves the stack back to
5522 // the frame structure (to preserve the outputs).
5524 // Originally reflect.call did not distinguish inputs from outputs: both memmoves
5525 // were for the full stack frame. However, in the case where the called function was
5526 // one of these wrappers, the rewritten receiver is almost certainly a different type
5527 // than the original receiver. This is not a problem on the stack, where we use the
5528 // program counter to determine the type information and understand that
5529 // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
5530 // memory word is now an *Inner. But in the statically typed argument frame created
5531 // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
5532 // off the stack into the frame will store an *Inner there, and then if a garbage collection
5533 // happens to scan that argument frame before it is discarded, it will scan the *Inner
5534 // memory as if it were an *Outer. If the two have different memory layouts, the
5535 // collection will interpret the memory incorrectly.
5537 // One such possible incorrect interpretation is to treat two arbitrary memory words
5538 // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
5539 // an interface requires dereferencing the itab word, the misinterpretation will try to
5540 // deference Inner.P1, causing a crash during garbage collection.
5542 // This came up in a real program in issue 7725.
5544 type Outer struct {
5545 *Inner
5546 R io.Reader
5549 type Inner struct {
5550 X *Outer
5551 P1 uintptr
5552 P2 uintptr
5555 func (pi *Inner) M() {
5556 // Clear references to pi so that the only way the
5557 // garbage collection will find the pointer is in the
5558 // argument frame, typed as a *Outer.
5559 pi.X.Inner = nil
5561 // Set up an interface value that will cause a crash.
5562 // P1 = 1 is a non-zero, so the interface looks non-nil.
5563 // P2 = pi ensures that the data word points into the
5564 // allocated heap; if not the collection skips the interface
5565 // value as irrelevant, without dereferencing P1.
5566 pi.P1 = 1
5567 pi.P2 = uintptr(unsafe.Pointer(pi))
5570 func TestCallMethodJump(t *testing.T) {
5571 // In reflect.Value.Call, trigger a garbage collection after reflect.call
5572 // returns but before the args frame has been discarded.
5573 // This is a little clumsy but makes the failure repeatable.
5574 *CallGC = true
5576 p := &Outer{Inner: new(Inner)}
5577 p.Inner.X = p
5578 ValueOf(p).Method(0).Call(nil)
5580 // Stop garbage collecting during reflect.call.
5581 *CallGC = false
5584 func TestMakeFuncStackCopy(t *testing.T) {
5585 target := func(in []Value) []Value {
5586 runtime.GC()
5587 useStack(16)
5588 return []Value{ValueOf(9)}
5591 var concrete func(*int, int) int
5592 fn := MakeFunc(ValueOf(concrete).Type(), target)
5593 ValueOf(&concrete).Elem().Set(fn)
5594 x := concrete(nil, 7)
5595 if x != 9 {
5596 t.Errorf("have %#q want 9", x)
5600 // use about n KB of stack
5601 func useStack(n int) {
5602 if n == 0 {
5603 return
5605 var b [1024]byte // makes frame about 1KB
5606 useStack(n - 1 + int(b[99]))
5609 type Impl struct{}
5611 func (Impl) F() {}
5613 func TestValueString(t *testing.T) {
5614 rv := ValueOf(Impl{})
5615 if rv.String() != "<reflect_test.Impl Value>" {
5616 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
5619 method := rv.Method(0)
5620 if method.String() != "<func() Value>" {
5621 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
5625 func TestInvalid(t *testing.T) {
5626 // Used to have inconsistency between IsValid() and Kind() != Invalid.
5627 type T struct{ v interface{} }
5629 v := ValueOf(T{}).Field(0)
5630 if v.IsValid() != true || v.Kind() != Interface {
5631 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
5633 v = v.Elem()
5634 if v.IsValid() != false || v.Kind() != Invalid {
5635 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
5639 // Issue 8917.
5640 func TestLargeGCProg(t *testing.T) {
5641 fv := ValueOf(func([256]*byte) {})
5642 fv.Call([]Value{ValueOf([256]*byte{})})
5645 func fieldIndexRecover(t Type, i int) (recovered interface{}) {
5646 defer func() {
5647 recovered = recover()
5650 t.Field(i)
5651 return
5654 // Issue 15046.
5655 func TestTypeFieldOutOfRangePanic(t *testing.T) {
5656 typ := TypeOf(struct{ X int }{10})
5657 testIndices := [...]struct {
5658 i int
5659 mustPanic bool
5661 0: {-2, true},
5662 1: {0, false},
5663 2: {1, true},
5664 3: {1 << 10, true},
5666 for i, tt := range testIndices {
5667 recoveredErr := fieldIndexRecover(typ, tt.i)
5668 if tt.mustPanic {
5669 if recoveredErr == nil {
5670 t.Errorf("#%d: fieldIndex %d expected to panic", i, tt.i)
5672 } else {
5673 if recoveredErr != nil {
5674 t.Errorf("#%d: got err=%v, expected no panic", i, recoveredErr)
5680 // Issue 9179.
5681 func TestCallGC(t *testing.T) {
5682 f := func(a, b, c, d, e string) {
5684 g := func(in []Value) []Value {
5685 runtime.GC()
5686 return nil
5688 typ := ValueOf(f).Type()
5689 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
5690 f2("four", "five5", "six666", "seven77", "eight888")
5693 // Issue 18635 (function version).
5694 func TestKeepFuncLive(t *testing.T) {
5695 // Test that we keep makeFuncImpl live as long as it is
5696 // referenced on the stack.
5697 typ := TypeOf(func(i int) {})
5698 var f, g func(in []Value) []Value
5699 f = func(in []Value) []Value {
5700 clobber()
5701 i := int(in[0].Int())
5702 if i > 0 {
5703 // We can't use Value.Call here because
5704 // runtime.call* will keep the makeFuncImpl
5705 // alive. However, by converting it to an
5706 // interface value and calling that,
5707 // reflect.callReflect is the only thing that
5708 // can keep the makeFuncImpl live.
5710 // Alternate between f and g so that if we do
5711 // reuse the memory prematurely it's more
5712 // likely to get obviously corrupted.
5713 MakeFunc(typ, g).Interface().(func(i int))(i - 1)
5715 return nil
5717 g = func(in []Value) []Value {
5718 clobber()
5719 i := int(in[0].Int())
5720 MakeFunc(typ, f).Interface().(func(i int))(i)
5721 return nil
5723 MakeFunc(typ, f).Call([]Value{ValueOf(10)})
5726 type UnExportedFirst int
5728 func (i UnExportedFirst) ΦExported() {}
5729 func (i UnExportedFirst) unexported() {}
5731 // Issue 21177
5732 func TestMethodByNameUnExportedFirst(t *testing.T) {
5733 defer func() {
5734 if recover() != nil {
5735 t.Errorf("should not panic")
5738 typ := TypeOf(UnExportedFirst(0))
5739 m, _ := typ.MethodByName("ΦExported")
5740 if m.Name != "ΦExported" {
5741 t.Errorf("got %s, expected ΦExported", m.Name)
5745 // Issue 18635 (method version).
5746 type KeepMethodLive struct{}
5748 func (k KeepMethodLive) Method1(i int) {
5749 clobber()
5750 if i > 0 {
5751 ValueOf(k).MethodByName("Method2").Interface().(func(i int))(i - 1)
5755 func (k KeepMethodLive) Method2(i int) {
5756 clobber()
5757 ValueOf(k).MethodByName("Method1").Interface().(func(i int))(i)
5760 func TestKeepMethodLive(t *testing.T) {
5761 // Test that we keep methodValue live as long as it is
5762 // referenced on the stack.
5763 KeepMethodLive{}.Method1(10)
5766 // clobber tries to clobber unreachable memory.
5767 func clobber() {
5768 runtime.GC()
5769 for i := 1; i < 32; i++ {
5770 for j := 0; j < 10; j++ {
5771 obj := make([]*byte, i)
5772 sink = obj
5775 runtime.GC()
5778 type funcLayoutTest struct {
5779 rcvr, t Type
5780 size, argsize, retOffset uintptr
5781 stack []byte // pointer bitmap: 1 is pointer, 0 is scalar (or uninitialized)
5782 gc []byte
5785 var funcLayoutTests []funcLayoutTest
5787 func init() {
5788 var argAlign uintptr = PtrSize
5789 if runtime.GOARCH == "amd64p32" {
5790 argAlign = 2 * PtrSize
5792 roundup := func(x uintptr, a uintptr) uintptr {
5793 return (x + a - 1) / a * a
5796 funcLayoutTests = append(funcLayoutTests,
5797 funcLayoutTest{
5798 nil,
5799 ValueOf(func(a, b string) string { return "" }).Type(),
5800 6 * PtrSize,
5801 4 * PtrSize,
5802 4 * PtrSize,
5803 []byte{1, 0, 1},
5804 []byte{1, 0, 1, 0, 1},
5807 var r []byte
5808 if PtrSize == 4 {
5809 r = []byte{0, 0, 0, 1}
5810 } else {
5811 r = []byte{0, 0, 1}
5813 funcLayoutTests = append(funcLayoutTests,
5814 funcLayoutTest{
5815 nil,
5816 ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
5817 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
5818 roundup(3*4, PtrSize) + PtrSize + 2,
5819 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
5824 funcLayoutTests = append(funcLayoutTests,
5825 funcLayoutTest{
5826 nil,
5827 ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
5828 4 * PtrSize,
5829 4 * PtrSize,
5830 4 * PtrSize,
5831 []byte{1, 0, 1, 1},
5832 []byte{1, 0, 1, 1},
5835 type S struct {
5836 a, b uintptr
5837 c, d *byte
5839 funcLayoutTests = append(funcLayoutTests,
5840 funcLayoutTest{
5841 nil,
5842 ValueOf(func(a S) {}).Type(),
5843 4 * PtrSize,
5844 4 * PtrSize,
5845 4 * PtrSize,
5846 []byte{0, 0, 1, 1},
5847 []byte{0, 0, 1, 1},
5850 funcLayoutTests = append(funcLayoutTests,
5851 funcLayoutTest{
5852 ValueOf((*byte)(nil)).Type(),
5853 ValueOf(func(a uintptr, b *int) {}).Type(),
5854 roundup(3*PtrSize, argAlign),
5855 3 * PtrSize,
5856 roundup(3*PtrSize, argAlign),
5857 []byte{1, 0, 1},
5858 []byte{1, 0, 1},
5861 funcLayoutTests = append(funcLayoutTests,
5862 funcLayoutTest{
5863 nil,
5864 ValueOf(func(a uintptr) {}).Type(),
5865 roundup(PtrSize, argAlign),
5866 PtrSize,
5867 roundup(PtrSize, argAlign),
5868 []byte{},
5869 []byte{},
5872 funcLayoutTests = append(funcLayoutTests,
5873 funcLayoutTest{
5874 nil,
5875 ValueOf(func() uintptr { return 0 }).Type(),
5876 PtrSize,
5879 []byte{},
5880 []byte{},
5883 funcLayoutTests = append(funcLayoutTests,
5884 funcLayoutTest{
5885 ValueOf(uintptr(0)).Type(),
5886 ValueOf(func(a uintptr) {}).Type(),
5887 2 * PtrSize,
5888 2 * PtrSize,
5889 2 * PtrSize,
5890 []byte{1},
5891 []byte{1},
5892 // Note: this one is tricky, as the receiver is not a pointer. But we
5893 // pass the receiver by reference to the autogenerated pointer-receiver
5894 // version of the function.
5898 func TestFuncLayout(t *testing.T) {
5899 t.Skip("gccgo does not use funcLayout")
5900 for _, lt := range funcLayoutTests {
5901 typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr)
5902 if typ.Size() != lt.size {
5903 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size)
5905 if argsize != lt.argsize {
5906 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize)
5908 if retOffset != lt.retOffset {
5909 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset)
5911 if !bytes.Equal(stack, lt.stack) {
5912 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack)
5914 if !bytes.Equal(gc, lt.gc) {
5915 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc)
5917 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
5918 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs)
5923 func verifyGCBits(t *testing.T, typ Type, bits []byte) {
5924 heapBits := GCBits(New(typ).Interface())
5925 if !bytes.Equal(heapBits, bits) {
5926 t.Errorf("heapBits incorrect for %v\nhave %v\nwant %v", typ, heapBits, bits)
5930 func verifyGCBitsSlice(t *testing.T, typ Type, cap int, bits []byte) {
5931 // Creating a slice causes the runtime to repeat a bitmap,
5932 // which exercises a different path from making the compiler
5933 // repeat a bitmap for a small array or executing a repeat in
5934 // a GC program.
5935 val := MakeSlice(typ, 0, cap)
5936 data := NewAt(ArrayOf(cap, typ), unsafe.Pointer(val.Pointer()))
5937 heapBits := GCBits(data.Interface())
5938 // Repeat the bitmap for the slice size, trimming scalars in
5939 // the last element.
5940 bits = rep(cap, bits)
5941 for len(bits) > 2 && bits[len(bits)-1] == 0 {
5942 bits = bits[:len(bits)-1]
5944 if len(bits) == 2 && bits[0] == 0 && bits[1] == 0 {
5945 bits = bits[:0]
5947 if !bytes.Equal(heapBits, bits) {
5948 t.Errorf("heapBits incorrect for make(%v, 0, %v)\nhave %v\nwant %v", typ, cap, heapBits, bits)
5952 func TestGCBits(t *testing.T) {
5953 t.Skip("gccgo does not use gcbits yet")
5955 verifyGCBits(t, TypeOf((*byte)(nil)), []byte{1})
5957 // Building blocks for types seen by the compiler (like [2]Xscalar).
5958 // The compiler will create the type structures for the derived types,
5959 // including their GC metadata.
5960 type Xscalar struct{ x uintptr }
5961 type Xptr struct{ x *byte }
5962 type Xptrscalar struct {
5963 *byte
5964 uintptr
5966 type Xscalarptr struct {
5967 uintptr
5968 *byte
5970 type Xbigptrscalar struct {
5971 _ [100]*byte
5972 _ [100]uintptr
5975 var Tscalar, Tint64, Tptr, Tscalarptr, Tptrscalar, Tbigptrscalar Type
5977 // Building blocks for types constructed by reflect.
5978 // This code is in a separate block so that code below
5979 // cannot accidentally refer to these.
5980 // The compiler must NOT see types derived from these
5981 // (for example, [2]Scalar must NOT appear in the program),
5982 // or else reflect will use it instead of having to construct one.
5983 // The goal is to test the construction.
5984 type Scalar struct{ x uintptr }
5985 type Ptr struct{ x *byte }
5986 type Ptrscalar struct {
5987 *byte
5988 uintptr
5990 type Scalarptr struct {
5991 uintptr
5992 *byte
5994 type Bigptrscalar struct {
5995 _ [100]*byte
5996 _ [100]uintptr
5998 type Int64 int64
5999 Tscalar = TypeOf(Scalar{})
6000 Tint64 = TypeOf(Int64(0))
6001 Tptr = TypeOf(Ptr{})
6002 Tscalarptr = TypeOf(Scalarptr{})
6003 Tptrscalar = TypeOf(Ptrscalar{})
6004 Tbigptrscalar = TypeOf(Bigptrscalar{})
6007 empty := []byte{}
6009 verifyGCBits(t, TypeOf(Xscalar{}), empty)
6010 verifyGCBits(t, Tscalar, empty)
6011 verifyGCBits(t, TypeOf(Xptr{}), lit(1))
6012 verifyGCBits(t, Tptr, lit(1))
6013 verifyGCBits(t, TypeOf(Xscalarptr{}), lit(0, 1))
6014 verifyGCBits(t, Tscalarptr, lit(0, 1))
6015 verifyGCBits(t, TypeOf(Xptrscalar{}), lit(1))
6016 verifyGCBits(t, Tptrscalar, lit(1))
6018 verifyGCBits(t, TypeOf([0]Xptr{}), empty)
6019 verifyGCBits(t, ArrayOf(0, Tptr), empty)
6020 verifyGCBits(t, TypeOf([1]Xptrscalar{}), lit(1))
6021 verifyGCBits(t, ArrayOf(1, Tptrscalar), lit(1))
6022 verifyGCBits(t, TypeOf([2]Xscalar{}), empty)
6023 verifyGCBits(t, ArrayOf(2, Tscalar), empty)
6024 verifyGCBits(t, TypeOf([10000]Xscalar{}), empty)
6025 verifyGCBits(t, ArrayOf(10000, Tscalar), empty)
6026 verifyGCBits(t, TypeOf([2]Xptr{}), lit(1, 1))
6027 verifyGCBits(t, ArrayOf(2, Tptr), lit(1, 1))
6028 verifyGCBits(t, TypeOf([10000]Xptr{}), rep(10000, lit(1)))
6029 verifyGCBits(t, ArrayOf(10000, Tptr), rep(10000, lit(1)))
6030 verifyGCBits(t, TypeOf([2]Xscalarptr{}), lit(0, 1, 0, 1))
6031 verifyGCBits(t, ArrayOf(2, Tscalarptr), lit(0, 1, 0, 1))
6032 verifyGCBits(t, TypeOf([10000]Xscalarptr{}), rep(10000, lit(0, 1)))
6033 verifyGCBits(t, ArrayOf(10000, Tscalarptr), rep(10000, lit(0, 1)))
6034 verifyGCBits(t, TypeOf([2]Xptrscalar{}), lit(1, 0, 1))
6035 verifyGCBits(t, ArrayOf(2, Tptrscalar), lit(1, 0, 1))
6036 verifyGCBits(t, TypeOf([10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6037 verifyGCBits(t, ArrayOf(10000, Tptrscalar), rep(10000, lit(1, 0)))
6038 verifyGCBits(t, TypeOf([1][10000]Xptrscalar{}), rep(10000, lit(1, 0)))
6039 verifyGCBits(t, ArrayOf(1, ArrayOf(10000, Tptrscalar)), rep(10000, lit(1, 0)))
6040 verifyGCBits(t, TypeOf([2][10000]Xptrscalar{}), rep(2*10000, lit(1, 0)))
6041 verifyGCBits(t, ArrayOf(2, ArrayOf(10000, Tptrscalar)), rep(2*10000, lit(1, 0)))
6042 verifyGCBits(t, TypeOf([4]Xbigptrscalar{}), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6043 verifyGCBits(t, ArrayOf(4, Tbigptrscalar), join(rep(3, join(rep(100, lit(1)), rep(100, lit(0)))), rep(100, lit(1))))
6045 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 0, empty)
6046 verifyGCBitsSlice(t, SliceOf(Tptr), 0, empty)
6047 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 1, lit(1))
6048 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 1, lit(1))
6049 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 2, lit(0))
6050 verifyGCBitsSlice(t, SliceOf(Tscalar), 2, lit(0))
6051 verifyGCBitsSlice(t, TypeOf([]Xscalar{}), 10000, lit(0))
6052 verifyGCBitsSlice(t, SliceOf(Tscalar), 10000, lit(0))
6053 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 2, lit(1))
6054 verifyGCBitsSlice(t, SliceOf(Tptr), 2, lit(1))
6055 verifyGCBitsSlice(t, TypeOf([]Xptr{}), 10000, lit(1))
6056 verifyGCBitsSlice(t, SliceOf(Tptr), 10000, lit(1))
6057 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 2, lit(0, 1))
6058 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 2, lit(0, 1))
6059 verifyGCBitsSlice(t, TypeOf([]Xscalarptr{}), 10000, lit(0, 1))
6060 verifyGCBitsSlice(t, SliceOf(Tscalarptr), 10000, lit(0, 1))
6061 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 2, lit(1, 0))
6062 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 2, lit(1, 0))
6063 verifyGCBitsSlice(t, TypeOf([]Xptrscalar{}), 10000, lit(1, 0))
6064 verifyGCBitsSlice(t, SliceOf(Tptrscalar), 10000, lit(1, 0))
6065 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 1, rep(10000, lit(1, 0)))
6066 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 1, rep(10000, lit(1, 0)))
6067 verifyGCBitsSlice(t, TypeOf([][10000]Xptrscalar{}), 2, rep(10000, lit(1, 0)))
6068 verifyGCBitsSlice(t, SliceOf(ArrayOf(10000, Tptrscalar)), 2, rep(10000, lit(1, 0)))
6069 verifyGCBitsSlice(t, TypeOf([]Xbigptrscalar{}), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6070 verifyGCBitsSlice(t, SliceOf(Tbigptrscalar), 4, join(rep(100, lit(1)), rep(100, lit(0))))
6072 verifyGCBits(t, TypeOf((chan [100]Xscalar)(nil)), lit(1))
6073 verifyGCBits(t, ChanOf(BothDir, ArrayOf(100, Tscalar)), lit(1))
6075 verifyGCBits(t, TypeOf((func([10000]Xscalarptr))(nil)), lit(1))
6076 verifyGCBits(t, FuncOf([]Type{ArrayOf(10000, Tscalarptr)}, nil, false), lit(1))
6078 verifyGCBits(t, TypeOf((map[[10000]Xscalarptr]Xscalar)(nil)), lit(1))
6079 verifyGCBits(t, MapOf(ArrayOf(10000, Tscalarptr), Tscalar), lit(1))
6081 verifyGCBits(t, TypeOf((*[10000]Xscalar)(nil)), lit(1))
6082 verifyGCBits(t, PtrTo(ArrayOf(10000, Tscalar)), lit(1))
6084 verifyGCBits(t, TypeOf(([][10000]Xscalar)(nil)), lit(1))
6085 verifyGCBits(t, SliceOf(ArrayOf(10000, Tscalar)), lit(1))
6087 hdr := make([]byte, 8/PtrSize)
6089 verifyMapBucket := func(t *testing.T, k, e Type, m interface{}, want []byte) {
6090 verifyGCBits(t, MapBucketOf(k, e), want)
6091 verifyGCBits(t, CachedBucketOf(TypeOf(m)), want)
6093 verifyMapBucket(t,
6094 Tscalar, Tptr,
6095 map[Xscalar]Xptr(nil),
6096 join(hdr, rep(8, lit(0)), rep(8, lit(1)), lit(1)))
6097 verifyMapBucket(t,
6098 Tscalarptr, Tptr,
6099 map[Xscalarptr]Xptr(nil),
6100 join(hdr, rep(8, lit(0, 1)), rep(8, lit(1)), lit(1)))
6101 verifyMapBucket(t, Tint64, Tptr,
6102 map[int64]Xptr(nil),
6103 join(hdr, rep(8, rep(8/PtrSize, lit(0))), rep(8, lit(1)), naclpad(), lit(1)))
6104 verifyMapBucket(t,
6105 Tscalar, Tscalar,
6106 map[Xscalar]Xscalar(nil),
6107 empty)
6108 verifyMapBucket(t,
6109 ArrayOf(2, Tscalarptr), ArrayOf(3, Tptrscalar),
6110 map[[2]Xscalarptr][3]Xptrscalar(nil),
6111 join(hdr, rep(8*2, lit(0, 1)), rep(8*3, lit(1, 0)), lit(1)))
6112 verifyMapBucket(t,
6113 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
6114 map[[64 / PtrSize]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
6115 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
6116 verifyMapBucket(t,
6117 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize, Tptrscalar),
6118 map[[64/PtrSize + 1]Xscalarptr][64 / PtrSize]Xptrscalar(nil),
6119 join(hdr, rep(8, lit(1)), rep(8*64/PtrSize, lit(1, 0)), lit(1)))
6120 verifyMapBucket(t,
6121 ArrayOf(64/PtrSize, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
6122 map[[64 / PtrSize]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
6123 join(hdr, rep(8*64/PtrSize, lit(0, 1)), rep(8, lit(1)), lit(1)))
6124 verifyMapBucket(t,
6125 ArrayOf(64/PtrSize+1, Tscalarptr), ArrayOf(64/PtrSize+1, Tptrscalar),
6126 map[[64/PtrSize + 1]Xscalarptr][64/PtrSize + 1]Xptrscalar(nil),
6127 join(hdr, rep(8, lit(1)), rep(8, lit(1)), lit(1)))
6130 func naclpad() []byte {
6131 if runtime.GOARCH == "amd64p32" {
6132 return lit(0)
6134 return nil
6137 func rep(n int, b []byte) []byte { return bytes.Repeat(b, n) }
6138 func join(b ...[]byte) []byte { return bytes.Join(b, nil) }
6139 func lit(x ...byte) []byte { return x }
6141 func TestTypeOfTypeOf(t *testing.T) {
6142 // Check that all the type constructors return concrete *rtype implementations.
6143 // It's difficult to test directly because the reflect package is only at arm's length.
6144 // The easiest thing to do is just call a function that crashes if it doesn't get an *rtype.
6145 check := func(name string, typ Type) {
6146 if underlying := TypeOf(typ).String(); underlying != "*reflect.rtype" {
6147 t.Errorf("%v returned %v, not *reflect.rtype", name, underlying)
6151 type T struct{ int }
6152 check("TypeOf", TypeOf(T{}))
6154 check("ArrayOf", ArrayOf(10, TypeOf(T{})))
6155 check("ChanOf", ChanOf(BothDir, TypeOf(T{})))
6156 check("FuncOf", FuncOf([]Type{TypeOf(T{})}, nil, false))
6157 check("MapOf", MapOf(TypeOf(T{}), TypeOf(T{})))
6158 check("PtrTo", PtrTo(TypeOf(T{})))
6159 check("SliceOf", SliceOf(TypeOf(T{})))
6162 type XM struct{ _ bool }
6164 func (*XM) String() string { return "" }
6166 func TestPtrToMethods(t *testing.T) {
6167 var y struct{ XM }
6168 yp := New(TypeOf(y)).Interface()
6169 _, ok := yp.(fmt.Stringer)
6170 if !ok {
6171 t.Fatal("does not implement Stringer, but should")
6175 func TestMapAlloc(t *testing.T) {
6176 m := ValueOf(make(map[int]int, 10))
6177 k := ValueOf(5)
6178 v := ValueOf(7)
6179 allocs := testing.AllocsPerRun(100, func() {
6180 m.SetMapIndex(k, v)
6182 if allocs > 0.5 {
6183 t.Errorf("allocs per map assignment: want 0 got %f", allocs)
6186 const size = 1000
6187 tmp := 0
6188 val := ValueOf(&tmp).Elem()
6189 allocs = testing.AllocsPerRun(100, func() {
6190 mv := MakeMapWithSize(TypeOf(map[int]int{}), size)
6191 // Only adding half of the capacity to not trigger re-allocations due too many overloaded buckets.
6192 for i := 0; i < size/2; i++ {
6193 val.SetInt(int64(i))
6194 mv.SetMapIndex(val, val)
6197 if allocs > 10 {
6198 t.Errorf("allocs per map assignment: want at most 10 got %f", allocs)
6200 // Empirical testing shows that with capacity hint single run will trigger 3 allocations and without 91. I set
6201 // the threshold to 10, to not make it overly brittle if something changes in the initial allocation of the
6202 // map, but to still catch a regression where we keep re-allocating in the hashmap as new entries are added.
6205 func TestChanAlloc(t *testing.T) {
6206 // Note: for a chan int, the return Value must be allocated, so we
6207 // use a chan *int instead.
6208 c := ValueOf(make(chan *int, 1))
6209 v := ValueOf(new(int))
6210 allocs := testing.AllocsPerRun(100, func() {
6211 c.Send(v)
6212 _, _ = c.Recv()
6214 if allocs < 0.5 || allocs > 1.5 {
6215 t.Errorf("allocs per chan send/recv: want 1 got %f", allocs)
6217 // Note: there is one allocation in reflect.recv which seems to be
6218 // a limitation of escape analysis. If that is ever fixed the
6219 // allocs < 0.5 condition will trigger and this test should be fixed.
6222 type TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678 int
6224 type nameTest struct {
6225 v interface{}
6226 want string
6229 var nameTests = []nameTest{
6230 {(*int32)(nil), "int32"},
6231 {(*D1)(nil), "D1"},
6232 {(*[]D1)(nil), ""},
6233 {(*chan D1)(nil), ""},
6234 {(*func() D1)(nil), ""},
6235 {(*<-chan D1)(nil), ""},
6236 {(*chan<- D1)(nil), ""},
6237 {(*interface{})(nil), ""},
6238 {(*interface {
6240 })(nil), ""},
6241 {(*TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678)(nil), "TheNameOfThisTypeIsExactly255BytesLongSoWhenTheCompilerPrependsTheReflectTestPackageNameAndExtraStarTheLinkerRuntimeAndReflectPackagesWillHaveToCorrectlyDecodeTheSecondLengthByte0123456789_0123456789_0123456789_0123456789_0123456789_012345678"},
6244 func TestNames(t *testing.T) {
6245 for _, test := range nameTests {
6246 typ := TypeOf(test.v).Elem()
6247 if got := typ.Name(); got != test.want {
6248 t.Errorf("%v Name()=%q, want %q", typ, got, test.want)
6254 gccgo doesn't really record whether a type is exported.
6255 It's not in the reflect API anyhow.
6257 func TestExported(t *testing.T) {
6258 type ΦExported struct{}
6259 type φUnexported struct{}
6260 type BigP *big
6261 type P int
6262 type p *P
6263 type P2 p
6264 type p3 p
6266 type exportTest struct {
6267 v interface{}
6268 want bool
6270 exportTests := []exportTest{
6271 {D1{}, true},
6272 {(*D1)(nil), true},
6273 {big{}, false},
6274 {(*big)(nil), false},
6275 {(BigP)(nil), true},
6276 {(*BigP)(nil), true},
6277 {ΦExported{}, true},
6278 {φUnexported{}, false},
6279 {P(0), true},
6280 {(p)(nil), false},
6281 {(P2)(nil), true},
6282 {(p3)(nil), false},
6285 for i, test := range exportTests {
6286 typ := TypeOf(test.v)
6287 if got := IsExported(typ); got != test.want {
6288 t.Errorf("%d: %s exported=%v, want %v", i, typ.Name(), got, test.want)
6294 type embed struct {
6295 EmbedWithUnexpMeth
6299 func TestNameBytesAreAligned(t *testing.T) {
6300 typ := TypeOf(embed{})
6301 b := FirstMethodNameBytes(typ)
6302 v := uintptr(unsafe.Pointer(b))
6303 if v%unsafe.Alignof((*byte)(nil)) != 0 {
6304 t.Errorf("reflect.name.bytes pointer is not aligned: %x", v)
6309 func TestTypeStrings(t *testing.T) {
6310 type stringTest struct {
6311 typ Type
6312 want string
6314 stringTests := []stringTest{
6315 {TypeOf(func(int) {}), "func(int)"},
6316 {FuncOf([]Type{TypeOf(int(0))}, nil, false), "func(int)"},
6317 {TypeOf(XM{}), "reflect_test.XM"},
6318 {TypeOf(new(XM)), "*reflect_test.XM"},
6319 {TypeOf(new(XM).String), "func() string"},
6320 {TypeOf(new(XM)).Method(0).Type, "func(*reflect_test.XM) string"},
6321 {ChanOf(3, TypeOf(XM{})), "chan reflect_test.XM"},
6322 {MapOf(TypeOf(int(0)), TypeOf(XM{})), "map[int]reflect_test.XM"},
6323 {ArrayOf(3, TypeOf(XM{})), "[3]reflect_test.XM"},
6324 {ArrayOf(3, TypeOf(struct{}{})), "[3]struct {}"},
6327 for i, test := range stringTests {
6328 if got, want := test.typ.String(), test.want; got != want {
6329 t.Errorf("type %d String()=%q, want %q", i, got, want)
6335 gccgo does not have resolveReflectName.
6337 func TestOffsetLock(t *testing.T) {
6338 var wg sync.WaitGroup
6339 for i := 0; i < 4; i++ {
6340 i := i
6341 wg.Add(1)
6342 go func() {
6343 for j := 0; j < 50; j++ {
6344 ResolveReflectName(fmt.Sprintf("OffsetLockName:%d:%d", i, j))
6346 wg.Done()
6349 wg.Wait()
6353 func BenchmarkNew(b *testing.B) {
6354 v := TypeOf(XM{})
6355 b.RunParallel(func(pb *testing.PB) {
6356 for pb.Next() {
6357 New(v)
6362 func TestSwapper(t *testing.T) {
6363 type I int
6364 var a, b, c I
6365 type pair struct {
6366 x, y int
6368 type pairPtr struct {
6369 x, y int
6370 p *I
6372 type S string
6374 tests := []struct {
6375 in interface{}
6376 i, j int
6377 want interface{}
6380 in: []int{1, 20, 300},
6381 i: 0,
6382 j: 2,
6383 want: []int{300, 20, 1},
6386 in: []uintptr{1, 20, 300},
6387 i: 0,
6388 j: 2,
6389 want: []uintptr{300, 20, 1},
6392 in: []int16{1, 20, 300},
6393 i: 0,
6394 j: 2,
6395 want: []int16{300, 20, 1},
6398 in: []int8{1, 20, 100},
6399 i: 0,
6400 j: 2,
6401 want: []int8{100, 20, 1},
6404 in: []*I{&a, &b, &c},
6405 i: 0,
6406 j: 2,
6407 want: []*I{&c, &b, &a},
6410 in: []string{"eric", "sergey", "larry"},
6411 i: 0,
6412 j: 2,
6413 want: []string{"larry", "sergey", "eric"},
6416 in: []S{"eric", "sergey", "larry"},
6417 i: 0,
6418 j: 2,
6419 want: []S{"larry", "sergey", "eric"},
6422 in: []pair{{1, 2}, {3, 4}, {5, 6}},
6423 i: 0,
6424 j: 2,
6425 want: []pair{{5, 6}, {3, 4}, {1, 2}},
6428 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}},
6429 i: 0,
6430 j: 2,
6431 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}},
6435 for i, tt := range tests {
6436 inStr := fmt.Sprint(tt.in)
6437 Swapper(tt.in)(tt.i, tt.j)
6438 if !DeepEqual(tt.in, tt.want) {
6439 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want)
6444 // TestUnaddressableField tests that the reflect package will not allow
6445 // a type from another package to be used as a named type with an
6446 // unexported field.
6448 // This ensures that unexported fields cannot be modified by other packages.
6449 func TestUnaddressableField(t *testing.T) {
6450 var b Buffer // type defined in reflect, a different package
6451 var localBuffer struct {
6452 buf []byte
6454 lv := ValueOf(&localBuffer).Elem()
6455 rv := ValueOf(b)
6456 shouldPanic(func() {
6457 lv.Set(rv)
6461 type Tint int
6463 type Tint2 = Tint
6465 type Talias1 struct {
6466 byte
6467 uint8
6469 int32
6470 rune
6473 type Talias2 struct {
6474 Tint
6475 Tint2
6478 func TestAliasNames(t *testing.T) {
6479 t1 := Talias1{byte: 1, uint8: 2, int: 3, int32: 4, rune: 5}
6480 out := fmt.Sprintf("%#v", t1)
6481 want := "reflect_test.Talias1{byte:0x1, uint8:0x2, int:3, int32:4, rune:5}"
6482 if out != want {
6483 t.Errorf("Talias1 print:\nhave: %s\nwant: %s", out, want)
6486 t2 := Talias2{Tint: 1, Tint2: 2}
6487 out = fmt.Sprintf("%#v", t2)
6488 want = "reflect_test.Talias2{Tint:1, Tint2:2}"
6489 if out != want {
6490 t.Errorf("Talias2 print:\nhave: %s\nwant: %s", out, want)
6494 func TestIssue22031(t *testing.T) {
6495 type s []struct{ C int }
6497 type t1 struct{ s }
6498 type t2 struct{ f s }
6500 tests := []Value{
6501 ValueOf(t1{s{{}}}).Field(0).Index(0).Field(0),
6502 ValueOf(t2{s{{}}}).Field(0).Index(0).Field(0),
6505 for i, test := range tests {
6506 if test.CanSet() {
6507 t.Errorf("%d: CanSet: got true, want false", i)
6512 type NonExportedFirst int
6514 func (i NonExportedFirst) ΦExported() {}
6515 func (i NonExportedFirst) nonexported() int { panic("wrong") }
6517 func TestIssue22073(t *testing.T) {
6518 m := ValueOf(NonExportedFirst(0)).Method(0)
6520 if got := m.Type().NumOut(); got != 0 {
6521 t.Errorf("NumOut: got %v, want 0", got)
6524 // Shouldn't panic.
6525 m.Call(nil)