【发布时间】:2019-11-11 10:40:48
【问题描述】:
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 Out 设为通用,但在初始化后无法使用它。
【问题讨论】:
标签: rust