Is this an exception to the ownership rule in Rust ?

61 points Neful34

Hello everyone ๐Ÿ‘‹ ! I'm currently learning rust and as I learn, I like to test many things. Now, after reading multiple learning material, I know there is a rule in rust where :

We can either exactly borrow only one mutable reference Or any number of immutable reference, and we can have only one owner of a value at a time.

The example that i'm about to show you is a totally crappy and useless and doesn't reflect any production usage, as it wouldn't make any sense.

​

#[derive(Debug)]
struct Test {
    id:u8,
}

fn main() {
    let mut x = Test { id: 10 };
    
    let mut r: &mut Test = &mut x;
    
        r.id = 11;
    
        x.id = 12;// Error : doesn't work as it is borrowed by r, 
                // that's OK
    
    // x is still accessible because it is in scope
    
    println!("{:?}", r);// Test { id: 11 }
    println!("{:p}", r);// 0x7fff19d785f7
    println!("{:?}", x);// Test { id: 11 }
    println!("{:p}", &x);// 0x7fff19d785f7
}

Even tho r is the lonely one able to edit a value here, are we not getting still 2 values able to point the same value / address and cheating on the "ownership" rule ? As x is still accessible because of the scope ?

​

Thank you rustaceans for your help ! ๐Ÿ˜