Bird
Raised Fist0
Goprogramming~10 mins

Accessing map values in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Accessing map values
Declare map with key-value pairs
↓
Access value using key
↓
Check if key exists?
No→Handle missing key
Yes↓
Use the value
This flow shows how to get a value from a map by key, check if the key exists, and then use the value or handle the missing key.
Execution Sample
Go
package main
import "fmt"
func main() {
  m := map[string]int{"a": 1, "b": 2}
  val, ok := m["a"]
  fmt.Println(val, ok)
}
This code creates a map, accesses the value for key "a", and prints the value and whether the key exists.
Execution Table
StepActionExpressionResultNotes
1Declare mapm := map[string]int{"a":1, "b":2}m = {"a":1, "b":2}Map created with keys "a" and "b"
2Access value and check keyval, ok := m["a"]val=1, ok=trueKey "a" exists, value is 1
3Print valuesfmt.Println(val, ok)Output: 1 truePrints value and key existence
4Access missing keyval2, ok2 := m["c"]val2=0, ok2=falseKey "c" does not exist, val2 is zero value
5Print missing key resultfmt.Println(val2, ok2)Output: 0 falseShows missing key returns zero and false
💡 Execution ends after printing values for existing and missing keys.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
mnil{"a":1, "b":2}{"a":1, "b":2}{"a":1, "b":2}{"a":1, "b":2}
valundefinedundefined111
okundefinedundefinedtruetruetrue
val2undefinedundefinedundefined00
ok2undefinedundefinedundefinedfalsefalse
Key Moments - 2 Insights
Why does accessing a missing key return 0 instead of an error?
In Go, accessing a map with a missing key returns the zero value of the map's value type (here int is 0) and false for the existence check, as shown in step 4 and 5.
What does the 'ok' variable represent when accessing a map?
The 'ok' variable is a boolean that tells if the key exists in the map. If true, the key was found (step 2); if false, it was missing (step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'ok' after step 2?
Aundefined
Bfalse
Ctrue
D0
💡 Hint
Check the 'Result' column for step 2 in the execution_table.
At which step does the program access a key that does not exist in the map?
AStep 2
BStep 4
CStep 1
DStep 3
💡 Hint
Look for the step where 'ok' is false in the execution_table.
If the map had a key "c" with value 5, what would 'val2' be after step 4?
A5
B0
Cfalse
Dundefined
💡 Hint
Refer to variable_tracker values for 'val2' and consider the map contents.
Concept Snapshot
Accessing map values in Go:
- Use val, ok := m[key] to get value and check existence.
- If key exists, ok is true and val is the value.
- If key missing, ok is false and val is zero value.
- Always check ok to avoid confusion with zero values.
- This helps safely handle map lookups.
Full Transcript
This visual trace shows how to access values in a Go map. First, a map m is declared with keys "a" and "b". Then, the program accesses the value for key "a" using val, ok := m["a"]. Since "a" exists, val is 1 and ok is true. The program prints these values. Next, it tries to access a missing key "c". The result is val2 = 0 (zero value for int) and ok2 = false, indicating the key is missing. This pattern helps safely check if a key exists before using its value. Variables are tracked step-by-step to show their changes. Key moments clarify why missing keys return zero values and the meaning of the ok variable. The quiz tests understanding of these steps. This is a beginner-friendly way to learn map access in Go.

Practice

(1/5)
1. What does the expression value, ok := myMap["key"] do in Go?
easy
A. It retrieves the value for "key" and checks if the key exists in the map.
B. It deletes the key "key" from the map.
C. It adds a new key "key" with value "ok" to the map.
D. It returns the number of keys in the map.

Solution

  1. Step 1: Understand map access syntax

    In Go, value, ok := myMap["key"] retrieves the value for the key and a boolean indicating if the key exists.
  2. Step 2: Explain the boolean ok

    The ok is true if the key is present, false otherwise.
  3. Final Answer:

    It retrieves the value for "key" and checks if the key exists in the map. -> Option A
  4. Quick Check:

    Map access with existence check = value, ok [OK]
Hint: Remember: value, ok checks key presence in map [OK]
Common Mistakes:
  • Thinking it deletes the key
  • Assuming it adds a key
  • Confusing it with map length
2. Which of the following is the correct way to check if a key exists in a Go map named m for key k?
easy
A. value, ok := m[k]; if ok { ... }
B. value := m[k]; if value != nil { ... }
C. if m.contains(k) { ... }
D. if m[k] != 0 { ... }

Solution

  1. Step 1: Recall Go map existence check syntax

    In Go, to check if a key exists, use value, ok := m[k] and then check ok.
  2. Step 2: Analyze options

    value := m[k]; if value != nil { ... } wrongly assumes value is nil for missing keys, which is not always true. if m.contains(k) { ... } uses a method that does not exist. if m[k] != 0 { ... } checks value but zero value can be valid.
  3. Final Answer:

    value, ok := m[k]; if ok { ... } -> Option A
  4. Quick Check:

    Use value, ok to check key presence [OK]
Hint: Use value, ok := map[key] to check key existence [OK]
Common Mistakes:
  • Checking value against nil or zero instead of ok
  • Using non-existent map methods
  • Assuming zero value means key missing
3. What will be the output of this Go code?
m := map[string]int{"a": 10, "b": 20}
value, ok := m["c"]
fmt.Println(value, ok)
medium
A. Compilation error
B. 0 true
C. 20 true
D. 0 false

Solution

  1. Step 1: Understand map lookup for missing key

    Key "c" is not in map m, so value gets zero value for int, which is 0, and ok is false.
  2. Step 2: Print output values

    Printing value and ok prints "0 false".
  3. Final Answer:

    0 false -> Option D
  4. Quick Check:

    Missing key returns zero value and false [OK]
Hint: Missing map keys return zero value and false [OK]
Common Mistakes:
  • Assuming missing key returns true
  • Expecting runtime error for missing key
  • Confusing zero value with actual stored value
4. Identify the error in this Go code snippet:
m := map[string]int{"x": 5}
value := m["y"]
if value {
    fmt.Println("Key exists")
}
medium
A. Missing declaration of map m.
B. Map key "y" does not exist, causing runtime panic.
C. Cannot use int value as boolean in if condition.
D. Syntax error in map initialization.

Solution

  1. Step 1: Analyze the if condition

    The variable value is an int, but Go requires a boolean expression in if conditions.
  2. Step 2: Understand Go type rules

    Using an int directly as a boolean causes a compile-time error.
  3. Final Answer:

    Cannot use int value as boolean in if condition. -> Option C
  4. Quick Check:

    if conditions need boolean, not int [OK]
Hint: if needs boolean, not int value [OK]
Common Mistakes:
  • Assuming missing key causes panic
  • Ignoring type mismatch in if condition
  • Thinking map declaration is missing
5. Given a map m := map[string]int{"a": 1, "b": 0, "c": 3}, how can you print only keys that exist and have a non-zero value?
hard
A. for k := range m { if m[k] { fmt.Println(k) } }
B. for k, v := range m { if v != 0 { fmt.Println(k) } }
C. for k, v := range m { if m[k] != nil { fmt.Println(k) } }
D. for k, v := range m { if v { fmt.Println(k) } }

Solution

  1. Step 1: Iterate over map with key and value

    Use for k, v := range m to get keys and values.
  2. Step 2: Check for non-zero values

    Check if v != 0 to filter keys with non-zero values.
  3. Step 3: Print keys that meet condition

    Print the key k inside the if block.
  4. Final Answer:

    for k, v := range m { if v != 0 { fmt.Println(k) } } -> Option B
  5. Quick Check:

    Filter keys by value != 0 using range loop [OK]
Hint: Use for k,v := range map and check v != 0 [OK]
Common Mistakes:
  • Using value as boolean directly
  • Checking map key against nil
  • Ignoring zero values in condition
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