gpt4 book ai didi

rust - 由于生命周期错误而产生光线追踪世界时出现问题

转载 作者:行者123 更新时间:2023-12-03 11:44:26 25 4
gpt4 key购买 nike

我一直在坚持如何最好地在Rust中创造一个世界(这是针对raytracer的)。我试图在这里举一个小例子。
参见操场here。我会遇到很多不同的生命周期错误,因此也许您更容易看一下代码。

trait Material {}

struct Metal {}

impl Material for Metal {}

trait Hit {
fn hit(&self) -> Option<HitRecord>;
}
struct Sphere<'a> {
material: &'a dyn Material,
}

impl<'a> Hit for Sphere<'a> {
fn hit(&self) -> Option<HitRecord> {
Some(HitRecord {
material: self.material,
})
}
}

struct HitRecord<'a> {
material: &'a dyn Material,
}

#[derive(Default)]
struct World {
materials: Vec<Box<dyn Material>>,
hitables: Vec<Box<dyn Hit>>,
}

impl World {
fn add_material(&mut self, mat: impl Material + 'static) -> &dyn Material {
self.materials.push(Box::new(mat));
self.materials.last().unwrap().as_ref()
}

fn add_hitable(&mut self, hitable: impl Hit + 'static) {
self.hitables.push(Box::new(hitable));
}
}

fn make_world() -> World {
let mut world = World::default();
let metal = Metal {};
let metal = world.add_material(metal);
let sphere = Sphere { material: metal };
world.add_hitable(sphere);
world
}

fn main() {
let world = make_world();
}

最佳答案

Rc的效率略低于裸引用,但使用起来却容易得多。

use std::rc::Rc;

trait Material {}

struct Metal {}

impl Material for Metal {}

trait Hit {
fn hit(&self) -> Option<HitRecord>;
}

struct Sphere {
material: Rc<dyn Material>,
}

impl Hit for Sphere {
fn hit(&self) -> Option<HitRecord> {
Some(HitRecord {
material: Rc::clone(&self.material),
})
}
}

struct HitRecord {
material: Rc<dyn Material>,
}

#[derive(Default)]
struct World {
materials: Vec<Rc<dyn Material>>,
hitables: Vec<Rc<dyn Hit>>,
}

impl World {
fn add_material(&mut self, mat: impl Material + 'static) -> Rc<dyn Material> {
let rc: Rc<dyn Material> = Rc::new(mat);
self.materials.push(Rc::clone(&rc));
rc
}
fn add_hitable(&mut self, hitable: impl Hit + 'static) {
self.hitables.push(Rc::new(hitable));
}
}

fn make_world() -> World {
let mut world = World::default();
let metal = Metal {};
let metal = world.add_material(metal);
let sphere = Sphere { material: metal };
world.add_hitable(sphere);
world
}

fn main() {
let world = make_world();
}
Playground link

关于rust - 由于生命周期错误而产生光线追踪世界时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64760544/

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