Is there a way to iterate over a range of integers?

go
Vishnu picture Vishnu · Feb 22, 2014 · Viewed 148.3k times · Source

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:

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?

Answer

Paul Hankin picture Paul Hankin · Feb 22, 2014

You can, and should, just write a for loop. Simple, obvious code is the Go way.

for i := 1; i <= 10; i++ {
    fmt.Println(i)
}