Reputation: 1540
I want to define a variable with a macro ident
and pass it to a derive macro, but I get an error:
Error
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
Code
#[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
});
Upvotes: 7
Views: 6459
Reputation: 373
You use the macro model!
where the compiler expects an item (function/struct/trait declaration or impl
block). A let
statement is only valid inside a code block. This is why your first example works (where the macro call is inside main
), while your second example doesn't.
This seems like an instance of the XY problem. Check out procedural macros if you want to run code to generate code at compile time.
Upvotes: 7