【发布时间】:2017-01-08 13:46:24
【问题描述】:
我正在编写一个宏来为包含单个泛型类型的给定结构动态生成Display 和Debug 等格式化程序。代码如下:
macro_rules! create_formatters {
($type_name:ident < $gen_param:ident > , $t:path) => {
impl<$gen_param: $t> $t for $type_name<$gen_param> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
let output = match stringify!($t) {
"std::fmt::Display" => format!("{}", self.0),
"std::fmt::Debug" => format!("{:?}", self.0),
// other formatters will be implemented soon
};
write!(f, "Content is: {}", output)
}
}
};
}
宏由create_formatters!(MyStruct<T>, std::fmt::Display);或create_formatters!(MyStruct<T>, std::fmt::Debug);调用
编译器给出以下错误:
error[E0277]: the trait bound `T: std::fmt::Debug` is not satisfied
--> <anon>:8:58
|
8 | "std::fmt::Debug" => format!("{:?}", self.0),
| ^^^^^^ the trait `std::fmt::Debug` is not implemented for `T`
...
28 | create_formatters!(Swagger<T>, std::fmt::Display);
| -------------------------------------------------- in this macro invocation
|
= help: consider adding a `where T: std::fmt::Debug` bound
= note: required by `std::fmt::Debug::fmt`
我该如何解决?
【问题讨论】:
标签: struct macros rust traits formatter