我正在编写光线跟踪器来学习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>`
测试将在Sphere
或Plane
成员函数中进行,并针对self
进行测试。
答案 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 ++中也不起作用。