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:

  1. pop item (point) item vector, modify , push back.
  2. 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:

  1. is (2) solution , if yes, how like?
  2. are there other solutions?
  3. 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

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -