深拷贝/浅拷贝

huangapple go评论70阅读模式
英文:

Go deep/shallow copy

问题

我正在尝试复制一个Go语言中的结构体,但是找不到很多相关资源。以下是我的代码:

type Server struct {
    HTTPRoot       string // 当前子目录的位置
    StaticRoot     string // 包含所有域的静态文件的文件夹
    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
}

第一个问题,这不是一个深拷贝,因为我没有复制s.Auth。这至少是一个正确的浅拷贝吗?第二个问题,有没有更符合惯用方式的进行深拷贝(或浅拷贝)的方法?

编辑:

我尝试了另一种非常简单的方法,利用了参数按值传递的特性。

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

这个版本有没有更好一些?(它是否正确?)

英文:

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

得分: 15

赋值是一种复制操作。你的第二个函数接近正确,只需要对s进行解引用。

这样将*Servers复制给c

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

至于深拷贝,你需要遍历字段,并确定哪些需要递归复制。根据*httprouter.Router的具体情况,如果它包含未导出字段中的数据,可能无法进行深拷贝。

英文:

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.

huangapple
  • 本文由 发表于 2015年7月1日 20:50:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/31161829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定