rust - 如何在结构中存储递归引用

标签 rust

让我们假设以下结构

struct Item<'a> {
    items: Vec<&'a Item<'a>>
}

假设以下变量包含许多 Item 对象,其中 items 字段为空。

let mut items: Vec<Item<'a>> = get_items();

假设我的任务是向每个 Itemitems 字段添加对 中所有其他 Item 对象的引用项目向量。

我目前的实现是

struct Item<'a> {
    items: Vec<&'a Item<'a>>,
}

impl<'a> Item<'a> {
    fn new() -> Item<'a> {
        Item { items: vec![] }
    }   
}

fn main() {
    let mut items = vec![Item::new(), Item::new()];
    while let Some(item) = items.pop() {
        for another_item in &mut items {
            item.items.push(another_item); 
        }   
        items.push(item);
    }   
}`

它失败了,因为我执行了 item.items.push(another_item);

最佳答案

您尝试做的事情是不合理的。在不了解您的用例的情况下,您的问题没有好的解决方案。

您有几个与可变性相关的错误。修复这些问题后,您的代码将变为:

struct Item<'a> {
    items: Vec<&'a Item<'a>>,
}

impl<'a> Item<'a> {
    fn new() -> Item<'a> {
        Item { items: vec![] }
    }   
}

fn main() {
    let mut items = vec![Item::new(), Item::new()];
    while let Some(mut item) = items.pop() {
        for another_item in items {
            item.items.push(&another_item); 
        }   
        items.push(item);
    }   
}

编译器现在提示 another_item 的生命周期:

error: another_item does not live long enough

for 循环拥有 another_item,它不能将所有权交还给引用的 Vec

无论您做什么,都无法回避这个基本问题。这些规则背后的原因之一是引用实际上只是指针。当您将元素移入和移出 items 时,每个 item 都会更改其位置,从而使先前创建的指向它的指针无效。 (这不是 Python,具有神奇的垃圾收集引用。)当然,Rust 的规则防止这种情况发生。

关于rust - 如何在结构中存储递归引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33264666/

相关文章:

rust - 匹配元组错误预期 String 但找到 Option<<generic#5>>

rust - 我如何检查 Rust 中的目录是否为空?

data-structures - 如何在安全的 Rust 中表达相互递归的数据结构?

rust - 在极坐标中加载数据框时如何定义列的类型?

rust - 如何在Rust中的定位索引处获取位值?

rust - 将值格式化为多种字符串的惯用 Rust 方法是什么?

rust - 如何在闭包和函数之间传递参数?

io - 使用 read_until() 时如何阻止 BufReader 在 Rust 中读取?

enums - 在不构造实例的情况下获取枚举判别式

rust - 为什么不能在结构定义中省略生命周期?