[英]How do I return a reference to a part of a recursive data structure?
I'm trying to define a recursive data structure in Rust, but there are some pieces missing in my understanding of Rust and memory - the only thing that I manage to do is pick a fight with the borrow checker. 我正在尝试在Rust中定义一个递归数据结构,但是我对Rust和内存的理解缺少一些内容-我唯一要做的就是与借阅检查器进行斗争。
I have the following stub of a quad tree and want to project one of the quadrants as follows. 我有一个四叉树的以下存根,并要按如下所示投影其中一个象限。
use CC::{Node, Leaf};
enum CC {
Node(i32, bool, i32, Rc<CC>, Rc<CC>, Rc<CC>, Rc<CC>),
Leaf(bool),
}
impl CC {
fn nw(&self) -> CC {
match *self {
Node(_, _, _, ref nw, _, _, _) => *nw.clone(),
_ => panic!()
}
}
}
But all I end up with is 但我最终得到的是
src/hashlife.rs:34:47: 34:58 error: cannot move out of borrowed content
src/hashlife.rs:34 Node(_, _, _, ref nw, _, _, _) => *nw.clone(),
^~~~~~~~~~~
You have two options here. 您在这里有两个选择。
First, you can return a reference to the subtree: 首先,您可以返回对子树的引用:
fn nw(&self) -> &CC {
match *self {
Node(_, _, _, ref nw, _, _, _) => &**nw,
_ => panic!()
}
}
Second, you can return a reference-counted pointer: 其次,您可以返回一个引用计数的指针:
fn nw(&self) -> Rc<CC> {
match *self {
Node(_, _, _, ref nw, _, _, _) => nw.clone()
_ => panic!()
}
}
You can't return just CC
, however, unless you are willing to clone the value itself. 但是,除非愿意克隆值本身,否则不能只返回
CC
。 The reason is that this would mean moving out of Rc
, leaving it in some undefined state, which is rightly prohibited. 原因是这将意味着移出
Rc
,使其处于未定义状态,这是正确禁止的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.