0

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?

1
  • 2
    You can use take on 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. Commented Jan 10, 2023 at 22:04

1 Answer 1

2

Looping or using an iterator adapter will consume an iterator. But if I is an iterator then so is &mut I!

You can use that instance to partially iterate through the iterator with one adapter and then continue with another. The first use consumes only the mutable reference, but not the iterator itself. For example using take:

let mut it = reader.lines().map(|l| l.unwrap()); for lines in (&mut it).take(n) { do_task_a(&lines); } for lines in it { do_task_b(&lines); } 

But I think your original code is still completely fine.

Sign up to request clarification or add additional context in comments.

2 Comments

I upvoted for the suggestion, but it doesn't mean I agree the original code is better :)
Thank you! I wouldn't have guessed that (&mut it) was the trick. I also find your code better than mine! :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.