实现特征或取消引用特征的类型的泛型类型

时间:2019-12-10 23:08:44

标签: rust

我正在寻找一种创建特征对象集合的方法。 但是我想接受实现给定特征的对象,或者包装并取消引用特征的对象。

trait TheTrait {
   // fn foo() -> ();
}

// "Direct" implementation
struct Implements {}
impl TheTrait for Implements {}

// "Proxy" implementation
struct DerefsTo {
    implements: Implements,
}
impl std::ops::Deref for DerefsTo {
    type Target = dyn TheTrait;
    fn deref(&self) -> &Self::Target {
        return &self.implements;
    }
}

fn main() -> () {
    let x1: Box<dyn TheTrait> = Box::new(Implements {}); // This is fine
    let x2: Box<dyn TheTrait> = Box::new(DerefsTo {implements: Implements {}}); // Trait TheTrait not implemented
    let x3: Box<dyn TheTrait> = Box::new(x1); // Trait TheTrait not implemented

    // Put x1, x2, x3 to collection, call foo
}

有没有办法做到这一点,而无需触摸Implements类型? 是否有任何通用的方法可以通过公开一个实现特质的字段来实现特质,例如“包装”类型?

1 个答案:

答案 0 :(得分:1)

您可能想要

impl<T: std::ops::Deref<Target = dyn TheTrait>> TheTrait for T

这允许您编写:

trait TheTrait {
    fn foo(&self) -> ();
}

// "Direct" implementation
struct Implements {}
impl TheTrait for Implements {
    fn foo(&self) {
        println!("Implements::foo")
    }
}

// "Proxy" implementation
struct DerefsTo {
    implements: Implements,
}
impl std::ops::Deref for DerefsTo {
    type Target = dyn TheTrait;
    fn deref(&self) -> &Self::Target {
        return &self.implements;
    }
}

impl<T: std::ops::Deref<Target = dyn TheTrait>> TheTrait for T {
    fn foo(&self) {
        self.deref().foo() // forward call
    }
}

fn main() -> () {
    let x1: Box<dyn TheTrait> = Box::new(Implements {});
    let x1_2: Box<dyn TheTrait> = Box::new(Implements {});
    let x2: Box<dyn TheTrait> = Box::new(DerefsTo {
        implements: Implements {},
    });
    let x3: Box<dyn TheTrait> = Box::new(x1_2);
    let vec = vec![x1, x2, x3];
    for x in vec {
        x.foo();
    }
}