Learning Rust, Day 2

I was able to make minor progress on the Cribbage game. It's been a few weeks since I had looked at it - turns out a global pandemic can be distracting. The code I left is just series of enums and a Card struct.

The goal for this round was simple: build an all function that returns all 52 cards and print the result. So, as a list:

  • Be able to informatively print a Card struct
  • Iterate across all ranks and suits to build a list of Card structs (we basically want the Cartesian product)
  • Write a test or two proving out the above behaviors

This is roughly what I came up with for the "give me all the cards" function:

 pub fn all() -> Vec<Card> {
     let mut cards = Vec::new();
     for suit in SUITS.iter() {
         for rank in RANKS.iter() {
             let card = Card::new(*rank, *suit);
     return cards

So far so normal.

I did run into an interesting case: std::fmt::Display. I tried to implement it for the Card struct to make printing easier. This:

impl std::fmt::Display for Card {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_string())

For some reason, this hilariously explodes with a stack overflow. It's probably something silly. For now, I'm just doing println!("{}", card.to_string()); I'll come back around to this next time so I can understand what's going on.

Some minor notes:

  • Via Elixir, I'm used to assert; assert_eq! has better output when something goes wrong.
  • My mod test blocks have a user super::*; call; this is required (?) for it to compile but I get warnings from cargo build about an unused import. I've even tried specifically calling use super::Card and it still complains about it being unused.
  • I'm trying out VS Code instead of vanilla vim. Per usual, the vim emulation is "weak"...it supports everything I use within a single editor window but when you pull in a terminal or side panel the shortcuts just bail. Having various cargo tasks available via shortcut is nice.

That's it for now.

More from dubdromic