-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Closed
Labels
C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesCategory: Enhancement of lints, like adding more cases or adding help messages
Description
Summary
When the elements of a vec/slice are tuples, it's pretty common to sort them as follows:
let mut v = [(1, "foo", (2, "bar")];
v.sort_by(|(_, s1), (_, s2)| s1.cmp(s2));It would be great if the lint could catch this, and suggest the following replacement:
let mut v = [(1, "foo", (2, "bar")];
v.sort_by_key(|(_, s)| s);Bonus thing: often, the variables in this context are given more descriptive names, usually something like xxx1, xxx2, xxx_a, xxx_b, or xxx_l, xxx_r. It would be very nice if the lint could detect such cases and suggest calling the replacement variable xxx. Of course, when the variables are called just l, r, there isn't much that can be done.
Lint Name
unnecessary_sort_by
Reproducer
I tried this code:
let mut v = [(1, "foo", (2, "bar")];
v.sort_by(|(_, s1), (_, s2)| s1.cmp(s2));I expected to see this happen:
warning: consider using `sort_by_key`
--> src/main.rs:2:1
|
2 | v.sort_by(|(_, s1), (_, s2)| s1.cmp(s2));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `v.sort_by_key(|(_, s)| s)`
|
Instead, this happened:
Version
rustc 1.94.0-nightly (0aced202c 2026-01-06)
binary: rustc
commit-hash: 0aced202c24f9356c1640fc0a7f07433b3a7124f
commit-date: 2026-01-06
host: x86_64-unknown-linux-gnu
release: 1.94.0-nightly
LLVM version: 21.1.8
profetia
Metadata
Metadata
Assignees
Labels
C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesCategory: Enhancement of lints, like adding more cases or adding help messages