]>
Commit | Line | Data |
---|---|---|
ea8adc8c XL |
1 | # Interior Mutability |
2 | ||
ba9703b0 | 3 | Sometimes a type needs to be mutated while having multiple aliases. In Rust this |
ea8adc8c XL |
4 | is achieved using a pattern called _interior mutability_. A type has interior |
5 | mutability if its internal state can be changed through a [shared reference] to | |
6 | it. This goes against the usual [requirement][ub] that the value pointed to by a | |
7 | shared reference is not mutated. | |
8 | ||
ff7c6d11 XL |
9 | [`std::cell::UnsafeCell<T>`] type is the only allowed way in Rust to disable |
10 | this requirement. When `UnsafeCell<T>` is immutably aliased, it is still safe to | |
ea8adc8c XL |
11 | mutate, or obtain a mutable reference to, the `T` it contains. As with all |
12 | other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>` | |
13 | aliases. | |
14 | ||
15 | Other types with interior mutability can be created by using `UnsafeCell<T>` as | |
16 | a field. The standard library provides a variety of types that provide safe | |
17 | interior mutability APIs. For example, [`std::cell::RefCell<T>`] uses run-time | |
18 | borrow checks to ensure the usual rules around multiple references. The | |
19 | [`std::sync::atomic`] module contains types that wrap a value that is only | |
20 | accessed with atomic operations, allowing the value to be shared and mutated | |
21 | across 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 |