How to Iterate Over a Range of Integers in Golang

To iterate over a range of integers in Go, you can use a “for loop” or “range construct”. 

Using for loop to iterate over a range of integers

package main

import (
  "fmt"
)

func main() {
  start := 1
  end := 5

  for i := start; i <= end; i++ {
    fmt.Println(i)
  }
}

Output

1
2
3
4
5

In this example, we use a for loop to iterate over a range of integers from start (1) to end (5) inclusive.

The range clause allows you to loop through the range of integers using the loop variable as the current integer value.

Alternatively, you can use the “range construct” and range over an initialized empty slice of integers.

Using range construct to io iterate an empty slice of integers

package main

import (
  "fmt"
)

func main() {
  for i := range [10]int{} {
    fmt.Println(i)
  }
}

Output

0
1
2
3
4
5
6
7
8
9

That’s it.