rust - Lifetime of reference to boxed value does not live long enough -


the following code doesn'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 following error:

error[e0597]: `*e.derp` not live long enough   --> src/main.rs:18:25    | 18 |         e.inner.v.push(&*e.derp);    |                         ^^^^^^^ not live long enough ... 21 |     }    |     - borrowed value lives until here    | note: borrowed value must valid lifetime 'a defined on impl @ 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 value inside of box live long 'a since member of foo, has lifetime.

i wondered if move of foo @ end of new function confusing it, if tried append in derp. different error:

error[e0495]: cannot infer appropriate lifetime borrow expression due conflicting requirements   --> main.rs:20:27    | 20 |         self.inner.v.push(& *self.derp);    |                           ^^^^^^^^^^ 

which gives me no indication of lifetime compiler thinks boxed value has.

i think though value inside of box live long 'a since member of foo has lifetime.

it possible assign new box derp member, @ point old box dropped , lifetime of value in ends.

i think trying impossible in safe rust: cross-references between struct members not supported. comes regularly question, it's not available in language.

you can use rc work around this, perhaps in combination refcell.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -