简体   繁体   English

如何返回对递归数据结构的一部分的引用?

[英]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.

相关问题 如何在javascript中转换为二进制文件? 我如何有一个递归函数一次从每个调用返回数据? - How do I convert to binary in javascript? How do I have a recursive function return data from each call all at once? 如何通过引用传递的结构参数传递 function? - How do I pass a function with an argument of a structure passed by reference? 如何进一步优化此数据结构? - How do I further optimize this Data Structure? 我该如何解决这个数据结构 - How do I solve this data structure 数据结构,递归函数 - Data Structure, Recursive functions 如何在安全的Rust中表达相互递归的数据结构? - How do I express mutually recursive data structures in safe Rust? 如何构造涉及2个或更多相关数据实体的数据 - How do I structure data that involves 2 or more related data entities Pands.read_excel返回什么数据结构,如何引用基础数据帧的列? - What data structure is returned by Pands.read_excel, and how can I reference the columns of the underlying data frames? 如何更改用于Google折线图的数据结构 - How do I change data structure for use with google line chart 如何比较结构内部的数据? - How do I compare Data which are Inside a structure?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM