11# Interior Mutability
22
3+ r[ interior-mut]
4+
5+ r[ interior-mut.intro]
36Sometimes a type needs to be mutated while having multiple aliases. In Rust this
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+ is achieved using a pattern called _ interior mutability_ .
8+
9+ r[ interior-mut.shared-ref]
10+ A type has interior mutability if its internal state can be changed through a [ shared reference] to
11+ it.
12+
13+ r[ interior-mut.no-constraint]
14+ This goes against the usual [ requirement] [ ub ] that the value pointed to by a
715shared reference is not mutated.
816
17+ r[ interior-mut.unsafe-cell]
918[ ` std::cell::UnsafeCell<T> ` ] type is the only allowed way to disable
1019this requirement. When ` UnsafeCell<T> ` is immutably aliased, it is still safe to
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> `
20+ mutate, or obtain a mutable reference to, the ` T ` it contains.
21+
22+ r[ interior-mut.mut-unsafe-cell]
23+ As with all other types, it is undefined behavior to have multiple ` &mut UnsafeCell<T> `
1324aliases.
1425
26+ r[ interior-mut.abstraction]
1527Other types with interior mutability can be created by using ` UnsafeCell<T> ` as
1628a 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
29+ interior mutability APIs.
30+
31+ r[ interior-mut.ref-cell]
32+ For example, [ ` std::cell::RefCell<T> ` ] uses run-time borrow checks to ensure the usual rules around multiple references.
33+
34+ r[ interior-mut.atomic]
35+ The [ ` std::sync::atomic ` ] module contains types that wrap a value that is only
2036accessed with atomic operations, allowing the value to be shared and mutated
2137across threads.
2238
@@ -26,4 +42,3 @@ across threads.
2642[ `std::cell::RefCell<T>` ] : ../std/cell/struct.RefCell.html
2743[ `std::sync::atomic` ] : ../std/sync/atomic/index.html
2844
29-
0 commit comments