Is `&mut T -> &mut ManuallyDrop` well-defined and sound?

⚓ Rust    📅 2026-05-07    👤 surdeus    👁️ 2      

surdeus

Like this:

const fn as_manually_drop<T>(x: &mut T) -> &mut ManuallyDrop<T> {
    let ptr: *mut ManuallyDrop<T> = std::ptr::from_mut(x).cast();
    unsafe { ptr.as_mut_unchecked() }
}

I can’t see a reason it wouldn’t be – reading through it doesn’t change anything, and writing seems to only be able to do the same things as ManuallyDrop::into_inner, which is safe – but it also seems like the kind of thing that would already exist if it were correct and useful, and I’m pretty new to writing sound interfaces that use unsafe Rust. (I’m only using it to ManuallyDrop::take a field of a struct that’s already in a ManuallyDrop, so nothing really changes if I have to mark it unsafe, but it would be nice to know what’s correct. Miri doesn’t report any issues with this use.)

5 posts - 3 participants

Read full topic

🏷️ Rust_feed