[英]Lifetimes of references in mutable Vector
我有一个类似的算法:
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
的寿命更长。 我怎样才能解决这个问题?
在while let
循环的每次迭代结束时,都会删除more_foos
及其内容。 但是,您尝试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);
这可能会更有效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.