]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/interior-mutability.md
New upstream version 1.44.1+dfsg1
[rustc.git] / src / doc / reference / src / interior-mutability.md
CommitLineData
ea8adc8c
XL
1# Interior Mutability
2
ba9703b0 3Sometimes a type needs to be mutated while having multiple aliases. In Rust this
ea8adc8c
XL
4is achieved using a pattern called _interior mutability_. A type has interior
5mutability if its internal state can be changed through a [shared reference] to
6it. This goes against the usual [requirement][ub] that the value pointed to by a
7shared reference is not mutated.
8
ff7c6d11
XL
9[`std::cell::UnsafeCell<T>`] type is the only allowed way in Rust to disable
10this requirement. When `UnsafeCell<T>` is immutably aliased, it is still safe to
ea8adc8c
XL
11mutate, or obtain a mutable reference to, the `T` it contains. As with all
12other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>`
13aliases.
14
15Other types with interior mutability can be created by using `UnsafeCell<T>` as
16a field. The standard library provides a variety of types that provide safe
17interior mutability APIs. For example, [`std::cell::RefCell<T>`] uses run-time
18borrow checks to ensure the usual rules around multiple references. The
19[`std::sync::atomic`] module contains types that wrap a value that is only
20accessed with atomic operations, allowing the value to be shared and mutated
21across threads.
22
416331ca
XL
23[shared reference]: types/pointer.md#shared-references-
24[ub]: behavior-considered-undefined.md
ea8adc8c
XL
25[`std::cell::UnsafeCell<T>`]: ../std/cell/struct.UnsafeCell.html
26[`std::cell::RefCell<T>`]: ../std/cell/struct.RefCell.html
27[`std::sync::atomic`]: ../std/sync/atomic/index.html
28
29