Hacker News new | past | comments | ask | show | jobs | submit login

&mut T does not mean what you think it means

&mut T means that there is only one pointer (the &mut T) that will be used to access some memory. You can have as many other pointers to that memory as you want, as long as you don't invalidate the first one.

This code is safe:

    let mut foo = 13_i32;
    let x: &mut i32 = &mut foo; // First &mut
    {
        let y: &mut i32 = unsafe { std::mem::transmute(x as *mut i32) }; // Second &mut T (copy)
        *y = 42; // Write through second
    }
    dbg!(*x); // Read through first
You can run this under miri here: https://play.rust-lang.org/?version=stable&mode=release&edit...



Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: