15

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

1 Answer 1

21

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

Sign up to request clarification or add additional context in comments.

2 Comments

More idiomatically seen as for row in &mut grid { and for cell in &mut row {.
^ nice, this is more convenient

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.