2

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • See also [The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want](https://stackoverflow.com/q/40053550/155423); [How does for<> syntax differ from a regular lifetime bound?](https://stackoverflow.com/a/35595491/155423); [How to write a trait bound for adding two references of a generic type?](https://stackoverflow.com/q/34630695/155423) – Shepmaster Jul 02 '21 at 18:23
  • As well as [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Jul 02 '21 at 18:23
  • The [duplicates applied to your case](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=cdf84406826600c73acc6e9ca2fb20fc). – Shepmaster Jul 02 '21 at 18:25
  • @Shepmaster based on the links, it looks like the problem is that the caller specifies the lifetimes, so since it doesn't know which `Arc` I will pass, it prepares the function for the worst case possible which would be an `Arc` with `'a` and `'b` being `'static`. Am I right? – Guerlando OCs Jul 02 '21 at 18:56
  • @Shepmaster didn't see the last link. Why does `'_` fix this? What's the difference from `for<'a> dyn Fn(&dyn DecodedPacket<'a>)>` and `dyn Fn(&dyn DecodedPacket<'_>)>`? – Guerlando OCs Jul 03 '21 at 04:00

0 Answers0