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 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图