rust-lang / rust-lang/rust-clippy
Lint: useless assignments to Copy temporaries
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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