rust - Is there a way to add elements to a container while immutably borrowing earlier elements? -
i'm building gui , want store used textures in 1 place, have add new textures while older textures immutably borrowed.
let (cat, mouse, dog) = (42, 360, 420); // example values let mut container = vec![cat, mouse]; // new container let foo = &container[0]; // container immutably borrowed container.push(dog); // error: mutable borrow
is there kind of existing structure allows this, or can implement using raw pointers?
the absolute easiest thing introduce shared ownership:
use std::rc::rc; fn main() { let (cat, mouse, dog) = (42, 360, 420); let mut container = vec![rc::new(cat), rc::new(mouse)]; let foo = container[0].clone(); container.push(rc::new(dog)); }
now container
and foo
jointly own cat
.
is there kind of existing structure allows this,
yes, there tradeoffs. above, used rc
share ownership, involves reference counter.
another potential solution use arena:
extern crate typed_arena; use typed_arena::arena; fn main() { let container = arena::new(); let cat = container.alloc(42); let mouse = container.alloc(360); let dog = container.alloc(420); }
this isn't indexable, cannot take ownership of value again, , cannot remove value.
being able remove things collection always makes invalidating references dangerous.
can implement using raw pointers
almost certainly. right tricky point.
but have add new textures while older textures immutably borrowed
many times, don't have such thing. example, can split logic phases. have 2 containers; 1 people take references into, , collect new values. @ end of phase, combine 2 collections one. have ensure no references used after end of phase, of course.
Comments
Post a Comment