且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何在 Rust 中创建一个范围?

更新时间:2023-01-08 09:34:33

从 1.0 开始,for 循环使用 Iterator trait.

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

本书在 第 3.5 章第 13.2 章.

如果您对 for 循环的运行方式感兴趣,请参阅 模块 std::iter.

If you are interested in how for loops operate, see the described syntactic sugar in Module std::iter.

例子:

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);
}

如果您需要数组中的索引和元素,惯用的方法是使用 Iterator::enumerate 方法:

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);
    }
}

注意事项:

  • 循环项是对迭代元素的借用引用.在这种情况下,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);
  }