rust 有打印枚举值的方法吗?

qojgxg4l  于 2023-03-18  发布在  其他
关注(0)|答案(4)|浏览(204)

有没有一种简单的方法来格式化和打印枚举值?我希望它们有一个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`
zdwk9cvp

zdwk9cvp1#

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

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

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

无法派生Display,因为Display的目的是向人类显示,编译器无法自动决定适合这种情况的样式。Debug是为程序员设计的,因此可以自动生成内部公开视图。

dgsult0t

dgsult0t2#

Debug trait输出Enum变体的名称。
如果您需要格式化输出,可以为Enum实现Display,如下所示:

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);
}
368yc8dk

368yc8dk3#

如果你想为枚举变量自动生成Display实现,你可能需要使用strum crate:

#[derive(strum_macros::Display)]
enum Suit {
    Heart,
    Diamond,
    Spade,
    Club,
}

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

qyuhtwio4#

结合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);
}

相关问题