Go Iterating over Maps 🎯

beginner
5 min

Go Iterating over Maps 🎯

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!

What are Maps in Go? 📝

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.

go
m := map[string]int { "Apple": 100, "Banana": 200, "Cherry": 300, }

Accessing Map Values 💡

To access a value in a map, you use its key.

go
fruit := m["Apple"] // fruit now equals 100

Modifying Map Values 💡

You can modify the value associated with a key by assigning a new value to the key.

go
m["Apple"] = 200 // Now the value for "Apple" is 200

Iterating through Maps 💡

Go provides two common ways to iterate through a map: using range keyword and traditional for loops.

Using range keyword

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.

go
for key, value := range m { fmt.Println("Key:", key, "Value:", value) }

Using Traditional For Loops

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.

go
for key := range m { fmt.Println("Key:", key) } for _, value := range m { fmt.Println("Value:", value) }

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🚀