我有一些嵌套的结构体,不能创建父结构体的反向引用。一个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