Hi! I have a function, with the following signature:
pub fn sort_unstable_by<T, F>(vec: & mut [T], to_slice: F)
where
F: Fn(&T) -> &[u8],
{
sort_req(vec, &to_slice, 0);
}
Within the sort function, I need to be able to call the to_slice function multiple times, but I only use the returned value within the sort function.
Now, this works for e.g. tuples of strings:
let mut tuples = vec![(String::from("b"), 2), (String::from("a"), 1)];
sort_unstable_by(&mut tuples, |t| t.0.as_bytes());
But when trying to sort a similar structure with &str, it does not seem to work out.
let mut tuples = vec![("b", 2), ("a", 1)];
super::sort_unstable_by(&mut tuples, |t| t.0.as_bytes());
..Gives me this error:
error[E0597]: `*t.0` does not live long enough
--> src/lib.rs:264:50
|
264 | sort_unstable_by(&mut tuples, |t| t.0.as_bytes());
| ^^^ does not live long enough
...
267 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #2 defined on the body at 264:46...
--> src/lib.rs:264:46
|
264 | sort_unstable_by(&mut tuples, |t| t.0.as_bytes());
| ^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
I don't understand what is going on. I have a decent understanding of lifetimes, but this one got me stuck. What I really don't get is why it works with Strings but not &str.
Any help would be much appreciated!