-
Notifications
You must be signed in to change notification settings - Fork 0
/
flyweight.go
65 lines (56 loc) · 1.11 KB
/
flyweight.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
55
56
57
58
59
60
61
62
63
64
65
package flyweight
import (
"reflect"
)
func Reset(v interface{}) {
r := reflect.ValueOf(v)
if r.Kind() == reflect.Ptr {
r = r.Elem()
}
for i := 0; i < r.NumField(); i++ {
field := r.Field(i)
ty := field.Type()
switch field.Kind() {
case reflect.Struct:
tryCallReset(field, ty)
case reflect.Slice:
for i := 0; i < field.Len(); i++ {
element := field.Index(i)
elementType := element.Type()
tryCallReset(element, elementType)
}
field.SetLen(0)
case reflect.Ptr:
if !field.IsNil() {
callReset(field)
}
default:
field.Set(reflect.Zero(ty))
}
}
}
func tryCallReset(field reflect.Value, ty reflect.Type) {
if called := callReset(field); called {
return
}
pt := ptr(field)
if called := callReset(pt); called {
field.Set(pt.Elem())
return
}
field.Set(reflect.Zero(ty))
}
func callReset(field reflect.Value) bool {
reset := field.MethodByName("Reset")
if reset.IsValid() {
reset.Call(nil)
return true
}
return false
}
func ptr(v reflect.Value) reflect.Value {
pt := reflect.PtrTo(v.Type())
pv := reflect.New(pt.Elem())
pv.Elem().Set(v)
return pv
}