Welcome to our comprehensive guide on iterating over maps in Go! In this lesson, we'll dive deep into understanding maps, learning how to access, modify, and iterate through them. Let's get started!
Maps in Go are similar to dictionaries or associative arrays in other programming languages. They allow you to store key-value pairs, where each key is unique and can be of any data type, and the associated value can also be of any data type.
m := map[string]int {
"Apple": 100,
"Banana": 200,
"Cherry": 300,
}To access a value in a map, you use its key.
fruit := m["Apple"] // fruit now equals 100You can modify the value associated with a key by assigning a new value to the key.
m["Apple"] = 200 // Now the value for "Apple" is 200Go provides two common ways to iterate through a map: using range keyword and traditional for loops.
The range keyword is a powerful feature in Go that allows you to iterate through collections like maps, slices, and strings. When iterating through a map with range, you get two values: the key and the value.
for key, value := range m {
fmt.Println("Key:", key, "Value:", value)
}You can also use traditional for loops to iterate through maps. In this case, you'll only get the keys or values, depending on your needs.
for key := range m {
fmt.Println("Key:", key)
}
for _, value := range m {
fmt.Println("Value:", value)
}How can you access the value associated with a key in a map?
Stay tuned for our next lesson, where we'll explore more advanced topics related to maps in Go, such as deleting keys, checking for existence, and more! 🚀