繁体   English   中英

实现 trait 或取消引用 trait 的类型的通用类型

[英]Generic type for types implementing trait or dereferencing to trait

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

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类型? 是否有任何通用方法通过公开实现它的字段来实现特性,例如“包装器”类型?

你可能想要

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();
    }
}

暂无
暂无

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

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