Go, lesson 13
You met maps in lesson 7. This lesson shows the patterns that make them one of the most useful tools in Go: counting, grouping and sets.
Because a missing key reads as the zero value, counting needs no special setup:
To print counts in a predictable order, sort the keys first with
slices.Sorted(maps.Keys(counts)). To rank by count, copy the keys into a slice and sort it
with slices.SortFunc, comparing counts[a] with counts[b].
A map whose values are slices groups items under a key. append on a missing key starts from
a nil slice, which works just like an empty one:
Keys can be any comparable type: numbers, strings, booleans, arrays, and structs made of comparable fields. Slices and maps cannot be keys. If you need a composite key, use a struct like .
2 exercises to try what you just read.
struct{ Row, Col int }Values in a map are not addressable, so m["k"].Field = 1 does not compile when the value
is a struct. Either read the struct, change it, and store it back, or store pointers
(map[string]*Item) so you can change the item through the pointer.
Go has no separate set type. A map whose values you ignore does the job. The idiomatic value
type is the empty struct struct{}, which takes no memory. A map[string]bool is also common
because set[x] then reads naturally as true or false.
With two sets a and b:
a, then add every key of b. maps.Copy(dst, src) does the
adding.a but not b): loop over a and keep keys that b lacks.Since results come back in random order, sort before printing.
== does not work on maps (only comparing to nil does). Use maps.Equal(a, b) to check
that two maps hold the same keys and values.
Read words (separated by whitespace) until input ends. Group words that are anagrams of each
other: they use exactly the same letters, like listen and silent. Two words are anagrams if
sorting their letters gives the same string. Ignore repeated copies of the same word.
Print one group per line, the words in each group sorted alphabetically and separated by spaces. Order the lines alphabetically by their first word.
Sample input:
Sample output:
Two clubs share their member lists. The first input line lists the chess club's members, the second line the drama club's members (names separated by spaces; a line may be empty). Print three lines, each with names sorted alphabetically and separated by single spaces:
If a list is empty, print the label followed by -, for example both: -.
Sample input:
Sample output:
counts := map[string]int{}
for _, w := range strings.Fields("to be or not to be") {
counts[w]++
}
// map[be:2 not:1 or:1 to:2]byLetter := map[byte][]string{}
for _, name := range []string{"ana", "bo", "al", "bea"} {
byLetter[name[0]] = append(byLetter[name[0]], name)
}
// a: [ana al], b: [bo bea]seen := map[string]struct{}{}
seen["go"] = struct{}{}
if _, ok := seen["go"]; ok {
fmt.Println("already seen")
}
delete(seen, "go")
fmt.Println(len(seen)) // 0func intersect(a, b map[string]bool) map[string]bool {
out := map[string]bool{}
for k := range a {
if b[k] {
out[k] = true
}
}
return out
}listen enlist google silent tinsel banana elgoogbanana
elgoog google
enlist listen silent tinselboth: <members of both clubs>
either: <members of at least one club>
chess only: <chess members who are not in drama>ana ben cy dot
cy eve anaboth: ana cy
either: ana ben cy dot eve
chess only: ben dot