假設下面的結構如何存儲遞歸REF一個struct內
struct Item<'a> {
items: Vec<&'a Item<'a>>
}
假設下面的變量包含許多Item
對象空items
領域。
let mut items: Vec<Item<'a>> = get_items();
假設我要添加到每個Item
引用的items
領域的所有其他Item
對象在items
矢量任務。
我目前的實現是
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);
錯誤結束。我犯了一個錯誤 –