One method impl for multiple traits

Hello,

If I want my struct to satisfy two traits that call for the same method, how can I write one common implementation?

For example, Display and Debug both call for a method fmt(&self, f: &mut Formatter<'_>), so I want to write the implementation of fmt only once.

Thanks!

Best, Oliver

In general, you can put all the method logic in a function and have both method implementations just call that function.

In almost all cases you should just #[derive(Debug)], not write an explicit implementation. After that, if for some reason you want the Display output to be the same as the Debug output, you can do this:

impl Display for Foo {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(self, f)
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.