`&` reference cannot be written

Hello, I started in Rust. I am trying to modify a variable in a loop but I have the message

`zombie` is a `&` reference, so the data it refers to cannot be written

for

zombie.state = StateZombie::ChangeDir

do not know how to make the iterration variable mutable

thanks in advance

pub enum StateZombie {
    NoneState,
    Walk,
    Bite,
    ChangeDir,
}

pub struct Zombie {
    pub vx: f32,
    pub vy: f32,
    pub state : StateZombie,
}

impl Zombie {
    pub fn new() -> Zombie {
        Zombie {
            vx: 0.0,
            vy: 0.0,
            state : StateZombie::NoneState,
        }
    }
}

fn main() {
    let mut zombies: Vec<Zombie> = vec![];
    for i in 0..10 {
            let zombie = Zombie::new();
            zombies.push(zombie);
    }
    for zombie in zombies.iter(){
    
        match zombie.state {
            StateZombie::NoneState =>  zombie.state = StateZombie::ChangeDir,
            StateZombie::Walk => println!("walk"),
            StateZombie::Bite => println!("bite"),
            StateZombie::ChangeDir => println!("change_dir"),
        }   
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f5acb0d2846e93fc83068a0267a8dd74

Hi, you just have to replace zombies.iter() with zombies.iter_mut().

1 Like

:lol, thank you.
I spent 2 hours to trying a lot of things, while it was simple

You can just iterate over a mutable reference to the collection:

-    for zombie in zombies.iter(){
+    for zombie in &mut zombies {

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=133b4dcc1655733029f148ab947aff6d