Search code examples
for-looprustiteratorinteger

How to loop certain (variable) number of times?


This question may seem extremely basic, but I'm having a hard time figuring out how to do this. I have an integer, and I need to use a for loop to loop integer number of times.

First, I tried -

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

this prints the error

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`

Next, I tried -

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

the compiler says there is no method iter for integer

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() {
  |                       ^^^^

How am I supposed to do this?


Solution

  • This is because you are saying to the compiler for a num contained in number where number is not an iterator and neither does implement iter, rather than for a num in the range 0..number which is an iterator.

    The documentation describes the for loop as:

    for loop_variable in iterator {
        code()
    }
    

    Change the code to:

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

    You can also change it to:

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

    Or to:

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

    Also see for documentation