宏扩展忽略标记“let”和任何后续内容

Ram*_*chi 7 macros rust

我想用宏定义一个变量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
Run Code Online (Sandbox Code Playgroud)

代码

#[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
});

Run Code Online (Sandbox Code Playgroud)

操场

mad*_*ina 7

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

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