Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

rust - Detect last item of an Iterator

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the peekable adapter.

This requires switching to manual iteration (a while let loop and explicitly calling next), but it lets you peek() the iterator to see if there is a next item. If there isn't, you know it's the last line (at least for the more fusable iterators).

let file = File::open(&files[index])
    .map_err(|e| format!("Could not open log file: {}", e))?;
let reader = BufReader::new(file);
let mut iterator = reader.lines().enumerate().peekable();
while let Some((index, line)) = iterator.next() {
    if line == "" && iterator.peek().is_none() {
        break;
    }
    // do something with the line...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...