简体   繁体   中英

How to get an implementation of fmt::Debug for a Vec of dyn Trait objects?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM