且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

参数类型可能不够长?

更新时间:2023-02-05 22:46:10

实际上有很多类型可以活得不够久":所有类型都有生命周期参数.

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 对任何生命周期都无效,但仅对 'a 有效.

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

所以在你的情况下

where T: Animal + 'static

我可以输入您的函数的唯一 ShortLivedBeeShortLivedBee.

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

造成这种情况的原因是,在创建 Box 时,您正在创建一个 trait 对象,该对象需要具有关联的生命周期.如果不指定,则默认为'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>>;

这就是为什么您的函数要求将 'static 绑定添加到 T:不可能存储 ShortLivedBeeBox 除非 'a = '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.

另一种方法是为您的 RcAnimal 添加生命周期注释,如下所示:

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>)
}