Slices, maps and strings
Use slices and maps for growing data, and understand strings as bytes over runes.
- Prefer slices over arrays for most sequences.
- Use append instead of trying to grow a slice by hand.
- Check the ok boolean when reading a map so a missing key is not confused with a zero value.
- Range over a string to visit runes rather than raw bytes.
In plain English
An array has a fixed length that is part of its type, while a slice is a flexible view over a sequence and is what you use most of the time. The built-in append adds elements to a slice, returning a new slice when it needs more room. A map stores key to value pairs, and looking up a key with two values gives you the value plus an ok boolean that is true only when the key exists. A string is a sequence of bytes, and ranging over it walks the string rune by rune, where a rune is a single character code point.
Step by step
- 1Pick a slice for a sequence whose length can change.
- 2Add an element with append and store the result back.
- 3Look up a map key and read the ok boolean.
- 4Range over a string to visit each rune.
package main
import "fmt"
func main() {
var fixed [3]string
fixed[0] = "HTML"
fixed[1] = "CSS"
fixed[2] = "Go"
fmt.Println(fixed)
titles := []string{"HTML", "CSS"}
titles = append(titles, "Go", "Rust")
fmt.Println(titles)
minutes := map[string]int{
"HTML": 8,
"CSS": 12,
}
fmt.Println(minutes)
value, ok := minutes["Go"]
fmt.Println(value, ok)
name := "Go"
fmt.Println(len(name))
for _, r := range name {
fmt.Println(string(r))
}
}Common mistakes
- Confusing an array with a slice can bite you, because an array length is fixed into its type.
- Ignoring the ok boolean from a map lookup makes a missing key look the same as a stored zero value.
- Reading a string by byte index on text outside ASCII can split a rune in half.
- Calling append without assigning the result back loses the new elements, since append may return a new slice.
Look up a key safely
Write a function lookup(scores map[string]int, name string) (int, bool) that returns the score for name and whether it exists.
func lookup(scores map[string]int, name string) (int, bool) {
return 0, false
}In value, ok := minutes[key], what does ok tell you?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.