rust-lang / rust-lang/rust-clippy
Suggest `Reverse` instead of casting number to signed counterpart and making it negative
Open
Nobody has claimed this yet.
A-lint
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
I saw this real-world example today:
multi_labels.sort_by_key(|m| -(m.span.len() as isize));
where len() returns a usize.
My suggestion would resolve it to this:
multi_labels.sort_by_key(|m| Reverse(m.span.len()))
Lint Name
negative_sort_by_key
Category
correctness, suspicious, style
Advantage
- Removes uncessary cast
- Removes panicable cast
- Makes expression more clear
Drawbacks
Importing the Reverse struct is necessary.
Example
use std::cmp::Reverse;
#[derive(Debug, Clone, Copy, PartialEq)]
struct S(usize);
fn sort_a(mut v: Vec<S>) -> Vec<S> {
v.sort_by_key(|m| -(m.0 as isize));
v
}
fn sort_b(mut v: Vec<S>) -> Vec<S> {
v.sort_by_key(|m| Reverse(m.0));
v
}
fn main() {
let vec = vec![S(3), S(0), S(0), S(5), S(13), S(18)];
assert_eq!(sort_a(vec.clone()), sort_b(vec));
}
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 locating the negative_sort_by_key lint and reviewing the sort_a and sort_b examples in this issue. Confirm how the suggested Reverse form should be recognized and what existing lint tests cover; done means the lint recommends Reverse for this cast-and-negation pattern without changing unrelated cases.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 50/100