How to generate a sequence of numbers

sepehr picture sepehr · Oct 5, 2016 · Viewed 26.4k times · Source

I want to generate a sequence of numbers in Go but I can't find any built-in functions for this.
Basically I want the equivalent of PHP's range function in Golang:

array range ( mixed $start , mixed $end [, number $step = 1 ] )

It would be useful when creating a slice/array of numeric types and you want to populate/initialize it with a numeric sequence.

Answer

icza picture icza · Oct 5, 2016

There is no equivalent to PHP's range in the Go standard library. You have to create one yourself. The simplest is to use a for loop:

func makeRange(min, max int) []int {
    a := make([]int, max-min+1)
    for i := range a {
        a[i] = min + i
    }
    return a
}

Using it:

a := makeRange(10, 20)
fmt.Println(a)

Output (try it on the Go Playground):

[10 11 12 13 14 15 16 17 18 19 20]

Also note that if the range is small, you can use a composite literal:

a := []int{1, 2, 3}
fmt.Println(a) // Output is [1 2 3]