Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change value inside an array while iterating over it in Rust

Tags:

rust

I want to change the value inside the loop like in the comment. It should be simple but I don't see the solution.

fn main() {
    let mut grid: [[i32; 10]; 10] = [[5; 10]; 10];
    for (i, row) in grid.iter_mut().enumerate() {
        for (y, col) in row.iter_mut().enumerate() {
            //grid[i][y] = 7;
            print!("{}", col);
        }
        print!("{}","\n");
    }
}
like image 672
Thomas Fournet Avatar asked Jan 28 '18 22:01

Thomas Fournet


1 Answers

The iter_mut iterator gives you a reference to the element, which you can use to mutate the grid. You usually shouldn't use indices.

fn main() {
    let mut grid: [[i32; 10]; 10] = [[5; 10]; 10];
    for row in grid.iter_mut() {
        for cell in row.iter_mut() {
            *cell = 7;
        }
    }

    println!("{:?}", grid)
}

Playground link

like image 166
mcarton Avatar answered Oct 30 '22 01:10

mcarton