Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect last item of an Iterator

Tags:

rust

My code analyzes log files line by line. The last line typically is an empty ("") line and should be ignored completely. But how can I detect the last line in my loop?
The iterator doesn't know how long it is and collecting all items to an array is inefficient and might fill up memory too much.

let file = File::open(&files[index])
    .map_err(|e| format!("Could not open log file: {}", e))?;
let reader = BufReader::new(file);
for (index, line) in reader.lines().enumerate() {
    let line = line.unwrap();
    if is_last_line() && line == "" {
        break;
    }
    // do something with the line...
}

is_last_line() doesn't exist. How to detect the last line?

like image 648
Michael Avatar asked Oct 26 '25 04:10

Michael


1 Answers

You could use the Itertools::with_position function:

use itertools::{Itertools, Position};

let file = File::open(&files[index]).map_err(|e| format!("Could not open log file: {}", e))?;
let reader = BufReader::new(file);

for line in reader.lines().enumerate().with_position() {
    match line {
        Position::Last((idx, _)) => println!("line {} is the last line!", idx),
        Position::First((idx, text)) | Position::Middle((idx, text)) => (),
        Position::Only((idx, _)) => println!("there is only one line in your file"),
    }
}
like image 187
hellow Avatar answered Oct 28 '25 03:10

hellow