range
range walks a string, array, slice, map, or channel (and, since Go 1.22, integer counts). Each iteration yields an index or key and a copy of the element, or a received value.
Detailed Explanation
You have a slice of user IDs and you want each one. for i := 0; i < len(ids); i++ works. for i, id := range ids says the same thing with less arithmetic and no chance of a wrong bound. range is the loop you write unless you need to step by two, walk backward, or mutate through an index on purpose.
What you get depends on the type.
| Range over | First value | Second value |
|---|---|---|
| slice, array | index | copy of element |
| string | byte index | rune |
| map | key | copy of value |
| channel | received value | (one variable only) |
integer n (Go 1.22+) | 0..n-1 | — |
The second value is a copy. for _, u := range users { u.Name = "x" } does not change users. You need for i := range users { users[i].Name = "x" } or a slice of pointers.
Maps are unordered. Each range over a map visits every key once, in a different order each time. Do not depend on the sequence. If you need a stable print, collect the keys and sort them.
Strings yield runes. for i, r := range s steps by UTF-8 sequence. i is the byte index of the rune, not a rune count. For raw bytes, range []byte(s) or index s[i].
Channels. for v := range ch receives until ch is closed and empty. If nobody closes the channel, the loop blocks forever. Ranging a nil channel blocks forever as well.
Skipping values. _ discards. for _, v := range s when you do not need the index. for i := range s when you do not need the copy — and this form does not copy the element, which matters for large structs.
What it costs. Ranging a slice is a tight loop plus a copy of each element into the iteration variable. For a large struct, for i := range s plus s[i] avoids that copy. Ranging a string decodes UTF-8. Ranging a map pays hash iteration; the randomization is a feature against you depending on order.
Code Examples
package main
import "fmt"
func main() {
ids := []int{10, 20, 30}
for i, id := range ids {
fmt.Println(i, id)
}
for i, r := range "Go€" {
fmt.Printf("%d %q\n", i, r)
}
}func rename(users []User) {
// Wrong: u is a copy.
for _, u := range users {
u.Name = "anon"
}
// Right: index into the slice.
for i := range users {
users[i].Name = "anon"
}
}
type User struct{ Name string }func drain(ch <-chan int) []int {
var out []int
for v := range ch { // ends when ch is closed
out = append(out, v)
}
return out
}Common Gotchas
The element is a copy
mutating the range variable does not mutate the slice, array, or map entry.
Map iteration order is randomized
tests that expect a fixed key order will flake.
Ranging a nil channel blocks forever
same as receiving from a nil channel. Close a channel only from the sending side when you mean the range to end.