1 回答
TA贡献1853条经验 获得超6个赞
关键点是:
将洗牌所需的特征纳入范围(SliceRandom对于 rand 版本 0.7)。
将所需类型纳入范围enum::iter()
货物.toml:
[package]
name = "mcve"
version = "0.1.0"
authors = ["Svetlin Zarev <svetlin.zarev@xxx.com>"]
edition = "2018"
[dependencies]
strum = "0.15"
strum_macros = "0.15"
rand = "0.7.0"
main.rs:
use strum_macros::EnumIter; // etc.
use strum::IntoEnumIterator;
use rand::thread_rng;
use rand::seq::SliceRandom;
#[derive(Debug, Copy, Clone,EnumIter)]
enum Suit {
DIAMONDS,
HEARTS,
CLUBS,
SPADES,
}
#[derive(Debug, Copy, Clone, EnumIter)]
enum Rank {
Ace,
King,
Queen,
Jack,
}
#[derive(Debug)]
struct Card {
suit: Suit,
rank: Rank,
}
impl Card {
fn new(suit: Suit, rank: Rank) -> Card {
Card { suit, rank }
}
}
fn main() {
let mut cards = Vec::<Card>::new();
for r in Rank::iter() {
for s in Suit::iter() {
cards.push(Card::new(s, r));
}
}
let mut rng = thread_rng();
cards.shuffle(&mut rng);
println!("{:?}", cards);
}
正如您所看到的,这几乎就像在 Java 中一样。唯一的区别是,有些方法不是来自结构体,而是来自接口(在 Rust 中,这些方法称为特征),您必须导入它们才能使用它们。
添加回答
举报