Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redundant x_by and x_by_key #2313

Closed
clarfonthey opened this issue Jan 2, 2018 · 7 comments · Fixed by #5756
Closed

Redundant x_by and x_by_key #2313

clarfonthey opened this issue Jan 2, 2018 · 7 comments · Fixed by #5756

Comments

@clarfonthey
Copy link
Contributor

clarfonthey commented Jan 2, 2018

For example, these:

x.sort_by(|l, r| l.cmp(r))
y.sort_by(|l, r| l.0.cmp(r.0))

could become:

x.sort();
y.sort_by_key(|z| z.0);

This also applies to binary_search_by and similar methods.

Perhaps we could also add a lint for adding _by but not _by_key when implementing a type.

Demonstrated on indexmap-rs/indexmap#55.

@bluss
Copy link
Member

bluss commented Jan 4, 2018

Just a reminder about the different conditions; sort_by is more general because it sometimes works when sort_by_key doesn't -- if the comparison value is a String, .sort_by_key would force you to clone the string for each comparison, that's as good as "doesn't work".

@clarfonthey
Copy link
Contributor Author

@bluss I don't see why that'd be the case when &T also implements Ord if T: Ord

@bluss
Copy link
Member

bluss commented Jan 4, 2018

The compiler will tell you if you try 😉

@clarfonthey
Copy link
Contributor Author

clarfonthey commented Jan 4, 2018

Oh! I see. It's a lifetime error in the original definition of the function.

fn sort_by_key<B, F>(&mut self, f: F) where
    B: Ord,
    F: FnMut(&T) -> B, 

Should be:

fn sort_by_key<'a, B, F>(&'a mut self, f: F) where
    B: Ord,
    F: FnMut(&'a T) -> B, 

@bluss
Copy link
Member

bluss commented Jan 4, 2018

Your definition is not valid - the elements move during sort.

@clarfonthey
Copy link
Contributor Author

No, but the elements do not need to be moved, simply compared. I'll write something up tomorrow to demonstrate.

@clarfonthey
Copy link
Contributor Author

clarfonthey commented Jan 5, 2018

…oh, I see the problem. K should really be K<'_>, and you're right that my definition is invalid. Larger issue regarding this: rust-lang/rust#34162

bors added a commit that referenced this issue Jul 3, 2020
unnecessary_sort_by: avoid linting if key borrows

changelog: Avoid linting if key borrows in [`unnecessary_sort_by`]

Fixes #5754
Closes #2313
@bors bors closed this as completed in 32ef448 Jul 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants