I'm trying to understand why I receive an error when attempting to compile the following code
trait Foo<'a> {
fn foo(&'a self) -> RefHolder<'a>;
}
struct SomeType;
impl<'a> Foo<'a> for SomeType {
fn foo(&'a self) -> RefHolder<'a> {
RefHolder(self)
}
}
struct RefHolder<'a>(&'a (dyn Foo<'a>));
struct Container<'a> {
pub objs: Vec<Box<dyn Foo<'a>>>,
}
fn main() {
let mut c = Container { objs: Vec::new() };
c.objs.push(Box::from(SomeType {}));
let o = &c.objs[0].as_ref();
let x = o.foo();
}
I receive the error
error[E0597]: `c.objs` does not live long enough
--> src/main.rs:21:14
|
21 | let o = &c.objs[0].as_ref();
| ^^^^^^ borrowed value does not live long enough
22 | let x = o.foo();
23 | }
| -
| |
| `c.objs` dropped here while still borrowed
| borrow might be used here, when `c` is dropped and runs the destructor for type `Container<'_>`
I'm confused as to why c.objs
is still borrowed at the end of main
. It's my understanding that x
will be dropped first, followed by o
, which means no references to c
should exist at that point, allowing c
to finally be dropped without issue.
'a
for everything. Removing it from everywhere exceptRefHolder<'a>
will make it compile, is this whay you want? – rodrigomain
, you still get the error when nothing exceptc
exists in the top scope ofmain
. – JMAA