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?
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"),
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With