Lifetime problem calling sort_unstable_by_key()

Viewed 24

I'm trying to call Vec::sort_unstable_by_key() on a Vec. This example is simplified; I realize I could use sort_unstable():

fn main() {
    let mut vec: Vec<String> = Default::default();
    vec.sort_unstable_by_key(|k| k);
}

but I get:

error: lifetime may not live long enough
 --> src/main.rs:7:34
  |
7 |     vec.sort_unstable_by_key(|k| k);
  |                               -- ^ returning this value requires that `'1` must outlive `'2`
  |                               ||
  |                               |return type of closure is &'2 String
  |                               has type `&'1 String`

I'm not sure why k's lifetime and the closure return value's lifetime aren't self-evidently the same, but I tried to fix it by providing a separate function that spells out the lifetimes:

fn get_key<'a>(entry: &'a String) -> &'a String {
    entry
}

fn main() {
    let mut vec: Vec<String> = Default::default();
    vec.sort_unstable_by_key(get_key);
}

but then I get:

error[E0308]: mismatched types
    --> src/main.rs:8:9
     |
8    |     vec.sort_unstable_by_key(get_key);
     |         ^^^^^^^^^^^^^^^^^^^^ lifetime mismatch
     |
     = note: expected associated type `<for<'a> fn(&'a String) -> &'a String {get_key} as FnOnce<(&String,)>>::Output`
                found associated type `<for<'a> fn(&'a String) -> &'a String {get_key} as FnOnce<(&String,)>>::Output`
     = note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here

The expected and found types are identical, but "the required lifetime does not necessarily outlive the empty lifetime". I'm not sure what this means. Why doesn't this work?

0 Answers
Related