Why does RefMut contain a NonNull?
⚓ Rust 📅 2025-07-27 👤 surdeus 👁️ 10I'm investigating the machine code that is generated when RefCells are involved. RefMut contains a NonNull, with a comment explaining its purpose:
pub struct RefMut<'b, T: ?Sized + 'b> {
// NB: we use a pointer instead of `&'b mut T` to avoid `noalias` violations, because a
// `RefMut` argument doesn't hold exclusivity for its whole scope, only until it drops.
value: NonNull<T>,
borrow: BorrowRefMut<'b>,
// `NonNull` is covariant over `T`, so we need to reintroduce invariance.
marker: PhantomData<&'b mut T>,
}
The comment isn't clear to me - how could a RefMut's whole scope extend past the time it is dropped? What sort of code would fail if &'b mut T was used instead of NonNull<T>?
The NonNull<T> is preventing machine code optimizations that I hoped would be present in my project that uses RefCells.
3 posts - 3 participants
🏷️ Rust_feed