My solution for the map exercise on A Tour of Go.

Ankit Wadhwana
1 min readJul 21, 2020

--

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.

package mainpackage mainimport (
"strings"
"golang.org/x/tour/wc"
)
func WordCount(s string) map[string]int {
//using make to initialise an empty map
stringSlice := make(map[string]int)

//words is a slice of substrings of s
words := strings.Fields(s)

for _, v := range words {
//If key is not in the map,
//then elem is the zero value for the map's element type.
//zero value of int is 0
//incrementing it by 1 for the number of times the key is found
stringSlice[v]++

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

Output:

output

Simple and straight forward let me know if there is a better solution (:

--

--