snippetgoCritical
How do I copy a struct
Viewed 0 times
copyhowstruct
Problem
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:
Can I fix this so that it really does a copy of the struct? There's nothing special about this structure.
aa := a
assert.NotEqual(t, &a, &aa, "Copied items should not be the same object.") // Test failsCan I fix this so that it really does a copy of the struct? There's nothing special about this structure.
Solution
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:
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.
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 valuesNote 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.
Code Snippets
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 valuesContext
Stack Overflow Q#51635766, score: 189
Revisions (0)
No revisions yet.