go - 在一系列数字上模仿 Go 中的 Python 列表理解
问题描述
在 Python 中,我可以执行以下操作:
numbers = [i for i in range(5)]
这将导致:
>> [0, 1, 2, 3, 4]
我正在学习 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)
}
输出:
>> [0, 1, 2, 3, 4]
看起来很冗长,有没有更简单的方法可以在 Go 中实现这一点?我也喜欢在 python 中我可以让它更复杂一点
evens = [i for i in range(10) if i % 2 == 0]
>> [0, 2, 4, 5, 8]
这个问题与其说是如何让 Go 像 Python 一样工作,我想知道 Go 开发人员如何本机/自然地实现同样的事情。
解决方案
[我]有没有更简单的方法可以在 Go 中实现这一目标?
基本上没有。
您可以使用范围简化您的 for 循环,但就是这样。经验法则:围棋没有魔法。
推荐阅读
- android - 事件发生一分钟后如何执行firebase云功能?
- apache-kafka - 无法在 Windows 10 上启动 Kafka 服务器 - Kafka 的日志目录(和子目录)应该只包含 Kafka 主题数据
- arrays - 有没有办法使用 Cosmos DB 中的 SQL API 按字符串数组中的值进行过滤?
- reactjs - 如何在 reactjs Progressive Web App(Pwa) 中缓存 api 以添加离线支持?
- mysql - “如何获取表 B 中不存在于表 A 中的所有 ip_id”
- javascript - 带有资源查询的 css 文件的正则表达式
- laravel - 如何自定义 laravel 图表
- r - rmarkdown::render 在“knit to html”按钮运行时提示错误
- visual-studio-2010 - Visual Studio 在创建 .ipa 时挂起
- git - 提交失败后提交更新的 gitignore