首页 > 解决方案 > 宏扩展忽略标记 `let` 和任何后续

问题描述

我想用宏定义一个变量ident并将其传递给派生宏,但出现错误:

错误

error: macro expansion ignores token `let` and any following
  --> database/src/models.rs:15:9
   |
15 |           let struct_name = stringify!($name);
   |           ^^^
...
50 | / model!(Person {
51 | |     name: String
52 | | });
   | |___- caused by the macro expansion here
   |
   = note: the usage of `model!` is likely invalid in item context

代码

#[macro_export]
macro_rules! model {
    ( 
        $(#[$met: meta])*
        $name: ident { $($attr: ident : $typ: ty),* } 
    ) => {

        let struct_name = stringify!($name);
        //let table_name = struct_name.to_camel_case();
        
        dbg!("{}", struct_name);
        
        #[derive(Debug)]
        struct $name {
            name: String
        };
    };
}

model!(Person {
        name: String
});

操场

标签: rustmacros

解决方案


model!您在编译器需要项目(函数/结构/特征声明或impl块)的地方使用宏。let语句仅在代码块内有效。这就是为什么你的第一个例子有效(宏调用在里面main),而你的第二个例子没有。

这似乎是XY 问题的一个实例。如果您想在编译时运行代码以生成代码,请查看过程宏。


推荐阅读