Consider this function that should return the file extension of a given Path
.
pub fn get_extension<'a>(path: &'a Path) -> Option<&'a str> {
let path_str = path.as_str().unwrap();
let ext_pos = regex!(".[a-z0-9]+$").find(path_str);
match ext_pos {
Some((start, _)) => {
return Some(path_str.as_slice().slice_from(start))
},
None => return None
}
}
The error message is as follows:
`path_str` does not live long enough
The error message is pretty clear and it's a shame I can't work it out on my own. I understand it in theory but there are still a couple of blurred things for me.
I understand that the compiler wants to tell me that path_str
does not live long enough to be valid as the return value with is marked with lifetime 'a
.
But this is where it stops for me:
I understand that the reference to
path
(the input parameter) should life exactly as long as the reference to thestr
that is wrapped in theOption
(the output parameter)since we return
Some(path_str.as_slice().slice_from(start))
I assume that in practice that means thatpath_str
needs to live as long aspath
.
What I don't understand is why exactly does path_str
not live long enough and how could I fix this? What makes it die to soon?
UPDATE
As pointed out in the comments and also on IRC removing the superflous as_slice()
makes the code compile. Does anyone know why that is? It was also pointed out that there exists a method to get the extension directly. But yep, I'm actually more interested in learning the story behind the problem though.