Trait implementation for both a trait object and for direct implementors of the trait

↘锁芯ラ 提交于 2019-11-27 15:17:13

Implement your trait for all Box<S> where S implements your trait. Then you simply delegate to the existing implementation:

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

You'll also find that it can be useful to do the same for references:

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

All together:

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

impl<'a, S: Solid + ?Sized> Solid for &'a S {
    fn intersect(&self, ray: f32) -> f32 {
        (**self).intersect(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<Solid>> = Group(vec![
        Box::new(direct),
        Box::new(boxed),
        Box::new(Point),
        Box::new(reference),
    ]);

    mixed.intersect(1.0);
}

The ?Sized bound allows the S to not have a size known at compile time. Importantly, this allows you to pass in trait objects such as Box<Solid> or &Solid as the type Solid does not have a known size.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!