📝In Rust, mut/const references are more about exclusive/shared access

In Rust, & and &mut are more about shared/exclusive access rather than mutability per se.

In Rust, mutable references never alias. Breaking this rule in any way results in undefined behavior.

On the other hand, many types have “interior mutability”—they can be mutated even through const references.

Thinking of & and &mut as shared/exclusive access (rather than constant/mutable) is most important when dealing with Sync types.

Furthermore

  • std::cell::UnsafeCell allows you to opt out of & immutability, but not & and &mut aliasing/sharing rules.

    Note that only the immutability guarantee for shared references is affected by UnsafeCell. The uniqueness guarantee for mutable references is unaffected. There is no legal way to obtain aliasing &mut, not even with UnsafeCell<T>.

Backlinks