eatonphil
eatonphil

Reputation: 13702

Go deep/shallow copy

I am trying to copy a struct in Go and cannot find many resources on this. Here is what I have:

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
}

First question, this will not be a deep copy because I am not copying s.Auth. Is this at least a correct shallow copy? Second question, is there a more idiomatic way to perform a deep (or shallow) copy?

Edit:

One other alternative I've played around with is really simple and uses the fact that arguments are passed by value.

func (s *Server) Copy() (s2 *Server) {
    tmp := s
    s2 = &tmp
    return
}

Is this version any better? (Is it correct?)

Upvotes: 10

Views: 11453

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109416

Assignment is a copy. Your second function comes close, you just need to dereference s.

This copies the *Server s to c

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

As for a deep copy, you need to go through the fields, and determine what needs to be copied recursively. Depending on what *httprouter.Router is, you may not be able to make a deep copy if it contains data in unexported fields.

Upvotes: 18

Related Questions