Implementing the Display trait for an enum

Im implementing the Display trait for an enum, to be passed as a trait constraint for a generic type, is there anything I am doing wrong? It keeps raising errors on the codebase

    impl std::fmt::Display for time_variable {
        
        fn fmt (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            
            match self {
                time_variable::A => write!("Afternoon"),
                time_variable::E => write!("Evening"),
                time_variable::M => write!("Morning")
            } 
                   
        }
    }

You haven't posted the error so it's hard to help you.
Though the first thin I notice is that you're not passing f to the write! macro.
Compare your code to the Example and you should see the problem.

5 Likes

Filed Error on incomplete macro call could provide more context, specially for built-in macros like `write!` not receiving the `Formatter` · Issue #152493 · rust-lang/rust · GitHub as the output for this case is not ideal:

error: unexpected end of macro invocation
   --> src/lib.rs:5:28
    |
  5 |             S => write!("S"),
    |                            ^ missing tokens in macro arguments
    |
note: while trying to match `,`
   --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/macros/mod.rs:611:15
    |
611 |     ($dst:expr, $($arg:tt)*) => {
    |               ^

The error should have at least a note with the first line of the docs: "This macro accepts a ‘writer’, a format string, and a list of arguments." Maybe even a link to the docs as well for some builtin macros.

1 Like

You need to pass f to the write! macro, so it would look like:

    impl std::fmt::Display for time_variable {
        
        fn fmt (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            
            match self {
                time_variable::A => write!(f, "Afternoon"),
                time_variable::E => write!(f, "Evening"),
                time_variable::M => write!(f, "Morning"),
            } 
                   
        }
    }

This should compile