dsy19811981 2019-08-30 03:57
浏览 79
已采纳

如何通过反射将非指针值复制到指针间接值

I want the Set method below to set the APtr field of a passed in B struct to a value that gets passed in by value, i.e. without a pointer indirection.

For that to work via go reflection, I will probably have to copy that value to a new location that I have the address of? Either way, how can I get this to work? What I have is a working version for non-pointers values.

type A struct {
    AnInt int
}

type B struct {
    AnA   A
    APtr *A
}

func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {
    struktValueElem := reflect.ValueOf(strukt).Elem()
    field := struktValueElem.FieldByName(fieldName)
    newFieldValueValue := reflect.ValueOf(newFieldValue)
    if field.Kind() == reflect.Ptr {
        // ?? implement me
    } else { // not a pointer? more straightforward:
        field.Set(newFieldValueValue)
    }
}

func main() {
    aB := B{}
    anA := A{4}
    Set(&aB, "AnA", anA) // works
    Set(&aB, "APtr", anA) // implement me
}

Playground: https://play.golang.org/p/6tcmbXxBcIm

  • 写回答

1条回答 默认 最新

  • douluoyou9876 2019-08-30 06:03
    关注
    func Set(strukt interface{}, fieldName string, newFieldValue interface{}) {
        struktValueElem := reflect.ValueOf(strukt).Elem()
        field := struktValueElem.FieldByName(fieldName)
        newFieldValueValue := reflect.ValueOf(newFieldValue)
        if field.Kind() == reflect.Ptr {
            rt := field.Type() // type *A
            rt = rt.Elem()     // type A
    
            rv := reflect.New(rt) // value *A
            el := rv.Elem()       // value A (addressable)
    
            el.Set(newFieldValueValue) // el is addressable and has the same type as newFieldValueValue (A), Set can be used
            field.Set(rv)              // field is addressable and has the same type as rv (*A), Set can be used
        } else { // not a pointer? more straightforward:
            field.Set(newFieldValueValue)
        }
    }
    

    https://play.golang.org/p/jgEK_rKbgO9

    https://play.golang.org/p/B6vOONQ-RXO (compact)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启