rust - Store reference of struct in other struct -
i have 2 structs. app
, item
.
what want achieve store item
in items
vector of app
struct passing mutable reference item
s constructor.
pub struct app<'a> { items: vec<&'a item> } impl<'a> app<'a> { pub fn new() -> app<'a> { app { items: vec::new() } } pub fn register_item(&mut self, item: &'a item) { self.items.push(item); } } pub struct item; impl item { pub fn new(app: &mut app) -> item { let item = item; app.register_item(&item); item } } fn main() { let mut app = app::new(); let item = item::new(&mut app);; }
the code thows following error:
test.rs:8:28: 8:32 error: `item` not live long enough test.rs:8 app.register_item(&item);
is there way this?
while rc
might correct use case, it's understand why getting error are. please read why can't store value , reference value in same struct? has more in-depth discussion why code cannot work as-is. simplified explanation follows.
let's @ constructor:
fn new(app: &mut app) -> item { let item = item; app.register_item(&item); item }
here, create new item
on stack @ address. let's pretend address 0x1000. take address of item
(0x1000) , store vec
inside app
. return item
calling function, resides in different stack frame. means address of item
change, means 0x1000 no longer guaranteed point valid item
! how rust prevents making whole classes of memory errors!
i'd you'd see written as:
fn main() { let item = item; let mut app = app::new(); app.register_item(&item); }
this have same problem if tried return app
or item
function, address change.
if have straight-forward tree structure, i'd advocate letting parent nodes own children:
struct app { items: vec<item> } impl app { fn new() -> app { app { items: vec::new() } } fn register_item(&mut self, item: item) { self.items.push(item); } } pub struct item; fn main() { let mut app = app::new(); app.register_item(item); }
Comments
Post a Comment