A map is an unordered collection of key-value pairs. Keys must be unique and comparable.
Maps are equivalent to dictionaries in Python or objects in Java
var m map[string]int
m = make(map[string]int)You can also initialize a map with values:
m := map[string]int{
"apples": 5,
"bananas": 10,
}m["grapes"] = 7
fmt.Println(m["apples"]) // prints 5If the key doesn’t exist, Go returns the zero value for the type (e.g., 0 for int).
val, ok := m["kiwi"]
if ok {
fmt.Println("Kiwi found:", val)
} else {
fmt.Println("Kiwi not in map")
}This is idiomatic Go — the second value of the map access tells you if the key exists.
delete(m, "bananas")This removes the key if it exists; otherwise it does nothing.
for k, v := range m {
fmt.Printf("%s: %d\n", k, v)
}Note: Map iteration order is not guaranteed.
Maps can store structs as values:
type Product struct {
Price int
}
inventory := map[string]Product{
"pen": {Price: 2},
"notebook": {Price: 5},
}data := map[string]map[string]int{
"alice": {"math": 95, "science": 88},
"bob": {"math": 72, "science": 91},
}Useful for representing JSON-like hierarchical data.
Ask the AI if you need help understanding or want to dive deeper in any topic