/
example_test.go
54 lines (47 loc) · 917 Bytes
/
example_test.go
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
package reflectutils_test
import (
"fmt"
"reflect"
"github.com/muir/reflectutils"
)
type S struct {
I1 int
S string
M T
}
type T struct {
I2 int
}
func makeIntDoubler(t reflect.Type) func(v reflect.Value) {
if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct {
panic("makeIntDoubler only supports pointers to structs")
}
var ints []reflect.StructField
reflectutils.WalkStructElements(t, func(f reflect.StructField) bool {
if f.Type.Kind() == reflect.Int {
ints = append(ints, f)
}
return true
})
return func(v reflect.Value) {
v = v.Elem()
for _, f := range ints {
i := v.FieldByIndex(f.Index)
i.SetInt(int64(i.Interface().(int)) * 2)
}
}
}
func Example() {
s := S{
I1: 3,
S: "string",
M: T{
I2: 5,
},
}
v := reflect.ValueOf(&s)
doubler := makeIntDoubler(v.Type())
doubler(v)
fmt.Printf("%v\n", v.Interface())
// Output: &{6 string {10}}
}