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
🌐
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

🌐
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.
Discussions

loops - Iterating over all the keys of a map - Stack Overflow
Sudhir: golang language spec explicitly defines maps as having undefined ordering of keys. Furthermore, since Go 1, key order is intentionally randomized between runs to prevent dependency on any perceived order. More on stackoverflow.com
🌐 stackoverflow.com
golang: range over slice or map
No, as far as I know this is not possible without writing two loops. any is just an alias for interface{}. The value that actually gets passed to your function is an interface value, which is a "box" containing a pointer to an underlying value, along with a pointer to its concrete type. In general, the only things you can do with interface values are to cast them to the underlying type (as you're doing in your second example) or to call methods on them (which go through the interface's vtable). (There are certain exceptions to this but they only apply to generic methods, where the interface is used as a type constraint at compile time, and not as an actual interface type at runtime.) Your second example works because in a case clause with a single type, the variable m is obtained by casting t to its underlying type. If the clause has multiple types, as in your first example, then there is a type check but no type cast (because there is no single concrete type it could be cast to) so m still has type interface{}. More on reddit.com
🌐 r/learnprogramming
4
2
May 26, 2023
How come I can range over a slice, map etc if they are `nil`, or check their len safely, but accessing a field of a `nil` ref will cause a runtime `npd` error?
Slices and maps aren't really that special. A map reference is just a type hmap struct internally and a slice reference is just a type slice struct internally, with a bit of syntactic sugar aliasing some of their methods. If you try to dereference a nil pointer normally then you'd end up with a panic — the same thing is happening here too, it's just that the panic comes from the standard library instead. len() is a bit of an exception as it has special behaviour to return 0 when the slice or map is nil, and the range keyword likely uses len() internally to know how many times to iterate (or to not iterate at all, in this case). More on reddit.com
🌐 r/golang
18
14
July 24, 2023
Access maps concurrently with range, any suggestions to make a better performance?
Whatever you do, ensure that you test and run your program with -race. Based on your description it sounds like it has data races. More on reddit.com
🌐 r/golang
22
10
September 4, 2023
🌐
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
🌐
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.
🌐
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 - Here we use three methods. The range keyword provides a simple and concise way to iterate over a map. Using keys and values, slices allows for more flexibility in handling keys and values separately.
Find elsewhere
🌐
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 - Range over function types is a new language feature in the Go 1.23 release. This blog post will explain why we are adding this new feature, what exactly it is, and how to use it. Since Go 1.18 we’ve had the ability to write new generic container types in Go. For example, let’s consider this very simple Set type, a generic type implemented on top of a map.
🌐
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.
🌐
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) } }
🌐
Medium
medium.com › @AlexanderObregon › go-map-iteration-behavior-e33dee785cb4
Go Map Iteration Behavior | Medium
November 6, 2025 - From the developer’s point of view, a for range loop over a map feels simple. Keys and values are handed back until the collection is exhausted. Beneath that, the runtime maintains a cursor that tracks which bucket and which slot is currently ...
🌐
YourBasic
yourbasic.org › golang › for-loop-range-array-slice-map-channel
4 basic range loop (for-each) patterns · YourBasic Go
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. m := map[string]int{ "one": 1, "two": 2, "three": 3, } for k, v := range m { fmt.Println(k, v) }
🌐
Golang Docs
golangdocs.com › home › golang – iterate over a map
Golang - Iterate over a map - Golang Docs
August 19, 2022 - package main import ( "fmt" ) func main() { // Allocate memory for the map var myMap = make(map[int]string) myMap[0] = "test" myMap[2] = "sample" myMap[1] = "Golang is Fun!" // Iterate over all keys for key, val := range myMap { fmt.Printf("Key: %d, Value: %s\n", key, val) } } Sample Output ·
🌐
Google Groups
groups.google.com › g › golang-nuts › c › 2AIAMD1WM38
Modifying a map while ranging over it
That is, if goroutine 1 is ranging ... 1. That behaviour is the unspecified behaviour. If you're modifying a map while iterating over it in another goroutine the behaviour of the entire program from then on is undefined. See http://golang.org/ref/mem ......
🌐
Reddit
reddit.com › r/learnprogramming › golang: range over slice or map
r/learnprogramming on Reddit: golang: range over slice or map
May 26, 2023 -

I want to range over either a map or slice:

package main  
import (  
	"fmt"  
)  
func f(t any) {  
	switch m := t.(type) {  
	case map[string]int, []int:  
		for k, v := range m {  
			fmt.Println(k, v)  
		}  
	default:  
	}  
}  
func main() {  
	f([]int{1, 2, 3})  
	f(map[string]int{"bob": 5})  
}  

but fails with this error:

cannot range over m (variable of type any)

if I change as follows:

package main

import (
	"fmt"
)

func f(t any) {
	switch m := t.(type) {
	case []int:
		for k, v := range m {
			fmt.Println(k, v)
		}
	case map[string]int:
		for k, v := range m {
			fmt.Println(k, v)
		}
	default:

	}
}

func main() {
	f([]int{1, 2, 3})
	f(map[string]int{"bob": 5})
}

it works but it has 2 case clauses. why doesn't it work with just 1 case clause ?

🌐
TutorialsPoint
tutorialspoint.com › go › go_range.htm
Go - Range
The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns ...
Top answer
1 of 3
14
Slices and maps aren't really that special. A map reference is just a type hmap struct internally and a slice reference is just a type slice struct internally, with a bit of syntactic sugar aliasing some of their methods. If you try to dereference a nil pointer normally then you'd end up with a panic — the same thing is happening here too, it's just that the panic comes from the standard library instead. len() is a bit of an exception as it has special behaviour to return 0 when the slice or map is nil, and the range keyword likely uses len() internally to know how many times to iterate (or to not iterate at all, in this case).
2 of 3
2
There is an additional consideration not yet mentioned, which is the choice of Go to have zero values that provide a default. Consider x := map[int]int{1: 2}. x[1] will of course yield 2. But x[10] does not yield a panic; it yields the default value for int, 0. If a map yields values for non-existent values, then var y map[int]int can be treated as a map that has no values in it, so y[10] can also yield 0. A nil map only needs to fail when you try to write to it because there is nowhere to write to. Combined with the fact that Go always knows the type of things, including the types of all nil pointers you have, it means that Go can and generally does take the type information alone to do sensible things in accordance with its zero-value default policy. It is all consistent. You may quibble with the details; I'm particularly not sure I love maps being populated with all possible keys when fetching things from them, so I'm not even sure I'm 100% comfortable myself even after all the programming I've done in Go. Almost all of my map accesses are the two-value form that tell me if the value is present, too. But it is certainly consistent once you understand that all the values are always typed so even nils can still make decisions based on type alone, and that default values are always available through the zero value.
🌐
ZetCode
zetcode.com › golang › range
Using Range in Go
$ go run map_range.go de => Germany it => Italy sk => Slovakia ---------------------- de => Germany it => Italy sk => Slovakia · The following example uses range to iterate over a Go string.
🌐
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.