0
0
Goprogramming~10 mins

Iterating over maps in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Iterating over maps
Start
Initialize map
Start loop over map
Get key, value
Process key, value
More items?
YesNext item
No
End loop
Program ends
This flow shows how Go loops over each key-value pair in a map until all items are processed.
Execution Sample
Go
package main
import "fmt"
func main() {
  m := map[string]int{"a":1, "b":2}
  for k, v := range m {
    fmt.Println(k, v)
  }
}
This code loops over a map and prints each key and its value.
Execution Table
StepActionKeyValueOutput
1Start loop
2Get first itema1Print: a 1
3Get second itemb2Print: b 2
4No more itemsLoop ends
💡 All map items processed, loop ends
Variable Tracker
VariableStartAfter 1After 2Final
kab
v12
Key Moments - 2 Insights
Why does the order of keys printed change each time?
Go maps do not guarantee order when iterating. The execution_table shows keys 'a' then 'b', but this can vary each run.
What happens if the map is empty?
The loop body does not run at all. The execution_table would skip steps 2 and 3 and go directly to step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the key and value at step 3?
AKey: a, Value: 1
BKey: b, Value: 2
CKey: c, Value: 3
DNo key, no value
💡 Hint
Check row with Step 3 in execution_table for key and value
At which step does the loop end according to the execution_table?
AStep 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look for the step where 'Loop ends' is in the Output column
If the map had 3 items, how many times would the loop run?
A1 time
B2 times
C3 times
D4 times
💡 Hint
Loop runs once per map item, see variable_tracker for iterations
Concept Snapshot
Go maps store key-value pairs.
Use 'for k, v := range map' to loop over them.
Each loop gets one key and its value.
Order is random, not guaranteed.
Loop ends after all items processed.
Full Transcript
This visual execution shows how Go iterates over maps using a for loop with range. The program initializes a map with two items. Then it starts a loop that runs once for each key-value pair. Each step gets one key and value, then prints them. The order of keys is not fixed and can change each run. The loop ends when all items are processed. Variables k and v change each iteration to hold the current key and value. Beginners often wonder why order changes or what happens if the map is empty. The execution table and variable tracker clarify these points. The quiz tests understanding of keys, loop steps, and iteration count.