Maps
In this page:
Creating a Map
A map associates keys with values, similar to a dictionary in Python or an object in JavaScript. It's created either with make(map[KeyType]ValueType) or a map literal listing initial key-value pairs.
Example: Creating a Map
package main
import "fmt"
func main() {
prices := map[string]float64{
"apple": 0.5,
"banana": 0.25,
}
fmt.Println(prices["apple"])
}
Login to try C/C++/Java/PHP code in the editor
The nil Map Trap
A map declared with just 'var m map[string]int' is nil, and while reading from a nil map is safe (it returns the zero value), writing to it causes a runtime panic. This is a very common beginner mistake.
Note: Always initialize a map with make() or a literal before writing to it.
Example: The nil Map Trap
package main
import "fmt"
func main() {
var scores map[string]int
fmt.Println("read from nil map is safe:", scores["nobody"])
scores = make(map[string]int)
scores["alice"] = 90
fmt.Println(scores)
}
Login to try C/C++/Java/PHP code in the editor
Checking If a Key Exists
Reading a key that doesn't exist returns the zero value for the map's value type rather than an error, which can be ambiguous. The 'comma ok' form -- value, ok := m[key] -- tells you definitively whether the key was actually present.
Note: Always use the comma-ok form when the zero value is a valid, ambiguous result (like 0 for a real score).
Example: Checking If a Key Exists
package main
import "fmt"
func main() {
ages := map[string]int{"amit": 30}
age, ok := ages["priya"]
fmt.Println("age:", age, "found:", ok)
}
Login to try C/C++/Java/PHP code in the editor
- Writing to a nil map (declared with 'var m map[K]V' but never initialized with make) which causes a runtime panic.
- Assuming maps preserve insertion order when iterating -- Go deliberately randomizes map iteration order.
- Reading a missing key and treating the returned zero value as if the key existed, instead of checking the second 'comma ok' return value.
- A map stores key-value pairs, declared as map[KeyType]ValueType.
- Maps must be initialized with make() or a map literal before you can write to them -- a nil map panics on write.
- Reading a missing key returns the value type's zero value, not an error, unless you use the comma-ok form.
- Map iteration order is randomized on purpose by the Go runtime.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: