To read more on the differences between deep copying and shallow copying, check this Answer.
Before seeing how to deep copy a struct
, let’s look at how we can perform a shallow copy first.
struct2 := struct1
package mainimport "fmt"type DemoStruct struct{name string; value int}func main(){struct1 := DemoStruct{name: "int", value: 30}fmt.Println(struct1.name)struct2 := &struct1struct2.name = "string"fmt.Printf("Struct1 : %s\nStruct2 : %s\n",struct1.name, struct2.name)fmt.Println(&struct1 == struct2)}
struct2 := struct1
This will only work for a struct with primitive fields.
For a pointer
referencing a struct
, we use *
to dereference it before creating its copy.
Here we use the append
function, but we can also use the map
function to achieve the same functionality.
package mainimport "fmt"type DemoStruct struct{name stringvalue intarr []string}func main() {p := DemoStruct{value: 20,name: "Struct1",arr: []string{"city1"},}q:=pq.arr = nilq.arr = append(q.arr,p.arr...)q.arr[0]= "Altered"fmt.Println(p)fmt.Println(q)fmt.Println(&p == &q)}
package mainimport "fmt"type DemoStruct struct{name stringvalue ints_pointer *string}func main() {x:= "Original"p := DemoStruct{ value: 20, name: "Struct1", s_pointer: &x }q:=pq.s_pointer = nily:= *p.s_pointerq.s_pointer = &y*q.s_pointer = "Altered"fmt.Println(*p.s_pointer)fmt.Println(*q.s_pointer)fmt.Println(&p.s_pointer == &q.s_pointer)}
We do not recommend that the
unsafe-package
be used for doing this.
Free Resources