繁体   English   中英

可变向量中引用的生命周期

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM