【问题标题】:How do I create a trait object from another trait object?如何从另一个 trait 对象创建一个 trait 对象?
【发布时间】:2018-07-07 11:55:07
【问题描述】:

Rust 的最新稳定版本 (1.27) 允许为 trait 对象实现一个 trait (dyn Trait),所以我尝试了following

trait T1 {
    fn f1(&self);
}
trait T2 {
    fn f2(&self);
}
impl T2 for dyn T1 {
    fn f2(&self) {
        self.f1()
    }
}
struct S();
impl T1 for S {
    fn f1(&self) {}
}

fn main() {
    let t1 = S();
    let t12: &T1 = &t1;
    t12.f2();
    let t2: &T2 = &t12;
    t2.f2();
}

以上代码导致错误:

error[E0277]: the trait bound `&T1: T2` is not satisfied
  --> src/main.rs:21:19
   |
21 |     let t2: &T2 = &t12;
   |                   -^^^
   |                   |
   |                   the trait `T2` is not implemented for `&T1`
   |                   help: consider removing 1 leading `&`-references
   |
   = help: the following implementations were found:
             <T1 + 'static as T2>
   = note: required for the cast to the object type `T2`

这很令人困惑,因为&amp;T1dyn T1 的一个实例,所以有一个T2 实现。我们甚至可以通过我们可以直接在t12 上调用f2 来见证这一点,因为删除main 中的最后两行使其编译。

是否可以从标记为不同特征的特征对象创建特征对象?

【问题讨论】:

  • Rust 的最新稳定版本 (1.27) 允许 - 从 Rust 1.0 开始允许这样做。唯一新的是文字 dyn 关键字。没有它,您的代码行为相同 (impl T2 for T1 { /* ... */ })。

标签: rust trait-objects


【解决方案1】:

您正在为 trait 对象本身 (dyn T1) 实现 T2,但试图将其用于 reference 到 trait 对象 (&amp;dyn T1)。

改用impl&lt;'a&gt; T2 for &amp;'a dyn T1 { ... }。这意味着“对于任何生命周期 'a,实现 T2 以获得对 'a 有效并引用 T1-trait 对象的引用”。
我不知道impl ... for dyn ... 本身有什么用处。

Adjusted code from the question in the playground

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多