我正在尝试在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
}
这个版本有改进吗?(是否正确?)