Hi,
I'm starting our with rust, and stumbled upon a behavior of the borrow checker that I don't understand. I'm hoping this is the right place to understand why this happens (I understand what happened). Suppose I have the following code:
struct Bar {}
impl Bar {
fn foo(&mut self, x: u8) -> u8 {
x
}
fn faz(&mut self) -> u8 {
0
}
}
fn main() {
let mut bar = Bar{};
println!("{}", bar.foo(bar.faz()));
}
This code fails to compile, with the compiler giving a perfect reason:
error[E0499]: cannot borrow `bar` as mutable more than once at a time
--> src/main.rs:15:28
|
15 | println!("{}", bar.foo(bar.faz()));
| --- --- ^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
|
help: try adding a local storing this argument...
--> src/main.rs:15:28
|
15 | println!("{}", bar.foo(bar.faz()));
| ^^^^^^^^^
help: ...and then using that local as the argument to this call
--> src/main.rs:15:20
|
15 | println!("{}", bar.foo(bar.faz()));
| ^^^^^^^^^^^^^^^^^^
For more information about this error, try `rustc --explain E0499`.
The error also gives us a fix - introducing a local variable:
struct Bar {}
impl Bar {
fn foo(&mut self, x: u8) -> u8 {
x
}
fn faz(&mut self) -> u8 {
0
}
}
fn main() {
let mut bar = Bar{};
let x = bar.faz();
println!("{}", bar.foo(x));
}
Now I'm getting what happened here, but not why the compiler didn't not introduce this local variable himself (manually writing a variable only for one time use seems a bit clunky to me). Is there any particular reason why the compiler could not solve this issue with the first code (internally introducing the variable)?
This is my first time posting here, so I'm hoping this is the right place. Thanks!