【问题标题】:Lifetimes of references in mutable Vector可变向量中引用的生命周期
【发布时间】:2016-09-07 01:50:31
【问题描述】:

我有一个类似的算法:

let seed: Foo = ...
let mut stack: Vec<&Foo> = Vec::new();
stack.push(&seed);
while let Some(next) = stack.pop {
    let more_foos: Vec<Foo> = some_function_of(next) // 0 to many Foos returned
    for foo in more_foos {
        stack.push(&foo);
    }
}

我收到foo 寿命不够长的错误。我认为这是因为stack 的寿命更长。我该如何解决这个问题?

【问题讨论】:

    标签: rust lifetime


    【解决方案1】:

    more_foos 及其内容在while let 循环的每次迭代结束时被删除。但是,您尝试将来自 more_foos 的项目的引用存储在 stack 中,这是无效的,因为这会导致指针悬空。

    相反,您应该让 stack 拥有 Foo 对象。

    fn main() {
        let seed: Foo = unimplemented!();
        let mut stack: Vec<Foo> = Vec::new();
        stack.push(seed);
        while let Some(next) = stack.pop() {
            let more_foos: Vec<Foo> = unimplemented!();
            for foo in more_foos {
                stack.push(foo);
            }
        }
    }
    

    注意:for 循环可以替换为:

            stack.extend(more_foos);
    

    这可能会更有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2015-05-03
      相关资源
      最近更新 更多