doushang1890 2015-07-01 12:50
浏览 41
已采纳

进行深/浅复制

I am trying to copy a struct in Go and cannot find many resources on this. Here is what I have:

type Server struct {
    HTTPRoot       string // Location of the current subdirectory
    StaticRoot     string // Folder containing static files for all domains
    Auth           Auth
    FormRecipients []string
    Router         *httprouter.Router
}

func (s *Server) Copy() (c *Server) {
    c.HTTPRoot = s.HTTPRoot
    c.StaticRoot = s.StaticRoot
    c.Auth = s.Auth
    c.FormRecipients = s.FormRecipients
    c.Router = s.Router
    return
}

First question, this will not be a deep copy because I am not copying s.Auth. Is this at least a correct shallow copy? Second question, is there a more idiomatic way to perform a deep (or shallow) copy?

Edit:

One other alternative I've played around with is really simple and uses the fact that arguments are passed by value.

func (s *Server) Copy() (s2 *Server) {
    tmp := s
    s2 = &tmp
    return
}

Is this version any better? (Is it correct?)

  • 写回答

1条回答 默认 最新

  • dpb56083 2015-07-01 13:01
    关注

    Assignment is a copy. Your second function comes close, you just need to dereference s.

    This copies the *Server s to c

    c := new(Server)
    *c = *s
    

    As for a deep copy, you need to go through the fields, and determine what needs to be copied recursively. Depending on what *httprouter.Router is, you may not be able to make a deep copy if it contains data in unexported fields.

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

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接