代码之家  ›  专栏  ›  技术社区  ›  Earth Engine

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

  •  0
  • Earth Engine  · 技术社区  · 6 年前

    最新稳定版本的rust(1.27)允许为特征对象实现特征。( 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`
    

    这是令人困惑的 &T1 是的一个实例 dyn T1 还有一个 T2 实施。我们甚至可以通过打电话来证明这一点 f2 t12 直接删除最后两行 main 使其编译。

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

    1 回复  |  直到 6 年前
        1
  •  3
  •   Shepmaster Tim Diekmann    6 年前

    你正在实施 T2 对于特征对象本身( dyn T1 ,但尝试将其用于 参考 到特征对象( &dyn T1 )

    尝试 impl<'a> T2 for &'a dyn T1 { ... } 相反。这意味着“终身 'a ,实施 T2 对于有效的引用 A 指的是 T1 -特征对象”。
    我不知道有什么好的用途 impl ... for dyn ... 本身。

    Adjusted code from the question in the playground