4
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?

0x00A5
  • 1,462
  • 1
  • 16
  • 20
  • Yes. You are right. Sorry I didn't describe my question properly. I will update my question. – 0x00A5 Jan 23 '20 at 15:59
  • I found it helpful reading this post: https://stackoverflow.com/questions/54165117/convert-string-into-tokenstream – 0x00A5 Jan 24 '20 at 02:04

2 Answers2

3

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.

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • Sorry. I think I didn't describe my question properly. I have update my question. Thanks for replying. – 0x00A5 Jan 23 '20 at 16:01
  • 1
    My case is a bit more complicated than what I described, but using `format!` first to concat and then put the result `&str` in `quote!` works for me. Thanks. – 0x00A5 Jan 27 '20 at 15:32
2

I found the extra part of solution that I need on top of Psidom's answer in this blog.

use quote::quote;
use syn;

fn main() {
    let foo = "foo";
    let foobar = syn::Ident::new(&format!("{}bar", foo), syn::export::Span::call_site());
    let q = quote!(#foobar);
    println!("{}", q);
}

Playground.

0x00A5
  • 1,462
  • 1
  • 16
  • 20