[英]the lifetime must be valid for the static lifetime
trait X {}
trait Y {}
struct A {}
impl X for A {}
struct B<'r> {
x: &'r mut Box<dyn X + 'r>,
id: i32,
}
impl <'r> Y for B<'r> {}
struct Out {
x: Box<dyn X>,
}
impl Out {
pub fn new() -> Self {
return Out {
x: Box::new(A{})
}
}
pub fn get_data(&mut self) -> Box<dyn Y> {
return Box::new(B{
id: 1,
x: &mut self.x
})
}
}
Run it here on playground. 在操场上运行它。
I am getting this note from the compiler:我从编译器得到这个注释:
note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected &mut std::boxed::Box<dyn X>
found &mut std::boxed::Box<(dyn X + 'static)>
I understand where static lifetime is coming from, but doesn't the same lifetime is passed to struct B during its creation which accepts any generic lifetime.我了解 static 生命周期的来源,但在其创建过程中不会将相同的生命周期传递给 struct B,它接受任何通用生命周期。
[Edit After below answer] [在以下答案后编辑]
I also tried making struct Out generic but then was unable to use it after initialization.我还尝试使 struct Out 通用,但在初始化后无法使用它。
I fixed it ( playground ).我修好了( 操场)。 Here's the relevant code:
以下是相关代码:
// note the lifetime!
struct Out<'a> {
x: Box<dyn X + 'a>,
}
// note the lifetime!
impl<'a> Out<'a> {
pub fn new() -> Self {
return Out {
x: Box::new(A{})
}
}
pub fn get_data(&'a mut self) -> Box<dyn Y + 'a> {
return Box::new(B {
id: 1,
x: &mut self.x,
})
}
}
Why is this necessary?为什么这是必要的?
Trait objects always have a lifetime.特征对象总是有生命周期的。 If no lifetime is specified or inferred, it defaults to
'static
.如果没有指定或推断生命周期,则默认为
'static
。 Therefore you have to make Out
generic over its lifetime and use it in the implementation.因此,您必须在其生命周期内使
Out
泛型并在实现中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.