Rust 循环中的变量寿命不够长

Rust 循环中的变量寿命不够长,rust,Rust,过去几天我一直在玩铁锈游戏, 我仍然在努力进行内存管理(图) 我编写了一个脚本,通过对文本文件进行词法分析创建结构层次(“关键字”) 关键字的定义如下: pub struct Keyword<'a> { name: String, code: u32, parent: Option<&'a Keyword<'a>>, } pub struct KeywordHierarchy<'a> { keywords:

过去几天我一直在玩铁锈游戏, 我仍然在努力进行内存管理(图)

我编写了一个脚本,通过对文本文件进行词法分析创建结构层次(“关键字”)

关键字的定义如下:

pub struct Keyword<'a> {
    name: String,
    code: u32,
    parent: Option<&'a Keyword<'a>>,
}
pub struct KeywordHierarchy<'a> {
    keywords: Vec<Box<Keyword<'a>>>,
}

impl<'a> KeywordHierarchy<'a> {
    fn add_keyword(&mut self, keyword: Box<Keyword<'a>>) {
        self.keywords.push(keyword);
    }
}
层次结构就是关键字的容器,定义如下:

pub struct Keyword<'a> {
    name: String,
    code: u32,
    parent: Option<&'a Keyword<'a>>,
}
pub struct KeywordHierarchy<'a> {
    keywords: Vec<Box<Keyword<'a>>>,
}

impl<'a> KeywordHierarchy<'a> {
    fn add_keyword(&mut self, keyword: Box<Keyword<'a>>) {
        self.keywords.push(keyword);
    }
}
有一个
while
循环通过lexer令牌

在第一个
if
中,我将ROOT关键字添加到层次结构中,这是唯一一个没有父级的关键字,一切都按照预期顺利进行

在第二个
if
中,我解析子关键字,调用
KeywordHierarchy.add_keyword()
时得到一个终生错误

你们能推荐一个惯用的方法来解决这个问题吗

干杯


另外,点击游乐场

我可以看到,在你的设计中,最直接的问题是你的循环将修改
层次结构。关键字
向量(在
first\u if
块中),但它也借用了
层次结构的元素。关键字
向量(在
second\u if
块中)

这是有问题的,因为修改向量可能会导致重新分配其备份缓冲区,如果允许的话,将使向量的所有现有借用无效。(因此这是不允许的。)

您是否考虑过使用一个按钮来保存关键字,而不是
Vec
?竞技场的设计是为了让你可以在竞技场中分配新的东西,同时还可以向竞技场中以前分配的元素借用未偿还的物品


更新:这里是您的代码的修订版本,说明了如何使用竞技场(在本例中是
rustc_竞技场::TypedArena
,但这只是为了让我可以在play.rust-lang.org服务上运行它)和
Vec
来处理查找

关键的代码是:

首先:
KeywordHierarchy
现在与vec并驾齐驱:

pub struct KeywordHierarchy<'a> {
    keywords: Vec<&'a Keyword<'a>>,
    kw_arena: &'a TypedArena<Keyword<'a>>,
}
第四:为了避免借用检查程序在遍历时将借用层次结构作为可变的问题,我将层次结构的修改移到了查找父项匹配之外:

        // Find parent
        let parent = match hierarchy.keywords.iter().find(|p| p.code == 0) {
            None => return Err(String::from("No such parent")),
            Some(parent) => *parent, // (this deref is important)
        };
        // If parent is found, create a child
        let child = Keyword {
            name: String::from("CHILD"),
            code: 1,
            parent: Some(parent),
        };
        hierarchy.add_keyword(child);
        second_if = false;

嘿,伙计,谢谢你的回复。我真的很感激你的回答。我现在在铁锈马厩,竞技场需要每晚休息。我有没有办法不用它来修复我的代码?谢谢
fn add_keyword(&mut self, keyword: Keyword<'a>) {
    let kw = self.kw_arena.alloc(keyword);
    self.keywords.push(kw);
}
fn parse<'a>(arena: &'a TypedArena<Keyword<'a>>) -> Result<KeywordHierarchy<'a>, String> {
    ...
        // Find parent
        let parent = match hierarchy.keywords.iter().find(|p| p.code == 0) {
            None => return Err(String::from("No such parent")),
            Some(parent) => *parent, // (this deref is important)
        };
        // If parent is found, create a child
        let child = Keyword {
            name: String::from("CHILD"),
            code: 1,
            parent: Some(parent),
        };
        hierarchy.add_keyword(child);
        second_if = false;