Why does Arc<dyn Fn(&'b Box<dyn DecodedPacket<'a>>)> require 'a to be 'static?

Viewed 69

On this example:

use std::sync::Arc;

trait DecodedPacket<'a> {}

struct ReferencePacket<'a> {
    data: &'a [u8],
}

impl<'a> DecodedPacket<'a> for ReferencePacket<'a> {}

struct Decoder {}

impl Decoder {
    pub fn receive<'a, 'b>(&self, on_packet: Arc<dyn Fn(&'b Box<dyn DecodedPacket<'a>>)>) {
        let slice: &[u8] = &[0, 1, 2];
        let reference_packet: Box<dyn DecodedPacket<'a>> =
            Box::new(ReferencePacket { data: slice });

        on_packet(&reference_packet);
    }
}

Playground

I get:

error[E0759]: `on_packet` has lifetime `'a` but it needs to satisfy a `'static` lifetime requirement
  --> src/lib.rs:17:13
   |
14 |     pub fn receive<'a, 'b>(&self, on_packet: Arc<dyn Fn(&'b Box<dyn DecodedPacket<'a>>)>) {
   |                                              ------------------------------------------- this data with lifetime `'a`...
...
17 |             Box::new(ReferencePacket { data: slice });
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...is captured here...
18 | 
19 |         on_packet(&reference_packet);
   |                   ----------------- ...and is required to live as long as `'static` here

I don't see any rule that specifies on_packet should only accept 'static lifetimes. I specifically made is such that 'a is parametrized in the function, so it should be whatever the caller decides.

0 Answers
Related