【问题标题】:"no rules expected the token `<`" when passing a type as an ident to macro_rules将类型作为标识传递给宏规则时,“没有规则需要令牌`<`”
【发布时间】:2018-04-30 19:58:00
【问题描述】:

玩具示例:

macro_rules! boo {
    ($T:ident) => {
        let x: $T;
    };
}

fn main() {
    boo!(i32);         // WORKS
    boo!(Option<i32>); // PROBLEM
}

boo!(Option&lt;i32&gt;); 导致错误:

error: no rules expected the token `<`
 --> src/main.rs:9:16
  |
9 |     boo!(Option<i32>);
  |                ^

我可以解决它:

type Opti32 = Option<i32>;
boo!(Opti32);

但是为每次使用宏都添加别名太无聊了。 是否可以使用boo!(Option&lt;i32&gt;); 之类的宏并隐藏 macro_rules里面的难点?

【问题讨论】:

    标签: rust


    【解决方案1】:

    $T:ident 只能匹配 identifier。

    如果您希望$T 匹配任何类型,即使它不是单个标识符,您也应该改用$T:ty

    macro_rules! boo {
        ($T:ty) => {
            let x: $T;
        }
    }
    

    identty 被称为“片段说明符”,因为它们指定元变量$T 可以匹配什么样的代码片段。 Rust 书的第一版有a chapter on macros,包括可能的片段说明符列表;在尝试编写宏之前,您绝对应该熟悉本章的内容。

    【讨论】:

    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-14
    相关资源
    最近更新 更多