Problem overview
The function countVote receives votes, a map[string]int from names to how many votes each person has, and the name on a new vote. It counts the vote, so that person has one more, and returns votes.
A name with no votes yet isn't in the map. Such a person starts from 0, so after the first vote the count is 1. With {"Ana": 3, "Ben": 5} and "Ana" the result is Ana: 4 and Ben: 5. With "Cara" instead, the result also has Cara: 1. With an empty map and "Max" it is just Max: 1.
Approach
This is the counting pattern, and Go makes it short. Reading a missing key gives the zero value of the value type, which for an int is 0. That is exactly the right starting count for a new name, so no check for the key is needed. Read the current count, add 1 and store it back. For a new name, the store creates the key. For an existing name, it replaces the old count.
It helps to see the two cases side by side. For "Ana", who has 3 votes, count is 3 and the store writes 4 over the old value. For "Cara", who is not a key, count is 0 and the store writes 1 under a new key. The same two lines handle both, which is the point of relying on the zero value.
Step by step
- Read the current count with a plain lookup:
count := votes[name]. - Store
count + 1under the keyname. - Return
votes.
The solution in Go
func countVote(votes map[string]int, name string) map[string]int {
count := votes[name]
votes[name] = count + 1
return votes
}
The comma-ok form isn't needed, because a missing name and a name with 0 votes should be treated the same way here. The function updates the caller's map in place, since a map argument is shared and not copied.
The same thing can be written in one line, votes[name]++. It reads the count (0 for a new key), adds 1 and stores it. The longer version in the lesson shows the three moves separately.
Testing
Printing the result for the statement's examples gives:
map[Ana:4 Ben:5]
map[Ana:3 Ben:5 Cara:1]
map[Max:1]
Calling the one-line form twice on an empty map for "Max" leaves map[Max:2].
Edge cases and common mistakes
- Storing 1 instead of
count + 1. That resets Ana's 3 votes to 1: the result for her would bemap[Ana:1]. - Adding a check for the key and forgetting the missing case. If the code only updates names that are already keys, a new name is never added, and Cara's vote is lost.
- An empty map. It works with no special case: the lookup gives 0 and the store adds the first key. A
nilmap would panic on the store, but the tests pass real maps. - Forgetting to return. The caller's map has the change, but the function must still return it to match its signature.
