I am trying to figure out how to continue iterating through a file from the current line I am on without having to start from the beginning. I am using BufReader
to accomplish the line by line iteration. Here is an example of what I am trying to do:
use std::{
fs::File,
io::{self, BufRead, BufReader},
};
fn main() -> io::Result<()> {
let chapter = "Chapter 1";
let sentence = "Sentence 1";
let file = File::open("document.txt")?;
let reader = BufReader::new(file);
for line in reader.lines() {
if chapter == line.unwrap() {
for line in reader.lines() {
if sentence == line.unwrap() {
println!("Found the reference!");
}
}
}
}
Ok(())
}
I cannot iterate like this due to the error:
error[E0382]: use of moved value: `reader`
--> src/main.rs:15:25
|
11 | let reader = BufReader::new(file);
| ------ move occurs because `reader` has type `std::io::BufReader<std::fs::File>`, which does not implement the `Copy` trait
12 |
13 | for line in reader.lines() {
| ------- `reader` moved due to this method call
14 | if chapter == line.unwrap() {
15 | for line in reader.lines() {
| ^^^^^^ value moved here, in previous iteration of loop
|
note: this function consumes the receiver `self` by taking ownership of it, which moves `reader`
Is there a way to continue line iteration using the same BufReader
?