模仿 Go 中的 Python 对一系列数字的列表理解

Ari*_*Ari 1 go

在Python中我可以做类似的事情:

numbers = [i for i in range(5)]
Run Code Online (Sandbox Code Playgroud)

这将导致:

>> [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我正在学习 Go,所以我想我应该尝试复制这个过程:

package main

import "fmt"

func inRange(num int) []int {
    // Make a slice to hold the number if int's specified
    output := make([]int, num)

    // For Loop to insert data
    for i := 0; i < num; i++ {
        output[i] = i
    }
    return output
}

func main() {
    x := inRange(10)
    fmt.Print(x)
}
Run Code Online (Sandbox Code Playgroud)

输出:

>> [0, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

看起来很冗长,有没有更简单的方法可以在 Go 中实现这一点?我也喜欢用 python 我可以让它变得更复杂一点

evens = [i for i in range(10) if i % 2 == 0]
>> [0, 2, 4, 5, 8]
Run Code Online (Sandbox Code Playgroud)

这个问题并不是如何让 Go 像 Python 一样工作,我想知道 Go 开发人员如何本机/自然地实现同样的事情。

Vol*_*ker 5

[I]有没有更简单的方法可以在 Go 中实现这一目标?

基本上没有。

您可以使用范围稍微简化 for 循环,但仅此而已。经验法则:Go 中没有魔法。

  • @zerkms:或者:“如果你想要Python,你知道在哪里可以找到它”?:-) (2认同)