Implementing fmt::Display for enum with fields

Viewed 331

I am trying to implement the fmt::Display trait for a Rust 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(())
}

But I am getting this error which I cannot understand:

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

what does it mean? why write! macro is not found for u32? Does u32 mean one of the enum's fields?

1 Answers

The problem here is that your match arm binding f: &u32 shadows the value parameter f: &mut Formatter. So instead of passing the Formatter to the write! macro, you are passing the integer (reference).

You can go with

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

Or rename the match arm binding from f to something else.

Related