]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/docs/declare_interior_mutable_const.txt
Auto merge of #101615 - compiler-errors:rpitit-perf, r=oli-obk
[rust.git] / src / tools / clippy / src / docs / declare_interior_mutable_const.txt
1 ### What it does
2 Checks for declaration of `const` items which is interior
3 mutable (e.g., contains a `Cell`, `Mutex`, `AtomicXxxx`, etc.).
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` should better be replaced by a `static` item if a global
12 variable is wanted, or replaced by a `const fn` if a constructor is wanted.
13
14 ### Known problems
15 A "non-constant" const item is a legacy way to supply an
16 initialized value to downstream `static` items (e.g., the
17 `std::sync::ONCE_INIT` constant). In this case the use of `const` is legit,
18 and this lint should be suppressed.
19
20 Even though the lint avoids triggering on a constant whose type has enums that have variants
21 with interior mutability, and its value uses non interior mutable variants (see
22 [#3962](https://github.com/rust-lang/rust-clippy/issues/3962) and
23 [#3825](https://github.com/rust-lang/rust-clippy/issues/3825) for examples);
24 it complains about associated constants without default values only based on its types;
25 which might not be preferable.
26 There're other enums plus associated constants cases that the lint cannot handle.
27
28 Types that have underlying or potential interior mutability trigger the lint whether
29 the interior mutable field is used or not. See issues
30 [#5812](https://github.com/rust-lang/rust-clippy/issues/5812) and
31
32 ### Example
33 ```
34 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
35
36 const CONST_ATOM: AtomicUsize = AtomicUsize::new(12);
37 CONST_ATOM.store(6, SeqCst); // the content of the atomic is unchanged
38 assert_eq!(CONST_ATOM.load(SeqCst), 12); // because the CONST_ATOM in these lines are distinct
39 ```
40
41 Use instead:
42 ```
43 static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15);
44 STATIC_ATOM.store(9, SeqCst);
45 assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance
46 ```