A new way to concatenate elements in Rust

85 points c410-f3r

${concat(..)} is a new meta-variable expression, behind the macro_metavar_expr_concat flag, that concatenates elements into a single identifier.

Due to previous failed and demotivating attempts, I ask this community to test the feature as much as possible to ensure a solid and robust background for a future stabilization.

Unlike concat_idents!(..), ${concat(..)} allows among other things.

  • The creation of identifiers in more places.
static concat_idents!(FOO, _BAR): i32 = 1; // Error !

macro_rules! create (() => { static ${concat(FOO, _BAR)}: i32 = 1; }); create!(); // OK !
  • The use of string literals.
fn foo0() {}

let _ = concat_idents!(foo, "0"); // Error !

macro_rules! create (() => { let _ = ${concat(foo, "0")}; }); create!(); // OK !
  • Scenarios with macro repetitions
macro_rules! create {
    ($($ident:ident)*) => {
        $( let _ = concat_idents!($ident, FOO); )* // Error !

        $( let ${concat($ident, FOO)}: i32 = 3; )* // OK !
    };
}

https://github.com/rust-lang/rust/issues/124225