]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/docs/borrow_interior_mutable_const.txt
Auto merge of #104673 - matthiaskrgr:rollup-85f65ov, r=matthiaskrgr
[rust.git] / src / tools / clippy / src / docs / borrow_interior_mutable_const.txt
1 ### What it does
2 Checks if `const` items which is interior mutable (e.g.,
3 contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.) has been borrowed directly.
4
5 ### Why is this bad?
6 Consts are copied everywhere they are referenced, i.e.,
7 every time you refer to the const a fresh instance of the `Cell` or `Mutex`
8 or `AtomicXxxx` will be created, which defeats the whole purpose of using
9 these types in the first place.
10
11 The `const` value should be stored inside a `static` item.
12
13 ### Known problems
14 When an enum has variants with interior mutability, use of its non
15 interior mutable variants can generate false positives. See issue
16 [#3962](https://github.com/rust-lang/rust-clippy/issues/3962)
17
18 Types that have underlying or potential interior mutability trigger the lint whether
19 the interior mutable field is used or not. See issues
20 [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
21 [#3825](https://github.com/rust-lang/rust-clippy/issues/3825)
22
23 ### Example
24 ```
25 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
26 const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
27
28 CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
29 assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
30 ```
31
32 Use instead:
33 ```
34 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
35 const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
36
37 static STATIC_ATOM: AtomicUsize = CONST_ATOM;
38 STATIC_ATOM.store(9, SeqCst);
39 assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
40 ```