如前所述,有很多方法可以生成枚举迭代器,但您可能对我的库感兴趣
exhaust
,它还可以为结构体(以及枚举变量中的字段值,但这不适用于这种情况)生成笛卡尔积迭代器:
use exhaust::Exhaust;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Exhaust)]
enum Suit {
Spades,
Hearts,
Diamonds,
Clubs,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Exhaust)]
enum Rank {
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Exhaust)]
struct Card {
rank: Rank,
suit: Suit,
}
fn main() {
for c in Card::exhaust() {
println!("{c:?}");
}
}
打印:
Card { rank: Two, suit: Spades }
Card { rank: Two, suit: Hearts }
Card { rank: Two, suit: Diamonds }
Card { rank: Two, suit: Clubs }
Card { rank: Three, suit: Spades }
Card { rank: Three, suit: Hearts }
Card { rank: Three, suit: Diamonds }
Card { rank: Three, suit: Clubs }
Card { rank: Four, suit: Spades }
Card { rank: Four, suit: Hearts }
...