为带有字段的枚举实现 fmt::Display

Implementing fmt::Display for enum with fields

我正在尝试为 Rust enum 实现 fmt::Display 特性:

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(())
}

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

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

这是什么意思?为什么找不到 u32write! 宏? u32 是否表示枚举的字段之一?

这里的问题是您的 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),
        }
    }
}

或者将匹配臂绑定从 f 重命名为其他名称。