I'm rather new to rust, and I'm struggling with the lifetime stuff rn. So basically I'm constructing a struct and I want to store a closure in that struct. But one of the captured variables does not live long enough.
struct HtmlOut<'a> {
echo_escaped: &'a dyn Fn(&String)
}
// not really implemented yet
fn escape(s: &String) -> &String {
return s;
}
impl<'a> HtmlOut<'a> {
fn new(echo: &'a dyn Fn(&String)) -> HtmlOut<'a> {
let echo_element_escaped_cls = |s: &String| { echo(escape(s)) };
let echo_element_escaped: &'a dyn Fn(&String) = &echo_element_escaped_cls;
return HtmlOut {
echo_escaped: echo_element_escaped
}
}
}
I get two errors:
|s: &String| { echo(escape(s)) };
------------ ^^^^ borrowed value does not live long enough
and
&'a dyn Fn(&String) = &echo_element_escaped_cls;
------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
|
type annotation requires that `echo_element_escaped_cls` is borrowed for `'a`
My questions are:
- why does echo not live long enough, when everything is annotated with the same lifetime specifier
'a
? - how do I rewrite this code so that
echo
lives long enough?