Keyword

Go range keyword

Iterates over an array, array pointer, slice, string, map, channel, integer or suitable iterator function, with the permitted variables depending on the operand. Map order is unspecified; strings yield byte offsets and runes. Integer iteration requires Go 1.22; function iteration Go 1.23. Example sums slice values.

Formal Syntax & Structure

go syntaxgo
for k, v := range operand { statements }

Working Example

Example Snippetgo
package main
import "fmt"
func main() {  sum := 0  for _, n := range []int{2, 4, 6} {    sum += n  }  fmt.Println(sum)}
Go Reference