rust-lang / rust-lang/rust-clippy
New lint: unused or discarded `std::mem::replace`/`std::mem::take`
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
rust suggests _ = ... when not using the return value of std::mem::replace/std::mem::take because of the #[must_use] tag on those functions.
but here a direct assignment just makes more sense.
_ = std::mem::replace(dest, src)->*dest = src_ = std::mem::take(dest)->*dest = Default::default()orT::default()
I found this in my own code when i was refactoring stuff and was surprised that clippy doesn't lint on this.
Advantage
- using a simple assignment is shorter and more idiomatic than a std::mem function
Drawbacks
The drop order changes.
- With
std::mem::replace/std::mem::take, the value is dropped at the end of the statement. - With
*dest = src, the value is dropped immediately.
Example
let mut x = 2;
let _ = std::mem::replace(&mut x, 6);
let x_ptr = &mut x;
let _ = std::mem::replace(x_ptr, 12);
let _ = std::mem::take(x_ptr);
Could be rewritten as:
let mut x = 2;
x = 6;
let x_ptr = &mut x;
*x_ptr = 12;
*x_ptr = Default::default();
Comparison with existing lints
No response
Additional Context
i already made a draft implementation for the replace case and would like to implement take aswell, if this idea for these lints gets accepted!
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
The issue names no files or tests; start by reviewing the existing draft implementation for the replace case and the examples in the proposal. Clarify whether both replace and take cases should be covered, including the stated drop-order difference, and confirm the expected lint scope before considering the work complete.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100