使用字段实现枚举的 fmt::Display

GG1*_*991 2 enums rust

我正在尝试实现fmt::DisplayRust 的特征enum

use std::fmt;
use std::error::Error;
use std::fmt::Display;

enum A {
    B(u32, String, u32, u32, char, u32),
}

impl Display for A {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       match *self {
           A::B(a, b, c, d, e, f) => write!(f, "{} {} {} {} {} {}", a, b, c, d, e, f),
       }
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let a = A::B(0, String::from("hola"), 1, 2, 'a', 3);
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

但我收到了这个我无法理解的错误:

error[E0599]: no method named `write_fmt` found for type `u32` in the current scope
  --> src/main.rs:14:38
   |
14 |            A::B(a, b, c, d, e, f) => write!(f, "{} {} {} {} {} {}", a, b, c, d, e, f),
   |                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ method not found in `u32`
   |
   = note: this error originates in the macro `write` (in Nightly builds, run with -Z macro-backtrace for more info)

For more information about this error, try `rustc --explain E0599`.
error: could not compile `test1` due to previous error
Run Code Online (Sandbox Code Playgroud)

这是什么意思?为什么write!没有找到宏u32?是否u32意味着枚举的字段之一?

pet*_*ulb 7

这里的问题是你的match arm binding f: &u32阴影value parameter f: &mut Formatter. 因此,您不是将 Formatter 传递给write!宏,而是传递整数(引用)。

你可以去

impl Display for A {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match &*self {
            A::B(a, b, c, d, e, f) => write!(formatter, "{} {} {} {} {} {}", a, b, c, d, e, f),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者将火柴臂绑定重命名f为其他名称。