[英]reflect: call of reflect.Value.Field on ptr Value
我正在嘗試將map [string] interface {}映射到結構。 我的結構包含指針類型:
type A struct{
f1 string
f2 *B
}
type B {
f1 string
f2 string
}
當我嘗試遍歷* B時,我得到:
"reflect: call of reflect.Value.Field on ptr Value"
來自輸出的val如下:
<*B Value>
碼:
func processNode(v *reflect.Value, t reflect.Type, data interface{}) error {
for i := 0; i < t.NumField(); i++ {
var f reflect.Value
if isPointer(v.Type()) {
fmt.Printf("val: %s\n", v)
f = v.Field(i) //Fails here!
} else {
f = v.Field(i)
}
ft := t.Field(i)
m := data.(map[string]interface{})
val, ok := findFieldValue(m, ft.Name)
if ok {
if isPointer(ft.Type) && !isSimpleType(ft.Type) {
processNode(&f, ft.Type.Elem(), val)
} else if !isSimpleType(ft.Type) {
processNode(&f, ft.Type, val)
} else {
err := setTyped(&f, val)
if err != nil {
return err
}
}
}
}
return nil
}
我想知道,如何通過參考值進行迭代? (在A上迭代效果很好)
該代碼取消引用該字段的類型,但不引用該字段的值。 更改
if isPointer(ft.Type) && !isSimpleType(ft.Type) {
processNode(&f, ft.Type.Elem(), val)
...
至:
if isPointer(ft.Type) && !isSimpleType(ft.Type) {
fv := f.Elem()
processNode(&fv, ft.Type.Elem(), val)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.