Compare and copy structs
Compare and copy structs
A struct is comparable when all its field types are comparable. Equality compares corresponding non-blank fields. Assigning a struct copies its field values, but a copied slice, map or pointer field can still refer to shared data. A struct copy is not necessarily a deep copy.
package main
import ( "fmt")
type Point struct{ X, Y int }
func main() { a := Point{X: 1, Y: 2} b := a fmt.Println(a == b) b.X = 9 fmt.Println(a.X, b.X, a == b)}The copied integer fields are independent. Changing b.X leaves a.X unchanged. A struct containing a slice cannot be compared with ==, even if that slice happens to be nil.
Expected output:
true1 9 falseCopy a slice field independently
package main
import ( "fmt")
type Record struct{ Values []int }
func main() { a := Record{Values: []int{1, 2}} b := a b.Values[0] = 7 fmt.Println(a.Values, b.Values) c := a c.Values = append([]int(nil), a.Values...) c.Values[0] = 9 fmt.Println(a.Values, c.Values)}Assignment copies the slice descriptor, not its backing array. Creating a fresh slice and appending the elements gives independent storage for these ints. If elements themselves contain references, another level of copying may be needed. Avoid copying values containing synchronization state once used; that contract is covered later.
Expected output:
[7 2] [7 2][7 2] [9 2]Try it locally
Define Pair with A and B int. Copy Pair{A:2,B:4} into another variable, change its B to 8, and print original.B, copy.B and equality.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 05: Compare and copy structs
Check the lesson objective before moving on.
Is struct{Data []int} comparable with ==?
What does assigning a struct with a slice field copy?