In fact, there are many types that may "not live long enough": all those that have a life expectancy parameter.
If I introduced this type:
struct ShortLivedBee<'a>; impl<'a> Animal for ShortLivedBee<'a> {}
ShortLivedBee not valid for any lifetime, but only those valid for 'a .
So in your case with binding
where T: Animal + 'static
the only ShortLivedBee I could use in your function is ShortLivedBee<'static> .
The reason for this is that when you create a Box<Animal> you create an object object that must have a lifetime associated with it. If you do not specify it, the default will be 'static . So the type you defined is actually:
type RcAnimal = Rc<Box<Animal + 'static>>;
For your function to require the addition of 'static in T : It is not possible to save ShortLivedBee<'a> in Box<Animal + 'static> , unless 'a = 'static .
Another approach would be to add an annotation for life to your RcAnimal , for example:
type RcAnimal<'a> = Rc<Box<Animal + 'a>>;
And change your function to explicit life relation:
fn new_rc_animal<'a, T>(animal: T) -> RcAnimal<'a> where T: Animal + 'a { Rc::new(Box::new(animal) as Box<Animal>) }
source share