Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a struct in Golang?

Tags:

go

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.

like image 604
Salim Fadhley Avatar asked Aug 01 '18 14:08

Salim Fadhley


People also ask

What is deep copy in Golang?

Go Deep CopyTo handle circular pointer references (e.g. a pointer to a struct with a pointer field that points back to the original struct), we keep track of a map of pointers that have already been visited. This serves two purposes. First, it keeps us from getting into any kind of infinite loop.

How can you copy one structure to another structure of the same data type give an example?

struct { char string[32]; size_t len; } a, b; strcpy(a. string, "hello"); a. len = strlen(a. string);

Are structs copied?

In C/C++, we can assign a struct (or class in C++ only) variable to another variable of same type. When we assign a struct variable to another, all members of the variable are copied to the other struct variable.


Video Answer


1 Answers

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.

like image 96
maerics Avatar answered Sep 20 '22 18:09

maerics