FAQ
I'm trying to build a list of consecutive numbers.

In python I could do range(5) to give me [0, 1, 2, 3, 4, 5]

I couldn't find a 'built-in' way to do it in go so I wrote a function to do
it for me. Is this the right approach?

My function looks like this:
func rangeNumber(start, end int) []int {
s := []int{}
for i := start; i < end; i++ {
s = append(s,i)
}
return s
}


--

Search Discussions

  • Rob Pike at Oct 14, 2012 at 7:47 pm
    allocate once.

    func rangeNumber(start, end int) []int {
    s := make([]int, end-start)
    for i := range s {
    s[i] = start + i
    }
    return s
    }

    --
  • Miki Tebeka at Oct 15, 2012 at 3:24 am
    I'm trying to build a list of consecutive numbers.
    Apart from Matty's reply, if you just want a range of numbers to iterate
    over - you can use a channel:

    func irange(start, end int) chan int {
    c := make(chan int)

    go func() {
    for start <= end {
    c <- start
    start ++
    }
    close(c)
    }()

    return c
    }

    ...
    for i := range(irange(0, 10)) {
    fmt.Println(i)
    }

    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedOct 14, '12 at 7:43p
activeOct 15, '12 at 3:24a
posts3
users3
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase