In Go, you can use the range keyword to iterate over a map. The range keyword returns two values: key and value.
Here is the sample code for traversing the map:
package main import "fmt" func main() { myMap := map[string]int{ "apple": 1, "banana": 2, "orange": 3, } // Use range to traverse map for key, value := range myMap { (key, value) } }
In the above code, we create a map called myMap with three key-value pairs. Then we use the range keyword to iterate over the map. In each iteration, range returns the key and corresponding values of the current iteration and assigns them to the key and value variables. Then, we use the() function to print out the key and the corresponding value.
The output result will be:
apple 1
banana 2
orange 3
In this way, you successfully traverse a map and print out the key-value pairs in it.
This is the end of this article about the method of golang traversing maps. For more related golang traversing maps, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!