Lesson 2 · Unit 04
Maps and strings
Values found by key, the comma-ok lookup, delete, no fixed order, bytes and runes.
What you practise
make, lookup and the comma-ok form, adding anddelete, looping in no fixed order, strings as bytes and as runes
Try a question from this lesson
Pick one
A slice finds values by position. A map finds them by a key, here the name of a fruit. What does this print?
stock := map[string]int{
"apple": 5,
"pear": 2,
}
fmt.Println(stock["pear"])Correct answer
2
Why
The map pairs each key with a value: "apple" with 5 and "pear" with 2. Putting a key in the square brackets looks up its value. No counting of positions is needed.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Maps
A map stores pairs: a key and its value. The type map[string]int reads "from string keys to int values".
m[key] looks a value up. m[key] = v adds the pair, or replaces the value if the key is already there: a key appears only once. make(map[string]int) creates an empty map, and len(m) counts the pairs.
ages := make(map[string]int)
ages["Ada"] = 36
ages["Bo"] = 20
fmt.Println(ages["Ada"], len(ages))
// 36 2Concept
Is it really there? And delete
A lookup can give a second value: v, ok := m[key]. ok is a bool that says whether the key is in the map. This is the "comma ok" form, and it tells a stored 0 apart from a missing key.
delete(m, key) removes a pair. Deleting a key that is not there does nothing.
stock := map[string]int{"apple": 0}
n, ok := stock["apple"]
fmt.Println(n, ok) // 0 true
delete(stock, "apple")
n, ok = stock["apple"]
fmt.Println(n, ok) // 0 falseConcept
Bytes and runes
A string is stored as bytes, and len and s[i] work on bytes. Plain English letters take one byte each, but é or ñ take two.
Go calls a whole character a rune. range over a string walks it rune by rune, and []rune(s) turns a string into a slice of its runes.
s := "café"
fmt.Println(len(s)) // 5 bytes
fmt.Println(len([]rune(s))) // 4 runes
for _, r := range s {
fmt.Println(string(r)) // c, a, f, é
}9 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.