Skip to content

unsafe { &mut *x } vs &mut unsafe { *x } #132063

Open
@hkBst

Description

@hkBst

I tried this code:

fn main() {
    let y: &mut [bool] = &mut [false; 2];
    let x = unsafe { &mut *(y as *mut [_] as *mut [std::mem::MaybeUninit<_>]) };
    let x = &x[0].write(true);
    println!("{x}");
}

which works fine, but if you move the unsafe ever so slightly inwards, like so:

fn main() {
    let y: &mut [bool] = &mut [false; 2];
    let x = &mut unsafe { *(y as *mut [_] as *mut [std::mem::MaybeUninit<_>]) };
    let x = &x[0].write(true);
    println!("{x}");
}

you get this error output:

error[[E0161]](https://doc.rust-lang.org/stable/error_codes/E0161.html): cannot move a value of type `[MaybeUninit<bool>]`
 --> src/main.rs:3:18
  |
3 |     let x = &mut unsafe { *(y as *mut [_] as *mut [std::mem::MaybeUninit<_>]) };
  |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the size of `[MaybeUninit<bool>]` cannot be statically determined

error[[E0508]](https://doc.rust-lang.org/stable/error_codes/E0508.html): cannot move out of type `[MaybeUninit<bool>]`, a non-copy slice
 --> src/main.rs:3:27
  |
3 |     let x = &mut unsafe { *(y as *mut [_] as *mut [std::mem::MaybeUninit<_>]) };
  |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |                           |
  |                           cannot move out of here
  |                           move occurs because value has type `[MaybeUninit<bool>]`, which does not implement the `Copy` trait

Some errors have detailed explanations: E0161, E0508.
For more information about an error, try `rustc --explain E0161`.
error: could not compile `playground` (bin "playground") due to 2 previous errors

Version tested is 1.82.0 and current nightly on the playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-raw-pointersArea: raw pointers, MaybeUninit, NonNullD-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions