Copy and compare arrays
Copy and compare arrays
Arrays are values. Assignment copies their elements. Changing an integer element of the copy leaves the original unchanged. Arrays of the same type can use == and != if their element type is comparable.
package main
import "fmt"
func main() { a := [3]int{1, 2, 3} b := a fmt.Println(a == b) b[0] = 9 fmt.Println(a, b, a == b)}Equality compares corresponding elements, not variable identity. After b changes, a still starts with 1. Arrays cannot be ordered using < or >.
Expected output:
true[1 2 3] [9 2 3] falseCompare fixed-size identifiers
package main
import "fmt"
func main() { expected := [3]byte{1, 2, 3} received := [3]byte{1, 2, 4} fmt.Println(expected != received) received[2] = 3 fmt.Println(expected == received)}Arrays containing slices are not comparable. Copying an array of pointers or slices copies those values, not the referenced objects or backing storage. Array assignment is not a universal deep copy.
Expected output:
truetrueTry it locally
Copy [2]string{"red","blue"} into b. Print equality, change b[1] to green, then print a, b and inequality.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 04: Copy and compare arrays
Check the lesson objective before moving on.
Does b[0]=9 change a[0] after b:=a for integer arrays?
Which type supports array equality?