1

我试图将 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 上工作正常)

4

1 回答 1

0

代码取消引用字段的类型,但不取消引用字段的值。改变

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)
    ...
于 2018-06-19T16:23:21.840 回答