libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / reflect / all_test.go
blob6c015ad029fc244d8521f5dd2b392eb6cc89daba
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/rand"
14 "os"
15 . "reflect"
16 "runtime"
17 "sort"
18 "sync"
19 "testing"
20 "time"
21 "unsafe"
24 func TestBool(t *testing.T) {
25 v := ValueOf(true)
26 if v.Bool() != true {
27 t.Fatal("ValueOf(true).Bool() = false")
31 type integer int
32 type T struct {
33 a int
34 b float64
35 c string
36 d *int
39 type pair struct {
40 i interface{}
41 s string
44 func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
46 func assert(t *testing.T, s, want string) {
47 if s != want {
48 t.Errorf("have %#q want %#q", s, want)
52 func typestring(i interface{}) string { return TypeOf(i).String() }
54 var typeTests = []pair{
55 {struct{ x int }{}, "int"},
56 {struct{ x int8 }{}, "int8"},
57 {struct{ x int16 }{}, "int16"},
58 {struct{ x int32 }{}, "int32"},
59 {struct{ x int64 }{}, "int64"},
60 {struct{ x uint }{}, "uint"},
61 {struct{ x uint8 }{}, "uint8"},
62 {struct{ x uint16 }{}, "uint16"},
63 {struct{ x uint32 }{}, "uint32"},
64 {struct{ x uint64 }{}, "uint64"},
65 {struct{ x float32 }{}, "float32"},
66 {struct{ x float64 }{}, "float64"},
67 {struct{ x int8 }{}, "int8"},
68 {struct{ x (**int8) }{}, "**int8"},
69 {struct{ x (**integer) }{}, "**reflect_test.integer"},
70 {struct{ x ([32]int32) }{}, "[32]int32"},
71 {struct{ x ([]int8) }{}, "[]int8"},
72 {struct{ x (map[string]int32) }{}, "map[string]int32"},
73 {struct{ x (chan<- string) }{}, "chan<- string"},
74 {struct {
75 x struct {
76 c chan *int32
77 d float32
79 }{},
80 "struct { c chan *int32; d float32 }",
82 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
83 {struct {
84 x struct {
85 c func(chan *integer, *int8)
87 }{},
88 "struct { c func(chan *reflect_test.integer, *int8) }",
90 {struct {
91 x struct {
92 a int8
93 b int32
95 }{},
96 "struct { a int8; b int32 }",
98 {struct {
99 x struct {
100 a int8
101 b int8
102 c int32
104 }{},
105 "struct { a int8; b int8; c int32 }",
107 {struct {
108 x struct {
109 a int8
110 b int8
111 c int8
112 d int32
114 }{},
115 "struct { a int8; b int8; c int8; d int32 }",
117 {struct {
118 x struct {
119 a int8
120 b int8
121 c int8
122 d int8
123 e int32
125 }{},
126 "struct { a int8; b int8; c int8; d int8; e int32 }",
128 {struct {
129 x struct {
130 a int8
131 b int8
132 c int8
133 d int8
134 e int8
135 f int32
137 }{},
138 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
140 {struct {
141 x struct {
142 a int8 `reflect:"hi there"`
144 }{},
145 `struct { a int8 "reflect:\"hi there\"" }`,
147 {struct {
148 x struct {
149 a int8 `reflect:"hi \x00there\t\n\"\\"`
151 }{},
152 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
154 {struct {
155 x struct {
156 f func(args ...int)
158 }{},
159 "struct { f func(...int) }",
161 {struct {
162 x (interface {
163 a(func(func(int) int) func(func(int)) int)
166 }{},
167 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
171 var valueTests = []pair{
172 {new(int), "132"},
173 {new(int8), "8"},
174 {new(int16), "16"},
175 {new(int32), "32"},
176 {new(int64), "64"},
177 {new(uint), "132"},
178 {new(uint8), "8"},
179 {new(uint16), "16"},
180 {new(uint32), "32"},
181 {new(uint64), "64"},
182 {new(float32), "256.25"},
183 {new(float64), "512.125"},
184 {new(complex64), "532.125+10i"},
185 {new(complex128), "564.25+1i"},
186 {new(string), "stringy cheese"},
187 {new(bool), "true"},
188 {new(*int8), "*int8(0)"},
189 {new(**int8), "**int8(0)"},
190 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
191 {new(**integer), "**reflect_test.integer(0)"},
192 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
193 {new(chan<- string), "chan<- string"},
194 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
195 {new(struct {
196 c chan *int32
197 d float32
199 "struct { c chan *int32; d float32 }{chan *int32, 0}",
201 {new(struct{ c func(chan *integer, *int8) }),
202 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
204 {new(struct {
205 a int8
206 b int32
208 "struct { a int8; b int32 }{0, 0}",
210 {new(struct {
211 a int8
212 b int8
213 c int32
215 "struct { a int8; b int8; c int32 }{0, 0, 0}",
219 func testType(t *testing.T, i int, typ Type, want string) {
220 s := typ.String()
221 if s != want {
222 t.Errorf("#%d: have %#q, want %#q", i, s, want)
226 func TestTypes(t *testing.T) {
227 for i, tt := range typeTests {
228 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
232 func TestSet(t *testing.T) {
233 for i, tt := range valueTests {
234 v := ValueOf(tt.i)
235 v = v.Elem()
236 switch v.Kind() {
237 case Int:
238 v.SetInt(132)
239 case Int8:
240 v.SetInt(8)
241 case Int16:
242 v.SetInt(16)
243 case Int32:
244 v.SetInt(32)
245 case Int64:
246 v.SetInt(64)
247 case Uint:
248 v.SetUint(132)
249 case Uint8:
250 v.SetUint(8)
251 case Uint16:
252 v.SetUint(16)
253 case Uint32:
254 v.SetUint(32)
255 case Uint64:
256 v.SetUint(64)
257 case Float32:
258 v.SetFloat(256.25)
259 case Float64:
260 v.SetFloat(512.125)
261 case Complex64:
262 v.SetComplex(532.125 + 10i)
263 case Complex128:
264 v.SetComplex(564.25 + 1i)
265 case String:
266 v.SetString("stringy cheese")
267 case Bool:
268 v.SetBool(true)
270 s := valueToString(v)
271 if s != tt.s {
272 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
277 func TestSetValue(t *testing.T) {
278 for i, tt := range valueTests {
279 v := ValueOf(tt.i).Elem()
280 switch v.Kind() {
281 case Int:
282 v.Set(ValueOf(int(132)))
283 case Int8:
284 v.Set(ValueOf(int8(8)))
285 case Int16:
286 v.Set(ValueOf(int16(16)))
287 case Int32:
288 v.Set(ValueOf(int32(32)))
289 case Int64:
290 v.Set(ValueOf(int64(64)))
291 case Uint:
292 v.Set(ValueOf(uint(132)))
293 case Uint8:
294 v.Set(ValueOf(uint8(8)))
295 case Uint16:
296 v.Set(ValueOf(uint16(16)))
297 case Uint32:
298 v.Set(ValueOf(uint32(32)))
299 case Uint64:
300 v.Set(ValueOf(uint64(64)))
301 case Float32:
302 v.Set(ValueOf(float32(256.25)))
303 case Float64:
304 v.Set(ValueOf(512.125))
305 case Complex64:
306 v.Set(ValueOf(complex64(532.125 + 10i)))
307 case Complex128:
308 v.Set(ValueOf(complex128(564.25 + 1i)))
309 case String:
310 v.Set(ValueOf("stringy cheese"))
311 case Bool:
312 v.Set(ValueOf(true))
314 s := valueToString(v)
315 if s != tt.s {
316 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
321 var _i = 7
323 var valueToStringTests = []pair{
324 {123, "123"},
325 {123.5, "123.5"},
326 {byte(123), "123"},
327 {"abc", "abc"},
328 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
329 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
330 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
331 {&[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})"},
332 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
333 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
336 func TestValueToString(t *testing.T) {
337 for i, test := range valueToStringTests {
338 s := valueToString(ValueOf(test.i))
339 if s != test.s {
340 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
345 func TestArrayElemSet(t *testing.T) {
346 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
347 v.Index(4).SetInt(123)
348 s := valueToString(v)
349 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
350 if s != want {
351 t.Errorf("[10]int: have %#q want %#q", s, want)
354 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
355 v.Index(4).SetInt(123)
356 s = valueToString(v)
357 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
358 if s != want1 {
359 t.Errorf("[]int: have %#q want %#q", s, want1)
363 func TestPtrPointTo(t *testing.T) {
364 var ip *int32
365 var i int32 = 1234
366 vip := ValueOf(&ip)
367 vi := ValueOf(&i).Elem()
368 vip.Elem().Set(vi.Addr())
369 if *ip != 1234 {
370 t.Errorf("got %d, want 1234", *ip)
373 ip = nil
374 vp := ValueOf(&ip).Elem()
375 vp.Set(Zero(vp.Type()))
376 if ip != nil {
377 t.Errorf("got non-nil (%p), want nil", ip)
381 func TestPtrSetNil(t *testing.T) {
382 var i int32 = 1234
383 ip := &i
384 vip := ValueOf(&ip)
385 vip.Elem().Set(Zero(vip.Elem().Type()))
386 if ip != nil {
387 t.Errorf("got non-nil (%d), want nil", *ip)
391 func TestMapSetNil(t *testing.T) {
392 m := make(map[string]int)
393 vm := ValueOf(&m)
394 vm.Elem().Set(Zero(vm.Elem().Type()))
395 if m != nil {
396 t.Errorf("got non-nil (%p), want nil", m)
400 func TestAll(t *testing.T) {
401 testType(t, 1, TypeOf((int8)(0)), "int8")
402 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
404 typ := TypeOf((*struct {
405 c chan *int32
406 d float32
407 })(nil))
408 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
409 etyp := typ.Elem()
410 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
411 styp := etyp
412 f := styp.Field(0)
413 testType(t, 5, f.Type, "chan *int32")
415 f, present := styp.FieldByName("d")
416 if !present {
417 t.Errorf("FieldByName says present field is absent")
419 testType(t, 6, f.Type, "float32")
421 f, present = styp.FieldByName("absent")
422 if present {
423 t.Errorf("FieldByName says absent field is present")
426 typ = TypeOf([32]int32{})
427 testType(t, 7, typ, "[32]int32")
428 testType(t, 8, typ.Elem(), "int32")
430 typ = TypeOf((map[string]*int32)(nil))
431 testType(t, 9, typ, "map[string]*int32")
432 mtyp := typ
433 testType(t, 10, mtyp.Key(), "string")
434 testType(t, 11, mtyp.Elem(), "*int32")
436 typ = TypeOf((chan<- string)(nil))
437 testType(t, 12, typ, "chan<- string")
438 testType(t, 13, typ.Elem(), "string")
440 // make sure tag strings are not part of element type
441 typ = TypeOf(struct {
442 d []uint32 `reflect:"TAG"`
443 }{}).Field(0).Type
444 testType(t, 14, typ, "[]uint32")
447 func TestInterfaceGet(t *testing.T) {
448 var inter struct {
449 E interface{}
451 inter.E = 123.456
452 v1 := ValueOf(&inter)
453 v2 := v1.Elem().Field(0)
454 assert(t, v2.Type().String(), "interface {}")
455 i2 := v2.Interface()
456 v3 := ValueOf(i2)
457 assert(t, v3.Type().String(), "float64")
460 func TestInterfaceValue(t *testing.T) {
461 var inter struct {
462 E interface{}
464 inter.E = 123.456
465 v1 := ValueOf(&inter)
466 v2 := v1.Elem().Field(0)
467 assert(t, v2.Type().String(), "interface {}")
468 v3 := v2.Elem()
469 assert(t, v3.Type().String(), "float64")
471 i3 := v2.Interface()
472 if _, ok := i3.(float64); !ok {
473 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
477 func TestFunctionValue(t *testing.T) {
478 var x interface{} = func() {}
479 v := ValueOf(x)
480 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
481 t.Fatalf("TestFunction returned wrong pointer")
483 assert(t, v.Type().String(), "func()")
486 var appendTests = []struct {
487 orig, extra []int
489 {make([]int, 2, 4), []int{22}},
490 {make([]int, 2, 4), []int{22, 33, 44}},
493 func sameInts(x, y []int) bool {
494 if len(x) != len(y) {
495 return false
497 for i, xx := range x {
498 if xx != y[i] {
499 return false
502 return true
505 func TestAppend(t *testing.T) {
506 for i, test := range appendTests {
507 origLen, extraLen := len(test.orig), len(test.extra)
508 want := append(test.orig, test.extra...)
509 // Convert extra from []int to []Value.
510 e0 := make([]Value, len(test.extra))
511 for j, e := range test.extra {
512 e0[j] = ValueOf(e)
514 // Convert extra from []int to *SliceValue.
515 e1 := ValueOf(test.extra)
516 // Test Append.
517 a0 := ValueOf(test.orig)
518 have0 := Append(a0, e0...).Interface().([]int)
519 if !sameInts(have0, want) {
520 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
522 // Check that the orig and extra slices were not modified.
523 if len(test.orig) != origLen {
524 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
526 if len(test.extra) != extraLen {
527 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
529 // Test AppendSlice.
530 a1 := ValueOf(test.orig)
531 have1 := AppendSlice(a1, e1).Interface().([]int)
532 if !sameInts(have1, want) {
533 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
535 // Check that the orig and extra slices were not modified.
536 if len(test.orig) != origLen {
537 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
539 if len(test.extra) != extraLen {
540 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
545 func TestCopy(t *testing.T) {
546 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
547 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
548 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
549 for i := 0; i < len(b); i++ {
550 if b[i] != c[i] {
551 t.Fatalf("b != c before test")
554 a1 := a
555 b1 := b
556 aa := ValueOf(&a1).Elem()
557 ab := ValueOf(&b1).Elem()
558 for tocopy := 1; tocopy <= 7; tocopy++ {
559 aa.SetLen(tocopy)
560 Copy(ab, aa)
561 aa.SetLen(8)
562 for i := 0; i < tocopy; i++ {
563 if a[i] != b[i] {
564 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
565 tocopy, i, a[i], i, b[i])
568 for i := tocopy; i < len(b); i++ {
569 if b[i] != c[i] {
570 if i < len(a) {
571 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
572 tocopy, i, a[i], i, b[i], i, c[i])
573 } else {
574 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
575 tocopy, i, b[i], i, c[i])
577 } else {
578 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
584 func TestCopyArray(t *testing.T) {
585 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
586 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
587 c := b
588 aa := ValueOf(&a).Elem()
589 ab := ValueOf(&b).Elem()
590 Copy(ab, aa)
591 for i := 0; i < len(a); i++ {
592 if a[i] != b[i] {
593 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
596 for i := len(a); i < len(b); i++ {
597 if b[i] != c[i] {
598 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
599 } else {
600 t.Logf("elem %d is okay\n", i)
605 func TestBigUnnamedStruct(t *testing.T) {
606 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
607 v := ValueOf(b)
608 b1 := v.Interface().(struct {
609 a, b, c, d int64
611 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
612 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
616 type big struct {
617 a, b, c, d, e int64
620 func TestBigStruct(t *testing.T) {
621 b := big{1, 2, 3, 4, 5}
622 v := ValueOf(b)
623 b1 := v.Interface().(big)
624 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
625 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
629 type Basic struct {
630 x int
631 y float32
634 type NotBasic Basic
636 type DeepEqualTest struct {
637 a, b interface{}
638 eq bool
641 // Simple functions for DeepEqual tests.
642 var (
643 fn1 func() // nil.
644 fn2 func() // nil.
645 fn3 = func() { fn1() } // Not nil.
648 var deepEqualTests = []DeepEqualTest{
649 // Equalities
650 {nil, nil, true},
651 {1, 1, true},
652 {int32(1), int32(1), true},
653 {0.5, 0.5, true},
654 {float32(0.5), float32(0.5), true},
655 {"hello", "hello", true},
656 {make([]int, 10), make([]int, 10), true},
657 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
658 {Basic{1, 0.5}, Basic{1, 0.5}, true},
659 {error(nil), error(nil), true},
660 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
661 {fn1, fn2, true},
663 // Inequalities
664 {1, 2, false},
665 {int32(1), int32(2), false},
666 {0.5, 0.6, false},
667 {float32(0.5), float32(0.6), false},
668 {"hello", "hey", false},
669 {make([]int, 10), make([]int, 11), false},
670 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
671 {Basic{1, 0.5}, Basic{1, 0.6}, false},
672 {Basic{1, 0}, Basic{2, 0}, false},
673 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
674 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
675 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
676 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
677 {nil, 1, false},
678 {1, nil, false},
679 {fn1, fn3, false},
680 {fn3, fn3, false},
681 {[][]int{[]int{1}}, [][]int{[]int{2}}, false},
683 // Nil vs empty: not the same.
684 {[]int{}, []int(nil), false},
685 {[]int{}, []int{}, true},
686 {[]int(nil), []int(nil), true},
687 {map[int]int{}, map[int]int(nil), false},
688 {map[int]int{}, map[int]int{}, true},
689 {map[int]int(nil), map[int]int(nil), true},
691 // Mismatched types
692 {1, 1.0, false},
693 {int32(1), int64(1), false},
694 {0.5, "hello", false},
695 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
696 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
697 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
698 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
701 func TestDeepEqual(t *testing.T) {
702 for _, test := range deepEqualTests {
703 if r := DeepEqual(test.a, test.b); r != test.eq {
704 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
709 func TestTypeOf(t *testing.T) {
710 // Special case for nil
711 if typ := TypeOf(nil); typ != nil {
712 t.Errorf("expected nil type for nil value; got %v", typ)
714 for _, test := range deepEqualTests {
715 v := ValueOf(test.a)
716 if !v.IsValid() {
717 continue
719 typ := TypeOf(test.a)
720 if typ != v.Type() {
721 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
726 type Recursive struct {
727 x int
728 r *Recursive
731 func TestDeepEqualRecursiveStruct(t *testing.T) {
732 a, b := new(Recursive), new(Recursive)
733 *a = Recursive{12, a}
734 *b = Recursive{12, b}
735 if !DeepEqual(a, b) {
736 t.Error("DeepEqual(recursive same) = false, want true")
740 type _Complex struct {
741 a int
742 b [3]*_Complex
743 c *string
744 d map[float64]float64
747 func TestDeepEqualComplexStruct(t *testing.T) {
748 m := make(map[float64]float64)
749 stra, strb := "hello", "hello"
750 a, b := new(_Complex), new(_Complex)
751 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
752 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
753 if !DeepEqual(a, b) {
754 t.Error("DeepEqual(complex same) = false, want true")
758 func TestDeepEqualComplexStructInequality(t *testing.T) {
759 m := make(map[float64]float64)
760 stra, strb := "hello", "helloo" // Difference is here
761 a, b := new(_Complex), new(_Complex)
762 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
763 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
764 if DeepEqual(a, b) {
765 t.Error("DeepEqual(complex different) = true, want false")
769 type UnexpT struct {
770 m map[int]int
773 func TestDeepEqualUnexportedMap(t *testing.T) {
774 // Check that DeepEqual can look at unexported fields.
775 x1 := UnexpT{map[int]int{1: 2}}
776 x2 := UnexpT{map[int]int{1: 2}}
777 if !DeepEqual(&x1, &x2) {
778 t.Error("DeepEqual(x1, x2) = false, want true")
781 y1 := UnexpT{map[int]int{2: 3}}
782 if DeepEqual(&x1, &y1) {
783 t.Error("DeepEqual(x1, y1) = true, want false")
787 func check2ndField(x interface{}, offs uintptr, t *testing.T) {
788 s := ValueOf(x)
789 f := s.Type().Field(1)
790 if f.Offset != offs {
791 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
795 // Check that structure alignment & offsets viewed through reflect agree with those
796 // from the compiler itself.
797 func TestAlignment(t *testing.T) {
798 type T1inner struct {
799 a int
801 type T1 struct {
802 T1inner
803 f int
805 type T2inner struct {
806 a, b int
808 type T2 struct {
809 T2inner
810 f int
813 x := T1{T1inner{2}, 17}
814 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
816 x1 := T2{T2inner{2, 3}, 17}
817 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
820 func Nil(a interface{}, t *testing.T) {
821 n := ValueOf(a).Field(0)
822 if !n.IsNil() {
823 t.Errorf("%v should be nil", a)
827 func NotNil(a interface{}, t *testing.T) {
828 n := ValueOf(a).Field(0)
829 if n.IsNil() {
830 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
834 func TestIsNil(t *testing.T) {
835 // These implement IsNil.
836 // Wrap in extra struct to hide interface type.
837 doNil := []interface{}{
838 struct{ x *int }{},
839 struct{ x interface{} }{},
840 struct{ x map[string]int }{},
841 struct{ x func() bool }{},
842 struct{ x chan int }{},
843 struct{ x []string }{},
845 for _, ts := range doNil {
846 ty := TypeOf(ts).Field(0).Type
847 v := Zero(ty)
848 v.IsNil() // panics if not okay to call
851 // Check the implementations
852 var pi struct {
853 x *int
855 Nil(pi, t)
856 pi.x = new(int)
857 NotNil(pi, t)
859 var si struct {
860 x []int
862 Nil(si, t)
863 si.x = make([]int, 10)
864 NotNil(si, t)
866 var ci struct {
867 x chan int
869 Nil(ci, t)
870 ci.x = make(chan int)
871 NotNil(ci, t)
873 var mi struct {
874 x map[int]int
876 Nil(mi, t)
877 mi.x = make(map[int]int)
878 NotNil(mi, t)
880 var ii struct {
881 x interface{}
883 Nil(ii, t)
884 ii.x = 2
885 NotNil(ii, t)
887 var fi struct {
888 x func(t *testing.T)
890 Nil(fi, t)
891 fi.x = TestIsNil
892 NotNil(fi, t)
895 func TestInterfaceExtraction(t *testing.T) {
896 var s struct {
897 W io.Writer
900 s.W = os.Stdout
901 v := Indirect(ValueOf(&s)).Field(0).Interface()
902 if v != s.W.(interface{}) {
903 t.Error("Interface() on interface: ", v, s.W)
907 func TestNilPtrValueSub(t *testing.T) {
908 var pi *int
909 if pv := ValueOf(pi); pv.Elem().IsValid() {
910 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
914 func TestMap(t *testing.T) {
915 m := map[string]int{"a": 1, "b": 2}
916 mv := ValueOf(m)
917 if n := mv.Len(); n != len(m) {
918 t.Errorf("Len = %d, want %d", n, len(m))
920 keys := mv.MapKeys()
921 newmap := MakeMap(mv.Type())
922 for k, v := range m {
923 // Check that returned Keys match keys in range.
924 // These aren't required to be in the same order.
925 seen := false
926 for _, kv := range keys {
927 if kv.String() == k {
928 seen = true
929 break
932 if !seen {
933 t.Errorf("Missing key %q", k)
936 // Check that value lookup is correct.
937 vv := mv.MapIndex(ValueOf(k))
938 if vi := vv.Int(); vi != int64(v) {
939 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
942 // Copy into new map.
943 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
945 vv := mv.MapIndex(ValueOf("not-present"))
946 if vv.IsValid() {
947 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
950 newm := newmap.Interface().(map[string]int)
951 if len(newm) != len(m) {
952 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
955 for k, v := range newm {
956 mv, ok := m[k]
957 if mv != v {
958 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
962 newmap.SetMapIndex(ValueOf("a"), Value{})
963 v, ok := newm["a"]
964 if ok {
965 t.Errorf("newm[\"a\"] = %d after delete", v)
968 mv = ValueOf(&m).Elem()
969 mv.Set(Zero(mv.Type()))
970 if m != nil {
971 t.Errorf("mv.Set(nil) failed")
975 func TestChan(t *testing.T) {
976 for loop := 0; loop < 2; loop++ {
977 var c chan int
978 var cv Value
980 // check both ways to allocate channels
981 switch loop {
982 case 1:
983 c = make(chan int, 1)
984 cv = ValueOf(c)
985 case 0:
986 cv = MakeChan(TypeOf(c), 1)
987 c = cv.Interface().(chan int)
990 // Send
991 cv.Send(ValueOf(2))
992 if i := <-c; i != 2 {
993 t.Errorf("reflect Send 2, native recv %d", i)
996 // Recv
997 c <- 3
998 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
999 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
1002 // TryRecv fail
1003 val, ok := cv.TryRecv()
1004 if val.IsValid() || ok {
1005 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
1008 // TryRecv success
1009 c <- 4
1010 val, ok = cv.TryRecv()
1011 if !val.IsValid() {
1012 t.Errorf("TryRecv on ready chan got nil")
1013 } else if i := val.Int(); i != 4 || !ok {
1014 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
1017 // TrySend fail
1018 c <- 100
1019 ok = cv.TrySend(ValueOf(5))
1020 i := <-c
1021 if ok {
1022 t.Errorf("TrySend on full chan succeeded: value %d", i)
1025 // TrySend success
1026 ok = cv.TrySend(ValueOf(6))
1027 if !ok {
1028 t.Errorf("TrySend on empty chan failed")
1029 } else {
1030 if i = <-c; i != 6 {
1031 t.Errorf("TrySend 6, recv %d", i)
1035 // Close
1036 c <- 123
1037 cv.Close()
1038 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1039 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
1041 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1042 t.Errorf("after close Recv %d, %t", i.Int(), ok)
1046 // check creation of unbuffered channel
1047 var c chan int
1048 cv := MakeChan(TypeOf(c), 0)
1049 c = cv.Interface().(chan int)
1050 if cv.TrySend(ValueOf(7)) {
1051 t.Errorf("TrySend on sync chan succeeded")
1053 if v, ok := cv.TryRecv(); v.IsValid() || ok {
1054 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
1057 // len/cap
1058 cv = MakeChan(TypeOf(c), 10)
1059 c = cv.Interface().(chan int)
1060 for i := 0; i < 3; i++ {
1061 c <- i
1063 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
1064 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
1068 // caseInfo describes a single case in a select test.
1069 type caseInfo struct {
1070 desc string
1071 canSelect bool
1072 recv Value
1073 closed bool
1074 helper func()
1075 panic bool
1078 var allselect = flag.Bool("allselect", false, "exhaustive select test")
1080 func TestSelect(t *testing.T) {
1081 selectWatch.once.Do(func() { go selectWatcher() })
1083 var x exhaustive
1084 nch := 0
1085 newop := func(n int, cap int) (ch, val Value) {
1086 nch++
1087 if nch%101%2 == 1 {
1088 c := make(chan int, cap)
1089 ch = ValueOf(c)
1090 val = ValueOf(n)
1091 } else {
1092 c := make(chan string, cap)
1093 ch = ValueOf(c)
1094 val = ValueOf(fmt.Sprint(n))
1096 return
1099 for n := 0; x.Next(); n++ {
1100 if testing.Short() && n >= 1000 {
1101 break
1103 if n >= 100000 && !*allselect {
1104 break
1106 if n%100000 == 0 && testing.Verbose() {
1107 println("TestSelect", n)
1109 var cases []SelectCase
1110 var info []caseInfo
1112 // Ready send.
1113 if x.Maybe() {
1114 ch, val := newop(len(cases), 1)
1115 cases = append(cases, SelectCase{
1116 Dir: SelectSend,
1117 Chan: ch,
1118 Send: val,
1120 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1123 // Ready recv.
1124 if x.Maybe() {
1125 ch, val := newop(len(cases), 1)
1126 ch.Send(val)
1127 cases = append(cases, SelectCase{
1128 Dir: SelectRecv,
1129 Chan: ch,
1131 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1134 // Blocking send.
1135 if x.Maybe() {
1136 ch, val := newop(len(cases), 0)
1137 cases = append(cases, SelectCase{
1138 Dir: SelectSend,
1139 Chan: ch,
1140 Send: val,
1142 // Let it execute?
1143 if x.Maybe() {
1144 f := func() { ch.Recv() }
1145 info = append(info, caseInfo{desc: "blocking send", helper: f})
1146 } else {
1147 info = append(info, caseInfo{desc: "blocking send"})
1151 // Blocking recv.
1152 if x.Maybe() {
1153 ch, val := newop(len(cases), 0)
1154 cases = append(cases, SelectCase{
1155 Dir: SelectRecv,
1156 Chan: ch,
1158 // Let it execute?
1159 if x.Maybe() {
1160 f := func() { ch.Send(val) }
1161 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1162 } else {
1163 info = append(info, caseInfo{desc: "blocking recv"})
1167 // Zero Chan send.
1168 if x.Maybe() {
1169 // Maybe include value to send.
1170 var val Value
1171 if x.Maybe() {
1172 val = ValueOf(100)
1174 cases = append(cases, SelectCase{
1175 Dir: SelectSend,
1176 Send: val,
1178 info = append(info, caseInfo{desc: "zero Chan send"})
1181 // Zero Chan receive.
1182 if x.Maybe() {
1183 cases = append(cases, SelectCase{
1184 Dir: SelectRecv,
1186 info = append(info, caseInfo{desc: "zero Chan recv"})
1189 // nil Chan send.
1190 if x.Maybe() {
1191 cases = append(cases, SelectCase{
1192 Dir: SelectSend,
1193 Chan: ValueOf((chan int)(nil)),
1194 Send: ValueOf(101),
1196 info = append(info, caseInfo{desc: "nil Chan send"})
1199 // nil Chan recv.
1200 if x.Maybe() {
1201 cases = append(cases, SelectCase{
1202 Dir: SelectRecv,
1203 Chan: ValueOf((chan int)(nil)),
1205 info = append(info, caseInfo{desc: "nil Chan recv"})
1208 // closed Chan send.
1209 if x.Maybe() {
1210 ch := make(chan int)
1211 close(ch)
1212 cases = append(cases, SelectCase{
1213 Dir: SelectSend,
1214 Chan: ValueOf(ch),
1215 Send: ValueOf(101),
1217 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1220 // closed Chan recv.
1221 if x.Maybe() {
1222 ch, val := newop(len(cases), 0)
1223 ch.Close()
1224 val = Zero(val.Type())
1225 cases = append(cases, SelectCase{
1226 Dir: SelectRecv,
1227 Chan: ch,
1229 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1232 var helper func() // goroutine to help the select complete
1234 // Add default? Must be last case here, but will permute.
1235 // Add the default if the select would otherwise
1236 // block forever, and maybe add it anyway.
1237 numCanSelect := 0
1238 canProceed := false
1239 canBlock := true
1240 canPanic := false
1241 helpers := []int{}
1242 for i, c := range info {
1243 if c.canSelect {
1244 canProceed = true
1245 canBlock = false
1246 numCanSelect++
1247 if c.panic {
1248 canPanic = true
1250 } else if c.helper != nil {
1251 canProceed = true
1252 helpers = append(helpers, i)
1255 if !canProceed || x.Maybe() {
1256 cases = append(cases, SelectCase{
1257 Dir: SelectDefault,
1259 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1260 numCanSelect++
1261 } else if canBlock {
1262 // Select needs to communicate with another goroutine.
1263 cas := &info[helpers[x.Choose(len(helpers))]]
1264 helper = cas.helper
1265 cas.canSelect = true
1266 numCanSelect++
1269 // Permute cases and case info.
1270 // Doing too much here makes the exhaustive loop
1271 // too exhausting, so just do two swaps.
1272 for loop := 0; loop < 2; loop++ {
1273 i := x.Choose(len(cases))
1274 j := x.Choose(len(cases))
1275 cases[i], cases[j] = cases[j], cases[i]
1276 info[i], info[j] = info[j], info[i]
1279 if helper != nil {
1280 // We wait before kicking off a goroutine to satisfy a blocked select.
1281 // The pause needs to be big enough to let the select block before
1282 // we run the helper, but if we lose that race once in a while it's okay: the
1283 // select will just proceed immediately. Not a big deal.
1284 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1285 pause := 10 * time.Microsecond
1286 if testing.Short() {
1287 pause = 100 * time.Microsecond
1289 time.AfterFunc(pause, helper)
1292 // Run select.
1293 i, recv, recvOK, panicErr := runSelect(cases, info)
1294 if panicErr != nil && !canPanic {
1295 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1297 if panicErr == nil && canPanic && numCanSelect == 1 {
1298 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1300 if panicErr != nil {
1301 continue
1304 cas := info[i]
1305 if !cas.canSelect {
1306 recvStr := ""
1307 if recv.IsValid() {
1308 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1310 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1311 continue
1313 if cas.panic {
1314 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1315 continue
1318 if cases[i].Dir == SelectRecv {
1319 if !recv.IsValid() {
1320 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1322 if !cas.recv.IsValid() {
1323 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1325 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1326 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1327 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1329 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1331 } else {
1332 if recv.IsValid() || recvOK {
1333 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1339 // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1340 // If the selectWatcher notices that the select has been blocked for >1 second, it prints
1341 // an error describing the select and panics the entire test binary.
1342 var selectWatch struct {
1343 sync.Mutex
1344 once sync.Once
1345 now time.Time
1346 info []caseInfo
1349 func selectWatcher() {
1350 for {
1351 time.Sleep(1 * time.Second)
1352 selectWatch.Lock()
1353 if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
1354 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1355 panic("select stuck")
1357 selectWatch.Unlock()
1361 // runSelect runs a single select test.
1362 // It returns the values returned by Select but also returns
1363 // a panic value if the Select panics.
1364 func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1365 defer func() {
1366 panicErr = recover()
1368 selectWatch.Lock()
1369 selectWatch.info = nil
1370 selectWatch.Unlock()
1373 selectWatch.Lock()
1374 selectWatch.now = time.Now()
1375 selectWatch.info = info
1376 selectWatch.Unlock()
1378 chosen, recv, recvOK = Select(cases)
1379 return
1382 // fmtSelect formats the information about a single select test.
1383 func fmtSelect(info []caseInfo) string {
1384 var buf bytes.Buffer
1385 fmt.Fprintf(&buf, "\nselect {\n")
1386 for i, cas := range info {
1387 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1388 if cas.recv.IsValid() {
1389 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1391 if cas.canSelect {
1392 fmt.Fprintf(&buf, " canselect")
1394 if cas.panic {
1395 fmt.Fprintf(&buf, " panic")
1397 fmt.Fprintf(&buf, "\n")
1399 fmt.Fprintf(&buf, "}")
1400 return buf.String()
1403 type two [2]uintptr
1405 // Difficult test for function call because of
1406 // implicit padding between arguments.
1407 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) {
1408 return b, c, d, e, f, g, h
1411 func TestFunc(t *testing.T) {
1412 ret := ValueOf(dummy).Call([]Value{
1413 ValueOf(byte(10)),
1414 ValueOf(20),
1415 ValueOf(byte(30)),
1416 ValueOf(two{40, 50}),
1417 ValueOf(byte(60)),
1418 ValueOf(float32(70)),
1419 ValueOf(byte(80)),
1421 if len(ret) != 7 {
1422 t.Fatalf("Call returned %d values, want 7", len(ret))
1425 i := byte(ret[0].Uint())
1426 j := int(ret[1].Int())
1427 k := byte(ret[2].Uint())
1428 l := ret[3].Interface().(two)
1429 m := byte(ret[4].Uint())
1430 n := float32(ret[5].Float())
1431 o := byte(ret[6].Uint())
1433 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1434 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)
1438 type emptyStruct struct{}
1440 type nonEmptyStruct struct {
1441 member int
1444 func returnEmpty() emptyStruct {
1445 return emptyStruct{}
1448 func takesEmpty(e emptyStruct) {
1451 func returnNonEmpty(i int) nonEmptyStruct {
1452 return nonEmptyStruct{member: i}
1455 func takesNonEmpty(n nonEmptyStruct) int {
1456 return n.member
1459 func TestCallWithStruct(t *testing.T) {
1460 r := ValueOf(returnEmpty).Call(nil)
1461 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1462 t.Errorf("returning empty struct returned %#v instead", r)
1464 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1465 if len(r) != 0 {
1466 t.Errorf("takesEmpty returned values: %#v", r)
1468 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1469 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1470 t.Errorf("returnNonEmpty returned %#v", r)
1472 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1473 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1474 t.Errorf("takesNonEmpty returned %#v", r)
1478 func TestMakeFunc(t *testing.T) {
1479 switch runtime.GOARCH {
1480 case "amd64", "386":
1481 default:
1482 t.Skip("MakeFunc not implemented for " + runtime.GOARCH)
1485 f := dummy
1486 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1487 ValueOf(&f).Elem().Set(fv)
1489 // Call g with small arguments so that there is
1490 // something predictable (and different from the
1491 // correct results) in those positions on the stack.
1492 g := dummy
1493 g(1, 2, 3, two{4, 5}, 6, 7, 8)
1495 // Call constructed function f.
1496 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1497 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1498 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)
1502 func TestMakeFuncInterface(t *testing.T) {
1503 switch runtime.GOARCH {
1504 case "amd64", "386":
1505 default:
1506 t.Skip("MakeFunc not implemented for " + runtime.GOARCH)
1509 fn := func(i int) int { return i }
1510 incr := func(in []Value) []Value {
1511 return []Value{ValueOf(int(in[0].Int() + 1))}
1513 fv := MakeFunc(TypeOf(fn), incr)
1514 ValueOf(&fn).Elem().Set(fv)
1515 if r := fn(2); r != 3 {
1516 t.Errorf("Call returned %d, want 3", r)
1518 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1519 t.Errorf("Call returned %d, want 15", r)
1521 if r := fv.Interface().(func(int) int)(26); r != 27 {
1522 t.Errorf("Call returned %d, want 27", r)
1526 type Point struct {
1527 x, y int
1530 // This will be index 0.
1531 func (p Point) AnotherMethod(scale int) int {
1532 return -1
1535 // This will be index 1.
1536 func (p Point) Dist(scale int) int {
1537 //println("Point.Dist", p.x, p.y, scale)
1538 return p.x*p.x*scale + p.y*p.y*scale
1541 func TestMethod(t *testing.T) {
1542 // Non-curried method of type.
1543 p := Point{3, 4}
1544 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
1545 if i != 250 {
1546 t.Errorf("Type Method returned %d; want 250", i)
1549 m, ok := TypeOf(p).MethodByName("Dist")
1550 if !ok {
1551 t.Fatalf("method by name failed")
1553 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1554 if i != 275 {
1555 t.Errorf("Type MethodByName returned %d; want 275", i)
1558 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1559 if i != 300 {
1560 t.Errorf("Pointer Type Method returned %d; want 300", i)
1563 m, ok = TypeOf(&p).MethodByName("Dist")
1564 if !ok {
1565 t.Fatalf("ptr method by name failed")
1567 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1568 if i != 325 {
1569 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
1572 // Curried method of value.
1573 tfunc := TypeOf((func(int) int)(nil))
1574 v := ValueOf(p).Method(1)
1575 if tt := v.Type(); tt != tfunc {
1576 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1578 i = v.Call([]Value{ValueOf(14)})[0].Int()
1579 if i != 350 {
1580 t.Errorf("Value Method returned %d; want 350", i)
1582 v = ValueOf(p).MethodByName("Dist")
1583 if tt := v.Type(); tt != tfunc {
1584 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1586 i = v.Call([]Value{ValueOf(15)})[0].Int()
1587 if i != 375 {
1588 t.Errorf("Value MethodByName returned %d; want 375", i)
1591 // Curried method of pointer.
1592 v = ValueOf(&p).Method(1)
1593 if tt := v.Type(); tt != tfunc {
1594 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1596 i = v.Call([]Value{ValueOf(16)})[0].Int()
1597 if i != 400 {
1598 t.Errorf("Pointer Value Method returned %d; want 400", i)
1600 v = ValueOf(&p).MethodByName("Dist")
1601 if tt := v.Type(); tt != tfunc {
1602 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1604 i = v.Call([]Value{ValueOf(17)})[0].Int()
1605 if i != 425 {
1606 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1609 // Curried method of interface value.
1610 // Have to wrap interface value in a struct to get at it.
1611 // Passing it to ValueOf directly would
1612 // access the underlying Point, not the interface.
1613 var x interface {
1614 Dist(int) int
1615 } = p
1616 pv := ValueOf(&x).Elem()
1617 v = pv.Method(0)
1618 if tt := v.Type(); tt != tfunc {
1619 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1621 i = v.Call([]Value{ValueOf(18)})[0].Int()
1622 if i != 450 {
1623 t.Errorf("Interface Method returned %d; want 450", i)
1625 v = pv.MethodByName("Dist")
1626 if tt := v.Type(); tt != tfunc {
1627 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1629 i = v.Call([]Value{ValueOf(19)})[0].Int()
1630 if i != 475 {
1631 t.Errorf("Interface MethodByName returned %d; want 475", i)
1635 func TestMethodValue(t *testing.T) {
1636 switch runtime.GOARCH {
1637 case "amd64", "386":
1638 default:
1639 t.Skip("reflect method values not implemented for " + runtime.GOARCH)
1642 p := Point{3, 4}
1643 var i int64
1645 // Curried method of value.
1646 tfunc := TypeOf((func(int) int)(nil))
1647 v := ValueOf(p).Method(1)
1648 if tt := v.Type(); tt != tfunc {
1649 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1651 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
1652 if i != 250 {
1653 t.Errorf("Value Method returned %d; want 250", i)
1655 v = ValueOf(p).MethodByName("Dist")
1656 if tt := v.Type(); tt != tfunc {
1657 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1659 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1660 if i != 275 {
1661 t.Errorf("Value MethodByName returned %d; want 275", i)
1664 // Curried method of pointer.
1665 v = ValueOf(&p).Method(1)
1666 if tt := v.Type(); tt != tfunc {
1667 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1669 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1670 if i != 300 {
1671 t.Errorf("Pointer Value Method returned %d; want 300", i)
1673 v = ValueOf(&p).MethodByName("Dist")
1674 if tt := v.Type(); tt != tfunc {
1675 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1677 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1678 if i != 325 {
1679 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
1682 // Curried method of pointer to pointer.
1683 pp := &p
1684 v = ValueOf(&pp).Elem().Method(1)
1685 if tt := v.Type(); tt != tfunc {
1686 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
1688 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1689 if i != 350 {
1690 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
1692 v = ValueOf(&pp).Elem().MethodByName("Dist")
1693 if tt := v.Type(); tt != tfunc {
1694 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1696 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1697 if i != 375 {
1698 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
1701 // Curried method of interface value.
1702 // Have to wrap interface value in a struct to get at it.
1703 // Passing it to ValueOf directly would
1704 // access the underlying Point, not the interface.
1705 var s = struct {
1706 X interface {
1707 Dist(int) int
1709 }{p}
1710 pv := ValueOf(s).Field(0)
1711 v = pv.Method(0)
1712 if tt := v.Type(); tt != tfunc {
1713 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1715 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
1716 if i != 400 {
1717 t.Errorf("Interface Method returned %d; want 400", i)
1719 v = pv.MethodByName("Dist")
1720 if tt := v.Type(); tt != tfunc {
1721 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1723 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
1724 if i != 425 {
1725 t.Errorf("Interface MethodByName returned %d; want 425", i)
1729 // Reflect version of $GOROOT/test/method5.go
1731 // Concrete types implementing M method.
1732 // Smaller than a word, word-sized, larger than a word.
1733 // Value and pointer receivers.
1735 type Tinter interface {
1736 M(int, byte) (byte, int)
1739 type Tsmallv byte
1741 func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1743 type Tsmallp byte
1745 func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1747 type Twordv uintptr
1749 func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1751 type Twordp uintptr
1753 func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1755 type Tbigv [2]uintptr
1757 func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1759 type Tbigp [2]uintptr
1761 func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1763 // Again, with an unexported method.
1765 type tsmallv byte
1767 func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1769 type tsmallp byte
1771 func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1773 type twordv uintptr
1775 func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1777 type twordp uintptr
1779 func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1781 type tbigv [2]uintptr
1783 func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1785 type tbigp [2]uintptr
1787 func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1789 type tinter interface {
1790 m(int, byte) (byte, int)
1793 // Embedding via pointer.
1795 type Tm1 struct {
1799 type Tm2 struct {
1800 *Tm3
1803 type Tm3 struct {
1804 *Tm4
1807 type Tm4 struct {
1810 func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
1812 func TestMethod5(t *testing.T) {
1813 switch runtime.GOARCH {
1814 case "amd64", "386":
1815 default:
1816 t.Skip("reflect method values not implemented for " + runtime.GOARCH)
1819 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1820 b, x := f(1000, 99)
1821 if b != 99 || x != 1000+inc {
1822 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1826 CheckV := func(name string, i Value, inc int) {
1827 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
1828 b := bx[0].Interface()
1829 x := bx[1].Interface()
1830 if b != byte(99) || x != 1000+inc {
1831 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1834 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1837 var TinterType = TypeOf(new(Tinter)).Elem()
1838 var tinterType = TypeOf(new(tinter)).Elem()
1840 CheckI := func(name string, i interface{}, inc int) {
1841 v := ValueOf(i)
1842 CheckV(name, v, inc)
1843 CheckV("(i="+name+")", v.Convert(TinterType), inc)
1846 sv := Tsmallv(1)
1847 CheckI("sv", sv, 1)
1848 CheckI("&sv", &sv, 1)
1850 sp := Tsmallp(2)
1851 CheckI("&sp", &sp, 2)
1853 wv := Twordv(3)
1854 CheckI("wv", wv, 3)
1855 CheckI("&wv", &wv, 3)
1857 wp := Twordp(4)
1858 CheckI("&wp", &wp, 4)
1860 bv := Tbigv([2]uintptr{5, 6})
1861 CheckI("bv", bv, 11)
1862 CheckI("&bv", &bv, 11)
1864 bp := Tbigp([2]uintptr{7, 8})
1865 CheckI("&bp", &bp, 15)
1867 t4 := Tm4{}
1868 t3 := Tm3{&t4}
1869 t2 := Tm2{&t3}
1870 t1 := Tm1{t2}
1871 CheckI("t4", t4, 40)
1872 CheckI("&t4", &t4, 40)
1873 CheckI("t3", t3, 40)
1874 CheckI("&t3", &t3, 40)
1875 CheckI("t2", t2, 40)
1876 CheckI("&t2", &t2, 40)
1877 CheckI("t1", t1, 40)
1878 CheckI("&t1", &t1, 40)
1880 methodShouldPanic := func(name string, i interface{}) {
1881 v := ValueOf(i)
1882 m := v.Method(0)
1883 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1884 shouldPanic(func() { m.Interface() })
1886 v = v.Convert(tinterType)
1887 m = v.Method(0)
1888 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1889 shouldPanic(func() { m.Interface() })
1892 _sv := tsmallv(1)
1893 methodShouldPanic("_sv", _sv)
1894 methodShouldPanic("&_sv", &_sv)
1896 _sp := tsmallp(2)
1897 methodShouldPanic("&_sp", &_sp)
1899 _wv := twordv(3)
1900 methodShouldPanic("_wv", _wv)
1901 methodShouldPanic("&_wv", &_wv)
1903 _wp := twordp(4)
1904 methodShouldPanic("&_wp", &_wp)
1906 _bv := tbigv([2]uintptr{5, 6})
1907 methodShouldPanic("_bv", _bv)
1908 methodShouldPanic("&_bv", &_bv)
1910 _bp := tbigp([2]uintptr{7, 8})
1911 methodShouldPanic("&_bp", &_bp)
1913 var tnil Tinter
1914 vnil := ValueOf(&tnil).Elem()
1915 shouldPanic(func() { vnil.Method(0) })
1918 func TestInterfaceSet(t *testing.T) {
1919 p := &Point{3, 4}
1921 var s struct {
1922 I interface{}
1923 P interface {
1924 Dist(int) int
1927 sv := ValueOf(&s).Elem()
1928 sv.Field(0).Set(ValueOf(p))
1929 if q := s.I.(*Point); q != p {
1930 t.Errorf("i: have %p want %p", q, p)
1933 pv := sv.Field(1)
1934 pv.Set(ValueOf(p))
1935 if q := s.P.(*Point); q != p {
1936 t.Errorf("i: have %p want %p", q, p)
1939 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
1940 if i != 250 {
1941 t.Errorf("Interface Method returned %d; want 250", i)
1945 type T1 struct {
1946 a string
1950 func TestAnonymousFields(t *testing.T) {
1951 var field StructField
1952 var ok bool
1953 var t1 T1
1954 type1 := TypeOf(t1)
1955 if field, ok = type1.FieldByName("int"); !ok {
1956 t.Fatal("no field 'int'")
1958 if field.Index[0] != 1 {
1959 t.Error("field index should be 1; is", field.Index)
1963 type FTest struct {
1964 s interface{}
1965 name string
1966 index []int
1967 value int
1970 type D1 struct {
1971 d int
1973 type D2 struct {
1974 d int
1977 type S0 struct {
1978 A, B, C int
1983 type S1 struct {
1984 B int
1988 type S2 struct {
1989 A int
1993 type S1x struct {
1997 type S1y struct {
2001 type S3 struct {
2004 D, E int
2005 *S1y
2008 type S4 struct {
2010 A int
2013 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2014 type S5 struct {
2020 type S6 struct {
2021 X int
2024 type S7 S6
2026 type S8 struct {
2030 type S9 struct {
2031 X int
2032 Y int
2035 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2036 type S10 struct {
2042 type S11 struct {
2046 type S12 struct {
2050 type S13 struct {
2054 // The X in S15.S11.S1 and S16.S11.S1 annihilate.
2055 type S14 struct {
2060 type S15 struct {
2064 type S16 struct {
2068 var fieldTests = []FTest{
2069 {struct{}{}, "", nil, 0},
2070 {struct{}{}, "Foo", nil, 0},
2071 {S0{A: 'a'}, "A", []int{0}, 'a'},
2072 {S0{}, "D", nil, 0},
2073 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2074 {S1{B: 'b'}, "B", []int{0}, 'b'},
2075 {S1{}, "S0", []int{1}, 0},
2076 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2077 {S2{A: 'a'}, "A", []int{0}, 'a'},
2078 {S2{}, "S1", []int{1}, 0},
2079 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2080 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2081 {S2{}, "D", nil, 0},
2082 {S3{}, "S1", nil, 0},
2083 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2084 {S3{}, "B", nil, 0},
2085 {S3{D: 'd'}, "D", []int{2}, 0},
2086 {S3{E: 'e'}, "E", []int{3}, 'e'},
2087 {S4{A: 'a'}, "A", []int{1}, 'a'},
2088 {S4{}, "B", nil, 0},
2089 {S5{}, "X", nil, 0},
2090 {S5{}, "Y", []int{2, 0, 1}, 0},
2091 {S10{}, "X", nil, 0},
2092 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
2093 {S14{}, "X", nil, 0},
2096 func TestFieldByIndex(t *testing.T) {
2097 for _, test := range fieldTests {
2098 s := TypeOf(test.s)
2099 f := s.FieldByIndex(test.index)
2100 if f.Name != "" {
2101 if test.index != nil {
2102 if f.Name != test.name {
2103 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
2105 } else {
2106 t.Errorf("%s.%s found", s.Name(), f.Name)
2108 } else if len(test.index) > 0 {
2109 t.Errorf("%s.%s not found", s.Name(), test.name)
2112 if test.value != 0 {
2113 v := ValueOf(test.s).FieldByIndex(test.index)
2114 if v.IsValid() {
2115 if x, ok := v.Interface().(int); ok {
2116 if x != test.value {
2117 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
2119 } else {
2120 t.Errorf("%s%v value not an int", s.Name(), test.index)
2122 } else {
2123 t.Errorf("%s%v value not found", s.Name(), test.index)
2129 func TestFieldByName(t *testing.T) {
2130 for _, test := range fieldTests {
2131 s := TypeOf(test.s)
2132 f, found := s.FieldByName(test.name)
2133 if found {
2134 if test.index != nil {
2135 // Verify field depth and index.
2136 if len(f.Index) != len(test.index) {
2137 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)
2138 } else {
2139 for i, x := range f.Index {
2140 if x != test.index[i] {
2141 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
2145 } else {
2146 t.Errorf("%s.%s found", s.Name(), f.Name)
2148 } else if len(test.index) > 0 {
2149 t.Errorf("%s.%s not found", s.Name(), test.name)
2152 if test.value != 0 {
2153 v := ValueOf(test.s).FieldByName(test.name)
2154 if v.IsValid() {
2155 if x, ok := v.Interface().(int); ok {
2156 if x != test.value {
2157 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
2159 } else {
2160 t.Errorf("%s.%s value not an int", s.Name(), test.name)
2162 } else {
2163 t.Errorf("%s.%s value not found", s.Name(), test.name)
2169 func TestImportPath(t *testing.T) {
2170 tests := []struct {
2171 t Type
2172 path string
2174 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
2175 {TypeOf(int(0)), ""},
2176 {TypeOf(int8(0)), ""},
2177 {TypeOf(int16(0)), ""},
2178 {TypeOf(int32(0)), ""},
2179 {TypeOf(int64(0)), ""},
2180 {TypeOf(uint(0)), ""},
2181 {TypeOf(uint8(0)), ""},
2182 {TypeOf(uint16(0)), ""},
2183 {TypeOf(uint32(0)), ""},
2184 {TypeOf(uint64(0)), ""},
2185 {TypeOf(uintptr(0)), ""},
2186 {TypeOf(float32(0)), ""},
2187 {TypeOf(float64(0)), ""},
2188 {TypeOf(complex64(0)), ""},
2189 {TypeOf(complex128(0)), ""},
2190 {TypeOf(byte(0)), ""},
2191 {TypeOf(rune(0)), ""},
2192 {TypeOf([]byte(nil)), ""},
2193 {TypeOf([]rune(nil)), ""},
2194 {TypeOf(string("")), ""},
2195 {TypeOf((*interface{})(nil)).Elem(), ""},
2196 {TypeOf((*byte)(nil)), ""},
2197 {TypeOf((*rune)(nil)), ""},
2198 {TypeOf((*int64)(nil)), ""},
2199 {TypeOf(map[string]int{}), ""},
2200 {TypeOf((*error)(nil)).Elem(), ""},
2202 for _, test := range tests {
2203 if path := test.t.PkgPath(); path != test.path {
2204 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2209 func TestVariadicType(t *testing.T) {
2210 // Test example from Type documentation.
2211 var f func(x int, y ...float64)
2212 typ := TypeOf(f)
2213 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
2214 sl := typ.In(1)
2215 if sl.Kind() == Slice {
2216 if sl.Elem() == TypeOf(0.0) {
2217 // ok
2218 return
2223 // Failed
2224 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
2225 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2226 for i := 0; i < typ.NumIn(); i++ {
2227 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2229 t.Error(s)
2232 type inner struct {
2233 x int
2236 type outer struct {
2237 y int
2238 inner
2241 func (*inner) m() {}
2242 func (*outer) m() {}
2244 func TestNestedMethods(t *testing.T) {
2245 t.Skip("fails on gccgo due to function wrappers")
2246 typ := TypeOf((*outer)(nil))
2247 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
2248 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
2249 for i := 0; i < typ.NumMethod(); i++ {
2250 m := typ.Method(i)
2251 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2256 type InnerInt struct {
2257 X int
2260 type OuterInt struct {
2261 Y int
2262 InnerInt
2265 func (i *InnerInt) M() int {
2266 return i.X
2269 func TestEmbeddedMethods(t *testing.T) {
2270 /* This part of the test fails on gccgo due to function wrappers.
2271 typ := TypeOf((*OuterInt)(nil))
2272 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
2273 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
2274 for i := 0; i < typ.NumMethod(); i++ {
2275 m := typ.Method(i)
2276 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
2281 i := &InnerInt{3}
2282 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
2283 t.Errorf("i.M() = %d, want 3", v)
2286 o := &OuterInt{1, InnerInt{2}}
2287 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
2288 t.Errorf("i.M() = %d, want 2", v)
2291 f := (*OuterInt).M
2292 if v := f(o); v != 2 {
2293 t.Errorf("f(o) = %d, want 2", v)
2297 func TestPtrTo(t *testing.T) {
2298 var i int
2300 typ := TypeOf(i)
2301 for i = 0; i < 100; i++ {
2302 typ = PtrTo(typ)
2304 for i = 0; i < 100; i++ {
2305 typ = typ.Elem()
2307 if typ != TypeOf(i) {
2308 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
2312 func TestPtrToGC(t *testing.T) {
2313 type T *uintptr
2314 tt := TypeOf(T(nil))
2315 pt := PtrTo(tt)
2316 const n = 100
2317 var x []interface{}
2318 for i := 0; i < n; i++ {
2319 v := New(pt)
2320 p := new(*uintptr)
2321 *p = new(uintptr)
2322 **p = uintptr(i)
2323 v.Elem().Set(ValueOf(p).Convert(pt))
2324 x = append(x, v.Interface())
2326 runtime.GC()
2328 for i, xi := range x {
2329 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2330 if k != uintptr(i) {
2331 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2336 func TestAddr(t *testing.T) {
2337 var p struct {
2338 X, Y int
2341 v := ValueOf(&p)
2342 v = v.Elem()
2343 v = v.Addr()
2344 v = v.Elem()
2345 v = v.Field(0)
2346 v.SetInt(2)
2347 if p.X != 2 {
2348 t.Errorf("Addr.Elem.Set failed to set value")
2351 // Again but take address of the ValueOf value.
2352 // Exercises generation of PtrTypes not present in the binary.
2353 q := &p
2354 v = ValueOf(&q).Elem()
2355 v = v.Addr()
2356 v = v.Elem()
2357 v = v.Elem()
2358 v = v.Addr()
2359 v = v.Elem()
2360 v = v.Field(0)
2361 v.SetInt(3)
2362 if p.X != 3 {
2363 t.Errorf("Addr.Elem.Set failed to set value")
2366 // Starting without pointer we should get changed value
2367 // in interface.
2368 qq := p
2369 v = ValueOf(&qq).Elem()
2370 v0 := v
2371 v = v.Addr()
2372 v = v.Elem()
2373 v = v.Field(0)
2374 v.SetInt(4)
2375 if p.X != 3 { // should be unchanged from last time
2376 t.Errorf("somehow value Set changed original p")
2378 p = v0.Interface().(struct {
2379 X, Y int
2381 if p.X != 4 {
2382 t.Errorf("Addr.Elem.Set valued to set value in top value")
2385 // Verify that taking the address of a type gives us a pointer
2386 // which we can convert back using the usual interface
2387 // notation.
2388 var s struct {
2389 B *bool
2391 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2392 *(ps.(**bool)) = new(bool)
2393 if s.B == nil {
2394 t.Errorf("Addr.Interface direct assignment failed")
2398 /* gccgo does do allocations here.
2400 func noAlloc(t *testing.T, n int, f func(int)) {
2401 if testing.Short() {
2402 t.Skip("skipping malloc count in short mode")
2404 if runtime.GOMAXPROCS(0) > 1 {
2405 t.Skip("skipping; GOMAXPROCS>1")
2407 i := -1
2408 allocs := testing.AllocsPerRun(n, func() {
2409 f(i)
2412 if allocs > 0 {
2413 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
2417 func TestAllocations(t *testing.T) {
2418 noAlloc(t, 100, func(j int) {
2419 var i interface{}
2420 var v Value
2421 i = 42 + j
2422 v = ValueOf(i)
2423 if int(v.Int()) != 42+j {
2424 panic("wrong int")
2431 func TestSmallNegativeInt(t *testing.T) {
2432 i := int16(-1)
2433 v := ValueOf(i)
2434 if v.Int() != -1 {
2435 t.Errorf("int16(-1).Int() returned %v", v.Int())
2439 func TestIndex(t *testing.T) {
2440 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2441 v := ValueOf(xs).Index(3).Interface().(byte)
2442 if v != xs[3] {
2443 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2445 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2446 v = ValueOf(xa).Index(2).Interface().(byte)
2447 if v != xa[2] {
2448 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2450 s := "0123456789"
2451 v = ValueOf(s).Index(3).Interface().(byte)
2452 if v != s[3] {
2453 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2457 func TestSlice(t *testing.T) {
2458 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2459 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
2460 if len(v) != 2 {
2461 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2463 if cap(v) != 5 {
2464 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2466 if !DeepEqual(v[0:5], xs[3:]) {
2467 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
2469 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2470 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
2471 if len(v) != 3 {
2472 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2474 if cap(v) != 6 {
2475 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2477 if !DeepEqual(v[0:6], xa[2:]) {
2478 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
2480 s := "0123456789"
2481 vs := ValueOf(s).Slice(3, 5).Interface().(string)
2482 if vs != s[3:5] {
2483 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2487 func TestSlice3(t *testing.T) {
2488 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2489 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
2490 if len(v) != 2 {
2491 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
2493 if cap(v) != 4 {
2494 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
2496 if !DeepEqual(v[0:4], xs[3:7:7]) {
2497 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
2499 rv := ValueOf(&xs).Elem()
2500 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2501 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2502 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2504 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2505 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
2506 if len(v) != 3 {
2507 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
2509 if cap(v) != 4 {
2510 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
2512 if !DeepEqual(v[0:4], xa[2:6:6]) {
2513 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
2515 rv = ValueOf(&xa).Elem()
2516 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2517 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2518 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2520 s := "hello world"
2521 rv = ValueOf(&s).Elem()
2522 shouldPanic(func() { rv.Slice3(1, 2, 3) })
2525 func TestSetLenCap(t *testing.T) {
2526 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2527 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2529 vs := ValueOf(&xs).Elem()
2530 shouldPanic(func() { vs.SetLen(10) })
2531 shouldPanic(func() { vs.SetCap(10) })
2532 shouldPanic(func() { vs.SetLen(-1) })
2533 shouldPanic(func() { vs.SetCap(-1) })
2534 shouldPanic(func() { vs.SetCap(6) }) // smaller than len
2535 vs.SetLen(5)
2536 if len(xs) != 5 || cap(xs) != 8 {
2537 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
2539 vs.SetCap(6)
2540 if len(xs) != 5 || cap(xs) != 6 {
2541 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
2543 vs.SetCap(5)
2544 if len(xs) != 5 || cap(xs) != 5 {
2545 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
2547 shouldPanic(func() { vs.SetCap(4) }) // smaller than len
2548 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
2550 va := ValueOf(&xa).Elem()
2551 shouldPanic(func() { va.SetLen(8) })
2552 shouldPanic(func() { va.SetCap(8) })
2555 func TestVariadic(t *testing.T) {
2556 var b bytes.Buffer
2557 V := ValueOf
2559 b.Reset()
2560 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
2561 if b.String() != "hello, 42 world" {
2562 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
2565 b.Reset()
2566 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
2567 if b.String() != "hello, 42 world" {
2568 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
2572 func TestFuncArg(t *testing.T) {
2573 f1 := func(i int, f func(int) int) int { return f(i) }
2574 f2 := func(i int) int { return i + 1 }
2575 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
2576 if r[0].Int() != 101 {
2577 t.Errorf("function returned %d, want 101", r[0].Int())
2581 var tagGetTests = []struct {
2582 Tag StructTag
2583 Key string
2584 Value string
2586 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2587 {`protobuf:"PB(1,2)"`, `foo`, ``},
2588 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2589 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2590 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2593 func TestTagGet(t *testing.T) {
2594 for _, tt := range tagGetTests {
2595 if v := tt.Tag.Get(tt.Key); v != tt.Value {
2596 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
2601 func TestBytes(t *testing.T) {
2602 type B []byte
2603 x := B{1, 2, 3, 4}
2604 y := ValueOf(x).Bytes()
2605 if !bytes.Equal(x, y) {
2606 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2608 if &x[0] != &y[0] {
2609 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2613 func TestSetBytes(t *testing.T) {
2614 type B []byte
2615 var x B
2616 y := []byte{1, 2, 3, 4}
2617 ValueOf(&x).Elem().SetBytes(y)
2618 if !bytes.Equal(x, y) {
2619 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2621 if &x[0] != &y[0] {
2622 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2626 type Private struct {
2627 x int
2628 y **int
2631 func (p *Private) m() {
2634 type Public struct {
2635 X int
2636 Y **int
2639 func (p *Public) M() {
2642 func TestUnexported(t *testing.T) {
2643 var pub Public
2644 v := ValueOf(&pub)
2645 isValid(v.Elem().Field(0))
2646 isValid(v.Elem().Field(1))
2647 isValid(v.Elem().FieldByName("X"))
2648 isValid(v.Elem().FieldByName("Y"))
2649 isValid(v.Type().Method(0).Func)
2650 isNonNil(v.Elem().Field(0).Interface())
2651 isNonNil(v.Elem().Field(1).Interface())
2652 isNonNil(v.Elem().FieldByName("X").Interface())
2653 isNonNil(v.Elem().FieldByName("Y").Interface())
2654 isNonNil(v.Type().Method(0).Func.Interface())
2656 var priv Private
2657 v = ValueOf(&priv)
2658 isValid(v.Elem().Field(0))
2659 isValid(v.Elem().Field(1))
2660 isValid(v.Elem().FieldByName("x"))
2661 isValid(v.Elem().FieldByName("y"))
2662 isValid(v.Type().Method(0).Func)
2663 shouldPanic(func() { v.Elem().Field(0).Interface() })
2664 shouldPanic(func() { v.Elem().Field(1).Interface() })
2665 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
2666 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
2667 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
2670 func shouldPanic(f func()) {
2671 defer func() {
2672 if recover() == nil {
2673 panic("did not panic")
2679 func isNonNil(x interface{}) {
2680 if x == nil {
2681 panic("nil interface")
2685 func isValid(v Value) {
2686 if !v.IsValid() {
2687 panic("zero Value")
2691 func TestAlias(t *testing.T) {
2692 x := string("hello")
2693 v := ValueOf(&x).Elem()
2694 oldvalue := v.Interface()
2695 v.SetString("world")
2696 newvalue := v.Interface()
2698 if oldvalue != "hello" || newvalue != "world" {
2699 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
2703 var V = ValueOf
2705 func EmptyInterfaceV(x interface{}) Value {
2706 return ValueOf(&x).Elem()
2709 func ReaderV(x io.Reader) Value {
2710 return ValueOf(&x).Elem()
2713 func ReadWriterV(x io.ReadWriter) Value {
2714 return ValueOf(&x).Elem()
2717 type Empty struct{}
2718 type MyString string
2719 type MyBytes []byte
2720 type MyRunes []int32
2721 type MyFunc func()
2722 type MyByte byte
2724 var convertTests = []struct {
2725 in Value
2726 out Value
2728 // numbers
2730 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2732 package main
2734 import "fmt"
2736 var numbers = []string{
2737 "int8", "uint8", "int16", "uint16",
2738 "int32", "uint32", "int64", "uint64",
2739 "int", "uint", "uintptr",
2740 "float32", "float64",
2743 func main() {
2744 // all pairs but in an unusual order,
2745 // to emit all the int8, uint8 cases
2746 // before n grows too big.
2747 n := 1
2748 for i, f := range numbers {
2749 for _, g := range numbers[i:] {
2750 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2752 if f != g {
2753 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2760 {V(int8(1)), V(int8(1))},
2761 {V(int8(2)), V(uint8(2))},
2762 {V(uint8(3)), V(int8(3))},
2763 {V(int8(4)), V(int16(4))},
2764 {V(int16(5)), V(int8(5))},
2765 {V(int8(6)), V(uint16(6))},
2766 {V(uint16(7)), V(int8(7))},
2767 {V(int8(8)), V(int32(8))},
2768 {V(int32(9)), V(int8(9))},
2769 {V(int8(10)), V(uint32(10))},
2770 {V(uint32(11)), V(int8(11))},
2771 {V(int8(12)), V(int64(12))},
2772 {V(int64(13)), V(int8(13))},
2773 {V(int8(14)), V(uint64(14))},
2774 {V(uint64(15)), V(int8(15))},
2775 {V(int8(16)), V(int(16))},
2776 {V(int(17)), V(int8(17))},
2777 {V(int8(18)), V(uint(18))},
2778 {V(uint(19)), V(int8(19))},
2779 {V(int8(20)), V(uintptr(20))},
2780 {V(uintptr(21)), V(int8(21))},
2781 {V(int8(22)), V(float32(22))},
2782 {V(float32(23)), V(int8(23))},
2783 {V(int8(24)), V(float64(24))},
2784 {V(float64(25)), V(int8(25))},
2785 {V(uint8(26)), V(uint8(26))},
2786 {V(uint8(27)), V(int16(27))},
2787 {V(int16(28)), V(uint8(28))},
2788 {V(uint8(29)), V(uint16(29))},
2789 {V(uint16(30)), V(uint8(30))},
2790 {V(uint8(31)), V(int32(31))},
2791 {V(int32(32)), V(uint8(32))},
2792 {V(uint8(33)), V(uint32(33))},
2793 {V(uint32(34)), V(uint8(34))},
2794 {V(uint8(35)), V(int64(35))},
2795 {V(int64(36)), V(uint8(36))},
2796 {V(uint8(37)), V(uint64(37))},
2797 {V(uint64(38)), V(uint8(38))},
2798 {V(uint8(39)), V(int(39))},
2799 {V(int(40)), V(uint8(40))},
2800 {V(uint8(41)), V(uint(41))},
2801 {V(uint(42)), V(uint8(42))},
2802 {V(uint8(43)), V(uintptr(43))},
2803 {V(uintptr(44)), V(uint8(44))},
2804 {V(uint8(45)), V(float32(45))},
2805 {V(float32(46)), V(uint8(46))},
2806 {V(uint8(47)), V(float64(47))},
2807 {V(float64(48)), V(uint8(48))},
2808 {V(int16(49)), V(int16(49))},
2809 {V(int16(50)), V(uint16(50))},
2810 {V(uint16(51)), V(int16(51))},
2811 {V(int16(52)), V(int32(52))},
2812 {V(int32(53)), V(int16(53))},
2813 {V(int16(54)), V(uint32(54))},
2814 {V(uint32(55)), V(int16(55))},
2815 {V(int16(56)), V(int64(56))},
2816 {V(int64(57)), V(int16(57))},
2817 {V(int16(58)), V(uint64(58))},
2818 {V(uint64(59)), V(int16(59))},
2819 {V(int16(60)), V(int(60))},
2820 {V(int(61)), V(int16(61))},
2821 {V(int16(62)), V(uint(62))},
2822 {V(uint(63)), V(int16(63))},
2823 {V(int16(64)), V(uintptr(64))},
2824 {V(uintptr(65)), V(int16(65))},
2825 {V(int16(66)), V(float32(66))},
2826 {V(float32(67)), V(int16(67))},
2827 {V(int16(68)), V(float64(68))},
2828 {V(float64(69)), V(int16(69))},
2829 {V(uint16(70)), V(uint16(70))},
2830 {V(uint16(71)), V(int32(71))},
2831 {V(int32(72)), V(uint16(72))},
2832 {V(uint16(73)), V(uint32(73))},
2833 {V(uint32(74)), V(uint16(74))},
2834 {V(uint16(75)), V(int64(75))},
2835 {V(int64(76)), V(uint16(76))},
2836 {V(uint16(77)), V(uint64(77))},
2837 {V(uint64(78)), V(uint16(78))},
2838 {V(uint16(79)), V(int(79))},
2839 {V(int(80)), V(uint16(80))},
2840 {V(uint16(81)), V(uint(81))},
2841 {V(uint(82)), V(uint16(82))},
2842 {V(uint16(83)), V(uintptr(83))},
2843 {V(uintptr(84)), V(uint16(84))},
2844 {V(uint16(85)), V(float32(85))},
2845 {V(float32(86)), V(uint16(86))},
2846 {V(uint16(87)), V(float64(87))},
2847 {V(float64(88)), V(uint16(88))},
2848 {V(int32(89)), V(int32(89))},
2849 {V(int32(90)), V(uint32(90))},
2850 {V(uint32(91)), V(int32(91))},
2851 {V(int32(92)), V(int64(92))},
2852 {V(int64(93)), V(int32(93))},
2853 {V(int32(94)), V(uint64(94))},
2854 {V(uint64(95)), V(int32(95))},
2855 {V(int32(96)), V(int(96))},
2856 {V(int(97)), V(int32(97))},
2857 {V(int32(98)), V(uint(98))},
2858 {V(uint(99)), V(int32(99))},
2859 {V(int32(100)), V(uintptr(100))},
2860 {V(uintptr(101)), V(int32(101))},
2861 {V(int32(102)), V(float32(102))},
2862 {V(float32(103)), V(int32(103))},
2863 {V(int32(104)), V(float64(104))},
2864 {V(float64(105)), V(int32(105))},
2865 {V(uint32(106)), V(uint32(106))},
2866 {V(uint32(107)), V(int64(107))},
2867 {V(int64(108)), V(uint32(108))},
2868 {V(uint32(109)), V(uint64(109))},
2869 {V(uint64(110)), V(uint32(110))},
2870 {V(uint32(111)), V(int(111))},
2871 {V(int(112)), V(uint32(112))},
2872 {V(uint32(113)), V(uint(113))},
2873 {V(uint(114)), V(uint32(114))},
2874 {V(uint32(115)), V(uintptr(115))},
2875 {V(uintptr(116)), V(uint32(116))},
2876 {V(uint32(117)), V(float32(117))},
2877 {V(float32(118)), V(uint32(118))},
2878 {V(uint32(119)), V(float64(119))},
2879 {V(float64(120)), V(uint32(120))},
2880 {V(int64(121)), V(int64(121))},
2881 {V(int64(122)), V(uint64(122))},
2882 {V(uint64(123)), V(int64(123))},
2883 {V(int64(124)), V(int(124))},
2884 {V(int(125)), V(int64(125))},
2885 {V(int64(126)), V(uint(126))},
2886 {V(uint(127)), V(int64(127))},
2887 {V(int64(128)), V(uintptr(128))},
2888 {V(uintptr(129)), V(int64(129))},
2889 {V(int64(130)), V(float32(130))},
2890 {V(float32(131)), V(int64(131))},
2891 {V(int64(132)), V(float64(132))},
2892 {V(float64(133)), V(int64(133))},
2893 {V(uint64(134)), V(uint64(134))},
2894 {V(uint64(135)), V(int(135))},
2895 {V(int(136)), V(uint64(136))},
2896 {V(uint64(137)), V(uint(137))},
2897 {V(uint(138)), V(uint64(138))},
2898 {V(uint64(139)), V(uintptr(139))},
2899 {V(uintptr(140)), V(uint64(140))},
2900 {V(uint64(141)), V(float32(141))},
2901 {V(float32(142)), V(uint64(142))},
2902 {V(uint64(143)), V(float64(143))},
2903 {V(float64(144)), V(uint64(144))},
2904 {V(int(145)), V(int(145))},
2905 {V(int(146)), V(uint(146))},
2906 {V(uint(147)), V(int(147))},
2907 {V(int(148)), V(uintptr(148))},
2908 {V(uintptr(149)), V(int(149))},
2909 {V(int(150)), V(float32(150))},
2910 {V(float32(151)), V(int(151))},
2911 {V(int(152)), V(float64(152))},
2912 {V(float64(153)), V(int(153))},
2913 {V(uint(154)), V(uint(154))},
2914 {V(uint(155)), V(uintptr(155))},
2915 {V(uintptr(156)), V(uint(156))},
2916 {V(uint(157)), V(float32(157))},
2917 {V(float32(158)), V(uint(158))},
2918 {V(uint(159)), V(float64(159))},
2919 {V(float64(160)), V(uint(160))},
2920 {V(uintptr(161)), V(uintptr(161))},
2921 {V(uintptr(162)), V(float32(162))},
2922 {V(float32(163)), V(uintptr(163))},
2923 {V(uintptr(164)), V(float64(164))},
2924 {V(float64(165)), V(uintptr(165))},
2925 {V(float32(166)), V(float32(166))},
2926 {V(float32(167)), V(float64(167))},
2927 {V(float64(168)), V(float32(168))},
2928 {V(float64(169)), V(float64(169))},
2930 // truncation
2931 {V(float64(1.5)), V(int(1))},
2933 // complex
2934 {V(complex64(1i)), V(complex64(1i))},
2935 {V(complex64(2i)), V(complex128(2i))},
2936 {V(complex128(3i)), V(complex64(3i))},
2937 {V(complex128(4i)), V(complex128(4i))},
2939 // string
2940 {V(string("hello")), V(string("hello"))},
2941 {V(string("bytes1")), V([]byte("bytes1"))},
2942 {V([]byte("bytes2")), V(string("bytes2"))},
2943 {V([]byte("bytes3")), V([]byte("bytes3"))},
2944 {V(string("runes♝")), V([]rune("runes♝"))},
2945 {V([]rune("runes♕")), V(string("runes♕"))},
2946 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2947 {V(int('a')), V(string("a"))},
2948 {V(int8('a')), V(string("a"))},
2949 {V(int16('a')), V(string("a"))},
2950 {V(int32('a')), V(string("a"))},
2951 {V(int64('a')), V(string("a"))},
2952 {V(uint('a')), V(string("a"))},
2953 {V(uint8('a')), V(string("a"))},
2954 {V(uint16('a')), V(string("a"))},
2955 {V(uint32('a')), V(string("a"))},
2956 {V(uint64('a')), V(string("a"))},
2957 {V(uintptr('a')), V(string("a"))},
2958 {V(int(-1)), V(string("\uFFFD"))},
2959 {V(int8(-2)), V(string("\uFFFD"))},
2960 {V(int16(-3)), V(string("\uFFFD"))},
2961 {V(int32(-4)), V(string("\uFFFD"))},
2962 {V(int64(-5)), V(string("\uFFFD"))},
2963 {V(uint(0x110001)), V(string("\uFFFD"))},
2964 {V(uint32(0x110002)), V(string("\uFFFD"))},
2965 {V(uint64(0x110003)), V(string("\uFFFD"))},
2966 {V(uintptr(0x110004)), V(string("\uFFFD"))},
2968 // named string
2969 {V(MyString("hello")), V(string("hello"))},
2970 {V(string("hello")), V(MyString("hello"))},
2971 {V(string("hello")), V(string("hello"))},
2972 {V(MyString("hello")), V(MyString("hello"))},
2973 {V(MyString("bytes1")), V([]byte("bytes1"))},
2974 {V([]byte("bytes2")), V(MyString("bytes2"))},
2975 {V([]byte("bytes3")), V([]byte("bytes3"))},
2976 {V(MyString("runes♝")), V([]rune("runes♝"))},
2977 {V([]rune("runes♕")), V(MyString("runes♕"))},
2978 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2979 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
2980 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
2981 {V(int('a')), V(MyString("a"))},
2982 {V(int8('a')), V(MyString("a"))},
2983 {V(int16('a')), V(MyString("a"))},
2984 {V(int32('a')), V(MyString("a"))},
2985 {V(int64('a')), V(MyString("a"))},
2986 {V(uint('a')), V(MyString("a"))},
2987 {V(uint8('a')), V(MyString("a"))},
2988 {V(uint16('a')), V(MyString("a"))},
2989 {V(uint32('a')), V(MyString("a"))},
2990 {V(uint64('a')), V(MyString("a"))},
2991 {V(uintptr('a')), V(MyString("a"))},
2992 {V(int(-1)), V(MyString("\uFFFD"))},
2993 {V(int8(-2)), V(MyString("\uFFFD"))},
2994 {V(int16(-3)), V(MyString("\uFFFD"))},
2995 {V(int32(-4)), V(MyString("\uFFFD"))},
2996 {V(int64(-5)), V(MyString("\uFFFD"))},
2997 {V(uint(0x110001)), V(MyString("\uFFFD"))},
2998 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
2999 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3000 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3002 // named []byte
3003 {V(string("bytes1")), V(MyBytes("bytes1"))},
3004 {V(MyBytes("bytes2")), V(string("bytes2"))},
3005 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3006 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3007 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3009 // named []rune
3010 {V(string("runes♝")), V(MyRunes("runes♝"))},
3011 {V(MyRunes("runes♕")), V(string("runes♕"))},
3012 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3013 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3014 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3016 // named types and equal underlying types
3017 {V(new(int)), V(new(integer))},
3018 {V(new(integer)), V(new(int))},
3019 {V(Empty{}), V(struct{}{})},
3020 {V(new(Empty)), V(new(struct{}))},
3021 {V(struct{}{}), V(Empty{})},
3022 {V(new(struct{})), V(new(Empty))},
3023 {V(Empty{}), V(Empty{})},
3024 {V(MyBytes{}), V([]byte{})},
3025 {V([]byte{}), V(MyBytes{})},
3026 {V((func())(nil)), V(MyFunc(nil))},
3027 {V((MyFunc)(nil)), V((func())(nil))},
3029 // can convert *byte and *MyByte
3030 {V((*byte)(nil)), V((*MyByte)(nil))},
3031 {V((*MyByte)(nil)), V((*byte)(nil))},
3033 // cannot convert mismatched array sizes
3034 {V([2]byte{}), V([2]byte{})},
3035 {V([3]byte{}), V([3]byte{})},
3037 // cannot convert other instances
3038 {V((**byte)(nil)), V((**byte)(nil))},
3039 {V((**MyByte)(nil)), V((**MyByte)(nil))},
3040 {V((chan byte)(nil)), V((chan byte)(nil))},
3041 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3042 {V(([]byte)(nil)), V(([]byte)(nil))},
3043 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
3044 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3045 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
3046 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3047 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
3048 {V([2]byte{}), V([2]byte{})},
3049 {V([2]MyByte{}), V([2]MyByte{})},
3051 // other
3052 {V((***int)(nil)), V((***int)(nil))},
3053 {V((***byte)(nil)), V((***byte)(nil))},
3054 {V((***int32)(nil)), V((***int32)(nil))},
3055 {V((***int64)(nil)), V((***int64)(nil))},
3056 {V((chan int)(nil)), V((<-chan int)(nil))},
3057 {V((chan int)(nil)), V((chan<- int)(nil))},
3058 {V((chan string)(nil)), V((<-chan string)(nil))},
3059 {V((chan string)(nil)), V((chan<- string)(nil))},
3060 {V((chan byte)(nil)), V((chan byte)(nil))},
3061 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3062 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3063 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3064 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3065 {V([]uint(nil)), V([]uint(nil))},
3066 {V([]int(nil)), V([]int(nil))},
3067 {V(new(interface{})), V(new(interface{}))},
3068 {V(new(io.Reader)), V(new(io.Reader))},
3069 {V(new(io.Writer)), V(new(io.Writer))},
3071 // interfaces
3072 {V(int(1)), EmptyInterfaceV(int(1))},
3073 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3074 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3075 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3076 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
3079 func TestConvert(t *testing.T) {
3080 canConvert := map[[2]Type]bool{}
3081 all := map[Type]bool{}
3083 for _, tt := range convertTests {
3084 t1 := tt.in.Type()
3085 if !t1.ConvertibleTo(t1) {
3086 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
3087 continue
3090 t2 := tt.out.Type()
3091 if !t1.ConvertibleTo(t2) {
3092 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
3093 continue
3096 all[t1] = true
3097 all[t2] = true
3098 canConvert[[2]Type{t1, t2}] = true
3100 // vout1 represents the in value converted to the in type.
3101 v1 := tt.in
3102 vout1 := v1.Convert(t1)
3103 out1 := vout1.Interface()
3104 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
3105 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
3108 // vout2 represents the in value converted to the out type.
3109 vout2 := v1.Convert(t2)
3110 out2 := vout2.Interface()
3111 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
3112 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
3115 // vout3 represents a new value of the out type, set to vout2. This makes
3116 // sure the converted value vout2 is really usable as a regular value.
3117 vout3 := New(t2).Elem()
3118 vout3.Set(vout2)
3119 out3 := vout3.Interface()
3120 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
3121 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
3124 if IsRO(v1) {
3125 t.Errorf("table entry %v is RO, should not be", v1)
3127 if IsRO(vout1) {
3128 t.Errorf("self-conversion output %v is RO, should not be", vout1)
3130 if IsRO(vout2) {
3131 t.Errorf("conversion output %v is RO, should not be", vout2)
3133 if IsRO(vout3) {
3134 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
3136 if !IsRO(MakeRO(v1).Convert(t1)) {
3137 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3139 if !IsRO(MakeRO(v1).Convert(t2)) {
3140 t.Errorf("RO conversion output %v is not RO, should be", v1)
3144 // Assume that of all the types we saw during the tests,
3145 // if there wasn't an explicit entry for a conversion between
3146 // a pair of types, then it's not to be allowed. This checks for
3147 // things like 'int64' converting to '*int'.
3148 for t1 := range all {
3149 for t2 := range all {
3150 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3151 if ok := t1.ConvertibleTo(t2); ok != expectOK {
3152 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3158 func TestOverflow(t *testing.T) {
3159 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3160 t.Errorf("%v wrongly overflows float64", 1e300)
3163 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3164 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3165 t.Errorf("%v wrongly overflows float32", maxFloat32)
3167 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3168 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3169 t.Errorf("%v should overflow float32", ovfFloat32)
3171 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3172 t.Errorf("%v should overflow float32", -ovfFloat32)
3175 maxInt32 := int64(0x7fffffff)
3176 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3177 t.Errorf("%v wrongly overflows int32", maxInt32)
3179 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3180 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3182 ovfInt32 := int64(1 << 31)
3183 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3184 t.Errorf("%v should overflow int32", ovfInt32)
3187 maxUint32 := uint64(0xffffffff)
3188 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3189 t.Errorf("%v wrongly overflows uint32", maxUint32)
3191 ovfUint32 := uint64(1 << 32)
3192 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3193 t.Errorf("%v should overflow uint32", ovfUint32)
3197 func checkSameType(t *testing.T, x, y interface{}) {
3198 if TypeOf(x) != TypeOf(y) {
3199 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3203 func TestArrayOf(t *testing.T) {
3204 // check construction and use of type not in binary
3205 type T int
3206 at := ArrayOf(10, TypeOf(T(1)))
3207 v := New(at).Elem()
3208 for i := 0; i < v.Len(); i++ {
3209 v.Index(i).Set(ValueOf(T(i)))
3211 s := fmt.Sprint(v.Interface())
3212 want := "[0 1 2 3 4 5 6 7 8 9]"
3213 if s != want {
3214 t.Errorf("constructed array = %s, want %s", s, want)
3217 // check that type already in binary is found
3218 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
3221 func TestSliceOf(t *testing.T) {
3222 // check construction and use of type not in binary
3223 type T int
3224 st := SliceOf(TypeOf(T(1)))
3225 v := MakeSlice(st, 10, 10)
3226 runtime.GC()
3227 for i := 0; i < v.Len(); i++ {
3228 v.Index(i).Set(ValueOf(T(i)))
3229 runtime.GC()
3231 s := fmt.Sprint(v.Interface())
3232 want := "[0 1 2 3 4 5 6 7 8 9]"
3233 if s != want {
3234 t.Errorf("constructed slice = %s, want %s", s, want)
3237 // check that type already in binary is found
3238 type T1 int
3239 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
3242 func TestSliceOverflow(t *testing.T) {
3243 // check that MakeSlice panics when size of slice overflows uint
3244 const S = 1e6
3245 s := uint(S)
3246 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
3247 if l*s >= s {
3248 t.Fatal("slice size does not overflow")
3250 var x [S]byte
3251 st := SliceOf(TypeOf(x))
3252 defer func() {
3253 err := recover()
3254 if err == nil {
3255 t.Fatal("slice overflow does not panic")
3258 MakeSlice(st, int(l), int(l))
3261 func TestSliceOfGC(t *testing.T) {
3262 type T *uintptr
3263 tt := TypeOf(T(nil))
3264 st := SliceOf(tt)
3265 const n = 100
3266 var x []interface{}
3267 for i := 0; i < n; i++ {
3268 v := MakeSlice(st, n, n)
3269 for j := 0; j < v.Len(); j++ {
3270 p := new(uintptr)
3271 *p = uintptr(i*n + j)
3272 v.Index(j).Set(ValueOf(p).Convert(tt))
3274 x = append(x, v.Interface())
3276 runtime.GC()
3278 for i, xi := range x {
3279 v := ValueOf(xi)
3280 for j := 0; j < v.Len(); j++ {
3281 k := v.Index(j).Elem().Interface()
3282 if k != uintptr(i*n+j) {
3283 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3289 func TestChanOf(t *testing.T) {
3290 // check construction and use of type not in binary
3291 type T string
3292 ct := ChanOf(BothDir, TypeOf(T("")))
3293 v := MakeChan(ct, 2)
3294 runtime.GC()
3295 v.Send(ValueOf(T("hello")))
3296 runtime.GC()
3297 v.Send(ValueOf(T("world")))
3298 runtime.GC()
3300 sv1, _ := v.Recv()
3301 sv2, _ := v.Recv()
3302 s1 := sv1.String()
3303 s2 := sv2.String()
3304 if s1 != "hello" || s2 != "world" {
3305 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
3308 // check that type already in binary is found
3309 type T1 int
3310 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
3313 func TestChanOfGC(t *testing.T) {
3314 done := make(chan bool, 1)
3315 go func() {
3316 select {
3317 case <-done:
3318 case <-time.After(5 * time.Second):
3319 panic("deadlock in TestChanOfGC")
3323 defer func() {
3324 done <- true
3327 type T *uintptr
3328 tt := TypeOf(T(nil))
3329 ct := ChanOf(BothDir, tt)
3331 // NOTE: The garbage collector handles allocated channels specially,
3332 // so we have to save pointers to channels in x; the pointer code will
3333 // use the gc info in the newly constructed chan type.
3334 const n = 100
3335 var x []interface{}
3336 for i := 0; i < n; i++ {
3337 v := MakeChan(ct, n)
3338 for j := 0; j < n; j++ {
3339 p := new(uintptr)
3340 *p = uintptr(i*n + j)
3341 v.Send(ValueOf(p).Convert(tt))
3343 pv := New(ct)
3344 pv.Elem().Set(v)
3345 x = append(x, pv.Interface())
3347 runtime.GC()
3349 for i, xi := range x {
3350 v := ValueOf(xi).Elem()
3351 for j := 0; j < n; j++ {
3352 pv, _ := v.Recv()
3353 k := pv.Elem().Interface()
3354 if k != uintptr(i*n+j) {
3355 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3361 func TestMapOf(t *testing.T) {
3362 // check construction and use of type not in binary
3363 type K string
3364 type V float64
3366 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
3367 runtime.GC()
3368 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
3369 runtime.GC()
3371 s := fmt.Sprint(v.Interface())
3372 want := "map[a:1]"
3373 if s != want {
3374 t.Errorf("constructed map = %s, want %s", s, want)
3377 // check that type already in binary is found
3378 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
3380 // check that invalid key type panics
3381 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3384 func TestMapOfGCKeys(t *testing.T) {
3385 type T *uintptr
3386 tt := TypeOf(T(nil))
3387 mt := MapOf(tt, TypeOf(false))
3389 // NOTE: The garbage collector handles allocated maps specially,
3390 // so we have to save pointers to maps in x; the pointer code will
3391 // use the gc info in the newly constructed map type.
3392 const n = 100
3393 var x []interface{}
3394 for i := 0; i < n; i++ {
3395 v := MakeMap(mt)
3396 for j := 0; j < n; j++ {
3397 p := new(uintptr)
3398 *p = uintptr(i*n + j)
3399 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
3401 pv := New(mt)
3402 pv.Elem().Set(v)
3403 x = append(x, pv.Interface())
3405 runtime.GC()
3407 for i, xi := range x {
3408 v := ValueOf(xi).Elem()
3409 var out []int
3410 for _, kv := range v.MapKeys() {
3411 out = append(out, int(kv.Elem().Interface().(uintptr)))
3413 sort.Ints(out)
3414 for j, k := range out {
3415 if k != i*n+j {
3416 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3422 func TestMapOfGCValues(t *testing.T) {
3423 type T *uintptr
3424 tt := TypeOf(T(nil))
3425 mt := MapOf(TypeOf(1), tt)
3427 // NOTE: The garbage collector handles allocated maps specially,
3428 // so we have to save pointers to maps in x; the pointer code will
3429 // use the gc info in the newly constructed map type.
3430 const n = 100
3431 var x []interface{}
3432 for i := 0; i < n; i++ {
3433 v := MakeMap(mt)
3434 for j := 0; j < n; j++ {
3435 p := new(uintptr)
3436 *p = uintptr(i*n + j)
3437 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
3439 pv := New(mt)
3440 pv.Elem().Set(v)
3441 x = append(x, pv.Interface())
3443 runtime.GC()
3445 for i, xi := range x {
3446 v := ValueOf(xi).Elem()
3447 for j := 0; j < n; j++ {
3448 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
3449 if k != uintptr(i*n+j) {
3450 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3456 type B1 struct {
3457 X int
3458 Y int
3459 Z int
3462 func BenchmarkFieldByName1(b *testing.B) {
3463 t := TypeOf(B1{})
3464 for i := 0; i < b.N; i++ {
3465 t.FieldByName("Z")
3469 func BenchmarkFieldByName2(b *testing.B) {
3470 t := TypeOf(S3{})
3471 for i := 0; i < b.N; i++ {
3472 t.FieldByName("B")
3476 type R0 struct {
3483 type R1 struct {
3490 type R2 R1
3491 type R3 R1
3492 type R4 R1
3494 type R5 struct {
3496 *R10
3497 *R11
3498 *R12
3501 type R6 R5
3502 type R7 R5
3503 type R8 R5
3505 type R9 struct {
3506 *R13
3507 *R14
3508 *R15
3509 *R16
3512 type R10 R9
3513 type R11 R9
3514 type R12 R9
3516 type R13 struct {
3517 *R17
3518 *R18
3519 *R19
3520 *R20
3523 type R14 R13
3524 type R15 R13
3525 type R16 R13
3527 type R17 struct {
3528 *R21
3529 *R22
3530 *R23
3531 *R24
3534 type R18 R17
3535 type R19 R17
3536 type R20 R17
3538 type R21 struct {
3539 X int
3542 type R22 R21
3543 type R23 R21
3544 type R24 R21
3546 func TestEmbed(t *testing.T) {
3547 typ := TypeOf(R0{})
3548 f, ok := typ.FieldByName("X")
3549 if ok {
3550 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
3554 func BenchmarkFieldByName3(b *testing.B) {
3555 t := TypeOf(R0{})
3556 for i := 0; i < b.N; i++ {
3557 t.FieldByName("X")
3561 type S struct {
3562 i1 int64
3563 i2 int64
3566 func BenchmarkInterfaceBig(b *testing.B) {
3567 v := ValueOf(S{})
3568 for i := 0; i < b.N; i++ {
3569 v.Interface()
3571 b.StopTimer()
3574 func TestAllocsInterfaceBig(t *testing.T) {
3575 if testing.Short() {
3576 t.Skip("skipping malloc count in short mode")
3578 v := ValueOf(S{})
3579 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
3580 t.Error("allocs:", allocs)
3584 func BenchmarkInterfaceSmall(b *testing.B) {
3585 v := ValueOf(int64(0))
3586 for i := 0; i < b.N; i++ {
3587 v.Interface()
3591 func TestAllocsInterfaceSmall(t *testing.T) {
3592 if testing.Short() {
3593 t.Skip("skipping malloc count in short mode")
3595 v := ValueOf(int64(0))
3596 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
3597 t.Error("allocs:", allocs)
3601 // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
3602 // The basic usage is:
3604 // for x.Next() {
3605 // ... code using x.Maybe() or x.Choice(n) to create test cases ...
3606 // }
3608 // Each iteration of the loop returns a different set of results, until all
3609 // possible result sets have been explored. It is okay for different code paths
3610 // to make different method call sequences on x, but there must be no
3611 // other source of non-determinism in the call sequences.
3613 // When faced with a new decision, x chooses randomly. Future explorations
3614 // of that path will choose successive values for the result. Thus, stopping
3615 // the loop after a fixed number of iterations gives somewhat stochastic
3616 // testing.
3618 // Example:
3620 // for x.Next() {
3621 // v := make([]bool, x.Choose(4))
3622 // for i := range v {
3623 // v[i] = x.Maybe()
3624 // }
3625 // fmt.Println(v)
3626 // }
3628 // prints (in some order):
3630 // []
3631 // [false]
3632 // [true]
3633 // [false false]
3634 // [false true]
3635 // ...
3636 // [true true]
3637 // [false false false]
3638 // ...
3639 // [true true true]
3640 // [false false false false]
3641 // ...
3642 // [true true true true]
3644 type exhaustive struct {
3645 r *rand.Rand
3646 pos int
3647 last []choice
3650 type choice struct {
3651 off int
3652 n int
3653 max int
3656 func (x *exhaustive) Next() bool {
3657 if x.r == nil {
3658 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
3660 x.pos = 0
3661 if x.last == nil {
3662 x.last = []choice{}
3663 return true
3665 for i := len(x.last) - 1; i >= 0; i-- {
3666 c := &x.last[i]
3667 if c.n+1 < c.max {
3668 c.n++
3669 x.last = x.last[:i+1]
3670 return true
3673 return false
3676 func (x *exhaustive) Choose(max int) int {
3677 if x.pos >= len(x.last) {
3678 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
3680 c := &x.last[x.pos]
3681 x.pos++
3682 if c.max != max {
3683 panic("inconsistent use of exhaustive tester")
3685 return (c.n + c.off) % max
3688 func (x *exhaustive) Maybe() bool {
3689 return x.Choose(2) == 1
3692 func GCFunc(args []Value) []Value {
3693 runtime.GC()
3694 return []Value{}
3697 func TestReflectFuncTraceback(t *testing.T) {
3698 f := MakeFunc(TypeOf(func() {}), GCFunc)
3699 f.Call([]Value{})
3702 func (p Point) GCMethod(k int) int {
3703 runtime.GC()
3704 return k + p.x
3707 func TestReflectMethodTraceback(t *testing.T) {
3708 p := Point{3, 4}
3709 m := ValueOf(p).MethodByName("GCMethod")
3710 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
3711 if i != 8 {
3712 t.Errorf("Call returned %d; want 8", i)
3716 func TestBigZero(t *testing.T) {
3717 const size = 1 << 10
3718 var v [size]byte
3719 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
3720 for i := 0; i < size; i++ {
3721 if z[i] != 0 {
3722 t.Fatalf("Zero object not all zero, index %d", i)