Why can I mutable borrow from struct twice


#1

I’m beginner of Rust. and I’m not good at English. But I’m gonna try to explain what i confused.

Here’s some short code

struct SS {
    x: Box<i32>,
}

fn main() {
    let mut ss = SS{x: Box::new(1)};
    let a = &mut ss;
    let b = &mut a.x;
}

I think rust should raise error because of last line of main function. ss has mutably borrowed by a, so rust should not allow to b borrowing ss's field via a. But rust compiler didn’t say anything about this!

What did I miss here? Could you explain to me what rust exactly do here and why it do that?


#2

I think this is a case of reborrowing, where the Rust compiler allows you to take a mutable reference out of another mutable reference.

This is safe because as long as the new “b” borrow is live, the original “a” reference becomes inaccessible, much like the original value is inaccessible in a regular borrow. For example, the following code will not compile:

struct SS {
    x: Box<i32>,
}

fn main() {
    let mut ss = SS{x: Box::new(1)};
    let a = &mut ss;
    let b = &mut a.x;
    *a.x = 3;
}

#3

Thanks to your anwser, I could have some points of view how rust handle variable and reference.
Thanks a lot!