我想在主函数中打印Tweet数据类型的实例,但是摘要特征没有实现调试特征。有什么方法可以实现特质上的特质或其他解决方法。取消注释第二行并注释第一行是可行的,因为String类型实现了Display特性。
#[derive(Debug)]
struct Tweet {
name: String,
}
pub trait Summary {
fn summarize(&self) -> String;
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("@{}", &self.name)
}
}
fn summarizeable(x: String) -> impl Summary {
Tweet { name: x }
}
fn main() {
//1.
println!("{:#?}", summarizeable(String::from("Alex")));
//2.println!("{}",summarizeable(String::from("Alex")).summarize());
}
错误[E0277]:
impl Summary
未实现std::fmt::Debug
->src / main.rs:26:29 | 26 | /1./println!(“ {:#?}”,summarizeable(String :: from(“ Alex”)))); |^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^impl Summary
不能为使用{:?}
格式化,因为它没有实现std::fmt::Debug
| =帮助:std::fmt::Debug
的特征impl Summary
未实现=注意:std::fmt::Debug::fmt
要求错误:由于先前的错误而中止
有关此错误的更多信息,请尝试
rustc --explain E0277
。错误:无法编译p1
。要了解更多,请使用--verbose再次运行命令。
您可以要求impl
Summary
的任何内容还必须是impl
std::fmt::Debug
,如下所示:
pub trait Summary : std::fmt::Debug { // Summary requires Debug
fn summarize(&self) -> String;
}
如果您不想将Debug
与Summary
绑定在一起,则可以始终引入包含其他两个特征的另一个特征:
pub trait DebuggableSummary : Summary + std::fmt::Display {}