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.
Syntax
The basic syntax for a for-range loop is:
for index, value := range mydatastructure {
fmt.Println(value)
}
indexis the index of the value we are accessing.valueis the actual value we have on each iteration.mydatastructureholds 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 mainimport "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 mainimport "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 mainimport "fmt"func main() {mychannel := make(chan int)go func() {mychannel <- 1mychannel <- 2mychannel <- 3close(mychannel)}()for n := range mychannel {fmt.Println(n)}}
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved