我如何在Rust的内部特征上实现外部特征?
我想在main函数中打印Tweet数据类型的实例,但是summary特性没有实现debug特性。有没有什么方法可以实现一个特征对一个特征或任何变通方法。 取消对第二行的注释并对第一行进行注释是可行的,因为字符串类型实现了显示特性我如何在Rust的内部特征上实现外部特征?,rust,thrust,rust-cargo,wasm-bindgen,Rust,Thrust,Rust Cargo,Wasm Bindgen,我想在main函数中打印Tweet数据类型的实例,但是summary特性没有实现debug特性。有没有什么方法可以实现一个特征对一个特征或任何变通方法。 取消对第二行的注释并对第一行进行注释是可行的,因为字符串类型实现了显示特性 #[derive(Debug)] struct Tweet { name: String, } pub trait Summary { fn summarize(&self) -> String; } impl Summary for
#[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/
普林顿!(“{:#?}”,可摘要(字符串::from(“Alex”))|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
impl Summary
不能为空
使用{:?}
格式化,因为它没有实现std::fmt::Debug
|=帮助:traitstd::fmt::Debug
没有为impl Summary
=注意:std::fmt::Debug::fmt实现
错误:由于上一个错误而中止
有关此错误的详细信息,请尝试rustc--explain E0277
。
错误:无法编译p1
要了解更多信息,请使用--verbose再次运行该命令
您可以要求任何
impl
sSummary
的内容也必须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 {}