rust - 生命周期必须对静态生命周期有效
问题描述
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
})
}
}
在操场上运行它。
我从编译器得到这个注释:
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 通用,但在初始化后无法使用它。
解决方案
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
. Therefore you have to make Out
generic over its lifetime and use it in the implementation.
推荐阅读
- r - 单词替换(使用 R 语言)
- html - 单击子导航时,Safari 中出现奇怪的重新渲染/重新绘制问题
- ansible - Ansible - 将一些计算属性添加到 dict 列表
- excel - #DIV/0!错误,SSIS 2010 - EXCEL 2013 - 格式化问题
- amazon-web-services - AppSync 验证错误不会触发响应映射模板中的错误处理程序
- f# - 如何在 F# 中使用 Akka.Streams.*.ConcatMany?
- clojure - 在 Clojure 中生成数据矩阵
- reactjs - ReactRouter 工作不正确,只更改 url 不查看
- python - 如何通过解析python中的列表来运行多个函数?
- svn - 如何根据目录名称设置 VisualSVN 权限?