Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 147 ยท Operators and Control Flow

Ranging Over Collections

Learn how Go's range clause iterates over slices, arrays, strings, maps, channels, integers and iterator functions, including copy semantics, random map order and modifying data while looping.

The range clause is how Go programs walk through almost everything: slices and arrays, strings, maps, channels, integers, and since Go 1.23 even functions. You write for key, value := range thing, and what key and value mean depends on what thing is.

Most range bugs come from the same few details: the value is a copy, the range expression is evaluated once, strings yield runes rather than bytes, and map order is random. This lesson covers each kind of range target, those pitfalls, and how to write your own iterators. It builds on for loops; slices, maps and strings have their own full lessons (Slices, Maps, Strings, Bytes and Runes), so we focus on iteration here.

Slices and arrays

For a slice or array, range yields the index and a copy of the element. Use the blank identifier _ to ignore one of them, or leave the second variable out to get just the index.

Go range over a slice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The value is a copy

The variable v in for _, v := range s holds a copy of each element. Assigning to it changes the copy only. To modify the slice, assign through the index. This matters most for slices of structs:

Go Modifying elements while ranging

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The range expression is evaluated once

Before the loop starts, Go evaluates the expression after range one time. For a slice, that fixes the length: appending inside the loop does not add iterations. For an array, Go iterates over a copy of the whole array when you also ask for the value, so changes made during the loop are not seen. A slice shares its elements, so changes are seen.

Go Evaluated once, arrays are copied

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output is [1 2 3 10 20 30], then array sees 3, then slice sees 100. If you want to avoid copying a large array, range over a slice of it (arr[:]) or over the index only.

Deleting elements while ranging over a slice by index is a classic source of bugs, because indexes shift. Build a new slice with the elements you keep, or use slices.DeleteFunc (see The slices and maps Packages).

Strings: runes, not bytes

A Go string is a sequence of bytes, usually UTF-8. Ranging over a string decodes it: each iteration yields the byte offset where a character starts and the rune (the Unicode code point). The offsets can jump by more than one because characters like รฉ or ไธ– take several bytes. Invalid UTF-8 produces the replacement rune U+FFFD for each bad byte.

Go range over a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The loop shows รฉ starting at offset 1 and l at offset 3, and ไธ– at 8 followed by ็•Œ at 11. The string has 14 bytes but only 9 runes. s[1] and s[2] print the two bytes (195 169) that together encode รฉ. Use range when you want characters; index when you really want bytes.

Maps: random order

Ranging over a map yields keys and values. The order is not specified and deliberately changes from run to run, so never depend on it. If you need a stable order, collect the keys, sort them, then look the values up.

Go Maps iterate in random order, so sort the keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You may delete entries while ranging over a map. If you add entries during the loop, the new ones may or may not show up in the iteration. Maps are not safe for concurrent use; see Maps. The maps and slices packages offer a shortcut for sorted keys: slices.Sorted(maps.Keys(m)).

Channels

For a channel, range receives values until the channel is closed. There is only one iteration variable. If nobody ever closes the channel, the loop waits forever. Channels are covered fully in Channels; here is a first taste:

Go range over a channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Integers

Go 1.22 added range over integers: for i := range 5 yields 0 to 4. It accepts only one iteration variable, so asking for two is an error:

Go Two variables over an integer (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler output is:

TEXT
./main.go:6:9: range over 3 (untyped int constant) permits only one iteration variable

Functions: range over iterators (Go 1.23)

Since Go 1.23 you can range over a function that follows the push iterator shape. The function receives a yield callback and calls it once per value; if yield returns false, the loop body executed break (or returned), and the iterator must stop. The standard iter package names the two shapes: iter.Seq[V] yields single values, iter.Seq2[K, V] yields pairs.

Go Writing and ranging over iterators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Iterators let a collection decide how it is walked (a tree in order, lines of a file, pages of an API) while the caller keeps a plain for loop. Iterators: range over Functions builds them in depth, including iter.Pull.

Which loop variables you get

Range over First variable Second variable
slice, array, pointer to array index element copy
string byte offset rune
map key value
channel element not allowed
integer n 0 to n-1 not allowed
iter.Seq[V] function V not allowed
iter.Seq2[K, V] function K V

In every form you can leave out both variables (for range x) when you only need the repetition count.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the first variable hold in for a, b := range "hi"?

    Ranging over a string yields byte offsets and runes. For multi-byte characters the offsets skip ahead.
  2. 2. After for _, v := range nums { v *= 2 } where nums := []int{1, 2, 3}, what is nums?

    v is a copy of each element, so changing it does not modify the slice. Use nums[i] *= 2 with the index.
  3. 3. What is the length of s after s := []int{1, 2}; for range s { s = append(s, 0) }?

    The range expression is evaluated once, so the loop runs exactly twice (the original length), appending two elements.
  4. 4. How do you print the entries of a map in alphabetical key order?

    Map iteration order is random. Sort the keys (for example with slices.Sorted(maps.Keys(m))) to get a stable order.
  5. 5. When does for v := range ch stop, where ch is a channel?

    range receives until the channel is closed. If nobody closes it, the loop blocks forever once the values run out.

Summary

  • range works on slices, arrays, strings, maps, channels, integers (Go 1.22) and iterator functions (Go 1.23).
  • Slices and arrays yield an index and a copy of each element; modify through the index.
  • The range expression is evaluated once; appending does not add iterations, and an array is copied for the loop.
  • Strings yield byte offsets and runes; maps yield keys and values in random order.
  • Ranging over a channel ends when the channel is closed.
  • iter.Seq and iter.Seq2 functions call yield for each value and must stop when yield returns false.

Next: Labels, break, continue and goto