“没有足够长的时间”错误与'弱<refcell <_>&gt;`

时间:2018-05-02 02:43:43

标签: rust borrow-checker

我最近有一些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<...>>)?

1 个答案:

答案 0 :(得分:3)

由于Lukas Kalbertodt提供了MCVEPlayground),我将使用他的代码:

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);
}

让我们一步一步地完成它:

  • 创建了Weak并将其移至MyType,其生命周期为'a
  • 当它传递给get_parent_struct<'a>(_: &'a MyType<'a>)时,您的生命周期为'a的引用为具有生命周期'a的类型
  • get_parent_struct期望它的参数与foo本身一样长,这是不正确的,因为foo一直存在到范围的最后

kazemakase所述,解决方案是使用不同的生命周期作为参考。如果您略微改变get_parent_struct的签名,那么它正在工作:

fn get_parent_struct<'a>(_: &MyType<'a>) {} 

Playground

编译器现在将生命周期缩短为

fn get_parent_struct<'a, 'b>(_: &'b MyType<'a>) where 'a: 'b {}

现在'a'b更长。

相关问题