When iterating through file.lines() how can I get the next line coming

Viewed 28

I'm iterating through a file like this:

for line in file.lines() {
    if line == something {
        println!("{}", line);
    }
}

This works great, but how can I get the line that's coming in the next iteration of the loop?

something like this would be great:

for line in file.lines() {
    if line == something {
        println!("{}", line);
        line.next();
        println!("{}", line); // This would be the next line coming in the file
    }
}
1 Answers

You can replace for with while let:

let mut lines = file.lines();
while let Some(line) = lines.next() {
    if line == something {
        println!("{}", line);
        let new_line = lines.next().unwrap();
        println!("{}", new_line);
    }
}
Related