有没有办法打印枚举值?

时间:2015-01-19 12:10:32

标签: enums rust

有没有简单的方法来格式化和打印枚举值?我预计他们会有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`

2 个答案:

答案 0 :(得分:35)

您可以派生std::format::Debug的实现:

#[derive(Debug)]
enum Suit {
    Heart,
    Diamond,
    Spade,
    Club
}

fn main() {
    let s = Suit::Heart;
    println!("{:?}", s);
}

无法派生Display因为Display旨在向人类展示,并且编译器无法自动确定该案例的适当样式。 Debug适用于程序员,因此可以自动生成内部公开视图。

答案 1 :(得分:21)

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 s = Suit::Heart;
    println!("{}", s);
}