How do I copy a struct in Golang?

Issue

I want to copy an object so that I have two identical objects with two different memory addresses. My first attempt at this has failed:

aa := a
assert.NotEqual(t, &a, &aa, "Copied items should not be the same object.") // Test fails

Can I fix this so that it really does a copy of the struct? There’s nothing special about this structure.

Solution

In go, primitive types, and structs containing only primitive types, are copied by value, so you can copy them by simply assigning to a new variable (or returning from a function). For example:

type Person struct{
  Name string
  Age  int
}

alice1 := Person{"Alice", 30}
alice2 := alice1
fmt.Println(alice1 == alice2)   // => true, they have the same field values
fmt.Println(&alice1 == &alice2) // => false, they have different addresses

alice2.Age += 10
fmt.Println(alice1 == alice2)   // => false, now they have different field values

Note that, as mentioned by commenters, the confusion in your example is likely due to the semantics of the test library you are using.

If your struct happens to include arrays, slices, or pointers, then you’ll need to perform a deep copy of the referenced objects unless you want to retain references between copies. Golang provides no builtin deep copy functionality so you’ll have to implement your own or use one of the many freely available libraries that provide it.

Answered By – maerics

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.