2

I'd like to be able to use a str input as ident inside a macro. The specific usage would be something like this:

macro_rules! foo {
    ( $x:ident ) => {
        let $x = "stuff";
        let $x_2 = "other_stuff"
    };
}

So then the macro, when called with foo!(bar) would create the variables bar and bar_2. However this doesn't work, I can't find any way to modify an ident.

It seems to me this would be possible if I could transform an expr into a ident, so that I can first operate on the expression and concatenate my suffix, but I haven't been able to find a way to do that. So it would look something like

macro_rules! foo {
    ( $x:expr ) => {
        let to_ident!($x) = "stuff";
        let to_ident!(concat!($x, "_2")) = "other_stuff"
    };
}
foo!("bar"); // creates variables bar and bar_2
trent
  • 25,033
  • 7
  • 51
  • 90
Dominus
  • 808
  • 11
  • 25
  • 2
    You can't do this in a declarative macro. – Peter Hall Mar 27 '21 at 10:40
  • 1
    Rust explicitly disallows this in declarative macros: identifiers are meant to be sanitized, thus all created identifiers should be passed in from the calling context. If you want to do this, use a [procedural macro](https://doc.rust-lang.org/reference/procedural-macros.html) instead. – Aplet123 Mar 27 '21 at 12:07

0 Answers0