Create ident in declarative macro

Hi everyone,

Is there a way to create ident from str without the help of external crate?
I m writing macro for generating cartesian product from vectors and wanna generate codes like

    for x in [1, 3, 5] {
        for y in [2, 5, 6] {
            for z in [0,4,8]{
            }
        }
    }

but need to generate different idents x,y,z ...... for different vector

No, this is not possible.

1 Like

Maybe you could skirt it by using recusive style.

// Not efficient. don't use in productive environment.
macro_rules! product {
    ($a:expr, $b:expr) => {
        {
            let mut result = Vec::with_capacity($a.len() * $b.len());
            for i in $a {
                for j in $b {
                    result.push(i * j);
                }
            }
            result
        }
    };
    ($a:expr, $b:expr, $($tail:tt)*) => {
        {
            product!(product!($a, $b), $($tail)*)
        }
    }
}
fn main() {
    let v = product![&[1, 2, 3], &[4, 5], &[4, 5]];
    println!("{:?}", v);
}
 Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.96s
     Running `target/debug/playground`
Standard Output
[16, 20, 20, 25, 32, 40, 40, 50, 48, 60, 60, 75]

Reference: Incremental TT munchers

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.