【发布时间】:2018-05-02 02:43:43
【问题描述】:
我最近遇到了很多关于 Rust 的借用检查器拒绝我的代码的问题。为了问这个问题,我简化了我的代码:
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);
}
}
此代码无法编译,我收到以下错误:
error[E0597]: `some_vect` does not live long enough
--> src/main.rs:33:46
|
33 | let some_struct = get_parent_struct(&some_vect);
| ^^^^^^^^^ borrowed value does not live long enough
...
36 | }
| - `some_vect` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
但奇怪的事实是:如果在MyType 类型中,我将Weak<RefCell<...>> 更改为Rc<RefCell<...>> 或RefCell<...> 或Weak<...>:它编译!
我的问题是:为什么?为什么借用检查器拒绝编译原始代码(为什么它接受其他类型的代码而不是Weak<RefCell<...>>)?
【问题讨论】:
-
对于任何有兴趣回答这个问题的人,我进一步simplified the code(它仍然显示相同的错误)(@Truc Truca,如果你愿意,你可以编辑你的问题并改用简化代码) .所以我很确定这与
RefCell的不变性有关。Rc和Weak也包含Cells,也许这是一个提示?我现在需要停止研究这个,但我很想看到这个有趣问题的一个很好的解释! -
解决方案是为引用使用不同的生命周期:
&'a Vec<MyType<'b>>(可能使用'b:'a)。至于为什么?我不确定,并将答案留给对生命有更好理解的人。
标签: rust borrow-checker