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.
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.
struct { char string[32]; size_t len; } a, b; strcpy(a. string, "hello"); a. len = strlen(a. string);
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With