【问题标题】:Problems with creating an impl-block using a macro in Rust在 Rust 中使用宏创建 impl-block 的问题
【发布时间】:2017-01-07 16:17:41
【问题描述】:

我想创建一个宏,为包含单个泛型类型的结构生成给定的格式化程序(DisplayDebug、...)。

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&lt;T&gt;, 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;)。但我不知道为什么。

标签: generics macros rust


【解决方案1】:

这看起来确实很神秘!似乎问题在于解析宏的输出的方式:由于在宏处理期间它已部分预解析为path,因此它不再匹配特征绑定的解析规则。有一个bug raised a few weeks ago 与此有关。

不过,有个好消息 - it's been fixed!该示例实际上适用于 beta 或 nightly 编译器 (playground),但请注意,我必须将 $trait 重命名为 $t,因为 trait 是关键字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多