summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/src/docs/borrow_interior_mutable_const.txt
blob: e55b6a77e6667aa7679e1e35c5b033f24be3b1a1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
### What it does
Checks if `const` items which is interior mutable (e.g.,
contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.

### Why is this bad?
Consts are copied everywhere they are referenced, i.e.,
every time you refer to the const a fresh instance of the `Cell` or `Mutex`
or `AtomicXxxx` will be created, which defeats the whole purpose of using
these types in the first place.

The `const` value should be stored inside a `static` item.

### Known problems
When an enum has variants with interior mutability, use of its non
interior mutable variants can generate false positives. See issue
[#3962](https://github.com/rust-lang/rust-clippy/issues/3962)

Types that have underlying or potential interior mutability trigger the lint whether
the interior mutable field is used or not. See issues
[#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
[#3825](https://github.com/rust-lang/rust-clippy/issues/3825)

### Example
```
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);

CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
```

Use instead:
```
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);

static STATIC_ATOM: AtomicUsize = CONST_ATOM;
STATIC_ATOM.store(9, SeqCst);
assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
```