Maps in Go provide a powerful way to store and retrieve key-value pairs. They are hash tables under the hood, offering fast lookups and flexible data organization.
To create a map, use the make
function or a map literal:
// Using make
scores := make(map[string]int)
// Using a map literal
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}
Insert or update values using the square bracket notation:
scores["John"] = 85
ages["Charlie"] = 35 // Add a new entry
ages["Alice"] = 31 // Update an existing entry
Retrieve values and check for existence using the comma-ok idiom. Remove entries with the delete
function:
score, exists := scores["John"]
if exists {
fmt.Printf("John's score: %d\n", score)
} else {
fmt.Println("John's score not found")
}
delete(ages, "Bob") // Remove Bob's age from the map
Use a Go for loop with the range keyword to iterate over map entries:
for name, age := range ages {
fmt.Printf("%s is %d years old\n", name, age)
}
Get the number of entries in a map using the len
function. Unlike Go slices, maps don't have a capacity concept.
fmt.Printf("Number of entries: %d\n", len(ages))
sync.Map
.nil
. Attempting to add elements to a nil map will cause a runtime panic.Maps in Go offer a versatile and efficient way to manage key-value data. They are essential for many programming tasks, from caching to data organization. By mastering maps, you'll enhance your ability to write clean and efficient Go code.