Hi,
I am new to Rust and experience some issue understanding the borrow checker in the following code.
Why does the following code work for the NonMut
struct and fails to compile for Mut
?
The only difference between the 2 is the mutability of v
.
I would be tempted to think that the 2 approaches should fail the same way but for NonMut
, it seems that I am allowed to borrow *self
mutably while it was borrowed immutably by the loop (?!?).
Thank you very much in advance for your help.
Happy coding,
Ramses
#![allow(dead_code)]
pub struct Mut<'a> {
v: &'a mut Vec<u8>,
}
impl<'a> Mut<'a> {
fn foo(&mut self) {
for _ in self.v.iter() {
self.bar();
}
}
fn bar(&mut self) {}
}
pub struct NonMut<'a> {
v: &'a Vec<u8>,
}
impl<'a> NonMut<'a> {
fn foo(&mut self) {
for _ in self.v.iter() {
self.bar();
}
}
fn bar(&mut self) {}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/lib.rs:10:13
|
9 | for _ in self.v.iter() {
| -------------
| |
| immutable borrow occurs here
| immutable borrow later used here
10 | self.bar();
| ^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: Could not compile `playground`.
To learn more, run the command again with --verbose.