Parameter type may not live long enough?

前端 未结 1 1894
逝去的感伤
逝去的感伤 2020-11-30 13:48

The following code segment gives me an error:

use std::rc::Rc;

// Definition of Cat, Dog, and Animal (see the last code block)
// ...

type RcAnimal = Rc<         


        
相关标签:
1条回答
  • 2020-11-30 14:28

    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>)
    }
    
    0 讨论(0)
提交回复
热议问题