我希望能够在Parent
中存储名为Child
的结构,其中Child
包含引用返回给父代。尝试将自引用数据拆分为单独的结构
它的工作原理,如果我直接有Child
结构像这样的家长里:
struct Parent<'s> {
cache: RefCell<Vec<Child<'s>>>
}
但是,如果我移动Vec
到一个单独的结构,那么它会失败,一生的错误进行编译。
struct Parent<'s> {
cache: RefCell<Cache<'s>>
}
struct Cache<'s> {
children: Vec<Child<'s>>
}
可以让这个例子与单独的结构一起工作吗?
这是full working code,编译好。当将children
移动到单独的结构中时,它就是fails。
我对这个问题的分析:
当Parent
包含children
直接,'s
是相同的寿命为Parent
结构本身的范围,因此,我可以调用采取&'s self
上Parent
方法。
当Parent
包含Cache
含有children
,'s
是相同的寿命作为Cache
结构,这是Parent
之前创建的范围内,因而这是不可能呼吁Parent
称取&'s self
方法。尝试这样做将产生误差
<anon>:33:15: 33:16 error: `p` does not live long enough
<anon>:33 let obj = p.create_object();
^
<anon>:30:48: 38:2 note: reference must be valid for the block suffix following statement 0 at 30:47...
<anon>:30 let cache = Cache { children: Vec::new() }; // the lifetime `'s` is essentially from this line to the end of the program
<anon>:31 let mut p = Parent { cache: RefCell::new(cache) }; // although the Parent instance was created here, 's still refers to the lifetime before it
<anon>:32 // this fails because p doesn't live long enough
<anon>:33 let obj = p.create_object();
我需要缩短's
到Parent
范围,而不是Cache
范围的一种方式。
免责声明: 这个问题是非常相似的,我问较早(https://stackoverflow.com/questions/32579518/rust-lifetime-error-with-self-referencing-struct?noredirect=1#comment53014063_32579518)中标记为重复。我已经阅读了答案,我相信我超越了这一点,因为我可以获得引用的正确时间(如我的第一个示例中所示)。我再次问这个(现在稍微不同)的问题,因为我现在有一个有效的具体例子,一个不起作用。我确信用一个结构可以完成两个,对吧?