patterngoCritical
Is there a way to iterate over a range of integers?
Viewed 0 times
overiterateintegerswayrangethere
Problem
Go's range can iterate over maps and slices, but I was wondering if there is a way to iterate over a range of numbers, something like this:
Or is there a way to represent range of integers in Go like how Ruby does with the class Range?
for i := range [1..10] {
fmt.Println(i)
}Or is there a way to represent range of integers in Go like how Ruby does with the class Range?
Solution
From Go 1.22 (expected release February 2024), you will be able to write:
(ranging over an integer in Go iterates from 0 to one less than that integer).
For versions of Go before 1.22, the idiomatic approach is to write a for loop like this.
for i := range 10 {
fmt.Println(i+1)
}(ranging over an integer in Go iterates from 0 to one less than that integer).
For versions of Go before 1.22, the idiomatic approach is to write a for loop like this.
for i := 1; i <= 10; i++ {
fmt.Println(i)
}Code Snippets
for i := range 10 {
fmt.Println(i+1)
}for i := 1; i <= 10; i++ {
fmt.Println(i)
}Context
Stack Overflow Q#21950244, score: 462
Revisions (0)
No revisions yet.