๐ŸŽ“ A1Learner
๐Ÿ”

Go Range

The range keyword walks through the items of a slice or an array. Each run of the loop gives one index and one value.

Index and value

Range gives the index first and the value second. Both print on each run.

package main

import "fmt"

func main() {
	nums := []int{5, 10, 15}
	for i, v := range nums {
		fmt.Println(i, v)
	}
}

Value only

The blank identifier takes the index and throws it away. Only the values print.

package main

import "fmt"

func main() {
	fruits := []string{"fig", "plum", "pear"}
	for _, v := range fruits {
		fmt.Println(v)
	}
}

Range over a string

Range over a string gives byte positions. The values are rune values, so the letter G prints as 71.

package main

import "fmt"

func main() {
	for i, r := range "Go" {
		fmt.Println(i, r)
	}
}

Add an array with range

Range also walks an array. The loop adds each value to total.

package main

import "fmt"

func main() {
	nums := [4]int{3, 4, 5, 6}
	total := 0
	for _, v := range nums {
		total += v
	}
	fmt.Println(total)
}

Example

package main

import "fmt"

func main() {
	scores := []int{80, 90, 70}
	for i, v := range scores {
		fmt.Println("Score", i+1, "is", v)
	}
}

Key points

  • Range gives an index and a value on each run.
  • The blank identifier _ throws a value away on purpose.
  • Range over a string gives byte positions and rune values.
  • A range loop needs no counter and no end test.
  • Range visits items in order from the first item to the last.

In this example, scores holds three results. Range gives each index and value in turn. Adding 1 to the index turns the first position into 1. The print lines list each score beside its position.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What does the blank identifier _ do in a range loop?