如何循环某些(可变)次数?

时间:2019-05-03 07:30:45

标签: for-loop rust iterator integer

这个问题似乎非常基础,但是我很难弄清楚该怎么做。我有一个整数,我需要使用for循环来循环整数次。

首先,我尝试-

fn main() {
    let number = 10; // Any value is ok
    for num in number {
        println!("success");
    }
}

这将显示错误

error[E0277]: `{integer}` is not an iterator
 --> src/main.rs:3:16
  |
3 |     for num in number{
  |                ^^^^^^ `{integer}` is not an iterator
  |
  = help: the trait `std::iter::Iterator` is not implemented for `{integer}`
  = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end`
  = note: required by `std::iter::IntoIterator::into_iter`

接下来,我尝试-

fn main() {
    let number = 10; // Any value is ok
    for num in number.iter() {
        println!("success");
    }
}

编译器说没有整数迭代方法

error[E0599]: no method named `iter` found for type `{integer}` in the current scope
 --> src/main.rs:3:23
  |
3 |     for num in number.iter() {
  |                       ^^^^

我应该怎么做?

1 个答案:

答案 0 :(得分:0)

这是因为您正在向编译器说num中包含的number,其中number不是迭代器,也不实现iter,而不是实现range num中的0..number是迭代器。

文档将for循环描述为:

for loop_variable in iterator {
    code()
}

将代码更改为:

fn main() {
    let number = 10; 
    for num in 0..number { // change it to get range
        println!("success");
    }
}

您也可以将其更改为:

fn main() {
    let number = 10; 
    for num in 1..=number { // inclusive range
        println!("success");
    }
}

或:

fn main() {
    let number = 10; 
    for _ in 0..number { // where _ is a "throw away" variable
        println!("success");
    }
}

另请参见for documentation