labeling data - Maps - zero values, assigned values
Head First Go、 Jay McGavren(著)、O’Reilly Media)の Chapter 7(labeling data - Maps)、p.217(Exercise)の解答を求めてみる。
コード
main.go
package main
import "fmt"
func main() {
data := []string{"a", "c", "e", "a", "e"}
counts := make(map[string]int)
for _, item := range data {
counts[item]++
}
letters := []string{"a", "b", "c", "d", "e"}
// a: 2
// b: not found
// c: 1
// d: not found
// e: 2
for _, letter := range letters {
count, ok := counts[letter]
if !ok {
fmt.Printf("%s: not found\n", letter)
} else {
fmt.Printf("%s: %d\n", letter, count)
}
}
}
入出力結果(Terminal, Zsh)
% go run ./main.go
a: 2
b: not found
c: 1
d: not found
e: 2
%