gpt4 book ai didi

rust - 可变 Vector 中引用的生命周期

转载 作者:行者123 更新时间:2023-11-29 08:25:24 31 4
gpt4 key购买 nike

我有一个这样的算法:

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 有更长的生命周期。我该如何解决这个问题?

最佳答案

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);

这可能会稍微更有效率。

关于rust - 可变 Vector 中引用的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39360127/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com