我最近遇到了很多关于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 我的问题是:为什么?为什么借用检查器拒绝编译原始代码(为什么它接受其他类型的代码,而不是Weak<RefCell<...>>)?
发布于 2018-05-02 18:09:58
因为Lukas Kalbertodt提供了一个MCVE (Playground),所以我将使用他的代码:
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);
}让我们一步一步地来看一下:
'aWeak并将其移动到MyType中它被传递给get_parent_struct<'a>(_: &'a MyType<'a>),您有一个生存期为'a的引用指向生存期为'a的类型get_parent_struct期望其参数的生存期与foo本身的生存期完全相同,但这不是真的,因为foo一直存在到作用域的末尾<代码>H219<代码>F220正如kazemakase所提到的,解决方案是对引用使用不同的生命周期。如果你稍微修改一下get_parent_struct的签名,它就能正常工作:
fn get_parent_struct<'a>(_: &MyType<'a>) {} 编译器现在将生命周期省略为
fn get_parent_struct<'a, 'b>(_: &'b MyType<'a>) where 'a: 'b {}现在'a比'b还长寿。
https://stackoverflow.com/questions/50126432
复制相似问题