您如何在Rust中创建范围? [英] How do you make a range in Rust?
问题描述
文档没有说明如何使用,本教程完全忽略了for循环.
The docs don't say how, and the tutorial completely ignores for loops.
推荐答案
As of 1.0, for loops work with values of types with the Iterator
trait.
如果您对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 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屋!