让我们假设以下结构
struct Item<'a> {
items: Vec<&'a Item<'a>>
}
假设以下变量包含许多 Item
对象,其中 items
字段为空。
let mut items: Vec<Item<'a>> = get_items();
假设我的任务是向每个 Item
的 items
字段添加对 中所有其他
向量。Item
对象的引用项目
我目前的实现是
struct Item<'a> {
items: Vec<&'a Item<'a>>,
}
impl<'a> Item<'a> {
fn new() -> Item<'a> {
Item { items: vec![] }
}
}
fn main() {
let mut items = vec![Item::new(), Item::new()];
while let Some(item) = items.pop() {
for another_item in &mut items {
item.items.push(another_item);
}
items.push(item);
}
}`
它失败了,因为我执行了 item.items.push(another_item);
最佳答案
您尝试做的事情是不合理的。在不了解您的用例的情况下,您的问题没有好的解决方案。
您有几个与可变性相关的错误。修复这些问题后,您的代码将变为:
struct Item<'a> {
items: Vec<&'a Item<'a>>,
}
impl<'a> Item<'a> {
fn new() -> Item<'a> {
Item { items: vec![] }
}
}
fn main() {
let mut items = vec![Item::new(), Item::new()];
while let Some(mut item) = items.pop() {
for another_item in items {
item.items.push(&another_item);
}
items.push(item);
}
}
编译器现在提示 another_item
的生命周期:
error:
another_item
does not live long enough
for
循环拥有 another_item
,它不能将所有权交还给引用的 Vec
。
无论您做什么,都无法回避这个基本问题。这些规则背后的原因之一是引用实际上只是指针。当您将元素移入和移出 items
时,每个 item
都会更改其位置,从而使先前创建的指向它的指针无效。 (这不是 Python,具有神奇的垃圾收集引用。)当然,Rust 的规则防止这种情况发生。
关于rust - 如何在结构中存储递归引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33264666/