How to Deep Copy in Go
Jay Singh
Feb 02, 2024
When you attempt to generate a duplicate of an object, the deep copy copies all fields of the original objects exactly. Moreover, if it has any objects as fields, a copy of those is also made.
This means that if you conduct a deep copy on an object that contains a reference (object), both the original and duplicated object refer to separate objects, and any changes made to the data in the copied object are not reflected in the original object.
Let’s look at a few instances to grasp better how to perform a deep copy in Go.
Perform Deep Copy Using struct
in Go
We can do such deep copying manually. In the case of a slice, use the following code to do a deep copy.
You’ll see that the slice is an entirely separate object, not only a reference to the same slice.
Example:
package main
import (
"fmt"
)
type Cat struct {
age int
name string
friends []string
}
func main() {
harry := Cat{1, "Harry", []string{"Ron", "Jenny", "Kety"}}
jay := harry
jay.friends = make([]string, len(harry.friends))
copy(jay.friends, harry.friends)
jay.friends = append(jay.friends, "Sid")
fmt.Println(harry)
fmt.Println(jay)
}
Output
{1 Harry [Ron Jenny Kety]}
{1 Harry [Ron Jenny Kety Sid]}