我正在尝试理解为什么以下代码无法编译:
trait Vehicle {
fn get_num_wheels(&self) -> u32;
}
impl std::fmt::Display for dyn Vehicle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Has {} wheels", self.get_num_wheels())
}
}
struct Car();
impl Vehicle for Car {
fn get_num_wheels(&self) -> u32 {
4
}
}
fn main() {
let car = Car {};
println!("{car}");
}
error[E0277]: `Car` doesn't implement `std::fmt::Display`
--> src/main.rs:21:16
|
21 | println!("{car}");
| ^^^ `Car` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Car`
我认为如果我针对
Vehicle
实现了Display
,那么所有实现Vehicle
的结构体也将继承Vehicle
对Display
的实现。我可以看出,如果Car
试图制作自己的Display
实现,这将是一个问题,但在这种情况下并非如此。我知道我可以通过更改来修复此示例。
impl std::fmt::Display for dyn Vehicle
到
impl std::fmt::Display for Car
但对于非平凡的示例,这似乎非常冗长。有什么正确的方法来做到这一点?
Vehicle::Car(c)
或Vehicle::Motorbike(m)
,每个枚举都包装了另一种类型,并可以在更高级别上实现Display
。您还可以拥有VehicleContainer<V> where V : Vehicle
,其中Vehicle
是某种 trait,就像您在这里看到的那样,尽管容器是实现Display
的部分。 - tadman