Lifetime for Fn


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
    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)


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

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



Thanks, but why this helps?

I reread , but it is still unclear for me.



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

1 Like