我有一些嵌套的結構體,不能創建父結構體的反向引用。一個example:帶參考的嵌套結構
struct Foo<'a> {
parent: &'a Bar<'a>,
}
impl<'a> Foo<'a> {
fn new(parent: &'a Bar) -> Self {
Foo { parent: parent }
}
fn hello_world(&self) -> String {
self.parent.hello().to_owned() + " world"
}
}
struct Bar<'b> {
child: Option<Foo<'b>>,
data: &'static str,
}
impl<'b> Bar<'b> {
fn new() -> Self {
Bar {
child: None,
data: "hello",
}
}
fn hello(&self) -> &str {
self.data
}
fn get_foo(&self) -> Option<&Foo> {
self.child.as_ref()
}
}
fn main() {
let bar = Bar::new();
assert_eq!("hello", bar.hello());
match bar.get_foo() {
Some(foo) => assert_eq!("hello world", foo.hello_world()),
None =>(),
}
}
我怎麼能一起Bar
參考替換None
與Some<Foo>
?到目前爲止,我不確定這是可能的。
你不行。請參閱http://stackoverflow.com/q/32300132/155423; http://stackoverflow.com/q/28833622/155423;以及關於循環參考的許多其他問題。 – Shepmaster
@Shepmaster,這是真的嗎?我在[我的]示例中錯過了什麼(https://play.rust-lang.org/?gist=ec859a25cc772183411a2dfb10258cbe&version=stable&backtrace=0)?當我添加一行調試打印我的父母對象,我得到一個堆棧溢出錯誤,它試圖打印父/子的循環引用... –
是的,這是真的;我不會故意騙人^ _ ^。 *參考*是'&Foo'。在你的評論中的例子中,你有一個'Arc',它不是一個簡單而無聊的參考,而是一個更智能的智能指針*。但是,您創建了一個無限循環(父節點指向父節點...)。通常,這就是['Weak'](https://doc.rust-lang.org/std/sync/struct.Weak.html)引用的用途。 – Shepmaster