I am writing a macro_rules
macro, and I want users to be able to provide a custom way to "format" the identifiers I create.
I came across this Stack Overflow answer that pointed out that you could pass in the name of a macro into a macro, and have it evaluate that macro. I figured this was exactly what I needed.
macro_rules! create_fn_let {
($create_ident:ident) => {
fn created_fn_let() {
let $create_ident!() = 1;
let $create_ident!(): u8 = 1;
}
};
}
macro_rules! create_foo_ident {
() => {foo};
}
create_fn_let!(create_foo_ident);
This successfully expands into:
fn created_fn_let() {
let foo = 1;
let foo: u8 = 1;
}
However, if I try to do the same thing with const
instead of let
, it doesn't work!
macro_rules! create_fn_const {
($create_ident:ident) => {
fn created_fn_const() {
const $create_ident!(): u8 = 1;
}
};
}
macro_rules! create_foo_ident {
() => {foo};
}
create_fn_const!(create_foo_ident);
This produces the following error:
error: expected one of `:`, `;`, `<`, `=`, or `where`, found `!`
--> src/macros.rs:71:32
|
71 | const $create_ident!(): u8 = 1;
| ^ expected one of `:`, `;`, `<`, `=`, or `where`
...
80 | create_fn_const!(foo; create_foo_ident);
| --------------------------------------- in this macro invocation
|
= note: this error originates in the macro `create_fn_const` (in Nightly builds, run with -Z macro-backtrace for more inf>
...snip...
error: missing type for `const` item
--> src/macros.rs:71:32
|
71 | const $create_ident!(): u8 = 1;
| ^
...
80 | create_fn_const!(foo; create_foo_ident);
| --------------------------------------- in this macro invocation
|
= note: this error originates in the macro `create_fn_const` (in Nightly builds, run with -Z macro-backtrace for more inf>
help: provide a type for the item
|
71 | const $create_ident: <type>!(): u8 = 1;
| ++++++++
Is there any reason that expanding a macro into a const
identifier should work differently than into a let
identifier? Is there some way to allow users to pass in a custom "formatting" macro while invoking my macro that I can use to define a const
?