如何在 Rust 中迭代数组时更改数组中的值 [英] How to change value inside an array while iterating over it in Rust

查看:63
本文介绍了如何在 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");
    }
}

推荐答案

iter_mut 迭代器为您提供对元素的引用,您可以使用它来改变网格.通常不应使用索引.

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

游乐场链接

这篇关于如何在 Rust 中迭代数组时更改数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆