Go Maps

Key-value pairs for efficient data storage in Go

πŸ—ΊοΈ What are Go Maps?

Maps are Go's built-in associative data type that store key-value pairs. They provide fast lookups, additions, and deletions based on keys, similar to dictionaries or hash tables.


// Create and use a map
ages := map[string]int{"Alice": 25, "Bob": 30}
ages["Charlie"] = 35
fmt.Println(ages["Alice"]) // Output: 25
                                    

Output:

25

Key Map Concepts

πŸ”‘

Key-Value Pairs

Store data as key-value associations

scores := map[string]int{
    "Math": 95,
    "Science": 87
}
⚑

Fast Lookup

Quick access to values using keys

mathScore := scores["Math"] // O(1) lookup
πŸ”„

Dynamic

Add, update, and delete entries anytime

scores["History"] = 92  // Add
delete(scores, "Math")  // Delete
🎯

Unique Keys

Each key can appear only once

// Keys must be unique
// Values can be duplicated

πŸ”Ή Creating Maps

Several ways to create and initialize maps in Go:

package main

import "fmt"

func main() {
    // Method 1: Map literal
    colors := map[string]string{
        "red":   "#FF0000",
        "green": "#00FF00",
        "blue":  "#0000FF",
    }
    
    // Method 2: Make function
    ages := make(map[string]int)
    ages["Alice"] = 25
    ages["Bob"] = 30
    
    // Method 3: Empty map literal
    var scores map[string]int
    scores = map[string]int{}
    scores["Math"] = 95
    
    // Method 4: Make with initial capacity
    inventory := make(map[string]int, 10)
    inventory["apples"] = 50
    
    fmt.Println("Colors:", colors)
    fmt.Println("Ages:", ages)
    fmt.Println("Scores:", scores)
    fmt.Println("Inventory:", inventory)
}

Output:

Colors: map[blue:#0000FF green:#00FF00 red:#FF0000]
Ages: map[Alice:25 Bob:30]
Scores: map[Math:95]
Inventory: map[apples:50]

πŸ”Ή Map Operations

Common operations for working with maps:

package main

import "fmt"

func main() {
    // Create a map
    students := map[string]int{
        "Alice":   85,
        "Bob":     92,
        "Charlie": 78,
    }
    
    // Access values
    fmt.Println("Alice's score:", students["Alice"])
    
    // Add new entry
    students["Diana"] = 96
    fmt.Println("After adding Diana:", students)
    
    // Update existing entry
    students["Bob"] = 95
    fmt.Println("After updating Bob:", students)
    
    // Check if key exists
    score, exists := students["Eve"]
    if exists {
        fmt.Println("Eve's score:", score)
    } else {
        fmt.Println("Eve not found")
    }
    
    // Delete entry
    delete(students, "Charlie")
    fmt.Println("After deleting Charlie:", students)
    
    // Get map length
    fmt.Println("Number of students:", len(students))
}

Output:

Alice's score: 85
After adding Diana: map[Alice:85 Bob:92 Charlie:78 Diana:96]
After updating Bob: map[Alice:85 Bob:95 Charlie:78 Diana:96]
Eve not found
After deleting Charlie: map[Alice:85 Bob:95 Diana:96]
Number of students: 3

πŸ”Ή Iterating Over Maps

Use range loops to iterate through map entries:

package main

import "fmt"

func main() {
    prices := map[string]float64{
        "apple":  1.20,
        "banana": 0.80,
        "orange": 1.50,
        "grape":  2.00,
    }
    
    // Method 1: Iterate over key-value pairs
    fmt.Println("All items and prices:")
    for item, price := range prices {
        fmt.Printf("%s: $%.2f\n", item, price)
    }
    
    // Method 2: Iterate over keys only
    fmt.Println("\nAll items:")
    for item := range prices {
        fmt.Println("-", item)
    }
    
    // Method 3: Iterate over values only
    fmt.Println("\nAll prices:")
    for _, price := range prices {
        fmt.Printf("$%.2f ", price)
    }
    fmt.Println()
    
    // Calculate total
    total := 0.0
    for _, price := range prices {
        total += price
    }
    fmt.Printf("\nTotal value: $%.2f\n", total)
}

Output:

All items and prices:
apple: $1.20
banana: $0.80
orange: $1.50
grape: $2.00

All items:
- apple
- banana
- orange
- grape

All prices:
$1.20 $0.80 $1.50 $2.00

Total value: $5.50

🧠 Test Your Knowledge

How do you check if a key exists in a Go map?