Arrays and Slices
Go's fixed-size arrays, and the far more commonly used, resizable slice.
What you'll learn
- Distinguish a fixed-size array from a slice
- Grow a slice with `append` and understand it returns a (possibly new) slice
- Use `len()` to get a slice's current length
Explanation
A Go array has a fixed size baked into its type: [3]int is a completely different type from [5]int. Arrays exist, but in everyday Go code you'll almost always use a slice instead -- a resizable, flexible view over an underlying array, declared as []int (no size in the brackets).
You grow a slice with the built-in append function: nums = append(nums, 4). Note that append returns a slice, which you must assign back -- append may need to allocate a new, larger underlying array if the current one is full, so the original slice variable might not reflect the change unless you capture the return value.
len(slice) gives you the current number of elements. An empty (nil) slice or an empty slice literal both have len 0, and appending to a nil slice works fine -- you don't need to explicitly initialize it first.
Guided lab
Predict: Growing a slice
Read this program and predict exactly what it prints.
package main
import "fmt"
func main() {
var names []string
names = append(names, "Ada")
names = append(names, "Grace", "Linus")
fmt.Println("names:", names)
fmt.Println("count:", len(names))
}Stuck? Get a hint.
Common mistakes
- Calling `append(nums, x)` without assigning the result back to `nums`, then being surprised the original variable is unchanged.
- Confusing a fixed-size array (`[3]int`) with a slice (`[]int`) -- they're different types with different capabilities.
- Assuming you must initialize a slice with `make` before appending -- appending to a `nil` slice works fine.
Knowledge check
Takeaway
Prefer slices over arrays in everyday Go code, and always assign `append`'s return value back to your variable.
Summary
Arrays have a fixed, type-level size; slices are resizable views grown with `append` (whose result must be reassigned) and measured with `len`.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.