4. Count Instances

Remember that you can check if a key is already present in a map by using the second return value from the index operation.

You can combine an if statement with an assignment operation to use the variables inside the if block:

example.go
names := map[string]int{}
missingNames := []string{}

if _, ok := names["Denna"]; !ok {
    // if the key doesn't exist yet,
    // append the name to the missingNames slice
    missingNames = append(missingNames, "Denna")
}

Assignment

Each time a user is sent a message, their username is logged in a slice. We want a more efficient way to count how many messages each user received.

Implement the updateCounts function. It takes as input:

  • messagedUsers: a slice of strings.

  • validUsers: a map of string -> int.

It should update the validUsers map with the number of times each user has received a message. Each string in the slice is a username, but they may not be valid. Only update the message count of valid users.

So, if "benji" is in the map and appears in the slice 3 times, the key "benji" in the map should have the value 3.

Loop Through All Messaged Users

  • Iterate through each username in the slice

  • _ ignores the index (don't need it)

  • name is the current username

Check If User Is Valid

  • validUsers[name] looks up the username in the map

  • _ ignores the current count (don't need it yet)

  • ok is true if the user exists in the map, false if not

  • if ok means "if the user is valid"

Increment Their Count

  • Only runs if the user exists in the map

  • Gets the current count and adds 1

  • Directly modifies the original map (no return needed)

How It Works - Example

What Happens Step-by-Step

1

Start

validUsers = {"alice": 0, "bob": 0}

2

Check "alice"

Exists β†’ increment β†’ {"alice": 1, "bob": 0}

3

Check "invalid"

Doesn't exist β†’ skip β†’ {"alice": 1, "bob": 0}

4

Check "alice" again

Exists β†’ increment β†’ {"alice": 2, "bob": 0}

5

Check "bob"

Exists β†’ increment β†’ {"alice": 2, "bob": 1}

6

Check "alice" again

Exists β†’ increment β†’ {"alice": 3, "bob": 1}

End: validUsers = {"alice": 3, "bob": 1}

Key Points About Your Solution

Map Check Pattern

This is the standard Go pattern for checking if a key exists.

Increment Operator

Same as:

No Return Needed

Maps are passed by reference, so modifications inside the function affect the original map.

Invalid Users Are Ignored

If a name isn't in validUsers, the if condition is false and nothing happens.