如何使用自定义步骤迭代范围? [英] How do I iterate over a range with a custom step?

查看:59
本文介绍了如何使用自定义步骤迭代范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Rust 中使用 1 以外的步长迭代一个范围?我来自 C++ 背景,所以我想做类似的事情

How can I iterate over a range in Rust with a step other than 1? I'm coming from a C++ background so I'd like to do something like

for(auto i = 0; i <= n; i+=2) {
    //...
}

在 Rust 中,我需要使用 range 函数,而且似乎没有第三个参数可用于自定义步骤.我怎样才能做到这一点?

In Rust I need to use the range function, and it doesn't seem like there is a third argument available for having a custom step. How can I accomplish this?

推荐答案

range_step_inclusiverange_step 早已不复存在.

range_step_inclusive and range_step are long gone.

从 Rust 1.28 开始,迭代器::step_by 稳定:

As of Rust 1.28, Iterator::step_by is stable:

fn main() {
    for x in (1..10).step_by(2) {
        println!("{}", x);
    }
}

这篇关于如何使用自定义步骤迭代范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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