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)

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?