Skip to content

Instantly share code, notes, and snippets.

@vly
Last active December 16, 2015 11:29
Show Gist options
  • Save vly/5428038 to your computer and use it in GitHub Desktop.
Save vly/5428038 to your computer and use it in GitHub Desktop.
Golang tour #40
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)
}
@teisman
Copy link

teisman commented Apr 23, 2013

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, the if/else block can be replaced by output[b]++

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