Explain the use of Go's map iteration and map element access?

In Go, maps are a built-in type for storing key-value pairs. Iterating over a map allows you to access and manipulate its elements. 

Here's an example:

m := map[string]int{
    "apple":  1,
    "banana": 2,
    "orange": 3,

// Iterate over map using a for loop
for key, value := range m {
    fmt.Println(key, value)

// Accessing an element in a map
fmt.Println(m["apple"]) // Output: 1

In the example above, we first create a map **m** with string keys and integer values using a map literal. We then use a **for** loop with the **range** keyword to iterate over the elements of the map, printing the key-value pairs to the console.

To access an element in the map, we simply use the key as the index in square brackets. If the key is present in the map, the corresponding value is returned. If the key is not present, the zero value for the value type is returned.

Note that the order in which elements are iterated over is not guaranteed, as Go maps are unordered.

Related Questions You Might Be Interested