Home >Backend Development >Golang >How to Iterate Over Integer Ranges in Go?
Iterating Over Integer Ranges in Go
The Go language provides the range keyword to iterate over maps and slices. This powerful feature enables developers to efficiently traverse collections. However, what if you need to iterate over a range of integers?
Go's Recent Solution (Go 1.22 and Above)
As of Go 1.22, Go introduced an elegant solution to iterate over integer ranges:
for i := range 10 { fmt.Println(i + 1) }
This syntax iterates over integers from 0 to 9. Note that it excludes the value equal to the integer specified (in this case, 10).
Pre-Go 1.22 Solution: Idiomatic For Loop
For versions of Go before 1.22, the established approach is to use a traditional for loop:
for i := 1; i <= 10; i++ { fmt.Println(i) }
This loop iterates over the integers from 1 to 10, inclusive.
The above is the detailed content of How to Iterate Over Integer Ranges in Go?. For more information, please follow other related articles on the PHP Chinese website!