[Solved] Iteration with 2d array

Hi everyone, new rust noob here

I followed several small tutorials to learn the basics of rust and I wanted to iterate through a 10x10 2-dimension array filled with int.
Here is the definition of the array.
let mut grid: [[i32; 10]; 10] = [[5; 10]; 10];

I would like to do something like this

for (i, row) in grid.iter_mut().enumerate() { for (y, col) in row[i].iter_mut().enumerate() { println!("{}", col[y]); } }

and then I’d like to be able to change each element of the grid

How can I simply do that ? I always have compilation errors

Just a short answer because I‘m on mobile.

You don‘t need to index. This works:

   for (i, row) in grid.iter_mut().enumerate() {
        for (y, col) in row.iter_mut().enumerate() {
            println!("{}", col);

If you want to avoid the nested loops and just want to do something with each element, you can use flat_map:

    for element in grid.iter_mut().flat_map(|r| r.iter_mut()) {
        println!("{}", element);



Thanks (sorry I was away)

1 Like