Maps in Go (also known as dictionaries in other languages) are like treasure chests. They let you store and retrieve values using unique keys—just like a pirate finding gold by following a map!
What is a Map?
A map in Go is a built-in data type that holds key-value pairs. Think of it as a real-world dictionary, where you look up a word (key) to find its meaning (value).
Declaring a Map
package main
import "fmt"
func main() {
var myMap map[string]int // Declaring a map
myMap = make(map[string]int) // Initializing the map
fmt.Println(myMap) // Output: map[]
}
A map must be initialized using make()
before you can use it. Otherwise, Go will panic like a pirate without a ship!
Adding and Accessing Elements
Once our map is ready, we can start storing and retrieving values.
package main
import "fmt"
func main() {
ages := make(map[string]int)
ages["Alice"] = 25
ages["Bob"] = 30
fmt.Println("Alice's Age:", ages["Alice"]) // Output: Alice's Age: 25
}
This works just like looking up someone’s birthday in your contacts list.
Deleting a Key-Value Pair
If you want to remove something from the map, use delete()
.
package main
import "fmt"
func main() {
fruits := map[string]string{
"apple": "red",
"banana": "yellow",
}
delete(fruits, "banana")
fmt.Println(fruits) // Output: map[apple:red]
}
No more bananas!
Checking If a Key Exists
To avoid looking for a non-existent treasure, check if the key exists.
package main
import "fmt"
func main() {
scores := map[string]int{"John": 90, "Jane": 85}
score, exists := scores["John"]
if exists {
fmt.Println("John's Score:", score)
} else {
fmt.Println("John's Score Not Found!")
}
}
This prevents you from searching for something that isn’t there.
Iterating Over a Map
Use range
to loop through all key-value pairs.
package main
import "fmt"
func main() {
capitals := map[string]string{
"France": "Paris",
"Japan": "Tokyo",
}
for country, capital := range capitals {
fmt.Printf("The capital of %s is %s\n", country, capital)
}
}
This is like exploring the world with your very own map!
Maps in Go are powerful tools for handling key-value pairs. Whether you're storing user data, configurations, or a list of pirate treasures, maps make it easy! Now go forth and map your way to success!
0 Comments