[英]life time of a trait object reference
With FooClass
that implements FooTrait
, and Bar
that takes the reference of a FooTrait
object, the code is working:使用实现
FooTrait
的FooClass
和引用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");
}
But for但对于
struct Bar<'a> {
foo: &'a (dyn FooTrait),
}
impl<'a> Bar<'a> {
fn new(_foo: &'a (dyn FooTrait)) -> Bar<'a> {
Bar { foo: _foo }
}
}
I have also seen they are written as我也看到他们写成
struct Bar<'a> {
foo: &'a (dyn FooTrait + 'a),
}
impl<'a> Bar<'a> {
fn new(_foo: &'a (dyn FooTrait + 'a)) -> Bar<'a> {
Bar { foo: _foo }
}
}
I think I understand that struct Bar<'a> { foo: &'a (dyn FooTrait + 'a), }
says, foo
should live at least as long as Bar
so that reference stay valid.我想我理解
struct Bar<'a> { foo: &'a (dyn FooTrait + 'a), }
说, foo
应该至少和Bar
一样长,这样引用才能保持有效。 But this explains only Bar<'a>
and foo: &'a
, that I don't see what does + 'a
do after dyn FooTrait
in the parentheses.但这仅解释了
Bar<'a>
和foo: &'a
,我看不到+ 'a
在括号中的dyn FooTrait
之后做了什么。 Also, removing +'a
doesn't seems to break the program.此外,删除
+'a
似乎不会破坏程序。 Can someone explain to me the purpose?有人可以向我解释目的吗?
The + 'a
says that not only does the concrete type need to implement FooTrait
, but it also may not itself contain references that live shorter than 'a
. + 'a
表示不仅具体类型需要实现FooTrait
,而且它本身也可能不包含比'a
更短的引用。
Consider:考虑:
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");
}
The compiler needs to know that not only does foo
not disappear during the lifetime of bar
, but also that nothing foo
itself references goes out of scope.编译器需要知道,不仅
foo
在bar
的生命周期内不会消失,而且foo
本身引用的任何内容都不会超出 scope。 The + 'a
condition ensures this. + 'a
条件确保了这一点。
(I can't think of a way to write an example that violates this condition that won't also violate the mere creation of the FooWithRefs
though.) (我想不出一种方法来编写一个违反此条件的示例,但也不会违反
FooWithRefs
的单纯创建。)
I don't know the exact semantics of omitting the lifetime bound, though.不过,我不知道省略生命周期限制的确切语义。 Trying it out suggests that it implicitly uses the same bound.
尝试一下表明它隐含地使用了相同的界限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.