Maps in Go
What is a Map?
A map is a collection of key-value pairs where each key is unique, and you can retrieve a value using its key.
What about sets in Go?
Go doesnβt have a built-in set type. You can use a map with a value of nil/boolean
to simulate a set.
Declaring and Initializing Maps
Declaring a Map
var m map[string]int // Declares a map without initializing
fmt.Println(m) // Output: map[]
fmt.Println(m == nil) // Output: true
Initializing a Map
// Using make
m := make(map[string]int)
fmt.Println(m) // Output: map[]
// Declaring and initializing in one step
m2 := map[string]int{
"Alice": 25,
"Bob": 30,
}
fmt.Println(m2) // Output: map[Alice:25 Bob:30]
Basic Operations on Maps
Adding or Updating Elements
m := make(map[string]int)
m["Alice"] = 25 // Add a key-value pair
m["Bob"] = 30 // Add another pair
m["Alice"] = 26 // Update the value for the key "Alice"
fmt.Println(m) // Output: map[Alice:26 Bob:30]
Accessing Values
Checking if a Key Exists
age, exists := m["Charlie"]
if exists {
fmt.Println("Charlieβs age:", age)
} else {
fmt.Println("Charlie not found") // Output: Charlie not found
}
Deleting a Key
Iterating Over a Map
Length of a Map
Maps as Function Arguments
Maps are reference types, so passing them to a function doesnβt copy the map; it passes a reference.
func updateMap(m map[string]int) {
m["Bob"] = 35
}
m := map[string]int{"Bob": 30}
updateMap(m)
fmt.Println(m["Bob"]) // Output: 35
Maps of Structs
type Person struct {
Name string
Age int
}
people := map[string]Person{
"Alice": {Name: "Alice", Age: 25},
"Bob": {Name: "Bob", Age: 30},
}
fmt.Println(people["Alice"]) // Output: {Alice 25}
Key Points
- Maps are reference types and are automatically garbage collected.
- Use
make
to initialize maps. Uninitialized maps will cause a runtime panic on writes. - Keys must be of a type that is comparable (e.g., numbers, strings, structs without slices or maps).
- Maps are not safe for concurrent use; use synchronization primitives like
sync.Mutex
orsync.Map
for concurrent scenarios.