[Solved] Iteration with 2d array


#1

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


#2

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);
        }
    }

Edit:
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);
    }

https://play.rust-lang.org/?gist=5c36ce6982389f3274d190a999bff949&version=stable


#3

Thanks (sorry I was away)