While let skip iter next outputs infinite same line

This is my sample extracted from my first bigger project

fn main() {
      let lines: Vec<String> = vec![
        "123456".to_string(),
        "234567".to_string(),
        "345678".to_string()
    ];

    let skip_lines: Vec<&String> = lines.iter().skip(1).collect();
    report2(skip_lines);
}

fn report2(lines: Vec<&String>) {
    while let Some(&l) = lines.iter().next() {
        println!("{}", l);
    }
}

This prints out always the same line 234567.

What did I do wrong?

Every time you call lines.iter(), it creates a new iterator that starts at the beginning. Call it only once and store it in a variable instead:

fn report2(lines: Vec<&String>) {
    let mut iter = lines.iter();
    while let Some(&l) = iter.next() {
        println!("{}", l);
    }
}

Or use a for loop, which only evaluates its argument once:

fn report2(lines: Vec<&String>) {
    for &line in lines.iter() {
        println!("{}", l);
    }
}
3 Likes