Bird
Raised Fist0
Goprogramming~10 mins

Map use cases in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Map use cases
Declare map variable
↓
Initialize map with make()
↓
Add key-value pairs
↓
Access values by key
↓
Check if key exists
↓
Delete key-value pair
↓
Iterate over map
↓
End
This flow shows how to declare, initialize, use, and manipulate maps step-by-step in Go.
Execution Sample
Go
package main
import "fmt"
func main() {
  m := make(map[string]int)
  m["apple"] = 5
  fmt.Println(m["apple"])
}
This code creates a map, adds a key-value pair, and prints the value for the key "apple".
Execution Table
StepActionMap StateOutput
1Declare map variable mm = nil
2Initialize map with makem = empty map {}
3Add key "apple" with value 5m = {"apple": 5}
4Print m["apple"]m = {"apple": 5}5
5Access m["banana"] (not set)m = {"apple": 5}0 (zero value)
6Check if "banana" existsm = {"apple": 5}false
7Add key "banana" with value 3m = {"apple": 5, "banana": 3}
8Delete key "apple"m = {"banana": 3}
9Iterate over map keys and valuesm = {"banana": 3}banana: 3
10End of programm = {"banana": 3}
💡 Program ends after iterating and printing map contents.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 7After Step 8Final
mnil{}{"apple": 5}{"apple": 5, "banana": 3}{"banana": 3}{"banana": 3}
Key Moments - 3 Insights
Why does accessing a key that doesn't exist return 0 instead of an error?
In Go, accessing a map with a missing key returns the zero value for the value type (here int is 0). See step 5 in execution_table.
How do we check if a key exists in the map?
Use the two-value assignment: value, ok := m[key]. The 'ok' is true if key exists. See step 6 in execution_table.
What happens when we delete a key from the map?
The key-value pair is removed, so the map no longer contains that key. See step 8 in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the output when accessing m["banana"]?
A0
Bnil
Cerror
Dbanana
💡 Hint
Check the Output column at step 5 in execution_table.
At which step is the key "apple" removed from the map?
AStep 3
BStep 7
CStep 8
DStep 9
💡 Hint
Look at the Map State column to see when "apple" disappears.
If we add m["orange"] = 10 at step 7, what will be the map state after step 7?
A{"banana": 3, "orange": 10}
B{"apple": 5, "banana": 3, "orange": 10}
C{"apple": 5, "orange": 10}
D{"orange": 10}
💡 Hint
Adding a new key adds it alongside existing keys, see variable_tracker after step 7.
Concept Snapshot
Map use cases in Go:
- Declare with var or :=
- Initialize with make(map[keyType]valueType)
- Add/update with m[key] = value
- Access with m[key], returns zero if missing
- Check existence: val, ok := m[key]
- Delete with delete(m, key)
- Iterate with for k, v := range m
Full Transcript
This visual execution trace shows how to use maps in Go. First, we declare a map variable which starts as nil. Then we initialize it with make to create an empty map. We add key-value pairs by assigning values to keys. Accessing a key returns its value or zero if the key is missing. We can check if a key exists using the two-value assignment. Deleting a key removes it from the map. Finally, we can iterate over the map to access all keys and values. The variable tracker shows how the map changes after each step. Key moments clarify common confusions like zero values and key existence checks. The quiz tests understanding of map behavior at specific steps.

Practice

(1/5)
1. What is the primary use of a map in Go?
easy
A. To store data with keys for fast lookup
B. To perform mathematical calculations
C. To create user interfaces
D. To handle file input/output

Solution

  1. Step 1: Understand the purpose of a map

    A map in Go is a collection of key-value pairs, designed for fast data retrieval using keys.
  2. Step 2: Compare with other options

    Options B, C, and D describe unrelated tasks like calculations, UI, or file handling, which are not the main use of maps.
  3. Final Answer:

    To store data with keys for fast lookup -> Option A
  4. Quick Check:

    Maps = key-value storage [OK]
Hint: Maps store key-value pairs for quick access [OK]
Common Mistakes:
  • Confusing maps with slices or arrays
  • Thinking maps are for calculations
  • Assuming maps handle UI or files
2. Which of the following is the correct way to create an empty map in Go?
easy
A. m := make([]string, 0)
B. var m map[string]int = make(map[string]int)
C. m := map[string]int
D. m := []int{}

Solution

  1. Step 1: Identify map creation syntax

    In Go, maps are created using make(map[keyType]valueType). var m map[string]int = make(map[string]int) uses this correctly.
  2. Step 2: Check other options

    m := []int{} creates a slice, not a map. m := map[string]int is invalid syntax for map creation. m := make([]string, 0) creates a slice, not a map.
  3. Final Answer:

    var m map[string]int = make(map[string]int) -> Option B
  4. Quick Check:

    Use make() to create maps [OK]
Hint: Use make() to create maps before use [OK]
Common Mistakes:
  • Using slice syntax instead of map syntax
  • Not using make() to initialize maps
  • Confusing map and slice creation
3. What will be the output of this Go code?
m := make(map[string]int)
m["apple"] = 5
m["banana"] = 3
fmt.Println(m["apple"] + m["banana"])
medium
A. 8
B. 53
C. 0
D. Compilation error

Solution

  1. Step 1: Understand map assignments

    The map m stores integers with string keys. "apple" maps to 5, "banana" maps to 3.
  2. Step 2: Calculate the sum

    Adding m["apple"] + m["banana"] equals 5 + 3 = 8.
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    5 + 3 = 8 [OK]
Hint: Sum values by accessing keys directly [OK]
Common Mistakes:
  • Concatenating values as strings
  • Expecting zero for existing keys
  • Thinking code causes error
4. What is wrong with this Go code snippet?
var m map[string]int
m["key"] = 10
fmt.Println(m["key"])
medium
A. Cannot assign int values to map
B. Key "key" is invalid syntax
C. Map is not initialized with make() before use
D. fmt.Println cannot print map values

Solution

  1. Step 1: Check map initialization

    The map m is declared but not initialized with make(). This causes a runtime panic on assignment.
  2. Step 2: Understand consequences

    Without initialization, m["key"] = 10 causes a panic: assignment to nil map.
  3. Final Answer:

    Map is not initialized with make() before use -> Option C
  4. Quick Check:

    Initialize maps with make() [OK]
Hint: Always initialize maps with make() before adding keys [OK]
Common Mistakes:
  • Forgetting to initialize map before use
  • Assuming declaration is enough
  • Misunderstanding map assignment rules
5. Given a map m := map[string]int{"a": 1, "b": 0, "c": 3}, which code snippet correctly checks if key "b" exists and its value is non-zero?
hard
A. if _, ok := m["b"]; ok { fmt.Println("Exists and non-zero") }
B. if m["b"] == 0 { fmt.Println("Exists and non-zero") }
C. if m["b"] >= 0 { fmt.Println("Exists and non-zero") }
D. if val, ok := m["b"]; ok && val != 0 { fmt.Println("Exists and non-zero") }

Solution

  1. Step 1: Understand map key existence check

    Using val, ok := m["b"] lets us check if key "b" exists (ok) and get its value (val).
  2. Step 2: Check value is non-zero

    The condition ok && val != 0 ensures key exists and value is not zero.
  3. Final Answer:

    if val, ok := m["b"]; ok && val != 0 { fmt.Println("Exists and non-zero") } -> Option D
  4. Quick Check:

    Check key existence and value together [OK]
Hint: Use val, ok := map[key] to check existence and value [OK]
Common Mistakes:
  • Checking value without verifying key existence
  • Assuming zero means key missing
  • Using only ok without value check
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard