use std::fmt;
struct TeamMember {
name: String,
age: u32,
}
struct Manager {
name: String,
age: u32,
}
impl fmt::Display for TeamMember {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TeamMember; name => {}, age => {}", self.name, self.age)
}
}
impl fmt::Display for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Manager; name => {}, age => {}", self.name, self.age)
}
}
trait Employee {}
impl fmt::Display for Employee {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", *self)
}
}
fn main() {
let t = TeamMember { name: "abc".to_string(), age: 23 };
let t2 = Manager { name: "xyz".to_string(), age: 18 };
let mut v: Vec<&Employee> = Vec::new();
v.push(&t);
v.push(&t2);
for it in &v {
println!("i am a {}", *it);
}
}
我想多態調用2種具體類型特徵的矢量對象引用的顯示器。我得到以下編譯錯誤:
<std macros>:2:21: 2:52 error: the trait `core::marker::Sized` is not implemented for the type `Employee` [E0277]
<std macros>:2 $ dst . write_fmt (format_args ! ($ ($ arg) *)))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<std macros>:2:21: 2:52 note: in this expansion of format_args!
矢量迭代應該呼籲的具體類型Display
功能...
我試過了你說的,即從fmt:Display中刪除了impl fmt :: Display for employee和extended Employee,但是沒有工作。 – ddastoor
現在我得到了=> rustc /home/dastoor/rust_examples/polymorphic_display_trait.rs /home/dastoor/rust_examples/polymorphic_display_trait.rs:40:12:40:14錯誤:特徵'Employee'沒有爲' TeamMember' [E0277] /home/dastoor/rust_examples/polymorphic_display_trait.rs:40 v.push(&t); – ddastoor
這些都是另一個問題,而且錯誤信息對於你需要做的事情很明確 –