Compilation 我不知道';我不明白借钱是怎么回事
我正在尝试编写kd树实现,但不断出现错误Compilation 我不知道';我不明白借钱是怎么回事,compilation,rust,borrow-checker,Compilation,Rust,Borrow Checker,我正在尝试编写kd树实现,但不断出现错误无法从借用的内容中移出。 这是我的KDTree结构 pub struct KDTree { pub bounding_box: Aabb, pub axis: Option<Axis>, left: Option<Box<KDTree>>, right: Option<Box<KDTree>>, pub objects: Option<Vec<B
无法从借用的内容中移出。
这是我的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>>>,
}
我需要在KDTree上实现复制吗?这不会占用大量cpu/内存来复制整个内容吗?您的代码需要KDTree的所有权的原因是因为您正在调用
选项::expect
和选项::unwrap
。可以找到这些的文档
这将把对选项的引用转换为不需要所有权的可选引用。您可以在函数的签名中看到这一点-它需要&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
}
pub fn direct_samples(&self)->Vec{
断言!(self.objects.is_some());
让mut direct_samples=Vec::new();
对于self.objects.as_ref()中的(i,object)
.expect(“期望树具有对象”)
.国际热核实验堆(iter)
.enumerate(){
如果object.material()发射度>0f32{
直接推送(i为u32);
}
}
如果self.left.is_some(){
direct_samples.extend(self.left.as_ref().unwrap().direct_samples());
}
如果self.right.is_some(){
direct_samples.extend(self.right.as_ref().unwrap().direct_samples());
}
直接取样
}
我需要在KDTree上实现复制吗?这不会占用大量的cpu/内存来复制整个内容吗
您无法在KDTree
上实现Copy
,因为它包含堆分配的内存(框)-Copy
意味着您的类型可以通过复制其字节来复制,但在这种情况下,如果不使单一所有权无效,则无法实现复制。搁置:选项似乎可疑,Vec
可能已经是空的,因此将其包装在一个选项中,然后断言该选项不应该存在,这似乎是毫无用处的。即使None
和Some(empty_vec)
确实有不同的含义,这也是一个相当混乱的区别。
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(),
}
}
impl<T> Option<T> {
fn unwrap(self) -> T {
...
}
}
impl<T> Option<T> {
fn as_ref(&self) -> Option<&T> {
...
}
}
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
}