Recall the rule that states you can’t have mutable and immutable references in the same scope,So running the code in the image above will give you an error.
But look at the code in the image below:
Why is there no error?
It's generally good practice to share code and error messages not via screenshots but via
// code blocks
fn f() {}
And for error messages to paste the full error as printed on the terminal by cargo check
or similar commands.
Also see here for more information on how to create code blocks ^^
The "scope" of references for the purpose of borrow checking works more fine grained than simple lexical scope. It usually goes from the point where the rerefence is defined to the point of last usage. The mutable access in the calls to push
each ends immediately after each call (it's not used, directly or indirectly, at any later time) and thus, if the last
reference is only defined after that, there's no conflict, since the referenced are not considered to exist at the same time.
The rule isn't "no &
and &mut
in the same scope"; it's closer to "using &mut
invalidates other borrows".
let mut v = ...;
v.push(5); // Takes a `&mut` which ends immediately
v.push(6); // Takes a `&mut` which ends immediately
// There is no `&mut` or moves of `v` beyond this point
You can even reborrow things through the &mut
, and then use the &mut
again.
But when you move or write through the &mut
, there must be no other observers (e.g. other &mut
or &
to the same data).
Thank you very much for your advice. I'll do it next time
Thank you very much.I understand
Thank you very much for your answer. I understand