如何迭代枚举,将其插入向量,然后在 Rust 中对其进行打乱?

我正在编写代码来初始化一副包含 52 张牌的牌并对它们进行洗牌。在 Java 中,我使用 anArrayList并迭代枚举Suit和Rank枚举,并Card(suit,rank)在进行过程中添加一个对象。然后我用Collections.shuffle().


我正在尝试使用向量和结构将此代码移植到 Rust。问题是我无法像 Java 中那样迭代枚举。Rust 尝试实现此结果的惯用方法是什么?


我曾尝试导入 strum 和 strum_macros 来获得枚举迭代,但我一直试图将结构推入其中Vec,然后随机对其进行洗牌。


Java代码


public class Deck {

    private List < Card > aCards = new ArrayList < > ();


    public Deck() {

        shuffle();

    }

    public void shuffle() {

        aCards.clear();

        for (Suit suit: Suit.values()) {

            for (Rank rank: Rank.values()) {

                aCards.add(new Card(rank, suit));

            }

        }

        Collections.shuffle(aCards);

    }

}

生锈尝试


use crate::card::Card;

use crate::rank::Rank;

use crate::suit::Suit;

use rand::{thread_rng, Rng};

use strum::IntoEnumIterator;


pub struct Deck {

    cards: Vec<Card>,

}


impl Deck {

    pub fn shuffle(&mut self) -> () {

        self.cards.clear();

        for s in Suit::iter() {

            for r in Rank::iter() {

                self.cards.push(Card::new(s, r));

            }

        }

    }

}

花色的结构(等级相似)


use strum_macros::*;


#[derive(EnumIter, Debug)]

pub enum Suit {

    SPADES,

    DIAMONDS,

    CLUBS,

    HEARTS,

}

卡结构


pub struct Card {

    suit: Suit,

    rank: Rank,

}

impl Card {

    pub fn new(psuit: Suit, prank: Rank) -> Card {

        Card {

            suit: psuit,

            rank: prank,

        }

    }

}

我只想简单地迭代两组枚举变体,然后重新排列输出对,但这似乎要复杂得多!我怀疑也许有更好的方法?


慕哥9229398
浏览 107回答 1
1回答

墨色风雨

关键点是:将洗牌所需的特征纳入范围(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 {&nbsp; &nbsp; DIAMONDS,&nbsp; &nbsp; HEARTS,&nbsp; &nbsp; CLUBS,&nbsp; &nbsp; SPADES,}#[derive(Debug, Copy, Clone, EnumIter)]enum Rank {&nbsp; &nbsp; Ace,&nbsp; &nbsp; King,&nbsp; &nbsp; Queen,&nbsp; &nbsp; Jack,}#[derive(Debug)]struct Card {&nbsp; &nbsp; suit: Suit,&nbsp; &nbsp; rank: Rank,}impl Card {&nbsp; &nbsp; fn new(suit: Suit, rank: Rank) -> Card {&nbsp; &nbsp; &nbsp; &nbsp; Card { suit, rank }&nbsp; &nbsp; }}fn main() {&nbsp; &nbsp; let mut cards = Vec::<Card>::new();&nbsp; &nbsp; for r in Rank::iter() {&nbsp; &nbsp; &nbsp; &nbsp; for s in Suit::iter() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cards.push(Card::new(s, r));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; let mut rng = thread_rng();&nbsp; &nbsp; cards.shuffle(&mut rng);&nbsp; &nbsp; println!("{:?}", cards);}正如您所看到的,这几乎就像在 Java 中一样。唯一的区别是,有些方法不是来自结构体,而是来自接口(在 Rust 中,这些方法称为特征),您必须导入它们才能使用它们。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java