Day 8: Mastering Maps in Go - Key-Value Collections
Maps are Go’s built-in associative data structure for storing key-value pairs. Today, we’ll explore how to declare, initialize, and manipulate maps in Go.
Step 1: Declaring and Initializing Maps
Maps in Go are declared using the make()
function or by using map literals:
m := make(map[string]int)
m["apple"] = 5
m["banana"] = 10
fmt.Println(m)
Alternatively, you can initialize maps using literals:
m := map[string]int{"apple": 5, "banana": 10}
Step 2: Accessing and Modifying Map Values
You can access map values using the key:
value := m["apple"]
fmt.Println(value) // Output: 5
To check if a key exists in a map, use the following pattern:
value, exists := m["orange"]
if exists {
fmt.Println("Key exists:", value)
} else {
fmt.Println("Key does not exist")
}
Step 3: Deleting Map Entries
To remove a key-value pair from a map, use the delete()
function:
delete(m, "banana")
fmt.Println(m)
Practical Exercise
Write a Go program that creates a map of fruits and their quantities, modifies an entry, deletes another, and prints the final map:
package main
import "fmt"
func main() {
fruits := map[string]int{
"apple": 5,
"banana": 10,
"orange": 8,
}
// Modify the quantity of apples
fruits["apple"] = 7
// Delete oranges from the map
delete(fruits, "orange")
fmt.Println(fruits)
}