Rust &引用;“活得不够长”;“弱”的错误<;RefCell<_&燃气轮机&燃气轮机`
我最近遇到了很多问题,借来检查我的代码。为了提问,我简化了代码:Rust &引用;“活得不够长”;“弱”的错误<;RefCell<_&燃气轮机&燃气轮机`,rust,borrow-checker,Rust,Borrow Checker,我最近遇到了很多问题,借来检查我的代码。为了提问,我简化了代码: use std::cell::RefCell; use std::rc::{Rc, Weak}; struct SomeOtherType<'a>{ data: &'a i32, } struct MyType<'a> { some_data: i32, link_to_other_type: Weak<RefCell<SomeOtherType<'a&
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct SomeOtherType<'a>{
data: &'a i32,
}
struct MyType<'a> {
some_data: i32,
link_to_other_type: Weak<RefCell<SomeOtherType<'a>>>,
}
struct ParentStruct<'a> {
some_other_other_data: i32,
first_types: &'a Vec<MyType<'a>>,
}
fn get_parent_struct<'a>(first_types: &'a Vec<MyType<'a>>) -> ParentStruct<'a> {
ParentStruct { some_other_other_data: 4, first_types: first_types }
}
fn consume(parent_struct: ParentStruct) {
print!("{}", parent_struct.first_types[0].some_data);
}
fn main() {
let some_vect = vec!(
MyType { some_data: 1, link_to_other_type: Weak::new() },
MyType { some_data: 2, link_to_other_type: Weak::new() }
);
loop {
let some_struct = get_parent_struct(&some_vect);
consume(some_struct);
}
}
但奇怪的事实是:如果在类型MyType
中,我将Weak
更改为Rc
或RefCell
或Weak
:它编译
我的问题是:为什么?为什么借阅检查器拒绝编译原始代码(为什么它接受其他类型的代码而不是弱)?既然提供了一个(),我将使用他的代码:
struct MyType<'a> {
link_to_other_type: Weak<RefCell<&'a i32>>,
}
fn get_parent_struct<'a>(_: &'a MyType<'a>) {}
fn main() {
let foo = MyType { link_to_other_type: Weak::new() };
get_parent_struct(&foo);
}
编译器现在将省略
fn get_parent_struct<'a, 'b>(_: &'b MyType<'a>) where 'a: 'b {}
fn get_parent_struct(&'b mytype对于任何有兴趣回答此问题的人,我进一步(它仍然显示相同的错误)(@Truc Truca,如果您愿意,您可以编辑您的问题并使用简化的代码).所以我很确定这与RefCell
Rc
的不变性有关,弱也包含单元格
s,也许这是一个提示?我现在需要停止研究这个问题,但我很好奇这个有趣的问题有一个好的解释!解决方法是对RefCell使用不同的生存期参考:&'a Veca也非常相关:
fn get_parent_struct<'a, 'b>(_: &'b MyType<'a>) where 'a: 'b {}