Course › Week 1 · Basics and a first CLI › Day 4 · lesson 4 of 42 · 20 min reading + 60–75 min practice
Slices and maps
The list and the lookup table you will use every day, range over both, and the nil traps.
On this page
A PHP array is a list and a dictionary at the same time. Go splits that into two types: a slice is an ordered list of values of one type, and a map is a lookup table from keys of one type to values of one type.
Today: making and growing slices, looping over them, maps, telling “missing” from “zero”, and the two mistakes that crash a Go program at runtime.
Slices
1. A slice of strings
[]string is “a slice of strings”. Write the values in braces after it. Read an element by its index, from 0, and get the length with len.
package main
import "fmt"
func main() {
guests := []string{"Astrid", "Bjorn", "Clara"}
fmt.Println(guests)
fmt.Println(guests[0], "is first of", len(guests))
fmt.Println(guests[1:3])
}
[Astrid Bjorn Clara]
Astrid is first of 3
[Bjorn Clara]Every element has the same type: a []string cannot hold a number. guests[1:3] is a smaller slice of elements 1 and 2 (the end index is not included), like array_slice($guests, 1, 2).
len is a built-in function: no package in front. It works on strings, slices and maps.
2. An index past the end panics
PHP returns null and a warning for a missing index. Go stops the program:
package main
import "fmt"
func main() {
guests := []string{"Astrid", "Bjorn", "Clara"}
fmt.Println(guests[3])
}
panic: runtime error: index out of range [3] with length 3
goroutine 1 [running]:
main.main()
/tmp/go-playbook/hello/main.go:8 +0x9
exit status 2A panic is a crash: Go prints what went wrong, then where (the goroutine trace: function, file and line, here main.go:8), and exits with code 2. go run reports that as exit status 2. The path is where the program was built.
It compiled because the compiler does not track how long a slice is. Check len before you index anything that came from outside your program.
3. append adds to the end
append takes a slice and new values, and returns the longer slice. Assign the result back.
package main
import "fmt"
func main() {
var bookingIDs []int
fmt.Println(bookingIDs, len(bookingIDs), bookingIDs == nil)
bookingIDs = append(bookingIDs, 1042)
bookingIDs = append(bookingIDs, 1043, 1051)
fmt.Println(bookingIDs, len(bookingIDs))
}
[] 0 true
[1042 1043 1051] 3A slice declared with var and no value is nil: the zero value of a slice. A nil slice has length 0, prints as [], and append works on it. You do not have to create an empty slice before you add to it.
bookingIDs = append(bookingIDs, …) is always the pattern. When the slice is full, append copies it into a bigger block of memory and returns the new one, so the old variable would be out of date. Forgetting the assignment is a compile error: append(bookingIDs, 1042) alone is a value nobody uses.
4. range over a slice
for index, value := range slice visits every element in order.
package main
import "fmt"
func main() {
nights := []int{3, 7, 2, 5}
for i, n := range nights {
fmt.Printf("booking %d: %d nights\n", i, n)
}
total := 0
for _, n := range nights {
total += n
}
fmt.Println("total nights:", total)
}
booking 0: 3 nights
booking 1: 7 nights
booking 2: 2 nights
booking 3: 5 nights
total nights: 17It is PHP’s foreach ($nights as $i => $n). When you do not need the index, write _ in its place: an unused i would be a compile error.
range gives you a copy of each element. Changing n inside the loop does not change the slice. To change elements, use the index: nights[i] = …. The structs lesson shows where that matters.
5. make, when you know the size
make([]T, length, capacity) creates a slice up front. With length 0 and a capacity, append fills it without copying the memory again.
package main
import "fmt"
func main() {
rows := []string{"a@example.com", "b@example.com", "c@example.com"}
emails := make([]string, 0, len(rows))
for _, row := range rows {
emails = append(emails, "<"+row+">")
}
fmt.Println(emails, len(emails), cap(emails))
}
[<a@example.com> <b@example.com> <c@example.com>] 3 3cap is how many elements fit before append must grow the slice. You never need make for correctness; it saves work when the final size is known, like turning 100K rows into 100K results. + joins strings, PHP’s ..
Maps
6. A map from strings to ints
map[string]int maps string keys to int values. Read and write with brackets.
package main
import "fmt"
func main() {
nightlyCents := map[string]int{
"nyhavn": 12950,
"vesterbro": 9900,
}
nightlyCents["christianshavn"] = 14500
fmt.Println(nightlyCents["nyhavn"], len(nightlyCents))
delete(nightlyCents, "vesterbro")
fmt.Println(nightlyCents)
}
12950 3
map[christianshavn:14500 nyhavn:12950]fmt prints a map with its keys sorted, to keep output readable; that is a feature of printing, not of the map. A trailing comma after the last entry is required when the closing brace is on its own line. delete removes a key, like unset($prices['vesterbro']); deleting a key that is not there does nothing.
7. A missing key gives the zero value
Reading a key that is not in the map is not an error: you get the value type’s zero value. To know whether the key was there, take a second result, by convention called ok.
package main
import "fmt"
func main() {
nightlyCents := map[string]int{"nyhavn": 12950}
fmt.Println(nightlyCents["nowhere"])
price, ok := nightlyCents["nowhere"]
fmt.Println(price, ok)
if price, ok := nightlyCents["nyhavn"]; ok {
fmt.Println("nyhavn costs", price)
}
}
0
0 false
nyhavn costs 12950This is the comma ok form. 0 alone cannot tell you whether the flat is free or unknown; ok can. It is PHP’s array_key_exists, built into the lookup.
The zero value is also what makes counting easy: counts[level]++ works for a key that was never set, because it starts from 0.
8. Counting, and the order of a map
A map has no order. range over a map visits the keys in a different order each run, on purpose, so that no program relies on it. To print in order, collect the keys and sort them.
package main
import (
"fmt"
"slices"
)
func main() {
levels := []string{"ERROR", "INFO", "INFO", "WARNING", "INFO", "ERROR"}
counts := map[string]int{}
for _, level := range levels {
counts[level]++
}
names := make([]string, 0, len(counts))
for name := range counts {
names = append(names, name)
}
slices.Sort(names)
for _, name := range names {
fmt.Printf("%-8s %d\n", name, counts[name])
}
}
ERROR 2
INFO 3
WARNING 1map[string]int{} is an empty map, ready to use. for name := range counts takes only the keys. slices.Sort sorts a slice in place; the slices package has much more, covered in Week 3. %-8s pads the text to 8 characters, aligned left.
PHP arrays keep insertion order. Go maps never do, and output that looks stable today changes tomorrow. Whenever output must be the same every time (a report, a test, a JSON file), sort first.
9. Writing to a nil map panics
A map declared with var and no value is nil. Reading from it works and gives zero values; writing to it crashes. staticcheck sees it before the program runs:
package main
import "fmt"
func main() {
var counts map[string]int
counts["ERROR"]++
fmt.Println(counts)
}
main.go:8:2: assignment to nil map (SA5000)panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
/tmp/go-playbook/hello/main.go:8 +0x28
exit status 2It compiles, then panics on line 8. A nil slice is fine to append to, but a nil map has nowhere to put the key. Create maps with a literal (map[string]int{}) or with make(map[string]int), never with a bare var.
This is why the lessons run staticcheck: it turns this crash into a warning with a code, SA5000, before the program ever runs.
Coming from PHP
<?php
$guests = ['Astrid', 'Bjorn', 'Clara']; // a list
$guests[] = 'Dagny'; // append
$prices = ['nyhavn' => 12950]; // a dictionary: the same type
echo $prices['nowhere'] ?? 0; // a missing key: null, so ?? 0
$counts = [];
foreach ($levels as $level) {
$counts[$level] = ($counts[$level] ?? 0) + 1;
}
ksort($counts);
PHP has one array type that can be a list, a dictionary, or both at once, with mixed value types. Go makes you choose: a slice when order and position matter, a map when you look things up by key, and one value type for each.
The honest difference: PHP arrays are copied when you assign them (copy-on-write), and Go slices and maps are not. Pass a slice or a map to a function, and the function sees and changes the same elements. Week 2 explains why, with pointers.
PracticeA Tour of Go: arrays to maps, the two exercises, one small program
In A Tour of Go, do the pages from Arrays to Exercise: Maps. Arrays ([3]int, with a fixed length in the type) exist but you will almost never write one; slices are what Go code uses. Exercise: Slices draws a picture and is optional.
Exercise: guests per property
You have two slices of the same length: properties := []string{"nyhavn", "vesterbro", "nyhavn", "amager", "nyhavn"} and guests := []int{2, 4, 3, 1, 2}, one entry per booking. Build a map with the total guests per property, and print it sorted by property name. Then look up "osterbro" and print osterbro: no bookings because ok is false, not because the total is 0.
Show the solution
package main
import (
"fmt"
"slices"
)
func main() {
properties := []string{"nyhavn", "vesterbro", "nyhavn", "amager", "nyhavn"}
guests := []int{2, 4, 3, 1, 2}
totals := map[string]int{}
for i, property := range properties {
totals[property] += guests[i]
}
names := make([]string, 0, len(totals))
for name := range totals {
names = append(names, name)
}
slices.Sort(names)
for _, name := range names {
fmt.Printf("%s: %d\n", name, totals[name])
}
if _, ok := totals["osterbro"]; !ok {
fmt.Println("osterbro: no bookings")
}
}
amager: 1
nyhavn: 7
vesterbro: 4
osterbro: no bookingsguests[i] is safe here only because both slices have the same length. With data from a file, check len(properties) == len(guests) first and return an error if not.
Remember
- Always assign
append’s result back:ids = append(ids, id). - Use the comma-ok form when “missing” and “zero” mean different things.
- Create maps with a literal or
make, never a barevar, and sort keys before printing them.
Tomorrow: your own types with struct, named types with constants, and switch.