Arrays & Slices
Go has arrays, but they're rarely used directly — their fixed length is actually part of their type, which makes them awkward to work with. Almost all real Go code reaches for a slice instead: a flexible, resizable view over an underlying array.
Arrays: fixed size, part of the type
package main import "fmt" func main() { var scores [3]int scores[0] = 88 scores[1] = 92 scores[2] = 79 fmt.Println(scores) fmt.Println("Length:", len(scores)) }
[88 92 79] Length: 3
[3]int is an array of exactly 3 ints — [3]int and [4]int are considered different, incompatible types, which is why arrays alone are too rigid for most everyday use.
Slices: a resizable view
A slice literal looks almost identical to an array literal, minus the size — and unlike an array, a slice can grow with append:
package main import "fmt" func main() { fruits := []string{"apple", "banana"} fruits = append(fruits, "cherry") fmt.Println(fruits) fmt.Println("Length:", len(fruits)) }
[apple banana cherry] Length: 3
append returns a (possibly new) slice with the extra element added — which is exactly why you have to write fruits = append(fruits, ...) and reassign it, rather than expecting append to change fruits in place.
make, len, and cap
package main import "fmt" func main() { numbers := make([]int, 0, 4) fmt.Println(len(numbers), cap(numbers)) numbers = append(numbers, 1, 2, 3, 4, 5) fmt.Println(len(numbers), cap(numbers)) }
0 4 5 8
make([]int, 0, 4) creates an empty slice with room for 4 elements before it needs to reallocate. len is how many elements are actually in the slice; cap is how much room the underlying array has before Go has to allocate a bigger one — which is exactly what happened when appending a 5th element pushed capacity past 4.
b := a[1:3]) doesn't copy the data — b is a view into a's array, so writing to an element through b can change what a sees too. But append only writes through that shared array while there's spare capacity; once capacity runs out, append allocates a fresh array behind the scenes, and from that point on the two slices are no longer connected. This is one of the most common sources of confusing bugs for people new to Go.