I recently have many problems with the borrow checker of Rust refusing my code. In order to ask the question, I simplified my code:
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);
}
}
This code doesn't compile, I have get following error:
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
But the strange fact is: if, in the type MyType
, I change Weak<RefCell<...>>
to Rc<RefCell<...>>
or to RefCell<...>
or to Weak<...>
: it compiles!!
My question is: why? Why does the borrow checker refuses to compile the original code (and why does it accept the code with the other types instead of Weak<RefCell<...>>
)?