rust - 特征对象和特征的直接实现者的特征实现

标签 rust traits

我有一个主要封装向量的结构:

struct Group<S> {
    elements: Vec<S>
}

我还有一个简单的特性,它也适用于其他结构:

trait Solid {
    fn intersect(&self, ray: f32) -> f32;
}

我想实现 Solid对于 Group , 但我希望能够使用 Group两者都用于 Solid 的相同实现列表以及 Solid 的混合实现列表.基本上我想同时使用 Group<Box<Solid>>Group<Sphere> ( Sphere 实现了 Solid )。

目前我正在使用这样的东西:

impl Solid for Group<Box<Solid>> {
    fn intersect(&self, ray: f32) -> f32 {
        //do stuff
    }
}

impl<S: Solid> Solid for Group<S> {
    fn intersect(&self, ray: f32) -> f32 {
        //do the same stuff, code copy-pasted from previous impl
    }
}

这行得通,但是让一行一行的相同代码重复两次并不是惯用的解决方案。我一定是遗漏了一些明显的东西吗?

在我的例子中,我测量了两个特征实现之间的显着性能差异,所以总是使用 Group<Box<Solid>>不是一个很好的选择。

最佳答案

为所有人实现你的特质 Box<S>其中 S实现你的特质。然后你可以委托(delegate)给现有的实现:

impl<S: Solid + ?Sized> Solid for Box<S> {
    fn intersect(&self, ray: f32) -> f32 {
        (**self).intersect(ray)
        // Some people prefer this less-ambiguous form
        // S::intersect(self, ray)
    }
}

您还会发现对引用做同样的事情会很有用:

impl<S: Solid + ?Sized> Solid for &'_ S {
    fn intersect(&self, ray: f32) -> f32 {
        (**self).intersect(ray)
        // Some people prefer this less-ambiguous form
        // S::intersect(self, ray)
    }
}

一起:

trait Solid {
    fn intersect(&self, ray: f32) -> f32;
}

impl<S: Solid + ?Sized> Solid for Box<S> {
    fn intersect(&self, ray: f32) -> f32 {
        (**self).intersect(ray)
        // S::intersect(self, ray)
    }
}

impl<S: Solid + ?Sized> Solid for &'_ S {
    fn intersect(&self, ray: f32) -> f32 {
        (**self).intersect(ray)
        // S::intersect(self, ray)
    }
}

struct Group<S>(Vec<S>);

impl<S: Solid> Solid for Group<S> {
    fn intersect(&self, _ray: f32) -> f32 {
        42.42
    }
}

struct Point;

impl Solid for Point {
    fn intersect(&self, _ray: f32) -> f32 {
        100.
    }
}

fn main() {
    let direct = Group(vec![Point]);
    let boxed = Group(vec![Box::new(Point)]);
    let pt = Point;
    let reference = Group(vec![&pt]);

    let mixed: Group<Box<dyn Solid>> = Group(vec![
        Box::new(direct),
        Box::new(boxed),
        Box::new(Point),
        Box::new(reference),
    ]);

    mixed.intersect(1.0);
}

?Sized绑定(bind)允许 S在编译时不知道大小。重要的是,这允许您传入 trait 对象,例如 Box<dyn Solid>&dyn Solid作为类型 Solid没有已知的大小。

另见:

关于rust - 特征对象和特征的直接实现者的特征实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46380283/

相关文章:

rust - 在Clap中的参数中采用多个值

rust - 如何将装箱移动到函数而不是调用方

rust - 具有特征的通用 API

新类型的 Rust 特征

rust - 如何使用Rust crate 'boolean_expression'来实现简单的逻辑电路?

rust - 如何编写带有可链接标记的宏?

rust - 如何在 actix-web 中接收多个具有相同名称的查询参数?

c++ - 使用特征强制类型定义

scala - 性状混合的限制

rust - 如何使用代表 StructOpt 子命令的枚举?