Pointer dereference desugaring

Some unsafe code that dereferences a raw pointer is equivalent to code using pointer methods:

  • unsafe { *ptr } is the same as unsafe { ptr.read() }

  • unsafe { *ptr = v; } is the same as unsafe { ptr.drop_in_place(); ptr.write(v); }

  • &*ptr is ptr.as_ref().unwrap_unchecked()

  • &mut *ptr is ptr.as_mut().unwrap_unchecked()

But I wonder if &mut (*ptr).field has an exact equivalent using methods, and more generally what syntactic patterns don't.

// &mut (*ptr).field
use std::mem::offset_of;
ptr.byte_add(offset_of!(Struct, field))
    .cast::<FieldTy>()
    .as_mut()
    .unwrap_unchecked()
3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.