Arrays are values
An array has a fixed length that is part of its type: [3]int and [4]int are different types and cannot be assigned to each other. A new array is filled with zero values. Writing [...]int{2, 3, 5} lets the compiler count the elements for you.
The big surprise for people coming from other languages: an array is a value, not a reference. Assigning it to another variable or passing it to a function copies every element. Arrays of comparable elements can also be compared with ==.
package main
import "fmt"
func setFirst(a [3]int) {
a[0] = 100 // changes the function's copy only
}
func main() {
var scores [3]int // [0 0 0]
scores[1] = 7
fmt.Println(scores, len(scores))
primes := [...]int{2, 3, 5, 7} // the compiler counts: [4]int
fmt.Printf("%v %T\n", primes, primes)
backup := scores // copies all 3 ints
backup[0] = 1
fmt.Println(scores, backup)
setFirst(scores)
fmt.Println(scores) // unchanged
fmt.Println(scores == [3]int{0, 7, 0})
}[0 7 0] 3
[2 3 5 7] [4]int
[0 7 0] [1 7 0]
[0 7 0]
trueChange setFirst to take a pointer, func setFirst(a *[3]int), and call it with setFirst(&scores). What prints now?
[32]byte, an RGB colour a [3]uint8, and an array makes a handy map key because it is comparable. Everywhere else, use a slice.invalid argument: index 5 out of bounds [0:3]
package main
import "fmt"
func main() {
var scores [3]int
scores[5] = 10
fmt.Println(scores)
}# command-line-arguments
./main.go:7:9: invalid argument: index 5 out of bounds [0:3]The length of an array is known at compile time, so a constant index outside 0 to len-1 is caught before the program ever runs. The [0:3] is the valid range, with 3 excluded.
Use an index inside the array, or use a slice and append if the collection needs to grow.
package main
import "fmt"
func main() {
var scores [3]int
scores[2] = 10
fmt.Println(scores)
}