0Pricing
Go Academy · Lesson

Iterating Collections with range

Using range over slices, maps and strings

What Is range?

range is a special form of the for loop that iterates over arrays, slices, maps, strings, and channels. It returns an index (or key) and a value on each iteration.

range Over a Slice

Returns the index and a copy of the element:

package main
import "fmt"

func main() {
    fruits := []string{"apple", "banana", "cherry"}
    for i, fruit := range fruits {
        fmt.Printf("%d: %s\n", i, fruit)
    }
}

All lessons in this course

  1. Arrays: Fixed-Length Collections
  2. Slices: Dynamic Lists
  3. Maps: Key-Value Stores
  4. Iterating Collections with range
← Back to Go Academy