dongwei2610
2016-10-05 07:37
浏览 780
已采纳

如何在Golang中生成数字序列?

I want to generate a sequence of numbers in Golang 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.

图片转代码服务由CSDN问答提供 功能建议

我想在Golang中生成一个数字序列,但是我找不到用于此的任何内置函数。
基本上,我希望在Golang中使用PHP的 range 函数的等效项:< / p>

 数组范围(混合$ start,混合$ end [,数字$ step = 1])
   
 
 

它 在创建数字类型的切片/数组并且您想用数字序列填充/初始化它时将非常有用。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dongshuan8722 2016-10-05 07:50
    最佳回答

    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]
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题