What is the for-range loop in Golang?

A for loop is used to iterate over elements in a variety of data structures (e.g., a slice, an array, a map, or a string).

The for statement supports one additional form that uses the keyword range to iterate over an expression that evaluates to an array, slice, map, string, or channel.

svg viewer

Syntax

The basic syntax for a for-range loop is:

for index, value := range mydatastructure {
		fmt.Println(value)
	}
  • index is the index of the value we are accessing.
  • value is the actual value we have on each iteration.
  • mydatastructure holds the data structure whose values will be accessed in the loop.

Note that the above example is highly generalized. The case-by-case examples given below will help you understand the syntax further.​

Code

1. Iterating over a string

The for-range loop can be used to access individual characters in a string.

package main
import "fmt"
func main() {
for i, ch := range "World" {
fmt.Printf("%#U starts at byte position %d\n", ch, i)
}
}

2. Iterating over a map

The for-range loop can be used to access individual key-value pairs in a map.

package main
import "fmt"
func main() {
m := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
for key, value := range m {
fmt.Println(key, value)
}
}

3. Iterating over channels

For channels, the iteration values are the successive values sent on the channel until its close.

package main
import "fmt"
func main() {
mychannel := make(chan int)
go func() {
mychannel <- 1
mychannel <- 2
mychannel <- 3
close(mychannel)
}()
for n := range mychannel {
fmt.Println(n)
}
}

Copyright ©2024 Educative, Inc. All rights reserved