Closed
Description
I tried this code:
#[derive(Debug)]
pub struct Test {
name: String,
}
impl Test {
fn name(&self) -> &str {
&self.name
}
}
fn main() {
let mut args: Vec<_> = std::env::args().map(|name| Test { name }).collect();
args.sort_by(|a, b| a.name().cmp(b.name()));
// Suggested by clippy, but causes a lifetime error:
// args.sort_by_key(|a| a.name());
println!("{:?}", args);
}
Clippy says:
Checking playground v0.0.1 (/playground)
warning: use Vec::sort_by_key here instead
--> src/main.rs:14:5
|
14 | args.sort_by(|a, b| a.name().cmp(b.name()));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `args.sort_by_key(|&a| a.name())`
|
= note: `#[warn(clippy::unnecessary_sort_by)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_sort_by
warning: 1 warning emitted
Finished dev [unoptimized + debuginfo] target(s) in 0.33s
When applying the suggestion (= uncommenting the marked line in the code), the following happens:
Checking playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/main.rs:16:26
|
16 | args.sort_by_key(|a| a.name());
| -- ^^^^^^^^ returning this value requires that `'1` must outlive `'2`
| ||
| |return type of closure is &'2 str
| has type `&'1 Test`
error: aborting due to previous error
error: could not compile `playground`.
To learn more, run the command again with --verbose.
Meta
No idea. This happens on the Rust playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=732732b92adbc28314716081acc4e733
The playground says this is clippy 0.0.212 (2020-06-26 7750c3d)
and I have no idea were to find the rustc version. Sorry.
I cannot reproduce locally with clippy 0.0.212 (d4092ac 2020-05-11)
.