So, I like to over-engineer things. I’ve been working through Go’s Tutorial, and I’d been stuck on the Maps exercise. It asks you to count up the number of times a word appears in a string, constructing a map to store the numbers each individual word shows up. I had thought, “Ok, they mentioned you could check if an element was already in the slice in the previous example. Great!”

func WordCount(s string) map[string]int {
m := make(map[string]int)
words := strings.Fields(s)
for _, v := range words {
v, ok := m[v]
if(ok){
m[v] += 1
} else {
m[v] = 1
}
}
return m
}

I knew that I had to split the string into a slice of substrings. Then, I knew I had to iterate over it by using range. Then, I fell into a deep hole of trying to check whether my Map had v in it already. I kept getting errors that I cannot use v (type int) as type string in map index. Naturally, I was confused by this. Isn’t v a string? No, as it turns out, it wasn’t. When I threw Println into both arms of the if clause, I found out that v was evaluating down to 0, while if I printed it outside the if, it evaluated to the proper word within my words slice.

In confusion, I deleted my if clause, and I tried to start from scratch. Since my map is already [string]int, maybe if I just adding one onto the key’s value, it’d be fine! Lo and behold, that was the intended answer.

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

Like I said, I’m big on over-engineering.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store