Rust-clippy: New lint: Use Reverse with sort_by_key

Created on 8 May 2020  路  4Comments  路  Source: rust-lang/rust-clippy

Suggesting a new lint to prefer using Reverse and sort_by_key.

Bad:

vec.sort_by(|a, b| b.foo().cmp(&a.foo()));

Good:

vec.sort_by_key(|e| Reverse(e.foo()));

It should work the same for sort_unstable_by / sort_unstable_by_key.

Lint name idea: sort_by_key_reverse

Maybe there are other cases where Reverse can simplify a sort?

A-complexity E-medium L-lint

Most helpful comment

I can implement this.

All 4 comments

I can implement this.

I'm curious if this will work with a lambda that does _any_ transformation to a and b? Does there need to be a complexity limit?

Another (contrived) example: vec.sort_by(|a, b| Ord::cmp(&d(e(b.f().g())), &d(e(a.f().g()))))

I think it should be possible to lint anything where b and a get the same transformation, so long as it looks completely identical (so things like b+b vs. a*2 would throw it off, even though they'd actually do the same thing), never mentions the other variable (so things like b+0*a would also throw it off), and never calls a function which could change one of it's arguments (by taking an &mut or some such).

Was this page helpful?
0 / 5 - 0 ratings