rust-lang / rust-lang/rust-clippy

declare_interior_mutable_const triggers on array initializer

Open
#7,665 5 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-enhancement
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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];

playground

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the declare_interior_mutable_const lint and reproduce the reported Rust 1.54.0 example in the linked Playground. Compare the diagnostic for [Cell::new(true); 7] with the documented const guidance and known issues. Done means the lint no longer gives an incorrect static-item suggestion for this valid array-initialization pattern, with regression coverage for the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.