【发布时间】:2018-10-29 15:50:39
【问题描述】:
鉴于此代码:
trait Trait {}
struct Child;
impl Trait for Child {}
struct Father<'a> {
child: &'a Box<dyn Trait>,
}
impl<'a> Trait for Father<'a> {}
fn main() {
let child: Box<dyn Trait> = Box::new(Child {});
let father: Box<dyn Trait> = Box::new(Father { child: &child });
let grandf: Box<dyn Trait> = Box::new(Father { child: &father });
}
此代码无法使用 Rust 1.30.0 编译,我收到以下错误:
error[E0597]: `child` does not live long enough
--> src/main.rs:11:60
|
11 | let father: Box<dyn Trait> = Box::new(Father { child: &child });
| ^^^^^ borrowed value does not live long enough
12 | let grandf: Box<dyn Trait> = Box::new(Father { child: &father });
13 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
我可以使用child: &'a Box<dyn Trait + 'a> 编译代码,但我不明白为什么会这样。
根据RFC 0599,默认的对象绑定规则应该将&'a Box<Trait>类型读取为&'a Box<Trait + 'a>。相反,它的行为与 &'a Box<Trait + 'static> 相同。
- 为什么我的原始代码无法编译?
- 默认对象绑定是否像看起来那样采用
&'a Box<Trait + 'static>?
这个问题和Why is adding a lifetime to a trait with the plus operator (Iterator<Item = &Foo> + 'a) needed? 有一个关键的区别。
根据该问题的答案中提到的RFC 0599,&'a Box<SomeTrait> 类型和 Box<SomeTrait> 类型之间存在差异,这使得它们具有不同的默认生命周期。因此,在这种情况下,根据 RFC,我认为 boxed trait 的默认生命周期应该是 'a 而不是 'static。
这意味着要么有更新的 RFC 更改了 RFC 0599 的规范,要么有其他原因导致此代码无法正常工作。
在这两种情况下,另一个问题的答案都不适用于这个问题,因此,这不是一个重复的问题。
【问题讨论】:
标签: rust