]> git.lizzy.rs Git - rust.git/blob - src/docs/cast_ref_to_mut.txt
fb5b4dbb62d82386ab073958a1a97ded27bddeb9
[rust.git] / src / docs / cast_ref_to_mut.txt
1 ### What it does
2 Checks for casts of `&T` to `&mut T` anywhere in the code.
3
4 ### Why is this bad?
5 It’s basically guaranteed to be undefined behavior.
6 `UnsafeCell` is the only way to obtain aliasable data that is considered
7 mutable.
8
9 ### Example
10 ```
11 fn x(r: &i32) {
12     unsafe {
13         *(r as *const _ as *mut _) += 1;
14     }
15 }
16 ```
17
18 Instead consider using interior mutability types.
19
20 ```
21 use std::cell::UnsafeCell;
22
23 fn x(r: &UnsafeCell<i32>) {
24     unsafe {
25         *r.get() += 1;
26     }
27 }
28 ```