宏扩展忽略标记 `let` 和任何后续
Macro expansion ignores token `let` and any following
我想用宏 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
});
您在编译器需要项目(function/struct/trait 声明或 impl
块)的地方使用宏 model!
。 let
语句仅在代码块内有效。这就是为什么您的 first example works (where the macro call is inside main
), while your second example 没有。
如果您想 运行 代码在编译时生成代码,这似乎是 XY problem. Check out procedural macros 的一个实例。
我想用宏 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
});
您在编译器需要项目(function/struct/trait 声明或 impl
块)的地方使用宏 model!
。 let
语句仅在代码块内有效。这就是为什么您的 first example works (where the macro call is inside main
), while your second example 没有。
如果您想 运行 代码在编译时生成代码,这似乎是 XY problem. Check out procedural macros 的一个实例。