英文:
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
进行解引用。
这样将*Server
的s
复制给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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论