I can't figure out why the presence of the RefCell
in the following code influences the lifetimes.
use std::cell::RefCell;
pub struct Foo<'f> {
pub value: RefCell<&'f usize>,
}
pub struct Wrapper<'w> {
pub foo: &'w Foo<'w>,
pub bar: &'w usize,
}
fn main() {
let foo = Foo {
value: RefCell::new(&0),
};
let bar = 0;
{
let _ = Wrapper {
foo: &foo,
bar: &bar,
};
}
} // line 25
When RefCell is used in Foo, the compiler exits with the following error.
error[E0597]: `bar` does not live long enough
--> src\main.rs:22:19
|
22 | bar: &bar,
| ^^^ borrowed value does not live long enough
...
25 | }
| - `bar` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
However, when I remove the RefCell
, bar
lives long enough. Another way to get this code to compile is changing the order of the declarations of foo
and bar
.
So, I have two questions.
- Why does
RefCell
influence the lifetimes? - Why does the order of
foo
andbar
has an influence?