A map in Go is a built-in data structure that allows you to store and retrieve values based on a key. It is similar to dictionaries in Python or hash tables in other languages. Maps are a collection of key-value pairs, and a map’s keys must be of the same type, as well as its values.
Here is a simple example of a map in Go:
package main
import "fmt"
func main() {
// Declare and initialize a map with string keys and int values
animalAges := map[string]int{
"cat": 3,
"dog": 5,
"horse": 6,
}
// Print the age of the dog
fmt.Println("Age of the dog:", animalAges["dog"]) // Output: Age of the dog: 5
// Add or update a key-value pair in the map
animalAges["tiger"] = 4
// Check if a key is present in the map
if age, ok := animalAges["lion"]; ok {
fmt.Println("Age of the lion:", age)
} else {
fmt.Println("Lion's age not found")
}
// Delete a key-value pair from the map
delete(animalAges, "horse")
// Iterate over the map
for animal, age := range animalAges {
fmt.Printf("Animal: %s, Age: %dn", animal, age)
}
}
In this example, we created a map named ‘animalAges‘ with string keys and int values. We then retrieved a value using a key (the age of the dog), added a new key-value pair (added tiger’s age), checked if a key existed (checked if lion’s age is present), deleted a key-value pair (deleted horse’s age), and iterated over the map to print all the key-value pairs.