Saturday, July 29, 2023

Delegating Display/Debug trait implementations

Suppose you want implement Display and Debug traits for your struct, but the output is the same. Instead of copy & paste the implementation, you can delegate the implementation by casting the Self type to the trait type:

impl std::fmt::Debug for MyStruct {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "MyStruct");
	}
}

impl std::fmt::Display for HRESULT {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		<Self as std::fmt::Debug>::fmt(self, f) // delegate
	}
}

As a reminder, the Self casting can be useful in other situations.

No comments: