Maps in Go
Introduction to Maps
Maps in Go are built-in data structures that store key-value pairs. They provide efficient lookups, inserts, and deletions, making them essential for managing associative data.
Declaring and Initializing a Map
A map can be created using the make
function or initialized with values directly.
package main
import "fmt"
func main() {
ages := make(map[string]int) // Creating an empty map
ages["Alice"] = 25
ages["Bob"] = 30
fmt.Println(ages)
}
Here, we create a map where names are keys and ages are values.
Initializing a Map with Values
We can directly initialize a map with key-value pairs.
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 35}
fmt.Println(ages)
}
This example demonstrates how to define a map with initial values.
Accessing and Modifying Map Values
Values can be accessed or updated using keys.
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30}
fmt.Println("Bob's age:", ages["Bob"])
ages["Bob"] = 32 // Updating Bob's age
fmt.Println("Updated age:", ages["Bob"])
}
Here, Bob’s age is updated from 30 to 32.
Checking for Key Existence
To check if a key exists in a map, use the second return value of a key lookup.
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30}
age, exists := ages["Charlie"]
if exists {
fmt.Println("Charlie's age:", age)
} else {
fmt.Println("Charlie not found")
}
}
Here, we check if "Charlie" exists before printing the value.
Deleting a Key
Use the delete
function to remove a key-value pair.
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30}
delete(ages, "Alice")
fmt.Println(ages)
}
Here, "Alice" is removed from the map.
Iterating Over a Map
Use a for
loop with range
to iterate over a map.
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 35}
for name, age := range ages {
fmt.Println(name, "is", age, "years old")
}
}
This example prints all key-value pairs in the map.
Conclusion
Maps in Go provide an efficient way to store and retrieve key-value pairs. They support dynamic updates, key existence checks, deletions, and iteration.
In the next lesson, we will explore Structs in Go, which allow defining custom data types.