Warm tip: This article is reproduced from stackoverflow.com, please click
concat rust token rust-macros

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

发布于 2020-04-19 09:19:55
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?

Questioner
YLyu
Viewed
54
Psidom 2020-01-23 09:28

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.