I have a map of type: map[string]interface{}
And finally, I get to create something like (after deserializing from a yml file using goyaml)
mymap = map[foo:map[first: 1] boo: map[second: 2]]
How can I iterate through this map? I tried the following:
for k, v := range mymap{ ... }
But I get an error:
cannot range over mymap typechecking loop involving for loop
Please help.
As a Golang map is an unordered collection, it does not preserve the order of keys. We can use additional data structures to iterate over these maps in sorted order.
Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one.
By default Golang prints the map with sorted keys but while iterating over a map, it follows the order of the keys appearing as it is.
To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.
For example,
package main import "fmt" func main() { type Map1 map[string]interface{} type Map2 map[string]int m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}} //m = map[foo:map[first: 1] boo: map[second: 2]] fmt.Println("m:", m) for k, v := range m { fmt.Println("k:", k, "v:", v) } }
Output:
m: map[boo:map[second:2] foo:map[first:1]] k: boo v: map[second:2] k: foo v: map[first:1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With