Golang : Iterate map
Got a question by a friend asking how to how to iterate through a map in Golang today. Thought that I have covered this initially with the tutorial on how to iterate over the values inside array., but then it is not similar.
In this short tutorial, we will learn how to iterate the elements inside a map. In this code example below, we will learn how to combine maps with the help of interface{}
(optional) and then iterate through the maps.
package main
import "fmt"
func main() {
type Map1 map[string]interface{}
type Map2 map[string]string
// because Map1 is type interface, it can handle 3 maps of Map2
m := Map1{"1": Map2{"position": "first"}, "2": Map2{"position": "second"}, "3": Map2{"position": "third"}, "4": Map2{"position": "fourth"}}
// print out all the elements in one line
fmt.Println("m:", m)
// iterate the map and print out the element one by one
for key, value := range m {
fmt.Println("key:", key, "value:", value)
}
// NOTE : maps in golang has no guaranteed order
}
Hope this tutorial can be helpful in solving or assisting your Golang learning process.
See also : Golang : How to iterate over a []string(array)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.2k Unix/Linux : How to get own IP address ?
+47.3k Golang : How to convert JSON string to map and slice
+9.7k Golang : Use regular expression to get all upper case or lower case characters example
+9.2k Golang : Qt get screen resolution and display on center example
+6.4k Golang : How to solve "too many .rsrc sections" error?
+22.4k Golang : Test file read write permission example
+8.6k Android Studio : Indicate progression with ProgressBar example
+5.1k How to check with curl if my website or the asset is gzipped ?
+7.4k Golang : Get today's weekday name and calculate target day distance example
+5.2k Unix/Linux/MacOSx : Get local IP address
+4.5k Which content-type(MIME type) to use for JSON data
+4.9k Golang : How to deal with configuration data?