rust-clippy
rust-clippy copied to clipboard
declare_interior_mutable_const triggers on array initializer
Lint name: declare_interior_mutable_const
I tried this code:
let _: [Cell<bool>; 7] = [Cell::new(true); 7];
Since the array initialization syntax requires T: Copy
, rustc errors and suggests this fix that works correctly:
const TRUE_CELL: Cell<bool> = Cell::new(true);
let _: [Cell<bool>; 7] = [TRUE_CELL; 7];
To my knowledge this is the best way to initialize an array with a const
but !Copy
value.
(stackoverflow answer)
However, declare_interior_mutable_const
triggers and incorrectly suggests "make this a static item (maybe with lazy_static)", which doesn't actually work at all. The lint documentation claims the code is bad because "Consts are copied everywhere they are referenced, ... , which defeats the whole purpose of using these types in the first place.", but in this case that is the entire reason for using a const
item.
The known issues mention "a legacy way to supply an initialized value to downstream static items" as a legit use, but it is not immediately clear if this case is covered by that.
Meta
Rust version (rustc -Vv
):
rustc 1.54.0 (a178d0322 2021-07-26)
binary: rustc
commit-hash: a178d0322ce20e33eac124758e837cbd80a6f633
commit-date: 2021-07-26
host: x86_64-unknown-linux-gnu
release: 1.54.0
LLVM version: 12.0.1