← Back to Go Course | Chapter 5: Arrays Slices Maps | Lesson 6 of 7

Map Operations

Once you have a map, you can add new entries, change existing ones, or delete entries you no longer need -- just like editing a contact list.

Adding and Updating Entries

Assigning to a key with m[key] = value adds a new entry if the key doesn't exist yet, or overwrites the existing value if it does -- there's no separate insert versus update operation.

Example: Adding and Updating Entries

markup
package main

import "fmt"

func main() {
	stock := map[string]int{"pens": 10}
	stock["pens"] = 15
	stock["pencils"] = 20
	fmt.Println(stock)
}

Deleting Entries

The built-in delete function removes a key-value pair from a map. Calling it with a key that isn't present is perfectly safe and simply does nothing.

Note: delete() never panics, even if the key is missing -- no need to check existence first.

Example: Deleting Entries

markup
package main

import "fmt"

func main() {
	stock := map[string]int{"pens": 10, "pencils": 20}
	delete(stock, "pencils")
	delete(stock, "erasers") // no-op, key doesn't exist
	fmt.Println(stock)
}

Getting the Size of a Map

len() works on maps just as it does on slices and strings, returning the current number of key-value pairs stored -- it updates automatically as entries are added or removed.

Example: Getting the Size of a Map

markup
package main

import "fmt"

func main() {
	inventory := map[string]int{"a": 1, "b": 2, "c": 3}
	fmt.Println("entries:", len(inventory))
	delete(inventory, "a")
	fmt.Println("entries after delete:", len(inventory))
}
Common Mistakes
  1. Trying to delete a key that doesn't exist and expecting an error -- delete() is a safe no-op on missing keys.
  2. Assuming len(m) counts something other than the number of key-value pairs currently in the map.
  3. Using a slice or other non-comparable type (like another map) as a map key, which fails to compile since map keys must be comparable.
Chapter Summary
  • Adding or updating a map entry uses the same syntax: m[key] = value.
  • delete(m, key) removes an entry, and is a safe no-op if the key isn't present.
  • len(m) returns the number of key-value pairs in the map.
  • Map keys must be a comparable type -- strings, numbers, and structs of comparable fields all qualify.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.