`&` 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


zombie.state = StateZombie::ChangeDir

do not know how to make the iterration variable mutable

thanks in advance

pub enum StateZombie {

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();
    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"),

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


: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 {
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.