Generate array with with range of integers

2019-09-13 02:55发布

问题:

I have two values:

[3:6]

I was trying to play something around in Golang but I can't manage to find a good method to create an array according to those values.

This what I would like to achieve:

[3,4,5,6]

回答1:

You can make use of the for ... range construct to make it more compact and maybe even faster:

lo, hi := 3, 6
s := make([]int, hi-lo+1)
for i := range s {
    s[i] = i + lo
}

As a matter of curiosity, the loop can be implemented without a loop variable, but it will be slower, and the code longer. By decrementing hi:

for ; hi >= lo; hi-- {
    s[hi-len(s)+1] = hi
}

Or incrementing lo:

for ; lo <= hi; lo++ {
    s[len(s)-1-hi+lo] = lo
}