簡體   English   中英

我使用什么生命周期來創建循環引用彼此的 Rust 結構?

[英]What lifetimes do I use to create Rust structs that reference each other cyclically?

我想要結構成員知道他們的父母。 這大約是我想要做的:

struct Parent<'me> {
    children: Vec<Child<'me>>,
}

struct Child<'me> {
    parent: &'me Parent<'me>,
    i: i32,
}

fn main() {
    let mut p = Parent { children: vec![] };
    let c1 = Child { parent: &p, i: 1 };
    p.children.push(c1);
}

我試圖在沒有完全理解我在做什么的情況下用生命來安撫編譯器。

這是我堅持的錯誤消息:

error[E0502]: cannot borrow `p.children` as mutable because `p` is also borrowed as immutable
  --> src/main.rs:13:5
   |
12 |     let c1 = Child { parent: &p, i: 1 };
   |                               - immutable borrow occurs here
13 |     p.children.push(c1);
   |     ^^^^^^^^^^ mutable borrow occurs here
14 | }
   | - immutable borrow ends here

這是有道理的,但我完全不確定從這里開始。

不能用借用的指針創建循環結構。

目前沒有什么好的方法可以實現循環數據結構; 唯一真正的解決方案是:

  1. 使用帶有Rc::newRc:downgrade的循環結構的Rc<T>引用計數。 閱讀rc模塊文檔並注意不要創建使用強引用的循環結構,因為它們會導致內存泄漏。
  2. 使用原始/不安全指針 ( *T )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM