Content-Length: 16524 | pFad | https://doc.rust-lang.org/reference/items/../names/../types/../items/../interior-mutability.html

Interior mutability - The Rust Reference

Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Interior mutability

Sometimes a type needs to be mutated while having multiple aliases. In Rust this is achieved using a pattern called interior mutability.

A type has interior mutability if its internal state can be changed through a shared reference to it.

This goes against the usual requirement that the value pointed to by a shared reference is not mutated.

std::cell::UnsafeCell<T> type is the only allowed way to disable this requirement. When UnsafeCell<T> is immutably aliased, it is still safe to mutate, or obtain a mutable reference to, the T it contains.

As with all other types, it is undefined behavior to have multiple &mut UnsafeCell<T> aliases.

Other types with interior mutability can be created by using UnsafeCell<T> as a field. The standard library provides a variety of types that provide safe interior mutability APIs.

For example, std::cell::RefCell<T> uses run-time borrow checks to ensure the usual rules around multiple references.

The std::sync::atomic module contains types that wrap a value that is only accessed with atomic operations, allowing the value to be shared and mutated across threads.









ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://doc.rust-lang.org/reference/items/../names/../types/../items/../interior-mutability.html

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy