Last active
December 16, 2015 11:29
-
-
Save vly/5428038 to your computer and use it in GitHub Desktop.
Golang tour #40
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 ( | |
"code.google.com/p/go-tour/wc" | |
"strings" | |
) | |
func WordCount(s string) map[string]int { | |
output := make(map[string]int) | |
for _,b := range strings.Fields(s) { | |
if _,ok := output[b]; ok { | |
output[b]++ | |
} else { | |
output[b] = 1 | |
} | |
} | |
return output | |
} | |
func main() { | |
wc.Test(WordCount) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, I just came across this post, and I hope you don't mind me pointing something out. You don't need an
if
statement. The reason is that when a key is not present in a map, the zero value will be returned. Consequently, theif/else
block can be replaced byoutput[b]++