2. Mutations

Insert an Element

m[key] = elem

Get an Element

elem = m[key]

Delete an Element

delete(m, key)

Check If a Key Exists

elem, ok := m[key]
  • If key is in m, then ok is true and elem is the value as expected.

  • If key is not in the map, then ok is false and elem is the zero value for the map's element type.

Assignment

It's important to keep up with privacy regulations and to respect our user's data. We need a function that will delete user records.

Complete the deleteIfNecessary function. The user struct has a scheduledForDeletion field that determines if they are scheduled for deletion or not.

1

Check existence

If the user doesn't exist in the map, return the error not found.

2

Not scheduled for deletion

If they exist but aren't scheduled for deletion, return deleted as false with no errors.

3

Delete when scheduled

If they exist and are scheduled for deletion, return deleted as true with no errors and delete their record from the map.

Note: Like slices, maps are also passed by reference into functions. This means that when a map is passed into a function we write, we can make changes to the original β€” we don't have a copy.

package main

func deleteIfNecessary(users map[string]user, name string) (deleted bool, err error) {
	// ?
}

type user struct {
	name                 string
	number               int
	scheduledForDeletion bool
}

Solution

What Each Line Does

Line 1: Check if user exists

  • elem = the user struct (if it exists) or zero value (if it doesn't)

  • ok = true if the key exists, false if not

  • name is the key we're looking up

Line 2: Handle missing user

  • !ok means "if ok is false" (user doesn't exist)

  • Return deleted = false and error message "not found"

  • Must import "errors" at the top

Line 3: Handle user not scheduled for deletion

  • elem.scheduledForDeletion accesses the field from the struct

  • !elem.scheduledForDeletion means "if NOT scheduled for deletion"

  • Return deleted = false with no error (nil)

Line 4: Delete the user

  • delete(users, name) removes the key-value pair from the map

  • First argument = the map

  • Second argument = the key (string)

  • Return deleted = true with no error

Key Mistakes You Made

Mistake 1: Wrong variable in delete

elem is the user struct, not the key. Should be:

Mistake 2: Trying to look up elem in the map

elem already IS the user struct. Just access the field:

Mistake 3: Wrong error syntax

Should be:

  • First return value is a bool, so use false not nil

  • Use errors.New() from the errors package

Tracing Through Example

Call: deleteIfNecessary(users, "Alice")

Result: Alice deleted, returns deleted=true, err=nil

Call: deleteIfNecessary(users, "Bob")

Result: Bob NOT deleted, returns deleted=false, err=nil

Call: deleteIfNecessary(users, "Charlie")

Result: returns deleted=false, err="not found"

Map Existence Check Pattern

This two-value pattern is how Go checks if a key exists in a map.