Reputation: 5157
I am taking data from text file
let fil1_json = File::open("fil1.json")?;
let mut fil1_json_reader = BufReader::new(fil1_json);
let fil2_json = File::open("fil2.json")?;
let mut fil2_json_reader = BufReader::new(fil2_json);
for fil1_line in fil1_json_reader.by_ref().lines() {
for fil2_line in fil2_json_reader.by_ref().lines() {
println!("{:#?} ----- {:#?}", fil1_line, fil2_line);
}
}
In the second nested loop, it is only going inside once. It looks like fil2_json_reader
is getting emptied after first iteration.
Where it is changing as I am not changing anywhere?
Upvotes: 2
Views: 306
Reputation: 26066
Where it is changing as I am not changing anywhere?
Readers consume the data. In the case of File
, this is the natural expectation, since file abstractions almost universally have a cursor that advances every time you read.
If you want to iterate several times over the same data, then the obvious option is saving it to memory (typically before splitting into lines()
, but you can also save a vector of those even if it will be slower). However, since the reader is backed by an actual file, it is better to re-iterate over the file by seek
ing to its beginning:
fil2_json_reader.seek(SeekFrom::Start(0))
Upvotes: 3