Arrays
Declaring a Fixed-Size Array
An array type includes its length, like [5]int for an array of exactly five integers. Once declared, its size can never change -- this is fundamentally different from arrays/lists in dynamically sized languages.
Example: Declaring a Fixed-Size Array
package main
import "fmt"
func main() {
var scores [5]int
scores[0] = 90
scores[1] = 85
fmt.Println(scores)
}
Login to try C/C++/Java/PHP code in the editor
Array Literals
An array can be declared and filled in one step using a literal, and the [...] syntax tells Go to count the elements automatically instead of you specifying the length by hand.
Note: Use [...]Type{...} to let Go count the elements for you.
Example: Array Literals
package main
import "fmt"
func main() {
primes := [...]int{2, 3, 5, 7, 11}
fmt.Println(primes, "length:", len(primes))
}
Login to try C/C++/Java/PHP code in the editor
Arrays Are Copied by Value
Unlike slices, assigning a Go array to a new variable (or passing it to a function) copies every element into a brand-new array -- modifying the copy never affects the original.
Example: Arrays Are Copied by Value
package main
import "fmt"
func main() {
original := [3]int{1, 2, 3}
copy := original
copy[0] = 99
fmt.Println("original:", original)
fmt.Println("copy:", copy)
}
Login to try C/C++/Java/PHP code in the editor
- Assuming an array can grow or shrink after creation -- Go arrays have a fixed length baked into their type.
- Forgetting that assigning an array to another variable copies the entire array, not a reference to the same data.
- Confusing arrays with slices and using [5]int and []int interchangeably -- they are different, incompatible types.
- A Go array has a fixed length that is part of its type, e.g. [5]int.
- Arrays are value types -- assigning or passing one copies all its elements.
- Array length can be inferred with [...]Type{...} literal syntax.
- In practice, slices (built on top of arrays) are used far more often than raw arrays.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: