Range
The range keyword provides a clean way to iterate over the elements of a slice or array.
Syntax
for index, element := range mySlice {
fmt.Println(index, element)
}
Key Behaviors
- Copies: The
elementreturned byrangeis a copy of the value in the slice. Modifying theelementvariable does not change the slice itself. - Ignoring Values: If you don’t need the index or the element, you can use the blank identifier (
_).
// Ignore index
for _, val := range mySlice { ... }
// Ignore value
for i := range mySlice { ... }
Strings and Range
When you use range on a string, it iterates over runes (Unicode code points) rather than bytes.