The lifespan of the boxed value link is not long enough
The following code won't compile:
use std::borrow::Borrow;
struct Inner<'a> {
v: Vec<&'a u8>,
}
struct Foo<'a> {
inner: Inner<'a>,
derp: Box<u8>,
}
impl<'a> Foo<'a> {
fn new() -> Foo<'a> {
let mut e = Foo {
inner: Inner { v: vec![] },
derp: Box::new(128),
};
e.inner.v.push(&*e.derp);
return e;
}
fn derp(&mut self) {
println!("{:?}", self.inner.v);
}
}
fn main() {
let mut f = Foo::new();
f.derp();
}
I am getting the following error:
error[E0597]: `*e.derp` does not live long enough --> src/main.rs:18:25 | 18 | e.inner.v.push(&*e.derp); | ^^^^^^^ does not live long enough ... 21 | } | - borrowed value only lives until here | note: borrowed value must be valid for the lifetime 'a as defined on the impl at 12:1... --> src/main.rs:12:1 | 12 | / impl<'a> Foo<'a> { 13 | | fn new() -> Foo<'a> { 14 | | let mut e = Foo { 15 | | inner: Inner { v: vec![] }, ... | 25 | | } 26 | | } | |_^
I think that the value inside the field actually persists for as long as 'a
, since it is a member Foo
that has exactly that lifetime.
I was wondering if this movement is confusing Foo
at the end of the new function, so if I try to do append in derp
. I am getting another error:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements --> main.rs:20:27 | 20 | self.inner.v.push(& *self.derp); | ^^^^^^^^^^
which gives me no indication of what the compiler thinks the lifetime is a short value.
source to share
I think the value inside the field really survives as long as "a", since it is a member of Foo that has exactly that lifetime.
You can assign a new field to an item derp
, after which the old field will be deleted and it will expire at the end.
I think what you are trying to do is not possible in safe Rust: cross-referencing between struct members is not supported. This often comes up as a question, but it just isn't available in that language.
- How to initialize fields of a structure that refer to each other
- Why can't I store a value and a reference to that value in the same structure?
You can use Rc
to get around this, possibly in conjunction with RefCell
.
source to share