Range over built in types
Context
Section titled “Context”The range keyword allows iteration over slices, arrays, maps, strings (runes), and channels. It returns one or two values depending on the type.
- Slices/arrays:
index, value - Maps:
key, value - Strings:
byte index, rune - Channels:
value(single parameter)
Example
Section titled “Example”Iterate over a slice, a map, and a string.
Code example
Section titled “Code example”package main
import "fmt"
func main() { // Slice nums := []int{2, 4, 6} for i, v := range nums { fmt.Printf("index=%d, value=%d\n", i, v) }
// Map colors := map[string]string{"red": "#FF0000", "green": "#00FF00"} for key, value := range colors { fmt.Printf("%s -> %s\n", key, value) }
// String (rune by rune) for pos, r := range "Hello, 世界" { fmt.Printf("%d: %c\n", pos, r) }}Output
Section titled “Output”index=0, value=2index=1, value=4index=2, value=6red -> #FF0000green -> #00FF000: H1: e2: l3: l4: o5: ,6:7: 世10: 界