Reputation: 50110
I want to make a macro that does this
mac1!("foo", x)
emits
foo(x)
is it even possible?
Upvotes: 0
Views: 141
Reputation: 16475
No, it's not possible. By the time the macro is expanded, the matching is done on the fact that "foo"
is an expression
(or a literal
). The compiler does not distinguish between an expression like "foo"
in your example and 123u8
, 1 + 2
, foo()
or { let f = fs::read("foo.txt"); ... }
as all of those are expressions. All the macro-by-example knows is that the first parameter is any kind of valid expression and it can't look deeper into it, because the compiler doesn't know what a "type" or a "value" is at this point.
You can use a procedural macro, which can use a parameter's value to generate new tokens, including identifiers.
Upvotes: 2