https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}

or

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

Answer from Jonathan Feinberg on Stack Overflow
🌐
Go
go.dev › tour › moretypes › 16
Range
More types: structs, slices, and maps. ... Congratulations! ... Congratulations! ... Congratulations! ... Where to Go from here... The range form of the for loop iterates over a slice or map.
🌐
Go by Example
gobyexample.com › range
Go by Example: Range
range iterates over elements in a variety of data structures. Let’s see how to use range with some of the data structures we’ve already learned · Here we use range to sum the numbers in a slice. Arrays work like this too
🌐
Bitfield Consulting
bitfieldconsulting.com › posts › map-iteration
Iterating over a Golang map — Bitfield Consulting
May 29, 2020 - To iterate over a map is to read each successive key-value pair in a loop. We can do this using the range operator.
Address   United States
🌐
YourBasic
yourbasic.org › golang › for-loop-range-array-slice-map-channel
4 basic range loop (for-each) patterns · YourBasic Go
yourbasic.org/golang · Basic for-each loop (slice or array) String iteration: runes or bytes · Map iteration: keys and values · Channel iteration · Gotchas · a := []string{"Foo", "Bar"} for i, s := range a { fmt.Println(i, s) } 0 Foo 1 Bar · The range expression, a, is evaluated once before beginning the loop.
🌐
Go
go.dev › wiki › Range
Go Wiki: Range Clauses - The Go Programming Language
A range clause provides a way to iterate over an array, slice, string, map, or channel.
🌐
Reddit
reddit.com › r/golang › range over map
r/golang on Reddit: Range over map
April 2, 2024 -

I was working on some leetcode problems to practice go, bu I encountered a weird issue when I range over a map. I am not sure if it's a bug or a skill issue on my part (probably the 2nd)

type TreeNode struct{
  Val int
  Left *TreeNode
  Right *TreeNode
}
func levelOrder(root *TreeNode) [][]int {
    retMap := rec(root, 0)
    var retList [][]int
    for _, val := range retMap{
        retList = append(retList, val)
    }
    return retList
}
func rec(root *TreeNode, level int) map[int][]int{
    if root == nil{
        return nil
    }
    retMap := make(map[int][]int)
    retMap[level] = []int{root.Val}

    leftMap := rec(root.Left, level+1)
    rightMap := rec(root.Right, level+1)
    
    for lvl := range leftMap{
        retMap[lvl] = append(retMap[lvl], leftMap[lvl]...)
    }
    for lvl := range rightMap{
        retMap[lvl] = append(retMap[lvl], rightMap[lvl]...)
    }
    return retMap
}

In the function `levelOrder` the order of val is random.
If the tree is:

0 --------1-------
1 ------2 - 3-----

Sometimes I get `[ [1], [2, 3] ]` and sometimes i get `[ [2, 3], [1] ]`

If i use

for i:=0; i<len(retMap); i++

as the bounds of the for loop, the values are return in the correct order.
Is this a skill issue on my part? Or is the range operator not supposed to be used like that?

Screen Shot of this in my terminal

🌐
TutorialsPoint
tutorialspoint.com › article › golang-program-to-iterate-map-elements-using-the-range
Golang Program to Iterate Map Elements using the Range
September 7, 2023 - This syntax uses the range keyword to iterate over the elements of the map mapName. In each iteration, the key and value variables are assigned to the corresponding key?value pair.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › go › go_range.htm
Go - Range
package main import "fmt" func main() { /* create a slice */ numbers := []int{0,1,2,3,4,5,6,7,8} /* print the numbers */ for i:= range numbers { fmt.Println("Slice item",i,"is",numbers[i]) } /* create a map*/ countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"} /* print map using keys*/ for country := range countryCapitalMap { fmt.Println("Capital of",country,"is",countryCapitalMap[country]) } /* print map using key-value*/ for country,capital := range countryCapitalMap { fmt.Println("Capital of",country,"is",capital) } }
🌐
ZetCode
zetcode.com › golang › range
Using Range in Go
In this article we show how to iterate over data structures in Golang. The Go for range form can be used to iterate over strings, arrays, slices, maps, and channels.
🌐
Go
go.dev › blog › maps
Go maps in action - The Go Programming Language
type Person struct { Name string Likes []string } var people []*Person likes := make(map[string][]*Person) for _, p := range people { for _, l := range p.Likes { likes[l] = append(likes[l], p) } }
🌐
GitHub
gist.github.com › d-schmidt › cd85136990de250df38956432517b253
Simple golang RangeMap implementation for sorted, not overlapping ranges of integers (like IP address ranges). Elements are found using binary search. · GitHub
Simple golang RangeMap implementation for sorted, not overlapping ranges of integers (like IP address ranges). Elements are found using binary search. - rangemap.go
🌐
Bacancy Technology
bacancytechnology.com › qanda › golang › iteration-over-map-golang
Mastering Iteration Over Map Golang: Iterate Over All Keys
April 16, 2024 - The most common method for iterating over a map in Go is to use the range keyword with a for loop.
🌐
Go
go.dev › blog › range-functions
Range Over Function Types - The Go Programming Language
August 20, 2024 - Here is an example of how you might use these new functions along with the Filter function we saw earlier. This function takes a map from int to string and returns a slice holding just the values in the map that are longer than some argument n.
🌐
Freshman Tech
freshman.tech › snippets › go › iterate-over-map
How to iterate over and order a map in Go - Freshman.tech
September 4, 2021 - The idiomatic way to iterate over a map in Go is by using the for..range loop construct. Instead of receiving index/value pairs as with slices, you’ll get key/value pairs with maps.
🌐
Programiz
programiz.com › golang › range
Go range (With Examples)
In Go, we use range with the for loop to iterate through the elements of array, string, or map. Before you learn about range, make sure you know the working of Golang for loop.
🌐
GeeksforGeeks
geeksforgeeks.org › go language › range-keyword-in-golang
Range Keyword in Golang - GeeksforGeeks
July 12, 2025 - Map: The first value returned in map is key and the second value is the value of the key-value pair in map. Channel: The first value returned in channel is element and the second value is none.
🌐
VictoriaMetrics
victoriametrics.com › blog › go maps explained: how key-value pairs are actually stored
Go Maps Explained: How Key-Value Pairs Are Actually Stored
August 16, 2024 - Take this example: Have you ever set a ‘hint’ for a map and wondered why it’s called a ‘hint’ and not something simple like length, like we do with slices? ... Or maybe you’ve noticed that when you use a for-range loop on a map, the order doesn’t match the insertion order, and it even changes if you loop over the same map at different times.
🌐
Scaler
scaler.com › home › topics › golang › range loop in golang
Range Loop in Golang - Scaler Topics
May 4, 2023 - The map contains the key-value of type string and int which is accessed by using for-range. ... Explanation: In this example, a function is made for a channel, and elements are inserted.
🌐
Google Groups
groups.google.com › g › golang-nuts › c › 2AIAMD1WM38
Modifying a map while ranging over it
If map entries are created during iteration, that entry may be produced during the iteration or may be skipped. However, is the same true of only modifying elements? So, for example: for k, v := range myMap { myMap[k] = getNewValue() } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group.