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)
}
@mistercorea
Copy link

package main

import (
    "golang.org/x/tour/wc"
    "strings"
)

func WordCount(s string) map[string]int {
    wc := make(map[string]int)
    for _ ,w:= range strings.Fields(s){
        wc[w]++
    }
    return wc
}

func main() {
    wc.Test(WordCount)
}

why did you initialize the m if it was first time using it?
doesn't go handles to set it to 0 if value was not set in first place?

@j611062000
Copy link

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.

@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