Search code examples
rusttokenconcatenationrust-macros

How to concatenate token right after a variable within `quote!` macro?


use quote::quote;

fn main() {
    let name = "foo";
    let res = quote!(#name bar);
    println!("{:?}", res.to_string());
}

The above code prints "\"foo\" bar". Please try running it here on Rust Playground.

How to adjust it to make the single ident out of the variable part and constant suffix?

I want to use the quote! returned value in a derive macro. How to get rid of the double quote characters?


Solution

  • Since you only need to quote bar, how about combining the usage of quote! and format!?

    use quote::quote;
    
    fn main() {
        let name = "foo";
        let res = format!("{} {}", name, quote!(bar));
        println!("{:?}", res.to_string());
    }
    

    playground.

    If you need the extra quote in the result:

    use quote::quote;
    
    fn main() {
        let name = "foo";
        let res = format!("\"{}{}\"", name, quote!(bar));
        println!("{:?}", res.to_string());
    }
    

    playground.