可选的递归类型[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有一个结构,其中包含我想要添加到队列的父属性。父类型与其本身相同,因此我需要将其包装在Box中。

use std::collections::vec_deque::VecDeque;

struct GraphNode {
    value: u32,
    parent: Option<Box<&GraphNode>>,
}

fn main() {
    let mut queue: VecDeque<GraphNode> = VecDeque::new();

    let parent = GraphNode {
        value: 23,
        parent: Option::None,
    };

    let second = GraphNode { value: 42, parent };

    let third = GraphNode {
        value: 19,
        parent: Option::Some(Box::from(&parent)),
    };

    queue.push_front(parent);
    queue.push_front(second);
    queue.push_front(third);
}

Playground

error[E0106]: missing lifetime specifier
 --> src/main.rs:5:24
  |
5 |     parent: Option<Box<&GraphNode>>,
  |                        ^ expected lifetime paramete

父级可以为null,所以我认为它需要是Box<Option<&GraphNode>>,但我得到错误expected lifetime parameter,但是文档中的内容对我来说并没有真正意义。

还有一个问题是,当我创建一个Box时,要保存到父级,值会被移动。我不想移动值,我只想在框中保存一个引用。

rust
1个回答
2
投票

我想你正在寻找std::rc::Rc,而不是Box

use std::collections::vec_deque::VecDeque;
use std::rc::Rc;

struct GraphNode {
    value: u32,
    parent: Option<Rc<GraphNode>>,
}

fn main() {
    let mut queue: VecDeque<Rc<GraphNode>> = VecDeque::new();

    let parent = Rc::new(GraphNode {
        value: 23,
        parent: None,
    });

    let second = Rc::new(GraphNode {
        value: 42,
        parent: None,
    });

    let third = Rc::new(GraphNode {
        value: 19,
        parent: Some(parent.clone()), // Clones the reference, still point to the same thing.
    });

    queue.push_front(parent);
    queue.push_front(second);
    queue.push_front(third);
}

Playground

Rc(引用计数),是一种将多个“所有者”放在同一个对象上的方法。克隆时,您只是克隆引用,因此对任何一个进行的更改都会影响另一个。

您遇到的生命周期问题是因为您存储了使用&制作的直接引用(实际上并不知道它应该被调用的内容)。

如果你想了解更多有关生命的信息,请点击此处查看the entry from the book

© www.soinside.com 2019 - 2024. All rights reserved.