gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:07:22 32 4
gpt4 key购买 nike

<分区>

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

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 进行测试.

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com