This is my code:
use std::fs::File;
use std::io::Write;
fn main() {
let f = File::create("").unwrap();
// Compiles
write!(&f, "hi").unwrap();
write_hi(&f);
}
fn write_hi(f: &File) {
// Doesn't compile (cannot borrow `f` as mutable, as it is not declared as mutable)
write!(f, "hi").unwrap();
}
When I have this line without the file being a parameter value, it compiles:
write!(&f, "hi").unwrap();
However, when the f
is a parameter value, I get a compile error. It works when I make some mutability changes in the declaration of the f
variable and method parameter, but isn't that odd?
Why doesn't the write!
macro work on a non-mutable reference when it is used as a parameter value, like it does compile when the referencing variable is declared in the same method?