In this simple example, I took the care of making sure DecoderProvider
is a function that expects a reference to a closure, so it expects &Box<dyn Fn(&Option<&Arc<u8>>)>
. This way, it uses the closure very shortly, and thus do not require the closure to be borrowed for 'static
. But below, it looks like calling decoder_provider(&provide_decoder);
forces provide_decoder
to live longer than fn main
, which contains on_packet_render
. Why?
use std::sync::Arc;
pub type DecoderProvider = Arc<dyn Fn(&Box<dyn Fn(&Option<&Arc<u8>>)>)>;
fn main() {
let on_packet_render =
Arc::new(|packet: Option<Box<u8>>| {
//render packet here
});
let decoder = Arc::new(0);
let decoder_provider:DecoderProvider = Arc::new(
move |b: &Box<dyn Fn(&Option<&Arc<u8>>)>| {
b(&Some(&decoder));
},
);
let provide_decoder: Box<dyn Fn(&Option<&Arc<u8>>)> =
Box::new(|decoder| {
on_packet_render(None);
});
decoder_provider(&provide_decoder);
}
error[E0597]: `on_packet_render` does not live long enough
--> src/main.rs:17:13
|
10 | let decoder_provider:DecoderProvider = Arc::new(
| --------------- type annotation requires that `on_packet_render` is borrowed for `'static`
...
16 | Box::new(|decoder| {
| --------- value captured here
17 | on_packet_render(None);
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
21 | }
| - `on_packet_render` dropped here while still borrowed