How do I copy a struct

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)