duanliaogui4133 2015-07-25 15:30
浏览 29
已采纳

复制结构

I am attempting to make a deep copy of a struct in go. Before going and building a solution myself, I attempted to find the idiomatic way to do so in go. I did find reference to this implementation. However, it appears to be well out of date and not actively maintained. I'm sure this is a scenario that people much require from time-to-time so I must be missing something. Does anybody have any guidance?

  • 写回答

1条回答 默认 最新

  • du67560 2015-07-25 15:50
    关注

    A more recent version of the google deepcopy code can be found in margnus1/go-deepcopy.

    It does illustrate why there is no deepcopy in the standard library.

    // basic copy algorithm:
    // 1) recursively scan object, building up a list of all allocated
    // memory ranges pointed to by the object.
    // 2) recursively copy object, making sure that references
    // within the data structure point to the appropriate
    // places in the newly allocated data structure.
    

    The all algo is quite convoluted and rely on reflection. And of course only access exported field.

    // Copy makes a recursive deep copy of obj and returns the result.
    //
    // Pointer equality between items within obj is preserved,
    // as are the relationships between slices that point to the same underlying data,
    // although the data itself will be copied.
    // a := Copy(b) implies reflect.DeepEqual(a, b).
    // Map keys are not copied, as reflect.DeepEqual does not
    // recurse into map keys.
    // Due to restrictions in the reflect package, only
    // types with all public members may be copied.
    //
    func Copy(obj interface{}) (r interface{}) {
    

    I'm sure this is a scenario that people much require from time-to-time so I must be missing something

    As mentioned in this thread:

    Passing struct values as opposed to struct pointers, for example, is generally good enough. If the programmer is good enough to effectively design tree or graph structures, then they can probably anticipate problems with sharing such a structure.
    Many of us consider the absence of mandatory deep-copy behavior to a feature, since we want Go to provide tools to aid safety, not obstacles to efficiency.


    A more recent and polished version of deepcopy is ulule/deepcopier

    // Deep copy instance1 into instance2
    Copy(instance1).To(instance2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决