我正在try 理解为什么以下代码不能编译:
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
的所有 struct 也将继承Vehicle
的Display
实现.我可以理解,如果Car
try 自己实现Display
,为什么这会是一个问题,但这里不是这样.
我知道我可以通过改变来修正这个例子
impl std::fmt::Display for dyn Vehicle
至
impl std::fmt::Display for Car
but for non-trivial examples, this seems really verbose. What's the right way 至 do this?