×

go · level 2 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.