rust-lang / rust-lang/rust-clippy
`almost_swapped`'s suggested alternative could be Rustier
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
almost_swapped will catch this faulty code which doesn't quite swap two variables:
fn main() {
let mut a = 2;
let mut b = 3;
a = b;
b = a;
println!("a: {}, b: {}", a, b);
}
error: this looks like you are trying to swap `a` and `b`
--> src/main.rs:4:5
|
4 | / a = b;
5 | | b = a;
| |_________^ help: try: `std::mem::swap(&mut a, &mut b)`
|
= note: or maybe you should use `std::mem::replace`?
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#almost_swapped
= note: `#[deny(clippy::almost_swapped)]` on by default
It suggests doing this instead: std::mem::swap(&mut a, &mut b)
At least for smaller values, I'd suggest changing this to
(a, b) = (b, a);
as this seems clearer and more idiomatic to me. Of course this runs the risk of copying around on the stack, but that should be the compilers job to avoid I reckon.
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 reading the almost_swapped lint documentation and its current diagnostic output in the rust-clippy repository. Compare the suggested std::mem::swap form with the proposed tuple-assignment form, including the stated copying concern. Done means the lint's recommendation is updated if the project accepts the change, with coverage for the resulting diagnostic.
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