Struct 在Rust中动态生成格式化程序的宏

Struct 在Rust中动态生成格式化程序的宏,struct,macros,rust,traits,formatter,Struct,Macros,Rust,Traits,Formatter,我正在编写一个宏来为包含单个泛型类型的给定结构动态生成格式化程序,如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(&a

我正在编写一个宏来为包含单个泛型类型的给定结构动态生成格式化程序,如
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)
            }
        }
    };
}
macro\u规则!创建格式化程序{
($type\u name:ident<$gen\u param:ident>,$t:path)=>{
$type\u name的impl$t{
fn fmt(&self,f:&mut std::fmt::Formatter)->结果{
让输出=匹配字符串化!($t){
“std::fmt::Display”=>format!(“{}”,self.0),
“std::fmt::Debug”=>格式!(“{:?}”,self.0),
//其他格式化程序将很快实施
};
写入!(f,“内容为:{}”,输出)
}
}
};
}
宏由
create\u格式化程序调用!(MyStruct,std::fmt::Display)
创建格式化程序!(MyStruct,std::fmt::Debug)

编译器出现以下错误:

error[E0277]:特性绑定'T:std::fmt::Debug'不满足
--> :8:58
|
8 |“std::fmt::Debug”=>格式!(“{:?}”,self.0),
|^^^^^T未实现特性“std::fmt::Debug”`
...
28 |创建|格式化程序!(昂首阔步,标准::fmt::显示);
|------------------------------------------------------在此宏调用中
|
=帮助:考虑添加一个“T:STD::FMT::调试”绑定
=注意:std::fmt::Debug::fmt需要`

我如何修复它?< /P> < P> <强>为什么你会得到这个错误?< /强>让我们看看 CuraTy*格式化程序的扩展!(MyStruct,std::fmt::Display)


<强>为什么你会得到这个错误?< /强>让我们看看<代码> CuraTy*格式化程序的扩展!(MyStruct,std::fmt::Display)

impl<T: std::fmt::Display> std::fmt::Display for MyStruct<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let output = match "std::fmt::Display" {
            "std::fmt::Display" => format!("{}", self.0),
            "std::fmt::Debug" => format!("{:?}", self.0),
            // other formatters will be implemented soon
        };
        write!(f, "Content is: {}", output)
    }
}
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    self.0.fmt(f)
}