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
})
}
}在操场上运行它的here。
我从编译器那里得到了这条信息:
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)>我知道静态生命周期是从哪里来的,但是在结构B的创建过程中不会传递相同的生命周期给它,因为它接受任何泛型生命周期。
在以下答案后编辑
我也尝试过将struct设为泛型,但在初始化后无法使用它。
发布于 2019-11-11 19:21:48
我修复了它(playground)。相关代码如下:
// 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,
})
}
}为什么需要这样做?
特征对象总是有一个生命周期。如果未指定或推断生存期,则默认为'static。因此,您必须使Out在其生命周期内成为泛型,并在实现中使用它。
https://stackoverflow.com/questions/58799788
复制相似问题