1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
package reflect_test
import (
. "reflect"
"sort"
"testing"
)
func TestIndirectPointers(t *testing.T) {
var m = map[string]int{}
m["x"] = 1
var a = &m
if ValueOf(a).Elem().Len() != 1 {
t.Errorf("bad map length via reflect")
}
var b struct {
Decoded *[3]byte
}
v1 := New(TypeOf(b.Decoded).Elem())
var bb [3]byte
bb[0] = 0xaa
v1.Elem().Set(ValueOf(bb))
if v1.Elem().Index(0).Uint() != 0xaa {
t.Errorf("bad indirect array index via reflect")
}
}
func TestMap(t *testing.T) {
m := make(map[string]int)
mtyp := TypeOf(m)
if got, want := mtyp.Key().Kind().String(), "string"; got != want {
t.Errorf("m.Type().Key().String()=%q, want %q", got, want)
}
if got, want := mtyp.Elem().Kind().String(), "int"; got != want {
t.Errorf("m.Elem().String()=%q, want %q", got, want)
}
m["foo"] = 2
mref := ValueOf(m)
two := mref.MapIndex(ValueOf("foo"))
if got, want := two.Interface().(int), 2; got != want {
t.Errorf("MapIndex(`foo`)=%v, want %v", got, want)
}
m["bar"] = 3
m["baz"] = 4
m["qux"] = 5
it := mref.MapRange()
var gotKeys []string
for it.Next() {
k := it.Key()
v := it.Value()
kstr := k.Interface().(string)
vint := v.Interface().(int)
gotKeys = append(gotKeys, kstr)
if m[kstr] != vint {
t.Errorf("m[%v]=%v, want %v", kstr, vint, m[kstr])
}
}
var wantKeys []string
for k := range m {
wantKeys = append(wantKeys, k)
}
sort.Strings(gotKeys)
sort.Strings(wantKeys)
if !equal(gotKeys, wantKeys) {
t.Errorf("MapRange return unexpected keys: got %v, want %v", gotKeys, wantKeys)
}
mref.SetMapIndex(ValueOf("bar"), Value{})
if _, ok := m["bar"]; ok {
t.Errorf("SetMapIndex failed to delete `bar`")
}
mref.SetMapIndex(ValueOf("baz"), ValueOf(6))
if got, want := m["baz"], 6; got != want {
t.Errorf("SetMapIndex(bar, 6) got %v, want %v", got, want)
}
}
func equal[T comparable](a, b []T) bool {
if len(a) != len(b) {
return false
}
for i, aa := range a {
if b[i] != aa {
return false
}
}
return true
}
|