Skip to content

How to Perform a Deep Copy in Golang

To perform a Deep Copy in Go, you can use a struct type as follows:

Deep Copying using a struct in Go

package main import ( "fmt" ) type Dog struct { age int name string friends []string } func main() { john := Dog{1, "Harry", []string{"Steve", "Matt", "Sarah"}} jack := john jack.friends = make([]string, len(john.friends)) copy(jack.friends, harry.friends) jack.friends = append(jay.friends, "Fred") fmt.Println(john) fmt.Println(jack) }
Code language: Go (go)

See also  How to Loop Forever in Golang
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x