How can I use `while let` to iterating through array?

I have the following code

fn print_array(arr: &[i32])
{
    while let Some(e) = arr.into_iter().enumerate().next() {
        println!("elem[{}] = {}", e.0, e.1);
    }
}

fn main() {
    let a = [1, 2, 3, 4, 5];
    print_array(&a);
}

But it repeats the loop indefinitely by outputting the following

elem[0] = 1
elem[0] = 1
...

I'm sure I miss something.
So how can I use while let to iterating through the array here?

Your loop keeps creating a new iterator each time. Create it first, then pull items from it.

let mut iter = arr.into_iter().enumerate();
while let Some(e) = iter.next() {
    //...
}

(or just use a for loop)

2 Likes

Awesome! Thank you very much.
I'm a few days in using Rust, and would like to know how to loop with while let.

Understand now, thanks!

By the way, typically for iterating over &[i32], you'd call the .iter() method rather than the .into_iter() method. (It's equivalent in this case, but the former is more idiomatic.)

Also for this specific case, a for loop would be more appropriate, syntactically. Of course using a for loop doesn't help if your goal is explicitly to learn about while let :stuck_out_tongue:

In any case, the code with those changes would look like

fn print_array(arr: &[i32])
{
    for e in arr.iter().enumerate() {
        println!("elem[{}] = {}", e.0, e.1);
    }
}

Both suggestions are also something that clippy would tell you. Make sure to set up and use clippy when learning Rust, it can teach a lot of small little improvements / good practices.

warning: this `.into_iter()` call is equivalent to `.iter()` and will not consume the `slice`
 --> src/main.rs:2:24
  |
2 |     let mut iter = arr.into_iter().enumerate();
  |                        ^^^^^^^^^ help: call directly: `iter`
  |
  = note: `#[warn(clippy::into_iter_on_ref)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#into_iter_on_ref

warning: this loop could be written as a `for` loop
 --> src/main.rs:3:5
  |
3 |     while let Some(e) = iter.next() {
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `for e in iter`
  |
  = note: `#[warn(clippy::while_let_on_iterator)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#while_let_on_iterator

warning: `playground` (bin "playground") generated 2 warnings
    Finished dev [unoptimized + debuginfo] target(s) in 0.55s
1 Like

Thank you very much for further detail on this.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.