Parameter type may not live long enough?

There are actually plenty of types that can “not live long enough”: all the ones that have a lifetime parameter.

If I were to introduce this type:

struct ShortLivedBee<'a>;
impl<'a> Animal for ShortLivedBee<'a> {}

ShortLivedBee is not valid for any lifetime, but only the ones that are valid for 'a as well.

So in your case with the bound

where T: Animal + 'static

the only ShortLivedBee I could feed into your function is ShortLivedBee<'static>.

What causes this is that when creating a Box<Animal>, you are creating a trait object, which need to have an associated lifetime. If you do not specify it, it defaults to 'static. So the type you defined is actually:

type RcAnimal = Rc<Box<Animal + 'static>>;

That’s why your function require that a 'static bound is added to T: It is not possible to store a ShortLivedBee<'a> in a Box<Animal + 'static> unless 'a="static.


An other approach would be to add a lifetime annotation to your RcAnimal, like this:

type RcAnimal<"a> = Rc<Box<Animal + 'a>>;

And change your function to explicit the lifetime relations:

fn new_rc_animal<'a, T>(animal: T) -> RcAnimal<'a>
        where T: Animal + 'a { 
    Rc::new(Box::new(animal) as Box<Animal>)
}

Leave a Comment