struct - 去深/浅复制

标签 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 []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/

相关文章:

c - 如何在 c 用户定义函数中返回 "struct"数据类型?

c - 为什么 Golang 比 ANSI C 快,我该如何优化我的解决方案?

linq - Enumerable.Repeat() 是否进行深拷贝?

java - 枚举类型引用或原始类型(带有示例)- 浅/深复制

javascript - Ruby => Javascript 翻译

ios - Swift 结构在自定义框架中不可见

c++ - 对 vector 中的较高值和较低值进行排序

go - nsq go 客户端跟不上

go - 在知道 UTC 时间和时间偏移量的情况下如何设置 Go 时间值的区域?

c++ - 如何在结构中的指针上使用 cudaMalloc?