普通网友 2018-06-19 16:13
浏览 680
已采纳

反射:调用ptr Value上的reflect.Value.Field

Im trying to map map[string]interface{} to structure. My structure contains pointer types:

type A struct{
  f1 string
  f2 *B
}

type B {
  f1 string
  f2 string
}

when I am trying to iterate through *B, I've got:

"reflect: call of reflect.Value.Field on ptr Value"

val from output is following:

<*B Value>

Code:

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
", 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
}

I wondering, how to iterate through reference value? (iteration works fine on A)

  • 写回答

1条回答 默认 最新

  • duang8642 2018-06-19 16:23
    关注

    The code dereferences the field's type, but not the field's value. Change

    if isPointer(ft.Type) && !isSimpleType(ft.Type) {
        processNode(&f, ft.Type.Elem(), val)
        ...
    

    to:

    if isPointer(ft.Type) && !isSimpleType(ft.Type) {
        fv := f.Elem()
        processNode(&fv, ft.Type.Elem(), val)
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题