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

  1. Copies: The element returned by range is a copy of the value in the slice. Modifying the element variable does not change the slice itself.
  2. 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.