Ranging Over Integers in Go
Go's range keyword efficiently iterates over data structures like maps and slices. However, can it be used to iterate over a range of integers?
Question:
Is it possible to iterate over a range of numbers in Go using a syntax similar to:
for i := range [1..10] { fmt.Println(i) }
Or is there a method like Ruby's Range class to represent ranges of integers?
Answer:
As of Go 1.22 (anticipated release in February 2024), you can achieve this using a simplified approach:
for i := range 10 { fmt.Println(i + 1) }
It's important to note that ranging over an integer in Go iterates from 0 to one less than that integer.
Prior to Go 1.22, the standard approach was to use a traditional for loop:
for i := 1; i <= 10; i++ { fmt.Println(i) }
This loop iterates from 1 to 10, inclusive.
The above is the detailed content of Can Go's `range` Keyword Iterate Over Integer Ranges?. For more information, please follow other related articles on the PHP Chinese website!