gpt4 book ai didi

rust - 如何在其多态类型上调用 Display 特征?

转载 作者:行者123 更新时间:2023-11-29 08:27:36 25 4
gpt4 key购买 nike

我有:

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函数...

最佳答案

这终于成功了,谢谢:

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: fmt::Display {}
impl Employee for TeamMember {}
impl Employee for Manager {}

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);
}
}

关于rust - 如何在其多态类型上调用 Display 特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37237831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com