Is there a way to print enum values?
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.
The Debug
trait prints out the name of the Enum
variant.
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);
}
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"
}
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);
}