1
1
# Interior Mutability
2
2
3
+ r[ interior-mut]
4
+
5
+ r[ interior-mut.intro]
3
6
Sometimes 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
7
15
shared reference is not mutated.
8
16
17
+ r[ interior-mut.unsafe-cell]
9
18
[ ` std::cell::UnsafeCell<T> ` ] type is the only allowed way to disable
10
19
this 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> `
13
24
aliases.
14
25
26
+ r[ interior-mut.abstraction]
15
27
Other types with interior mutability can be created by using ` UnsafeCell<T> ` as
16
28
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
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
20
36
accessed with atomic operations, allowing the value to be shared and mutated
21
37
across threads.
22
38
@@ -26,4 +42,3 @@ across threads.
26
42
[ `std::cell::RefCell<T>` ] : ../std/cell/struct.RefCell.html
27
43
[ `std::sync::atomic` ] : ../std/sync/atomic/index.html
28
44
29
-
0 commit comments