Lifetime for Fn

#1

The compiler tell me that String s does not live long enough.
But actually I do not need borrow of s after call of fun.
So is any way to convince compiler that after call to fun I don’t need s,
so borrow checked becomes happy?

fn f<'a, 'b, F>(fun: F) -> bool
where
    F: Fn(&'a str) -> Option<&'b i32>,
{
    let s = "aaaa".to_string(); //in real code there is some calculation

    fun(s.as_str()).map_or(true, |x| *x == 17)
}
0 Likes

#2

Drop the 'a in the F bound, i.e.:

fn f<'b, F>(fun: F) -> bool
where
    F: Fn(&str) -> Option<&'b i32>,
1 Like

#3

@vitalyd

Thanks, but why this helps?

I reread https://doc.rust-lang.org/book/ch19-02-advanced-lifetimes.html , but it is still unclear for me.

0 Likes

#4

This SO answer is the one I typically refer people to.

1 Like