Rust 嵌套 for 循环遍历两个枚举

Rust nested for loop over two enums

我正在尝试学习 Rust 并定义了两个枚举和一个结构来实现卡片组:

use strum::IntoEnumIterator;
use strum_macros::EnumIter;

#[derive(Debug, EnumIter)]
enum Colors {
    Hearts,
    Spades,
    Diamonds,
    Clubs
}

#[derive(Debug, EnumIter)]
enum Numbers {
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace
}

struct Card {
    color : Colors,
    number : Numbers
}

当对其中一个枚举进行循环时,它按预期工作:

fn main() {
    for color in Colors::iter() {
       let card = Card {
            color: color,
            number: Numbers::Ace
        };
        println!("My card is a {:?} of {:?}", card.number, card.color);       
    }   
}

输出:

My card is a Ace of Hearts
My card is a Ace of Spades
My card is a Ace of Diamonds
My card is a Ace of Clubs

但是当尝试嵌套两个 for 循环时,如下所示:

fn main() {
    for color in Colors::iter() {
        for number in Numbers::iter() {
            let card = Card {
                color: color,
                number: number
            };
            println!("My card is a {:?} of {:?}", card.number, card.color);       
        }
    }   
}

我得到编译错误:error: use of moved value: 'color'

我做错了什么?

好的,仔细阅读编译器错误信息后发现问题所在;-(

内部循环将颜色移动到结构中,因此在第一次内部循环迭代之后,颜色不再是该值的所有者。因此,颜色在内循环的第二次迭代中不可用。

解决方案是为 Colors 枚举实现克隆特性:

#[derive(Clone, Debug, EnumIter)]
enum Colors {
    Hearts,
    Spades,
    Diamonds,
    Clubs
}

然后移动颜色的克隆,这样外层循环的原始值的所有权在任何时候都不会移动到结构中。

    for color in Colors::iter() {
        for number in Numbers::iter() {
            let card = Card {
                color: color.clone(),
                number: number
            };
            println!("My card is a {:?} of {:?}", card.number, card.color);
        }