【问题标题】:Why is &'a Box<Trait> treated as &'a Box<Trait + 'static> and not &'a Box<Trait + 'a>?为什么 &'a Box<Trait> 被视为 &'a Box<Trait + 'static> 而不是 &'a Box<Trait + 'a>?
【发布时间】: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: &amp;'a Box&lt;dyn Trait + 'a&gt; 编译代码,但我不明白为什么会这样。

根据RFC 0599,默认的对象绑定规则应该将&amp;'a Box&lt;Trait&gt;类型读取为&amp;'a Box&lt;Trait + 'a&gt;。相反,它的行为与 &amp;'a Box&lt;Trait + 'static&gt; 相同。

  1. 为什么我的原始代码无法编译?
  2. 默认对象绑定是否像看起来那样采用&amp;'a Box&lt;Trait + 'static&gt;?

这个问题和Why is adding a lifetime to a trait with the plus operator (Iterator<Item = &Foo> + 'a) needed? 有一个关键的区别。

根据该问题的答案中提到的RFC 0599,&amp;'a Box&lt;SomeTrait&gt; 类型和 Box&lt;SomeTrait&gt; 类型之间存在差异,这使得它们具有不同的默认生命周期。因此,在这种情况下,根据 RFC,我认为 boxed trait 的默认生命周期应该是 'a 而不是 'static。

这意味着要么有更新的 RFC 更改了 RFC 0599 的规范,要么有其他原因导致此代码无法正常工作。

在这两种情况下,另一个问题的答案都不适用于这个问题,因此,这不是一个重复的问题。

【问题讨论】:

    标签: rust


    【解决方案1】:

    这些规则由RFC 1156(强调我的)调整:

    针对&amp;'x Box&lt;Trait&gt; 和&amp;'x Arc&lt;Trait&gt; 等情况调整对象默认绑定算法。现有算法将默认为&amp;'x Box&lt;Trait+'x&gt;。建议的更改是默认为&amp;'x Box&lt;Trait+'static&gt;。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 2021-10-01
      相关资源
      最近更新 更多