ProgramGuru

Accessing and Updating Maps

Start with Accessing and Updating Maps

A map lookup can return a value and a boolean indicating whether the key exists. This is important when the zero value could also be a legitimate stored value.

What you’ll learn

  • Explain the main purpose of accessing and updating maps.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Use the two-result lookup value, ok := m[key]. If the key exists, ok is true, even if the stored value is zero. Assigning m[key] = newValue either updates an existing entry or inserts a new key.

Maps are good for counting occurrences: counts[word]++ works even for a previously unseen word because reading its missing count gives zero. This depends on the map itself being initialized before writing.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for map accessA condition branches into true or false paths before continuing.Lookup keyTRUEFALSEExists? ok=trueMissing? ok=falseUse the value appropriately
Trace control flow in the order shown, then compare it with the program.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func main() {
	stock := map[string]int{"pen": 0, "book": 5}
	pen, exists := stock["pen"]
	ruler, found := stock["ruler"]
	fmt.Println("Pen:", pen, exists)
	fmt.Println("Ruler:", ruler, found)
	stock["book"] += 2
	fmt.Println("Books:", stock["book"])
}

Output

Pen: 0 true
Ruler: 0 false
Books: 7

Trace what the program does

The key pen is present with value zero, so exists is true. Ruler is absent, so its value is also zero but found is false. The book entry increases from five to seven.

Avoid common mistakes

  • A single-value lookup cannot distinguish a missing key from a stored zero value.
  • Updating a nil map panics; initialize it first.

Try it yourself

Add a key with value zero and show that its existence check returns true. Then increment it twice.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which lookup distinguishes a stored zero from a missing key?
Choose one answer. You can try again.

Answer and explanation

value, ok := m[key]

Correct. The key pen is present with value zero, so exists is true.

What you should remember

You have practiced Accessing and Updating Maps in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Deleting Map Elements →