有没有简单的方法来格式化和打印枚举值?我希望他们有一个默认的实现std::fmt::Display,但似乎并非如此.
enum Suit {
Heart,
Diamond,
Spade,
Club
}
fn main() {
let s: Suit = Suit::Heart;
println!("{}", s);
}
Run Code Online (Sandbox Code Playgroud)
期望的输出: Heart
错误:
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`
Run Code Online (Sandbox Code Playgroud)
DK.*_*DK. 42
您可以派生出一个实现std::format::Debug:
#[derive(Debug)]
enum Suit {
Heart,
Diamond,
Spade,
Club
}
fn main() {
let s = Suit::Heart;
println!("{:?}", s);
}
Run Code Online (Sandbox Code Playgroud)
导出是不可能的,Display因为Display它旨在向人类显示,并且编译器无法自动决定该情况的适当样式.Debug适用于程序员,因此可以自动生成内部公开视图.
Mat*_*eds 31
该Debug特性打印出的名称Enum变型.
如果您需要格式化输出,可以实现Display你Enum像这样:
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);
}
Run Code Online (Sandbox Code Playgroud)
nja*_*jam 28
如果您想自动生成Display枚举变体的实现,您可能需要使用strum crate:
#[derive(strum_macros::Display)]
enum Suit {
Heart,
Diamond,
Spade,
Club,
}
fn main() {
let s: Suit = Suit::Heart;
println!("{}", s); // Prints "Heart"
}
Run Code Online (Sandbox Code Playgroud)
结合两个DK。Matilda Smeds回答了一个稍微简洁的版本:
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);
}
Run Code Online (Sandbox Code Playgroud)