Maps (Key-Value Storage, Comma-Ok Idiom & Iteration) - Go Tutorial for Beginners #10
Video: Maps (Key-Value Storage, Comma-Ok Idiom & Iteration) - Go Tutorial for Beginners #10 by Taught by Celeste AI - AI Coding Coach
Watch full page →Maps (Key-Value Storage, Comma-Ok Idiom & Iteration) in Go
Maps in Go provide a built-in hash table structure to store and retrieve data using key-value pairs efficiently. This guide covers creating maps, safely accessing elements with the comma-ok idiom, deleting entries, iterating over maps, and working with maps containing struct values.
Code
package main
import "fmt"
func main() {
// Create and initialize a map with string keys and int values
ages := map[string]int{
"Alice": 25,
"Bob": 30,
}
// Access a value directly
fmt.Println("Alice's age:", ages["Alice"])
// Use the comma-ok idiom to safely check if a key exists
age, exists := ages["Carol"]
if exists {
fmt.Println("Carol's age:", age)
} else {
fmt.Println("Carol not found in map")
}
// Add or update a value
ages["Carol"] = 22
fmt.Println("Added Carol:", ages["Carol"])
// Delete a key from the map
delete(ages, "Bob")
// Iterate over the map
fmt.Println("Current map entries:")
for name, age := range ages {
fmt.Printf("%s: %d\n", name, age)
}
// Maps with struct values
type Person struct {
Age int
City string
}
people := make(map[string]Person)
people["Dave"] = Person{Age: 40, City: "New York"}
fmt.Println("Dave's info:", people["Dave"])
}
Key Points
- Maps are Go’s built-in hash tables for fast key-value storage and retrieval.
- The comma-ok idiom safely checks if a key exists, preventing ambiguity with zero values.
- Use the built-in delete function to remove keys from a map.
- Iterate over maps using a for-range loop to access keys and values.
- Maps can store complex data types like structs as values for richer data modeling.