rustquasiquotes

Is there a way to access variable fields in quote variable interpolation?


I have a tuple with 5 elements and I want to include each one of them in the quote!{...} block.

I tried accessing the fields directly in the quote!{} block in a few ways without success:

let tuple = (1, true, -3, 4., "five");
quote! { #tuple.0 };    // error
quote! { #{tuple.0} };  // error
quote! { tuple.#0 };    // error

The only way that works for me is assigning each element to a different variable, and inserting them individually:

let tuple = (1, true, -3, 4., "five");
let tuple_0 = tuple.0;
let tuple_1 = tuple.1;
let tuple_2 = tuple.2;
let tuple_3 = tuple.3;
let tuple_4 = tuple.4;
quote! { #tuple_0, #tuple_1, #tuple_2, #tuple_3, #tuple_4 };

Although it works, this way is more tedious. Is there a better way to achieve this?


Solution

  • No. You need to assign the values to variables. But you can use destructuring:

    let tuple = (1, true, -3, 4., "five");
    let (tuple_0, tuple_1, tuple_2, tuple_3, tuple_4) = tuple;
    quote! { #tuple_0, #tuple_1, #tuple_2, #tuple_3, #tuple_4 };