-
Notifications
You must be signed in to change notification settings - Fork 2
/
elem_init.go
52 lines (47 loc) · 1.16 KB
/
elem_init.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
package reflecthelper
import (
"reflect"
)
// GetInitElem gets the element of a pointer value.
// It initialize the element of a pointer value if it is nil.
func GetInitElem(val reflect.Value) (res reflect.Value) {
res = val
if !IsValueElemable(res) {
return
}
if res.IsNil() {
if !res.CanSet() || !IsTypeValueElemable(res) {
return
}
res.Set(reflect.New(res.Type().Elem()))
}
res = res.Elem()
return
}
// GetInitChildElem gets the child elem (root child) if it is a pointer with an element of pointer.
// It also initializes the child elem if it is CanSet and IsNil.
func GetInitChildElem(val reflect.Value) (res reflect.Value) {
res = val
var tempRes reflect.Value
for IsValueElemable(res) {
tempRes = GetInitElem(res)
if res == tempRes {
return
}
res = tempRes
}
return
}
// GetInitChildPtrElem is similar with GetInitChildElem but the function stops when the elem is ptr and the elem of that ptr is non ptr.
func GetInitChildPtrElem(val reflect.Value) (res reflect.Value) {
res = val
var tempRes reflect.Value
for IsValueElemableParentElem(res) {
tempRes = GetInitElem(res)
if res == tempRes {
return
}
res = tempRes
}
return
}