dtolnay / quote

Rust quasi-quoting
Apache License 2.0
1.32k stars 90 forks source link

Multiple variables that repeat as a unit? #188

Closed Rua closed 2 years ago

Rua commented 3 years ago

In the standard macro language, you can declare a set of variables that repeats collectively. When expanding the macro, you can then use all those variables at the same repetition depth. Unfortunately I can't see how this would be done in quote!. The equivalent would be a Vec of structs, and being able to access the members of the struct within the quote. But it seems like the way to handle this is to have

.map(|s| {
    let Foo {..} = &s;
    quote! { .. }
})

and then assign/collect it to a variable and include it in a larger quote? It seems rather cumbersome, is there a better way?

dtolnay commented 2 years ago

What you've described is fine.

struct Foo { x: u8, y: u8 }
let vec = vec![Foo { x: 0, y: 0 }, Foo { x: 1, y: 1 }];
let sums = vec
    .iter()
    .map(|Foo { x, y }| quote! { #x + #y });
let t = quote! { #(f(#sums);)* };
println!("{}", t);

One alternative that is occasionally more suitable is unzip():

let (xs, ys): (Vec<&u8>, Vec<&u8>) = vec
    .iter()
    .map(|Foo { x, y }| (x, y))
    .unzip();
let t = quote! { #(f(#xs + #ys);)* };