是否有一种简单的方法来格式化和打印枚举值?我预计他们会有 std::fmt::Display
的默认实现,但事实并非如此。
enum Suit {
Heart,
Diamond,
Spade,
Club
}
fn main() {
let s: Suit = Suit::Heart;
println!("{}", s);
}
期望的输出: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`
最佳答案
您可以派生 std::format::Debug
的实现:
#[derive(Debug)]
enum Suit {
Heart,
Diamond,
Spade,
Club
}
fn main() {
let s = Suit::Heart;
println!("{:?}", s);
}
不可能派生 Display
,因为 Display
旨在向人类显示,而编译器无法自动确定适合该情况的样式。 Debug
是为程序员准备的,因此可以自动生成内部公开 View 。
关于enums - 有没有办法打印枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024373/