drd43058 2018-09-29 14:10
浏览 13

引用结构的指针并克隆它

Please ignore that this seems like a bad idea, is bad style, etc.

The main issue here is that process() gets a pointer to a struct of an unknown type passed in as interface{} and I need to clone the underlying struct.

The core issue is that I can't figure out how to deference the pointer, since its passed in as interface{}, so I can clone the underlying struct and return it.

package main

import (
    "fmt"
    "reflect"
)

type Foo struct {
    Value string
}

func main() {
    foo1 := Foo{"bar"}
    foo2 := process(&foo1)
    result := reflect.DeepEqual(foo1, foo2)
    fmt.Println(result) // how do I make this true?
}

// objective: pointer to struct is passed it, clone of underlying struct is returned
func process(i interface{}) interface{} {
    return clone(i)
}
  • 写回答

1条回答 默认 最新

  • douluxia0606 2018-09-30 04:20
    关注

    Using some reflection magic, I was able to get this to work. Thanks, JimB, for all your help! The code in this question is obviously contrived. I need this functionality for a testing utility that takes "snapshots" of structs of any type at different stages before various mutations are applied.

    ...    
    func process(i interface{}) (interface{}, error) {
        value := reflect.ValueOf(i)
        if value.Kind() == reflect.Ptr {
            i = value.Elem().Interface()
        }
    
        return copystructure.Copy(i)
    }
    ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探