且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Rust 中迭代和更改可变数组中的值?

更新时间:2022-06-09 00:39:13

首先,你的牌组是不可变的.请记住,rust 绑定默认是不可变的:

First, your deck is not mutable. Remember in rust bindings are non-mutable by default:

let mut deck: [Option<Card>; 52] = [None; 52];

接下来,要获得可以修改的迭代器,请使用iter_mut():

Next, to obtain an iterator you can modify, you use iter_mut():

for i in deck.iter_mut() {

最后:循环中的i 是对deck 元素的可变引用.要将某些内容分配给引用,您需要取消引用它:

Finally: the i that you have in your loop is a mutable reference to the elements of deck. To assign something to the reference, you need to dereference it:

*i = Some(Card {
    card_num: 1,
    card_suit: Suits::Hearts,
});

游乐场链接