Reputation: 376
I have a trait MyTrait of which all implementations could implement fmt::Debug.
I have a struct MyStruct that contains a Vec<Rc<dyn MyTrait>>
.
How do I implement fmt::Debug for MyStruct?
My first idea was to just implement Debug for MyStruct manually but that seems very wrong, considering that only the implementation of Debug of the MyTrait objects could vary.
Logically I should be able to require MyTrait to "include" (in Java terms that would be interface inheritance) Debug and then simply derive Debug for MyStruct automatically. But how would I achieve this? I haven't found anything to that effect in the docs.
Upvotes: 6
Views: 2734
Reputation: 28005
Add Debug
as a supertrait of MyTrait
:
trait MyTrait: std::fmt::Debug {...}
Some people call this feature "trait inheritance", but a supertrait is not much like a base class in languages that support class inheritance. It's really just a constraint on implementors of MyTrait
: "If you implement MyTrait
, you have to implement Debug
too." Since dyn MyTrait
is a type that implements MyTrait
, it too has its own (automatically generated) Debug
implementation, which just defers to the Debug
for the concrete type.
However, you cannot upcast a trait object to a supertrait, at least not without some extra work.
Upvotes: 9