繁体   English   中英

特征 object 参考的寿命

[英]life time of a trait object reference

使用实现FooTraitFooClass和引用FooTrait object 的Bar ,代码正在运行:

trait FooTrait {
    fn print(self);
}

struct FooClass {}

impl FooTrait for FooClass {
    fn print(self) {
        println!("It's a Foo");
    }
}

struct Bar<'a> {
    foo: &'a (dyn FooTrait),
}

impl<'a> Bar<'a> {
    fn new(_foo: &'a (dyn FooTrait)) -> Bar<'a> {
        Bar { foo: _foo }
    }
}

fn main() {
    let foo = FooClass {};
    let bar = Bar::new(&foo);
    println!("hello world");
}

但对于

struct Bar<'a> {
    foo: &'a (dyn FooTrait),
}

impl<'a> Bar<'a> {
    fn new(_foo: &'a (dyn FooTrait)) -> Bar<'a> {
        Bar { foo: _foo }
    }
}

我也看到他们写成

struct Bar<'a> {
    foo: &'a (dyn FooTrait + 'a),
}

impl<'a> Bar<'a> {
    fn new(_foo: &'a (dyn FooTrait + 'a)) -> Bar<'a> {
        Bar { foo: _foo }
    }
}

我想我理解struct Bar<'a> { foo: &'a (dyn FooTrait + 'a), }说, foo应该至少和Bar一样长,这样引用才能保持有效。 但这仅解释了Bar<'a>foo: &'a ,我看不到+ 'a在括号中的dyn FooTrait之后做了什么。 此外,删除+'a似乎不会破坏程序。 有人可以向我解释目的吗?

+ 'a表示不仅具体类型需要实现FooTrait ,而且它本身也可能不包含比'a更短的引用。

考虑:

struct FooWithRefs<'b> { reff: &'b i32, }
impl <'b> FooTrait for FooWithRefs<'b> { ... }

fn main() {
    let i = 100;
    let foo = FooWithRefs { reff: &i };
    let bar = Bar::new(&foo);
    println!("hello world");
}

编译器需要知道,不仅foobar的生命周期内不会消失,而且foo本身引用的任何内容都不会超出 scope。 + 'a条件确保了这一点。

(我想不出一种方法来编写一个违反此条件的示例,但也不会违反FooWithRefs的单纯创建。)

不过,我不知道省略生命周期限制的确切语义。 尝试一下表明它隐含地使用了相同的界限。

在操场上看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM