0

Rust 的最新稳定版本(1.27)允许为特征对象(dyn Trait)实现特征,所以我尝试了以下方法:

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`

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

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

4

1 回答 1

3

您正在实现T2一个特征对象本身 ( dyn T1),但尝试使用它来引用一个特征对象 ( &dyn T1)。

试试impl<'a> T2 for &'a dyn T1 { ... }吧。这意味着“对于任何生命周期'a,实现对-trait 对象T2有效'a并引用的引用”。 我不知道自己有什么好用的。T1
impl ... for dyn ...

从操场上的问题调整代码

于 2018-07-07T13:47:00.780 回答