Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Struct 深入/浅层复制_Struct_Go_Deep Copy - Fatal编程技术网

Struct 深入/浅层复制

Struct 深入/浅层复制,struct,go,deep-copy,Struct,Go,Deep Copy,我正在尝试复制Go中的一个结构,但在这个结构上找不到很多资源。以下是我所拥有的: type Server struct { HTTPRoot string // Location of the current subdirectory StaticRoot string // Folder containing static files for all domains Auth Auth FormRecipients []s

我正在尝试复制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

这会将
*服务器
s
复制到
c

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

对于深度复制,您需要遍历字段,并确定需要递归复制的内容。根据
*httprouter.Router
是什么,如果深度复制包含未报告字段中的数据,则可能无法进行深度复制

除非使用指针,否则赋值始终是副本。@SebastienC.:赋值始终是副本。当它是指针时,您正在复制指针值。