我试图在 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
}
这个版本好点了吗?(这是正确的吗?)
ITMISS
相关分类