patternrustMajor
Is there a way to print enum values?
Viewed 0 times
enumprintwayvaluesthere
Problem
Is there an easy way to format and print enum values? I expected that they'd have a default implementation of
Desired output:
Error:
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:
HeartError:
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
Solution
You can derive an implementation of
It is not possible to derive
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.Code Snippets
#[derive(Debug)]
enum Suit {
Heart,
Diamond,
Spade,
Club
}
fn main() {
let s = Suit::Heart;
println!("{:?}", s);
}Context
Stack Overflow Q#28024373, score: 95
Revisions (0)
No revisions yet.