检测迭代器的最后一项

Mic*_*ael 4 rust

我的代码逐行分析日志文件。最后一行通常是空 ("") 行,应完全忽略。但是我如何检测循环中的最后一行呢?
迭代器不知道它有多长,并且将所有项目收集到数组中效率低下,并且可能会过多填满内存。

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...
}
Run Code Online (Sandbox Code Playgroud)

is_last_line()不存在。如何检测最后一行?

hel*_*low 7

您可以使用该Itertools::with_position功能:

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"),
    }
}
Run Code Online (Sandbox Code Playgroud)