鉴于这一守则:
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 + 'a) needed?有一个关键的区别。
根据该问题的答案中提到的RFC 0599,&'a Box<SomeTrait>类型与仅使其具有不同默认寿命的Box<SomeTrait>之间存在差异。因此,在这种情况下,根据RFC,我认为装箱特征的默认生存期应该是'a,而不是'static。
这意味着,要么有一个更新的RFC更改了RFC 0599的规范,要么该代码无法工作的另一个原因。
在这两种情况下,另一个问题的答案都不适用于这个问题,因此,这不是一个重复的问题。
发布于 2018-10-30 15:20:20
这些规则是由RFC 1156 (重点雷)调整的:
为
&'x Box<Trait>和&'x Arc<Trait>这样的情况调整对象默认界限算法。现有算法默认为&'x Box<Trait+'x>。建议的更改为默认为
https://stackoverflow.com/questions/53049213
复制相似问题