A Tour of Go chapter 43
Exercise: Maps
Implement WordCount. It should return a map of the counts of each “word” in the string s. The wc.Test function runs a test suite against the provided function and prints success or failure.
You might find strings.Fields helpful.
Example
package main import ( "code.google.com/p/go-tour/wc" "strings" ) func WordCount(s string) map[string]int { words := make(map[string]int) for _, word := range strings.Fields(s) { words[word] += 1 } return words } func main() { wc.Test(WordCount) }
付言
strings.Fields(s string) []string
は、文字列を与えると、その文字列の空白文字で区切ったスライスを、或いは空のスライスを返す。JavaScriptで言えば
" SOME STRINGS ".trim().split(/ +/)
と同じ。スライス (slice) とは配列の様なものである。#golang §44 Exercise: Slicesではスライスがテーマである。
words[word] = 0
の如き初期化は不要である。