【发布时间】:2017-01-07 16:17:41
【问题描述】:
我想创建一个宏,为包含单个泛型类型的结构生成给定的格式化程序(Display、Debug、...)。
macro_rules! create_formatter {
($type_name:ident<$gen_param:ident>, $trait:path) => {
impl<$gen_param: $trait> $trait for $type_name<$gen_param> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
// isn't yet implemented
}
}
};
}
当我稍后在代码中调用宏 (create_formatter!(MyStruct<T>, std::fmt::Display);) 时,编译器会给出以下反馈:
error: expected one of `,`, `=`, `>`, or `?`, found `std::fmt::Display`
--> test.rs:6:26
|
6| impl<$gen_param: $trait> $trait for $type_name<$gen_param> {
| ^^^^^^^^
我做错了什么?
【问题讨论】:
-
如果您使用
ident作为用于特征绑定的片段说明符,它确实有效。 (这也意味着您需要使用Display调用它并添加use std::fmt::Display;)。但我不知道为什么。