I'm new at Rust and I'm trying to implement a cards' deck on Rust, I'm trying to use most idiomatic code I can, but since I'm new at this language, I'd like to hear advice from more experienced programmers. There's my code. (P.D: Thanks in advance! :>)
use std::fmt;
use rand::seq::SliceRandom;
use rand::thread_rng;
#[derive(PartialEq)]
pub struct Card<'a> {
name: &'a str,
value: i8,
suit: char,
}
impl<'a> fmt::Debug for Card<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} of {}", self.name, self.suit)
}
}
pub struct Deck<'a> {
pub cards: Vec<Card<'a>>,
}
impl<'a> Deck<'a> {
const SUITS: [char; 4] = ['♥', '♦', '♣', '♠'];
const CARDS: [(&'a str, i8); 13] = [
("ACE", 11),
("TWO", 2),
("THREE", 3),
("FOUR", 4),
("FIVE", 5),
("SIX", 6),
("SEVEN", 7),
("EIGHT", 8),
("NINE", 9),
("TEN", 10),
("JACK", 10),
("QUEEN", 10),
("KING", 10),
];
pub fn new() -> Deck<'a> {
let mut deck: Vec<Card> = Vec::new();
for suit in Deck::SUITS.iter() {
for (card_name, card_value) in Deck::CARDS.iter() {
deck.push(Card {
name: card_name,
value: *card_value,
suit: *suit,
});
}
}
let mut rng = thread_rng();
deck.shuffle(&mut rng);
Deck { cards: deck }
}
pub fn deal_card(&mut self) -> Card<'a> {
if self.cards.is_empty() {
self.initialize_deck()
}
self.cards.pop().unwrap()
}
pub fn get_initial_cards(&mut self) -> Vec<Card> {
vec![self.deal_card(), self.deal_card()]
}
/// When the cards vector is empty, shuffle a new deck
fn initialize_deck(&mut self) {
*self = Deck::new();
}
}
EDIT: This module is meaned to be used with a BlackJack game, that is the reason because the cards have those particular values