rust-lang / rust-lang/rust-clippy

New lint: mutating implicit copy of const

Open
#4,882 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint E-medium L-correctness
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Constants are instantiated every time they are used, even for non-Copy types. This results in behavior that may seem unintuitive at a first glance. The following code looks like it shouldn't compile at all:

#[derive(Debug)]
struct Foo {
    v: Vec<usize>,
}

const FOO: Foo = Foo { v: Vec::new() };

fn main() {
    for i in 0..32 {
        FOO.v.push(i); // attempting to modify a constant
    }
    println!("{:?}", FOO);
}

However, this code is actually valid. Of course, constants can't actually be modified. What really happens is that every usage of FOO creates a new temporary-like value that can be freely mutated even though FOO is const.

Suggest creating a local variable from the constant and mutating the variable instead, or using a static with interior mutability if a global state is truly necessary.


As a side note, the following code does work. Is it bad style?

fn main() {
    let foo = &mut FOO; // actually borrows an implicit local variable, not FOO
    for i in 0..32 {
        foo.v.push(i);
    }
    println!("{:?}", foo); // Foo: { v: [0, 1, 2, 3, ...] }
    println!("{:?}", FOO); // Foo: { v: [] }
}

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 by reproducing the two Rust examples in the issue and compare the behavior of direct mutation with borrowing the constant. Then inspect Clippy's existing lint conventions and tests to determine where a lint for mutating an implicit copy would belong. Done means the intended cases are diagnosed without flagging the valid borrowing behavior, with tests covering both examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 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.