有没有办法迭代一系列整数? [英] Is there a way to iterate over a range of integers?

查看:32
本文介绍了有没有办法迭代一系列整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go 的 range 可以迭代 map 和 slices,但我想知道是否有一种方法可以迭代一系列数字,如下所示:

Go's range can iterate over maps and slices, but I was wondering if there is a way to iterate over a range of numbers, something like this:

for i := range [1..10] {
    fmt.Println(i)
}

或者有没有一种方法可以在 Go 中表示整数范围,就像 Ruby 使用 类范围?

Or is there a way to represent range of integers in Go like how Ruby does with the class Range?

推荐答案

Go 的惯用方法是编写这样的 for 循环.

The idiomatic approach in Go is to write a for loop like this.

for i := 1; i <= 10; i++ {
    fmt.Println(i)
}

范围肯定有优势,并且它们在许多其他语言中都有使用,但是 Go 的设计原则是仅在收益显着超过成本(包括使语言变得更大的成本)时才引入抽象.合理的人不同意范围的成本和收益,但这个答案是我试图描述我认为惯用的围棋是什么.

There's definitely advantages in ranges and they're used in many other languages, but a Go design principle is to only introduce an abstraction if the benefits significantly outweigh the costs (including the cost of making the language larger). Reasonable people disagree about the costs and benefits of ranges, but this answer is my attempt to describe what I think idiomatic Go is.

这篇关于有没有办法迭代一系列整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆