如何测试与实现特征的给定盒装对象的相等性?

时间:2018-09-10 21:25:04

标签: rust

我正在编写光线跟踪器来学习Rust。我有一个Scene,其中包含Shape,可以与光线相交的形状。至少,它类似于:

pub trait Shape {
    fn draw(&self);
}

pub struct Plane {}

impl Shape for Plane {
    fn draw(&self) {}
}

pub struct Sphere {}

impl Shape for Sphere {
    fn draw(&self) {}
}

pub struct Scene {
    objects: Vec<Box<dyn Shape>>,
}

fn main() {
    let mut scene = Scene { objects: vec![] };

    let plane1 = Box::new(Plane {});
    let plane2 = Box::new(Plane {});
    let sphere = Box::new(Sphere {});

    scene.objects.push(plane1);
    scene.objects.push(plane2);
    scene.objects.push(sphere);

    for object in scene.objects {
        // I want to test if a given object in the scene is the same as another
        if object == plane2 {}
    }
}

给定存储在Vec<Box<dyn Shape>>中的形状,我如何测试与实现Shape特征的给定盒装对象的相等性?

error[E0369]: binary operation `==` cannot be applied to type `std::boxed::Box<Shape>`
  --> src/main.rs:34:12
   |
34 |         if object == plane2 {}
   |            ^^^^^^^^^^^^^^^^
   |
   = note: an implementation of `std::cmp::PartialEq` might be missing for `std::boxed::Box<Shape>`

测试将在SpherePlane成员函数中进行,并针对self进行测试。

1 个答案:

答案 0 :(得分:2)

在C ++中,您可以从指向Sphere的指针转换为指向Intersector的指针(即,从Sphere*Intersector*)。尽管对于C ++来说这不是惯用语言,但它也可以与参考一起使用。

这与Rust完全相同,除了在Rust中使用引用而不是原始指针更惯用:

impl Scene {
    pub fn some_function(&self, intersector: &Intersector) {
        for object in &self.objects {
            if intersector == object {}
        }
    }
}

请注意,您的原始代码使用了*const Box<dyn Intersector>,它是指向包含Intersector的盒子的指针,并在C ++中大致转换为smart_pointer<Intersector>*,因此您的Rust代码相当于传递一个Intersector*到一个期望smart_pointer<Intersector>*的函数,该函数在C ++中也不起作用。