Understand the contract
An array in Go holds a fixed number of elements of one type. Its length is part of its type, so [3]int and [4]int are different types. Arrays make value semantics visible: assigning an array copies its elements, and changing the copy does not change the original.
This block of the series follows the choices you make when representing data. Use an array for a fixed-size value, a slice for a sequence with a variable length and a map for key-based lookup. Structs combine named fields; pointers allow explicit access to an existing value.
Work through the example
The example changes only copyOfScores and prints [10 20 30] followed by [99 20 30]. An array index begins at zero. Reading or writing outside its bounds is invalid; when the compiler cannot reject it statically, the operation panics at runtime.
package main
import "fmt"
func main() {
scores := [3]int{10, 20, 30}
copyOfScores := scores
copyOfScores[0] = 99
fmt.Println(scores, copyOfScores)
}Watch this boundary
An array whose elements contain pointers or slices copies those element values, not every object reachable through them. The independent integer arrays here are a deliberately simple case. Continue to the slice and pointer lessons before assuming that every collection assignment creates fully independent underlying data.
Practice with a changed input
Change the array length to four, leave one element uninitialized and observe its zero value. Then try assigning it to a [3]int variable and read the type error.
Lesson 12 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services