Deep copy struct of pointers

1,758 views
Skip to first unread message

Bernhard Konrad

unread,
May 4, 2016, 2:04:26 AM5/4/16
to golang-nuts
Hi,

I was wondering if there is a way to get a deep copy of a struct which includes pointers. Following the example here: https://groups.google.com/d/msg/golang-nuts/__BPVgK8LN0/NqXMW7nDmvwJ

type Location struct {
city string
}

type Pet struct {
name     string
location *Location
}

func main() {
locationPointer := &Location{
city: "MTV",
}
var huski *Pet = new(Pet)
huski.name = "huski"
huski.location = locationPointer

dog := *huski // copies location by (pointer) value
dog.name = "dog"
dog.location.city = "SF"
fmt.Println(huski.name)          // "huski"
fmt.Println(huski.location.city) // "SF" <-- would like "MTV"
}

Is the only alternative to define my own, recursive, copy function?

Thank you
Bernhard

Matt Harden

unread,
May 4, 2016, 10:26:18 AM5/4/16
to Bernhard Konrad, golang-nuts

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages