Ranges
suggest changefor ... range is the loop you use most in Go. It walks over the elements of a collection and gives you one or two values per iteration.
The basics are simple, but range has rules that are easy to get wrong: the values are copies, the range expression is evaluated only once, maps are iterated in random order, and since Go 1.22 each iteration has its own loop variables.
This article covers all forms of range and the rules behind them. For a quick introduction to the basic forms see range statement.
What you can range over
| range expression | 1st value | 2nd value |
|---|---|---|
integer n |
index 0 to n-1 |
- |
| string | byte index | rune |
| array, pointer to array, slice | index | element |
| map | key | value |
| channel | element | - |
func(yield func() bool) |
- | - |
func(yield func(V) bool) |
V |
- |
func(yield func(K, V) bool) |
K |
V |
You can omit the values you don't need:
package main
import "fmt"
func main() {
s := []string{"a", "b", "c"}
// index and element
for i, v := range s {
fmt.Print(i, "=", v, " ")
}
fmt.Println()
// only index
for i := range s {
fmt.Print(i, " ")
}
fmt.Println()
// only element: use _ for the index
for _, v := range s {
fmt.Print(v, " ")
}
fmt.Println()
// no values: just repeat len(s) times
n := 0
for range s {
n++
}
fmt.Println("iterations:", n)
}
0=a 1=b 2=c
0 1 2
a b c
iterations: 3
Go doesn't allow unused variables, so for i, v := range s where v is not used is a compile error. Use for i := range s instead.
Range over an integer
Since Go 1.22 you can range over an integer. for i := range n runs n times with i going from 0 to n-1:
package main
import "fmt"
func main() {
for i := range 5 {
fmt.Print(i, " ")
}
fmt.Println()
// same as the classic 3-clause loop
for i := 0; i < 5; i++ {
fmt.Print(i, " ")
}
fmt.Println()
// when you don't need the index
for range 3 {
fmt.Print("hip ")
}
fmt.Println("hooray!")
// zero or negative n: the body doesn't run
for i := range -2 {
fmt.Println("never printed", i)
}
}
0 1 2 3 4
0 1 2 3 4
hip hip hip hooray!
The type of i is the type of n. With an untyped constant like 5 it's int. With a value of a named integer type, i has that type, which is handy for enum-like types:
package main
import "fmt"
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
numWeekdays // not a real day, the count of days
)
var names = [...]string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
func (d Weekday) String() string { return names[d] }
func main() {
for d := range numWeekdays {
// d is Weekday, so fmt calls its String method
fmt.Printf("%d:%v ", int(d), d)
}
fmt.Println()
var n uint8 = 3
for i := range n {
fmt.Printf("%T ", i)
}
fmt.Println()
}
0:Sun 1:Mon 2:Tue 3:Wed 4:Thu 5:Fri 6:Sat
uint8 uint8 uint8
Use range n when you count from 0 up with step 1. For any other pattern (counting down, step 2, starting at 1) use the 3-clause for loop.
Arrays, slices and pointers to arrays
For arrays and slices range gives you the index and a copy of the element. You can also range over a pointer to an array:
package main
import "fmt"
func main() {
arr := [3]string{"x", "y", "z"}
for i, v := range arr {
fmt.Print(i, ":", v, " ")
}
fmt.Println()
p := &arr
for i, v := range p {
fmt.Print(i, ":", v, " ")
}
fmt.Println()
// the number of iterations of an array is known at compile time,
// a nil pointer to an array is fine if you only use the index
var np *[4]int
for i := range np {
fmt.Print(i, " ")
}
fmt.Println()
}
0:x 1:y 2:z
0:x 1:y 2:z
0 1 2 3
The element is a copy
The second value is a copy of the element. Changing it doesn't change the slice:
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
for _, v := range nums {
v *= 10 // changes the copy only
}
fmt.Println("after v *= 10:", nums)
for i := range nums {
nums[i] *= 10 // changes the element in the slice
}
fmt.Println("after nums[i] *= 10:", nums)
}
after v *= 10: [1 2 3]
after nums[i] *= 10: [10 20 30]
This matters most for slices of structs. To modify a struct in place, index into the slice or take a pointer to the element:
package main
import "fmt"
type User struct {
Name string
Active bool
}
func main() {
users := []User{{Name: "alice"}, {Name: "bob"}}
for _, u := range users {
u.Active = true // modifies a copy, lost after this iteration
}
fmt.Println(users)
for i := range users {
users[i].Active = true
}
fmt.Println(users)
for i := range users {
u := &users[i] // pointer to the element in the slice
u.Name = "user " + u.Name
}
fmt.Println(users)
}
[{alice false} {bob false}]
[{alice true} {bob true}]
[{user alice true} {user bob true}]
Copying also costs time. Ranging over []BigStruct with for _, v := range copies every struct. For large structs, for i := range s and using s[i] avoids the copy. If the slice holds pointers ([]*User), v is a copy of the pointer, and modifying v.Active does change the shared struct.
The range expression is evaluated once
The expression after range is evaluated once, before the loop starts. For slices, this means the length is fixed at the start. Appending inside the loop doesn't make the loop run longer:
package main
import "fmt"
func main() {
s := []int{1, 2, 3}
for i, v := range s {
s = append(s, v*10)
fmt.Println("i:", i, "v:", v, "len(s):", len(s))
}
fmt.Println(s)
}
i: 0 v: 1 len(s): 4
i: 1 v: 2 len(s): 5
i: 2 v: 3 len(s): 6
[1 2 3 10 20 30]
Without this rule the loop above would never end.
The loop works on a copy of the slice header (pointer, length, capacity), not on a copy of the elements. Changes to elements that the loop hasn't reached yet are visible:
package main
import "fmt"
func main() {
s := []int{1, 2, 3, 4}
for i, v := range s {
if i == 0 {
s[2] = 300 // the loop sees this change
}
fmt.Print(v, " ")
}
fmt.Println()
// shrinking the slice doesn't shorten the loop either
s = []int{1, 2, 3, 4}
for i, v := range s {
if i == 0 {
s = s[:1]
}
fmt.Print(v, " ")
}
fmt.Println("len(s):", len(s))
}
1 2 300 4
1 2 3 4 len(s): 1
Arrays behave differently. When you use the second value, range over an array iterates over a copy of the whole array, so changes made during the loop are not visible. Range over a pointer to the array (or a slice of it) to see them:
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
for i, v := range arr { // iterates over a copy of arr
if i == 0 {
arr[2] = 300
}
fmt.Print(v, " ")
}
fmt.Println("arr:", arr)
arr = [3]int{1, 2, 3}
for i, v := range &arr { // no copy
if i == 0 {
arr[2] = 300
}
fmt.Print(v, " ")
}
fmt.Println("arr:", arr)
}
1 2 3 arr: [1 2 300]
1 2 300 arr: [1 2 300]
Copying a large array is also slow, which is another reason to range over &arr or arr[:].
Each iteration has its own variables
Since Go 1.22, variables declared by for (both in range loops and 3-clause loops) are created anew for every iteration. A closure or a goroutine that captures i or v sees the value from its own iteration:
package main
import (
"fmt"
"sync"
)
func main() {
var funcs []func()
for i, v := range []string{"a", "b", "c"} {
funcs = append(funcs, func() { fmt.Print(i, v, " ") })
}
for _, f := range funcs {
f()
}
fmt.Println()
var ptrs []*int
for i := range 3 {
ptrs = append(ptrs, &i) // a different i every iteration
}
for _, p := range ptrs {
fmt.Print(*p, " ")
}
fmt.Println()
var wg sync.WaitGroup
results := make([]int, 3)
for i := range 3 {
wg.Go(func() {
results[i] = i * i // safe: each goroutine has its own i
})
}
wg.Wait()
fmt.Println(results)
}
0a 1b 2c
0 1 2
[0 1 4]
wg.Go was added in Go 1.25. See Wait for goroutines to finish for more about sync.WaitGroup.
Before Go 1.22 there was only one i and one v for the whole loop. All closures shared them and saw the last value. Which semantics you get depends on the go line in go.mod, not on the compiler version. You can see the old behavior by setting the language version of a single file with a build constraint:
//go:build go1.21
package main
import "fmt"
func main() {
var funcs []func()
for i, v := range []string{"a", "b", "c"} {
funcs = append(funcs, func() { fmt.Print(i, v, " ") })
}
for _, f := range funcs {
f()
}
fmt.Println()
}
2c 2c 2c
In old code you will often see v := v inside a loop. It made a per-iteration copy. In modules with go 1.22 or later it's not needed and can be removed.
Maps
Map iteration order is not specified, and the runtime deliberately randomizes it. Running the same loop twice can give different orders:
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
for range 3 {
for k := range m {
fmt.Print(k, " ")
}
fmt.Println()
}
// for a stable order, sort the keys
for _, k := range slices.Sorted(maps.Keys(m)) {
fmt.Print(k, "=", m[k], " ")
}
fmt.Println()
}
a b c d e
a b c d e
a b c d e
a=1 b=2 c=3 d=4 e=5
The first three lines will be different every time you run the program. maps.Keys returns an iterator and slices.Sorted collects it into a sorted slice. See Sorting for more about sorting.
Changing a map while ranging over it is allowed, with these rules:
- deleting an entry that hasn't been reached yet means it won't be produced
- deleting the current entry (or any entry) is safe
- an entry added during iteration may or may not be produced
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
// delete entries while iterating: safe
for k, v := range m {
if v%2 == 0 {
delete(m, k)
}
}
fmt.Println(slices.Sorted(maps.Keys(m)))
// maps.DeleteFunc does the same
m2 := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
maps.DeleteFunc(m2, func(k string, v int) bool { return v%2 == 1 })
fmt.Println(slices.Sorted(maps.Keys(m2)))
}
[a c]
[b d]
Because entries added during iteration may or may not show up, don't add to a map you are ranging over. Build a new map, or collect the changes and apply them after the loop.
The map value is a copy, just like a slice element. To change a field of a struct stored in a map you must write the whole value back: u := m[k]; u.Active = true; m[k] = u.
Strings
range over a string decodes UTF-8. The first value is the byte index where the rune starts, the second is the rune. An invalid byte produces utf8.RuneError (U+FFFD) and advances by one byte:
package main
import "fmt"
func main() {
s := "añ€😀"
for i, r := range s {
fmt.Printf("%d: %c U+%04X\n", i, r, r)
}
fmt.Println("len(s):", len(s), "bytes")
bad := "a\xffb"
for i, r := range bad {
fmt.Printf("%d: %q U+%04X\n", i, r, r)
}
}
0: a U+0061
1: ñ U+00F1
3: € U+20AC
6: 😀 U+1F600
len(s): 10 bytes
0: 'a' U+0061
1: '�' U+FFFD
2: 'b' U+0062
To iterate over bytes, use a 3-clause loop with s[i], or range []byte(s). See range over a string for details.
Channels
range over a channel receives values until the channel is closed and drained. There is only one iteration variable:
package main
import "fmt"
func main() {
ch := make(chan int, 3)
go func() {
for i := range 3 {
ch <- i * i
}
close(ch) // without close the loop below never ends
}()
for v := range ch {
fmt.Print(v, " ")
}
fmt.Println("done")
}
0 1 4 done
Ranging over a nil channel blocks forever. See range over a channel.
Functions (iterators)
Since Go 1.23 you can range over functions of the form func(yield func(...) bool). The standard library has many of them:
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
s := []string{"a", "b", "c", "d", "e"}
// backwards, with indexes
for i, v := range slices.Backward(s) {
fmt.Print(i, v, " ")
}
fmt.Println()
// in chunks of 2
for chunk := range slices.Chunk(s, 2) {
fmt.Print(chunk, " ")
}
fmt.Println()
// split a string without allocating a slice of parts (Go 1.24)
for part := range strings.SplitSeq("a,b,c", ",") {
fmt.Print(part, " ")
}
fmt.Println()
// lines, including the trailing "\n" (Go 1.24)
for line := range strings.Lines("one\ntwo\n") {
fmt.Printf("%q ", line)
}
fmt.Println()
}
4e 3d 2c 1b 0a
[a b] [c d] [e]
a b c
"one\n" "two\n"
Writing your own iterator takes a few lines:
package main
import (
"fmt"
"iter"
)
// Evens yields even numbers from start up to and including end.
func Evens(start, end int) iter.Seq[int] {
return func(yield func(int) bool) {
if start%2 != 0 {
start++
}
for i := start; i <= end; i += 2 {
if !yield(i) { // false: the loop ended early
return
}
}
}
}
func main() {
for n := range Evens(3, 12) {
if n > 9 {
break
}
fmt.Print(n, " ")
}
fmt.Println()
}
4 6 8
See Iterators and range over functions for the full story.
nil and empty collections
Ranging over a nil slice, an empty slice, a nil map or an empty string runs zero iterations. You don't need to check for nil first:
package main
import "fmt"
func main() {
var s []int
var m map[string]int
var str string
for range s {
fmt.Println("never")
}
for range m {
fmt.Println("never")
}
for range str {
fmt.Println("never")
}
fmt.Println("len:", len(s), len(m), len(str))
defer func() {
fmt.Println("recovered:", recover())
}()
var f func(func(int) bool)
for v := range f { // calls f, which is nil
fmt.Println(v)
}
}
len: 0 0 0
recovered: runtime error: invalid memory address or nil pointer dereference
The exceptions are a nil channel, which blocks forever, and a nil function, which panics.
Assigning to existing variables
for i, v := range declares new variables that exist only inside the loop. With = instead of :=, range assigns to variables declared before the loop, and their values are still there after the loop ends:
package main
import "fmt"
func main() {
words := []string{"go", "rust", "zig", "odin"}
var i int
var w string
for i, w = range words {
if len(w) > 3 {
break
}
}
fmt.Println("first long word:", i, w)
}
first long word: 1 rust
This form is rare. A function that returns from inside the loop, or slices.IndexFunc, is usually clearer.
break and continue with labels
break and continue apply to the innermost for, switch or select. To break out of an outer loop, or out of a loop from inside a switch, use a label:
package main
import "fmt"
func main() {
grid := [][]int{
{1, 2, 3},
{4, -5, 6},
{7, 8, 9},
}
outer:
for r, row := range grid {
for c, v := range row {
if v < 0 {
fmt.Printf("negative %d at row %d col %d\n", v, r, c)
break outer
}
}
}
for _, v := range []int{1, 2, 3, 4, 5} {
switch {
case v == 2:
continue // continues the for loop: continue ignores switch
case v == 4:
break // only exits the switch
}
fmt.Print(v, " ")
}
fmt.Println()
}
negative -5 at row 1 col 1
1 3 4 5
See break and continue for more.
Things to keep in mind
- the element (or map value) you get is a copy; modify
s[i]orm[k], notv - the range expression is evaluated once: appending to a slice inside the loop doesn't extend the loop
- ranging over an array (not a pointer to it) with two variables copies the whole array
- map order is random; sort the keys when order matters
- deleting from a map while ranging over it is fine; adding is unpredictable
- since Go 1.22 every iteration has its own loop variables, so capturing them in closures and goroutines is safe; this depends on the
goversion ingo.mod range ncounts from0ton-1andihas the type ofnrangeover a string yields runes and byte indexes, not characters and character indexesnilslices, maps and strings give zero iterations; anilchannel blocks forever; anilfunction panics