Skip to content

Instantly share code, notes, and snippets.

@aizatto
Created May 31, 2013 12:50
Show Gist options
  • Save aizatto/5684758 to your computer and use it in GitHub Desktop.
Save aizatto/5684758 to your computer and use it in GitHub Desktop.
http://tour.golang.org/#40 A Tour of Go 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.
package main
import (
"strings"
"code.google.com/p/go-tour/wc"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
for _, v := range strings.Fields(s) {
if _, ok := m[v]; ok == true {
m[v] += 1
} else {
m[v] = 1
}
}
return m
}
func main() {
wc.Test(WordCount)
}
@mridulgain
Copy link

mridulgain commented Jun 30, 2020

I'd like to point out that,
The line wc := make(map[string]int) defines that the elements of the map will be of int type(and keys will be of string type). So no matter what your OS or env is, the elements are going to be initialized to the zero value of int data type which is nothing but '0'. So, @mistercorea made a valid point here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment