我正在尝试在 Go 中复制一个结构,但找不到很多相关资源。这是我所拥有的:
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
}
第一个问题,这不会是深度复制,因为我没有复制 s.Auth。这至少是一个正确的浅拷贝吗?第二个问题,是否有更惯用的方式来执行深(或浅)复制?
编辑:
我试过的另一种选择非常简单,它使用了参数按值传递的事实。
func (s *Server) Copy() (s2 *Server) {
tmp := s
s2 = &tmp
return
}
这个版本好点了吗? (正确吗?)
最佳答案
作业是一份副本。你的第二个函数很接近,你只需要取消引用 s
。
这会将 *Server
s
复制到 c
c := new(Server)
*c = *s
对于深拷贝,需要遍历字段,递归判断需要拷贝什么。根据 *httprouter.Router
是什么,如果它包含未导出字段中的数据,您可能无法进行深度复制。
关于struct - 去深/浅复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161829/