简体   繁体   English

如何为 dyn Trait 对象的 Vec 获取 fmt::Debug 的实现?

[英]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.我有一个特征 MyTrait,其中所有实现都可以实现 fmt::Debug。 I have a struct MyStruct that contains a Vec<Rc<dyn MyTrait>> .我有一个包含Vec<Rc<dyn MyTrait>>的结构 MyStruct 。 How do I implement fmt::Debug for MyStruct?如何为 MyStruct 实现 fmt::Debug?

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.我的第一个想法是手动为 MyStruct 实现 Debug 但这似乎是非常错误的,因为只有 MyTrait 对象的 Debug 实现可能会有所不同。

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.从逻辑上讲,我应该能够要求 MyTrait “包含”(在 Java 术语中,这将是接口继承)Debug,然后简单地自动为 MyStruct 派生 Debug。 But how would I achieve this?但我将如何实现这一目标? I haven't found anything to that effect in the docs.我在文档中没有发现任何与此相关的内容。

Add Debug as a supertrait of MyTrait :Debug添加为MyTraitMyTrait

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.有些人称这个特性为“trait 继承”,但在支持类继承的语言中,supertrait 并不像基类。 It's really just a constraint on implementors of MyTrait : "If you implement MyTrait , you have to implement Debug too."这实际上只是对MyTrait实现者的一个限制:“如果你实现了MyTrait ,你也必须实现Debug 。” 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.由于dyn MyTrait是一种实现了MyTrait的类型,它也有自己的(自动生成的) Debug实现,它只是遵从具体类型的Debug

However, you cannot upcast a trait object to a supertrait , at least not without some extra work.但是,您不能将 trait 对象向上转换为 supertrait ,至少在没有一些额外工作的情况下不能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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