您如何在Rust中创建范围? [英] How do you make a range in Rust?

查看:388
本文介绍了您如何在Rust中创建范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档没有说明如何使用,本教程完全忽略了for循环.

The docs don't say how, and the tutorial completely ignores for loops.

推荐答案

从1.0开始,for循环使用

As of 1.0, for loops work with values of types with the Iterator trait.

这本书在第3.5章第13.2章.

如果您对for循环的操作方式感兴趣,请参见此处描述的语法糖:

If you are interested in how for loops operate, see the described syntactic sugar here:

http://doc.rust-lang.org/std/iter/index.html

示例:

fn main() {
    let strs = ["red", "green", "blue"];

    for sptr in strs.iter() {
        println!("{}", sptr);
    }
}

(游乐场)

如果只想遍历一个数字范围,例如在C的for循环中,则可以使用a..b语法创建一个数字范围:

If you just want to iterate over a range of numbers, as in C's for loops, you can create a numeric range with the a..b syntax:

for i in 0..3 {
    println!("{}", i);
}

如果需要索引和数组中的元素,则使用

If you need both, the index and the element from an array, the idiomatic way to get that is with the Iterator::enumerate method:

fn main() {
    let strs = ["red", "green", "blue"];

    for (i, s) in strs.iter().enumerate() {
        println!("String #{} is {}", i, s);
    }
}

注意:

  • 循环项是对iteratee元素的借用引用.在这种情况下,strs的元素的类型为&'static str-它们是借用的指向静态字符串的指针.这意味着sptr具有类型&&'static str,因此我们将其取消引用为*sptr.我更喜欢的另一种形式是:

  • The loop items are borrowed references to the iteratee elements. In this case, the elements of strs have type &'static str - they are borrowed pointers to static strings. This means sptr has type &&'static str so we dereference it as *sptr. An alternative form which I prefer is:

for &s in strs.iter() {
    println!("{}", s);
}

这篇关于您如何在Rust中创建范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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