unsafe { &mut *x } vs &mut unsafe { *x }
Open
Nobody has claimed this yet.
A-diagnostics
A-raw-pointers
D-terse
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce both snippets in src/main.rs using the stable 1.82.0 compiler and current nightly on the linked Playground, then compare the diagnostics for the two placements of unsafe. Trace the compiler behavior involved in the differing treatment of the dereference; done means the issue's expected behavior and resulting diagnostics are resolved or clearly documented.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100