Created
May 31, 2013 12:50
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
Hi mistercorea,
I agree that your way is more elegant. However, this could be dangerous, because you assume the default value is always zero no matter what your OS or env is.