rust - Modifying structure while iterating - any elegant solution? -
i've started rust , i'm trying build vector of points changed while iterating on them:
struct point { x: i16, y: i16 } fn main() { let mut points: vec<point> = vec![]; // unsure if point mutable points.push(point {x:10, y:10}); // trying explicitly let mut p1 = point {x:20, y:20}; points.push(p1); in points.iter() { println!("{}", i.x); i.x = i.x + 10; } }
when compiling, error:
error: cannot assign immutable field `i.x` i.x = i.x + 10;
as learned here, rust doesn't allow modify structure while iterating on it, error.
ok, how modify in elegant way? if read this answer , right following comes mind:
- pop item (point) item vector, modify , push back.
- create temporary structure push changed items (points) , replace original structure temporary 1 outside loop (how?).
while think can (1) working, i'm not happy pop's , push's (is high-performance anyhow?). concerning (2), have no idea how working - if work @ all.
questions:
- is (2) solution , if yes, how like?
- are there other solutions?
- what's advantage or disadvantage of different solutions, respect performance?
thanks in advance.
you cannot modify structure iterating over, is, vector points
. however, modifying elements iterator unproblematic, have opt mutability:
for in points.iter_mut() {
or, more modern syntax:
for in &mut points {
mutability opt-in because iterating mutably further restricts can points
while iterating. since mutable aliasing (i.e. 2 or more pointers same memory, @ least 1 of &mut
) prohibited, can't read points
while iter_mut()
iterator around.
Comments
Post a Comment