81

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

6 Answers 6

100

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why when I try to write like this, it always print the first one . Heart => write!(f, "♥") Diamond => write!(f, "♦")
To print ♦ you need to create a reference to Suit::Diamond and then print it. For instance let diamond = Suit::Diamond; println!("{}", diamond);
What is the need of dereferencing self in your answer?
Nice catch, it is not needed!
95

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 Comments

This is not the answer
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)?
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.
32

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 Comment

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.
8

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 Comments

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.
I am suggesting an implementation of std::fmt::Display, exactly because that is what is usually expected in most contexts.
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); 
}

Comments

0

I have tried to print values of enum using pattern matching, where based on the enum values I assing them to certain string which I can print using call_print_fun, where input args is variable assign using enum

fn main(){
   let direction=Dirs::North;
   let _direction=Dirs::South;
   call_print_fun(direction);
}
enum Dirs{
    North,
    South
}

fn call_print_fun(_dir: Dirs){
    println!("The Direction Class:");
    let girl: &str = match _dir {
        Dirs::North => "North",
        Dirs::South => "South",
    };
    print!("{}",girl)
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.