0
0
Goprogramming~10 mins

Map creation in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Map creation
Start
Declare map variable
Initialize map with make()
Add key-value pairs
Use map
End
This flow shows how to declare, initialize, and add key-value pairs to a map in Go.
Execution Sample
Go
package main
import "fmt"
func main() {
  var m map[string]int
  m = make(map[string]int)
  m["apple"] = 5
  fmt.Println(m)
}
This code creates a map from strings to integers, adds one key-value pair, and prints the map.
Execution Table
StepActionMap StateOutput
1Declare map variable mmap is nil (not initialized)
2Initialize map with make(map[string]int)empty map {}
3Add key "apple" with value 5{"apple":5}
4Print map m{"apple":5}map[apple:5]
5Program ends{"apple":5}
💡 Program ends after printing the map with one key-value pair.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
mnil{}{"apple":5}{"apple":5}
Key Moments - 2 Insights
Why do we need to use make() to initialize the map?
In step 2, the map is initialized with make(), creating an empty map. Without this, the map is nil and cannot store key-value pairs, so adding keys would cause a runtime error.
What happens if we try to add a key-value pair before initializing the map?
Before step 2, the map is nil (step 1). Adding a key then would cause a runtime panic because the map is not ready to hold data, as shown by the empty map state only after step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of map 'm' after step 1?
Anil (not initialized)
Bempty map {}
Cmap with one key-value pair
Dmap with default values
💡 Hint
Check the 'Map State' column in row for step 1.
At which step does the map 'm' get its first key-value pair?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'Map State' columns to see when 'apple':5 is added.
If we skip step 2 (make initialization), what will happen when adding a key-value pair?
AMap will be empty and accept the pair
BProgram will panic at runtime
CMap will automatically initialize
DNothing happens, map stays nil
💡 Hint
Refer to key moment about adding keys before initialization.
Concept Snapshot
Map creation in Go:
- Declare map variable: var m map[string]int
- Initialize with make(): m = make(map[string]int)
- Add key-value: m["key"] = value
- Maps must be initialized before use
- Print with fmt.Println(m)
Full Transcript
This example shows how to create a map in Go. First, we declare a map variable 'm' which is nil initially. Then we initialize it using make(), which creates an empty map ready to store data. Next, we add a key-value pair with key "apple" and value 5. Finally, we print the map, which shows map[apple:5]. Without initialization, adding keys would cause a runtime error. This step-by-step trace helps understand how maps are created and used in Go.