rust-lang / rust-lang/rust-clippy

Lint: useless assignments to Copy temporaries

Open
#7,117 5 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

What it does

Detect assignments to Copy values that are immediately discarded.

rustc is pretty good at detecting when variables are assigned but never read, and Clippy has a temporary_assignments lint to catch assignments to temporaries, but neither of them catch the following case:

struct Point { x: u64, y: u64 }

fn new_point() -> Point {
    Point {
        x: 10,
        y: 30,
    }
}

fn main() {
    new_point().x = 11;
}

Whether or not new_point has side-effects should be irrelevant: assigning to its .x field and then immediately throwing it away is definitely pointless (no pun intended 😏). Things are more complicated if Point has a drop implementation, hence the lint should probably be restricted to types that implement Copy.

Categories
  • Kind: correctness
Drawbacks

Potentially difficult to implement

Example

This example is more similar to the one I encountered in the real world: a Copy type with a mutable getter and a copying getter, where the copying getter is called by mistake:

#[derive(Debug, Clone, Copy)]
struct Point { x: u64, y: u64 }

#[derive(Debug)]
struct Container {
    point: Point,
}

impl Container {
    fn get_point(&self) -> Point {
        self.point
    }
    
    #[allow(unused)]
    fn get_point_mut(&mut self) -> &mut Point {
        &mut self.point
    }
}

fn main() {
    let container = Container {
        point: Point { x: 10, y: 30 },
    };
    container.get_point().x = 0; // oops! I meant `get_point_mut`!
    println!("{:?}", container);
}

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 reviewing Clippy's existing temporary_assignments lint and the two examples in this issue. Determine how to recognize assignments to fields of immediately discarded Copy temporaries while excluding types with drop behavior, then add coverage for both examples and verify that the mistaken copying getter is diagnosed.

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.