Bimo's Meatball Stall has 3 tables bolted to the floor. A fourth table means rebuilding the stall. The order book is a different story: it can keep being written in, and when a page is full, Bimo moves to a thicker book and copies all the old notes over.
In Go, the tables are an array and the order book is a slice. Both hold many values of the same type in order, and you reach an item through its index, which starts at 0. The difference: an array has a fixed number of slots, a slice can grow.
Arrays: a fixed number of slots
tables := [3]string{"Sari", "Andi", "Dina"}
fmt.Println(tables) // [Sari Andi Dina]
fmt.Println(tables[0]) // Sari
fmt.Println(len(tables)) // 3
backup := tables
backup[0] = "Rudi"
fmt.Println(tables, backup) // [Sari Andi Dina] [Rudi Andi Dina]
[3]stringmeans 3 slots, each holding a string. The 3 is part of the type:[3]stringand[4]stringare different types, and the size can't change.tables[0]is the first slot,tables[2]the last.len(tables)is the number of slots, 3.- An array that hasn't been filled holds zero values:
var portions [3]intis[0 0 0]. - An array is a value:
backup := tablescopies all three items into a new array. Changingbackupdoesn't touchtables.
Slices: a list that can grow
orders := []string{"Tendon Meatballs", "Chicken Noodles", "Iced Tea"}
fmt.Println(len(orders), cap(orders)) // 3 3
orders = append(orders, "Crackers")
fmt.Println(orders) // [Tendon Meatballs Chicken Noodles Iced Tea Crackers]
fmt.Println(len(orders), cap(orders)) // 4 6
[]stringwith no number in the square brackets: that's a slice. In practice, slices are used far more often than arrays.append(slice, item)adds the item at the end and returns the resulting slice, so store it back:orders = append(...). Several items at once work too:numbers = append(numbers, 40, 50).lenis how many items it holds now.cap(capacity) is how many slots the array that stores them has.
Behind every slice there is an array. While there are empty slots, append fills one straight away. Once it's full, Go makes a new, bigger array, copies the old items there, and only then adds the new one:
| After | len |
cap |
What happens |
|---|---|---|---|
| start | 3 | 3 | an array of 3 slots, full |
append "Crackers" |
4 | 6 | full, so it moves to a new array of 6 slots |
append "Iced Orange" |
5 | 6 | there's an empty slot, filled straight away |
append "Hot Tea" |
6 | 6 | the last slot is filled |
append "Water" |
7 | 12 | full again, moves to an array of 12 slots |
For small slices the capacity roughly doubles. The exact numbers are up to Go's runtime, so don't rely on them. If you already know roughly how many you need, set it up front: make([]int, 0, 10) makes an empty slice (len 0) with cap 10.
Slicing: take a piece with [start:end]
numbers := []int{10, 20, 30, 40, 50}
fmt.Println(numbers[1:4]) // [20 30 40]
fmt.Println(numbers[:3]) // [10 20 30]
fmt.Println(numbers[3:]) // [40 50]
numbers[1:4]takes indexes 1, 2 and 3. The start index is included, the end index is not, so its length is 4 - 1 = 3.- Leaving out the start means from index 0. Leaving out the end means to the end.
A slice shares the array behind it
With the array above, backup := tables made a separate copy. Now guess for a slice: if copied := orders and then copied[0] = "Egg Meatballs", does orders still have Tendon Meatballs at the front, or does it change too?
A slice doesn't hold its items itself. It's only a window onto an array: a pointer to that array, plus len and cap. copied := orders copies the window, not the items, so both see the same array:
orders := []string{"Tendon Meatballs", "Chicken Noodles", "Iced Tea"}
copied := orders
copied[0] = "Egg Meatballs"
fmt.Println(orders) // [Egg Meatballs Chicken Noodles Iced Tea]
orders changes too, the opposite of the array above. Slicing works the same way: with a := []int{1, 2, 3, 4, 5} and b := a[1:3], the slot b[0] is the very same slot as a[1], so b[0] = 99 makes fmt.Println(a) print [1 99 3 4 5].
Once append moves to a new array, the two part ways: the slice that was appended to points to the new array, the other one still to the old array. A change through one no longer shows in the other.
An index out of range: panic
The only valid indexes are 0 to len - 1. Go past that and the program stops with a panic:
orders := []string{"Tendon Meatballs", "Chicken Noodles", "Iced Tea"}
i := 5
fmt.Println(orders[i])
panic: runtime error: index out of range [5] with length 3
goroutine 1 [running]:
main.main()
/app/main.go:8 +0x1d
exit status 2
- The first line is the one that matters: index 5 was asked for, and the length is only 3. Index 3 already panics.
- The lines after it point to the file and line where the panic happened. The code after it never runs.
- When the index is a plain number and the length is already known, Go catches it at compile time.
tables[5]on a[3]stringarray fails withinvalid argument: index 5 out of bounds [0:3].
💡 append can overwrite another slice's items
When a piece still has spare slots in the same array, append writes into such a slot, and any other slice using that slot changes too:
a := []int{1, 2, 3, 4, 5}
c := a[:2] // [1 2], but its cap is 5
c = append(c, 77) // written into the slot a[2]
fmt.Println(a) // [1 2 77 4 5]
Need a copy that is truly separate? Copy the items into a new slice: b := append([]int{}, a[1:3]...), or b := make([]int, 2) and then copy(b, a[1:3]).
⚠️ Slices that change along and indexes that go too far
appendwithout storing it.append(numbers, 40)on its own fails to compile withappend(numbers, 40) (value of type []int) is not used. Writenumbers = append(numbers, 40).- Thinking a slice is copied like an array.
copied := ordersshares the items. Arrays get copied, slices don't. - The end of a slice expression.
numbers[1:3]is only 2 items. For index 1 to 3, writenumbers[1:4]. - The last index. A slice of 3 items has indexes 0, 1, 2.
orders[3]panics.
TL;DR: An array [3]string has a fixed number of slots and is copied whole when assigned. A slice []string can grow with x = append(x, item) (the result must be stored), has a len (items held) and a cap (slots in the array behind it), and moves to a new, bigger array when it's full. x[start:end] takes a piece without the end index. A slice that is assigned or sliced shares the same array, so a change through one shows in the other. An index outside 0 to len - 1 panics: index out of range [5] with length 3.
⚡ Arrays: fixed slots
Write:
tables := [3]string{"Sari", "Andi", "Dina"}
fmt.Println(tables[0]) // Sari
Meaning: [3]string is 3 slots holding strings, and the 3 is part of the type, so the size can't change. The index starts at 0.
⚡ Slices: they can grow
Write:
orders := []string{"Tendon Meatballs", "Chicken Noodles", "Iced Tea"}
orders = append(orders, "Crackers")
Meaning: No number in the square brackets means a slice. append returns the resulting slice, so store it back in the variable.
⚡ A piece without the end index
Write:
numbers := []int{10, 20, 30, 40, 50}
fmt.Println(numbers[1:4]) // [20 30 40]
Meaning: The start index is included, the end index is not.
⚡ Slices share their items
Guess first: copied := orders, then copied[0] = "Egg Meatballs". Does orders change too?
It does. A slice is only a window onto the array behind it, so both see the same array. An array is different: backup := tables copies all its items.
Meaning: An index outside 0 to len - 1 panics: index out of range [5] with length 3.