Hello community,
I'm new to Rust and I'm learning to use the BufReader struct. I don't understand why this code doesn't compile:
use std::fs;
use std::io;
use std::io::BufRead;
pub fn read_a_file() {
let file_name = "/tmp/text_file.txt";
let input_file = fs::File::open(file_name).expect("failed to open file");
let mut buf_reader = io::BufReader::new(input_file);
loop {
let content = buf_reader.fill_buf().expect("failed to fill buffer");
if content.is_empty() {
println!("no more data to read");
break;
}
for u8_value in content {
print!("{}", *u8_value as char);
}
buf_reader.consume(content.len());
}
println!();
}
Rustc says: error[E0499]: cannot borrow buf_reader
as mutable more than once at a time
--> src/check_read.rs:18:9
|
10 | let content = buf_reader.fill_buf().expect("failed to fill buffer");
| --------------------- first mutable borrow occurs here
...
18 | buf_reader.consume(content.len());
| ^^^^^^^^^^^^^^^^^^^-------------^
| | |
| | first borrow later used here
| second mutable borrow occurs here
It seems that everyone on the internet first calls fill_buf() then consume(), I don't understand why it doesn't work in my code. Can someone please help explain? Thanks in advance.