75

Is there an easy way to format and print enum values? I expected that they'd have a default implementation of std::fmt::Display, but that doesn't appear to be the case.

enum Suit {
    Heart,
    Diamond,
    Spade,
    Club
}

fn main() {
    let s: Suit = Suit::Heart;
    println!("{}", s);
}

Desired output: Heart

Error:

error[E0277]: the trait bound `Suit: std::fmt::Display` is not satisfied
  --> src/main.rs:10:20
   |
10 |     println!("{}", s);
   |                    ^ the trait `std::fmt::Display` is not implemented for `Suit`
   |
   = note: `Suit` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
   = note: required by `std::fmt::Display::fmt`
1

5 Answers 5

93

The Debug trait prints out the name of the Enumvariant.

If you need to format the output, you can implement Display for your Enum like so:

use std::fmt;

enum Suit {
    Heart,
    Diamond,
    Spade,
    Club
}

impl fmt::Display for Suit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       match self {
           Suit::Heart => write!(f, "♥"),
           Suit::Diamond => write!(f, "♦"),
           Suit::Spade => write!(f, "♠"),
           Suit::Club => write!(f, "♣"),
       }
    }
}

fn main() {
    let heart = Suit::Heart;
    println!("{}", heart);
}
4
  • Why when I try to write like this, it always print the first one . Heart => write!(f, "♥") Diamond => write!(f, "♦")
    – wonderflow
    Aug 22, 2019 at 8:51
  • To print ♦ you need to create a reference to Suit::Diamond and then print it. For instance let diamond = Suit::Diamond; println!("{}", diamond); Aug 22, 2019 at 15:03
  • 1
    What is the need of dereferencing self in your answer?
    – Trí Phan
    Feb 27 at 4:52
  • Nice catch, it is not needed! Mar 2 at 16:09
92

You can derive an implementation of std::format::Debug:

#[derive(Debug)]
enum Suit {
    Heart,
    Diamond,
    Spade,
    Club
}

fn main() {
    let s = Suit::Heart;
    println!("{:?}", s);
}

It is not possible to derive Display because Display is aimed at displaying to humans and the compiler cannot automatically decide what is an appropriate style for that case. Debug is intended for programmers, so an internals-exposing view can be automatically generated.

3
  • 28
    This is not the answer Aug 23, 2020 at 16:19
  • For enum's with values appended, e.g. Heart(u8), where u8 could be the card number from ace = 1, 2 to 13 (10, J, Q, K); is it possible to output only the enum name, not the value; Heart instead of Heart(7)?
    – Anatoly
    Jul 25, 2021 at 12:14
  • 4
    The OP asked for "an easy way to format and print enum values". This is the easiest of all the answers, and it format's and print's.. Answer is correct for OP. Feb 2 at 22:00
27

If you want to auto-generate Display implementations for enum variants you might want to use the strum crate:

#[derive(strum_macros::Display)]
enum Suit {
    Heart,
    Diamond,
    Spade,
    Club,
}

fn main() {
    let s: Suit = Suit::Heart;
    println!("{}", s); // Prints "Heart"
}
1
  • 4
    While it doesn't have many votes (currently), this is probably what you want as it's the least work to provide simple Display support to any enum.
    – optevo
    Jul 29, 2022 at 0:25
7

Combining both DK. and Matilda Smeds answers for a slightly cleaner version:

use std::fmt;

#[derive(Debug)]
enum Suit {
    Heart,
    Diamond,
    Spade,
    Club
}

impl fmt::Display for Suit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       write!(f, "{:?}", self)
    }
}

fn main() {
    let heart = Suit::Heart;
    println!("{}", heart);
}
2
  • I do not understand... if using derive(Debug) why use fmt::Display than ? It would be the same as: #[derive(Debug)] enum Suit { Heart } fn main() { let heart = Suit::Heart; println!("{:?}", heart); } which defeats the whole purpose of trying to make a Display.
    – fsan
    Jun 1, 2022 at 20:34
  • 1
    I am suggesting an implementation of std::fmt::Display, exactly because that is what is usually expected in most contexts.
    – raugfer
    Jun 3, 2022 at 13:13
3

you need to use "{:#?}" for format. This will work now.

#[derive(Debug)]
enum Suit {
    Heart,
    Diamond,
    Spade,
    Club
}

fn main() {
    let s: Suit = Suit::Heart;
    println!("{:#?}", s); 
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.