Consider the following example:
struct Test<'l, T> {
t: &'l T,
}
fn test<'lt, F, T>(f: F) -> T
where
F: for<'t> FnOnce(&'t String) -> T,
{
let str = String::from("test");
return f(&str);
}
fn main(){
test(|s| {
println!("{}", s);
Test { t: s } //error: lifetime may not live long enough
});
}
Here is the detailed error message rust compiler emits:
Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/main.rs:16:9
|
14 | test(|s| {
| -- return type of closure is Test<'2, String>
| |
| has type `&'1 String`
15 | println!("{}", s);
16 | Test { t: s } //error: lifetime may not live long enough
| ^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
From what I understand the lifetime &'2 is related to fn main() function scope since the return value Test { t: s } transfers ownership to a caller from main and therefore should be valid within main.
I'm curious if there any other way to debug incorrect lifetimes than looking at it with eyes and trying to understand what went wrong? Maybe some verbose rustc output or similar?
I suspect in much more complicated cases such debugging might be time consuming so probably there's an automated way to track lifetimes out there?