用整数范围生成数组 [英] Generate array with with range of integers
本文介绍了用整数范围生成数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个值:
I have two values:
[3:6]
[3:6]
我试图在Golang中玩弄一些东西,但我无法找到一个好方法根据这些值创建一个数组。
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]
推荐答案
您可以使用 / code>构造使其更紧凑,甚至更快:
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
}
作为好奇心,循环可以在没有循环变量的情况下实现,但会更慢,代码更长。通过递减 hi
:
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
}
或递增 lo
:
Or incrementing lo
:
for ; lo <= hi; lo++ {
s[len(s)-1-hi+lo] = lo
}
这篇关于用整数范围生成数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文