Go Range
The range keyword is used to iterate over elements in a variety of data structures. It's Go's universal "for-each" loop.
1. Range over Slices
When ranging over a slice, it returns two values: the index and a copy of the element at that index.
2. Range over Maps
For maps, range iterates over key/value pairs.
3. Range over Strings
Ranging over a string iterates over Unicode code points (runes). The first value is the starting byte index of the rune, and the second is the rune itself.
Summary Table
| Data Structure | 1st Return Value | 2nd Return Value |
|---|---|---|
| Array/Slice | Index (int) |
Value (type) |
| Map | Key (type) |
Value (type) |
| String | Index (int) |
Rune (rune) |
| Channel | Value (type) |
(None) |