Go map Iteration

Go map is a collection type that allows you to store key-value pairs. Maps are similar to dictionaries in Python or hash tables in other programming languages. In Go, maps are created using the built-in make() function.

Here’s an example of creating a map in Go:

// Creating a map
myMap := make(map[string]int)

In this example, we’re creating a map with string keys and int values. You can also create a map using a literal notation:

// Creating a map with literal notation
myMap := map[string]int{"key1": 1, "key2": 2, "key3": 3}

To access the values in a map, you can use the key:

// Accessing values in a map
myMap := map[string]int{"key1": 1, "key2": 2, "key3": 3}
fmt.Println(myMap["key2"]) // Output: 2

You can also update the value of a key in a map:

// Updating values in a map
myMap := map[string]int{"key1": 1, "key2": 2, "key3": 3}
myMap["key2"] = 5
fmt.Println(myMap) // Output: map[key1:1 key2:5 key3:3]

To iterate over a map, you can use a for loop:

// Iterating over a map
myMap := map[string]int{"key1": 1, "key2": 2, "key3": 3}

for key, value := range myMap {
    fmt.Println(key, value)
}

// Output:
// key1 1
// key2 2
// key3 3

In this example, we’re using the range keyword to iterate over the map. The range keyword returns the key and value of each element in the map.

Follow us on social media
Follow Author