繁体   English   中英

如何从另一个特征对象创建特征对象?

[英]How do I create a trait object from another trait object?

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`

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

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

您正在为特征对象本身( dyn T1 )实现T2 ,但是尝试将其用于对特征对象( &dyn T1 )的引用

尝试将impl<'a> T2 for &'a dyn T1 { ... } 这意味着“对于任何生命周期'a ,针对对'a有效且引用了T1 trait对象的引用实现T2 ”。
我不知道将impl ... for dyn ...很好地impl ... for dyn ...本身。

从操场上的问题调整代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM