你如何在 Rust 中创建一个范围? [英] How do you make a range in 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.
如果您对 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 meanssptr
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屋!