Implementation of the Map exercise in “A Tour of Go”
1 min readAug 8, 2017
When you begin to learn the trending Go lang you may have encounter with the map exercise to implement the WordCount. Here is how I implemented it.
package main
import (
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
var stringArray []string = strings.Fields(s)
wordMap := make(map[string]int)
for _, word := range stringArray {
count, ok := wordMap[word]
if ok {
wordMap[word] = count + 1
} else {
wordMap[word] = 1
}
}
return wordMap
}
func main() {
wc.Test(WordCount)
}