While iterating over lines in a file I need to first do "task_A" and then "task_B". The first few lines there is some data that I need to put into some data structure (task_A) and after that the lines describe how the data inside of the data structure is manipulated (task_B). Right now I use a for-loop with enumerate and if-else statements that switch depending on which file number:
let file = File::open("./example.txt").unwrap(); let reader = BufReader::new(file); for (i, lines) in reader.lines().map(|l| l.unwrap()).enumerate() { if i < n { do_task_a(&lines); } else { do_task_b(&lines); } } There is also the take_while()-method for iterators. But this only solves one part. Ideally I would pass the iterator for n steps to one function and after that to another function. I want to have a solution that only needs to iterate over the file one time. (For anyone wondering: I want a more elegant solution for 5th day of Advent of Code 2022 Is there a way to do that? To "re-use" the iterator when it is already advanced n steps?
takeon a borrow of the iterator over the lines of the file to pass along to the first function, and then process the original iterator (which would resume after the last line the first function read) in the second function.