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.
package main import "fmt" func main() { var m map[string]int m = make(map[string]int) m["apple"] = 5 fmt.Println(m) }
| Step | Action | Map State | Output |
|---|---|---|---|
| 1 | Declare map variable m | map is nil (not initialized) | |
| 2 | Initialize map with make(map[string]int) | empty map {} | |
| 3 | Add key "apple" with value 5 | {"apple":5} | |
| 4 | Print map m | {"apple":5} | map[apple:5] |
| 5 | Program ends | {"apple":5} |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| m | nil | {} | {"apple":5} | {"apple":5} |
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)
make is used to create maps with specified key and value types.make(map[string]int) creates an empty map with string keys and int values.[]int as a key type causes a syntax error because slices cannot be map keys.m := make(map[string]int) m["apple"] = 5 m["banana"] = 3 fmt.Println(m["apple"] + m["banana"])
m stores key-value pairs: "apple"=5 and "banana"=3.m["apple"] (5) and m["banana"] (3) results in 8.var m map[string]int m["key"] = 10 fmt.Println(m["key"])
m is declared but not initialized with make, so it is nil.keys := []string{"a", "b", "c"} and a slice of ints values := []int{1, 2, 3}, which code snippet correctly creates a map from keys to values?m[keys[i]] = values[i], correctly pairing keys to values.Pass the test and this pattern moves unknown