As a disclaimer, this is day#1 Rust, but I come from a C/C++/D background.
First of all, what a wonderful documentation and support ecosystem. Still, the concept of ownership and borrowing has a lot of corners to explore and understand probably through experience only.
In addition to exercises in The Book, I am working on practical problems related to my work. One of these is linewise reading and parsing of (potentially) GByte sized files.
My first attempt uses the Lines
iterator returned by BufReader::lines()
and is thus inefficient in terms of heap alloc:
use std::io::{self,BufRead};
use std::fs::File;
fn main() -> std::result::Result<(), std::io::Error> {
let filename = "test.bed";
let fi = File::open(filename)?;
let bedreader = io::BufReader::new(fi);
for line in bedreader.lines() {
println!("{}", line?);
}
Ok(())
}
In order to reuse a preallocated buffer, it looks like I can use read_line
directly:
let mut line = String::new();
while bedreader.read_line(&mut line).unwrap() > 0 {
println!("{}", line.trim_end());
line.clear();
}
but the above code compiles only if bedreader
is defined as mutable:
11 | while bedreader.read_line(&mut line).unwrap() > 0 {
| ^^^^^^^^^ cannot borrow as mutable
Question: Why is this? in both cases, the BufReader instance is not mutated nor does it need to be; it is not updated as a part of the while
condition; only a member function return value changes. In the case of the iterator, it (bedreader: BufReader
) does not need to be defined as mut
.
Could someone please explain in more detail why the borrow checker gripes about this? Is it related to the fact that I passed a mutable reference (&mut line
) to the member function?
Thank you so much in advance