go · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Keep a in a map, then the keys to walk it.
Maps are perfect for a tally. counts[pet]++ adds one to that pet's count. A pet that is not there yet starts at the zero value, 0, so its first vote makes it 1 with no extra code.
for key, value := range counts visits every key in a map. There is a catch: Go picks a different order every time the program runs, on purpose, so that nobody relies on it.
For a steady order, sort the keys. Collect every key in a slice, call sort.Strings(keys) from the sort toolbox to put them A to Z, then loop over that slice and look each value up.
package main
import "fmt"
import "sort"
func main() {
votes := []string{"cat", "dog", "cat", "fish", "cat", "dog"}
counts := make(map[string]int)
for _, pet := range votes {
counts[pet]++
}
keys := []string{}
for key := range counts {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
fmt.Println(key, counts[key])
}
} With only one name, for key := range counts hands you the keys and leaves out the values.
guess first
Count the fruit bowl. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
fruit := []string{"apple", "pear", "apple", "plum", "apple"}
counts := make(map[string]int)
for _, f := range fruit {
counts[f]++
}
fmt.Println(counts["apple"], counts["kiwi"], len(counts))
}
your turn
Your turn. Tally the snack orders.
Type four snacks your friends asked for. Repeat at least one of them, so the tally has something to count, then run it to see the orders A to Z.
output
press run to see what happens
fix it
The class register will not sort. Can you fix it?
output
press run to see what happens
- Read the error on line 10. What does Go say about
sort.Strings? - Unlike
append,sort.Stringshands nothing back. It sorts the slice right where it is. - Delete names = from line 10, so it says sort.Strings(names), then run.
nailed it
you can count anything now. :D
counts[key]++keeps a tally that starts from zero.rangevisits every key, but in no fixed order.- Sort the keys with
sort.Stringsfor a steady order.
new words in your collection
- tally
- sort
This lesson isn’t saved. A free account remembers every lesson you finish.