Hello,
I have a small snippet of code that doesn't compile and I would like to understand a bit more why.
use std::path::PathBuf;
pub fn test() {
let v = [PathBuf::new(), PathBuf::new()];
let _max = v.iter().max_by_key(|s| s.file_name());
}
This piece of code compile, there are no issues, and _max
contains a reference to a specific value inside v
.
Now if I want a mutable reference, I naively wrote
use std::path::PathBuf;
pub fn test() {
let mut v = [PathBuf::new(), PathBuf::new()];
let _max = v.iter_mut().max_by_key(|s| s.file_name());
}
However, this time
error: lifetime may not live long enough
--> src/lib.rs:5:44
|
5 | let _max = v.iter_mut().max_by_key(|s| s.file_name());
| -- ^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
| ||
| |return type of closure is Option<&'2 OsStr>
| has type `&'1 &mut PathBuf`
And I don't think I have a real understanding of what's happening.
Is it because there is both a mutable ref and immutable ref at the same time ?
Any way I could get around this issue (maybe by not using a closure but a function with lifetime, I tried but without success) ?
Thank you very much for your time