gpt4 book ai didi

compilation - 我不明白借贷是如何运作的

转载 作者:行者123 更新时间:2023-11-29 08:35:51 26 4
gpt4 key购买 nike

我正在尝试编写一个 kd-tree 实现,但我一直收到错误 cannot move out of borrowed content.

这是我的 KDTree 结构

pub struct KDTree {
pub bounding_box: Aabb,
pub axis: Option<Axis>,
left: Option<Box<KDTree>>,
right: Option<Box<KDTree>>,
pub objects: Option<Vec<Box<Geometry>>>,
}

但是,此方法会抛出该错误。

pub fn direct_samples(&self) -> Vec<u32> {
assert!(self.objects.is_some());
let mut direct_samples = Vec::new();
for (i, object) in self.objects
.expect("Expected tree to have objects")
.iter()
.enumerate() {
if object.material().emittance > 0f32 {
direct_samples.push(i as u32);
}
}
if self.left.is_some() {
direct_samples.extend(self.left.unwrap().direct_samples());
}
if self.right.is_some() {
direct_samples.extend(self.right.unwrap().direct_samples());
}
direct_samples
}

我知道如果我将参数更改为 self 而不是 &self,它应该可以工作,但是当我调用它时,它会给出错误 use移动值。

pub fn from_objects(objects: Vec<Box<Geometry>>) -> Scene {
let tree = KDTree::from_objects(objects);

Scene {
camera: Camera::new(),
objects: tree,
direct_samples: tree.direct_samples(),
}
}

我需要在我的 KDTree 上实现 Copy 吗?这不会使用大量 CPU/内存来复制整个内容吗?

最佳答案

您的代码需要 KDTree 所有权的原因是因为您正在调用 Option::expectOption::unwrap。可以找到这些文档 here .

impl<T> Option<T> {
fn unwrap(self) -> T {
...
}
}

因此,当您调用 unwrap(或 expect)时,编译器会正确地提示您正在按值获取结构的元素。要解决此问题,请使用 Option::as_ref method .

impl<T> Option<T> {
fn as_ref(&self) -> Option<&T> {
...
}
}

这会将对选项的引用变成可选引用,不需要所有权。您可以在函数的签名中看到这一点 - 它采用 &self 而不是 self

pub fn direct_samples(&self) -> Vec<u32> {
assert!(self.objects.is_some());
let mut direct_samples = Vec::new();
for (i, object) in self.objects.as_ref()
.expect("Expected tree to have objects")
.iter()
.enumerate() {
if object.material().emittance > 0f32 {
direct_samples.push(i as u32);
}
}
if self.left.is_some() {
direct_samples.extend(self.left.as_ref().unwrap().direct_samples());
}
if self.right.is_some() {
direct_samples.extend(self.right.as_ref().unwrap().direct_samples());
}
direct_samples
}

Do I need to implement Copy on my KDTree? Won't this use a lot of cpu/memory to copy the entire thing?

你不能在你的KDTree上实现Copy,因为它包含堆分配的内存(盒子)——Copy意味着你的类型可以只需复制其字节即可复制,但在这种情况下,如果不使单一所有权无效,就不可能发生这种情况。

关于compilation - 我不明白借贷是如何运作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40372763/

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