creating copy of variable

6,347 views
Skip to first unread message

Abiola Ibrahim

unread,
Sep 24, 2012, 9:56:16 AM9/24/12
to golan...@googlegroups.com
I want to able to have a copy of struct variable where i can manipulate the copy and leave the original intact. 

This is currently how I go about it http://play.golang.org/p/fIuMu-dMiG. Is there a better way ?

Thanks.

roger peppe

unread,
Sep 24, 2012, 10:02:24 AM9/24/12
to Abiola Ibrahim, golan...@googlegroups.com

Robert Carlsen

unread,
Sep 24, 2012, 10:04:33 AM9/24/12
to golan...@googlegroups.com
I'm pretty sure that won't give you a full deep-copy if that is what you need (e.g. a slice of struct pointers won't have copies of the pointed-to-structs).

Peter S

unread,
Sep 24, 2012, 10:12:33 AM9/24/12
to Abiola Ibrahim, golan...@googlegroups.com
As long as your struct only contains boolean, numeric, string, and array types (and nested structs of these types), you can just do "b := a", and manipulating b won't affect a. Otherwise you will need to implement some kind of deep copy, but AFAIK there is no generic solution for that.

I am assuming that in reality you want to manipulate more complicated data structures than struct { int }; it is easier for people in the group to provide more specific advice if you can share the actual data structure definition.

Peter

--
 
 

Abiola Ibrahim

unread,
Sep 24, 2012, 10:23:30 AM9/24/12
to golan...@googlegroups.com
The struct contains int, int64, bool, string, [4][4]int and map[string][]int elements.

Volker Dobler

unread,
Sep 24, 2012, 10:28:51 AM9/24/12
to golang-nuts
On 24 Sep., 16:23, Abiola Ibrahim <abiol...@gmail.com> wrote:
> The struct contains int, int64, bool, string, [4][4]int and
> map[string][]int elements.

You will need to "deep copy" the map manually.
You might want to provide a Copy() method on your
struct type which manually creates and populates
the map from the original.

Volker

Abiola Ibrahim

unread,
Sep 24, 2012, 10:44:19 AM9/24/12
to golan...@googlegroups.com
I was trying to run away from manually creating a Copy method but its good to know I have only the map element to bother about. Thanks. 
Reply all
Reply to author
Forward
0 new messages