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

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

问题描述

文档没有说明如何和教程完全忽略 for 循环.

The documentation doesn't say how and the tutorial completely ignores for loops.

推荐答案

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

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

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