Why can I borrow structure field as mutable while `self` is mutable?

I am not allowed to run the following code because there can’t be two mutable references to a value.


struct Bar {
    a: String,
}


fn main() {
    let mut bar = Bar {
        a: String::from("a"),
    };
    let r = &mut bar;
    let ra = &mut bar.a;
}

However, why can I run the following code? I have borrowed self as mutable and also borrowed its field as mutable.

impl Bar {
    fn foo(&mut self) {
        let ra = &mut self.a;
    }
}

&mut self is short for self: &mut Self
The line of code in the first that works the same is;
let ra = &mut r.a;

1 Like

in method foo(), self has ready borrow some Bar as mutable. However, why can ra borrow its field as mutable: let ra = &mut self.a?

iosmanthus
I compiled your first example with Rust 2018 Edition without any errors.

Rust lets you split a borrow into its component fields. You can’t pass the original struct while the fields are borrowed, but you can do what you want with the members separately.

1 Like

No self in foo() is a mutable reference; just the same as r.
Neither self or r have been borrowed from themself and so the next expression allows their use.

1 Like