【问题标题】:How to concatenate token right after a variable within `quote!` macro?如何在“引号!”宏中的变量之后连接标记?
【发布时间】:2020-05-09 05:46:07
【问题描述】:
use quote::quote;

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

上面的代码打印"\"foo\" bar"。请尝试在 Rust Playground 上运行 here

如何调整使可变部分和常量后缀成为单一标识?

我想在派生宏中使用quote! 返回值。如何去掉双引号字符?

【问题讨论】:

标签: rust token concat rust-macros


【解决方案1】:

我在blog 中找到了除 Psidom 的答案之外我需要的额外部分解决方案。

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.

【讨论】:

    【解决方案2】:

    既然你只需要引用bar,那么quote!format!的用法如何结合起来呢?

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

    playground.

    如果您需要结果中的额外引号:

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

    playground.

    【讨论】:

    • 对不起。我想我没有正确描述我的问题。我已经更新了我的问题。感谢您的回复。
    • 我的情况比我描述的要复杂一些,但是首先使用format! 连接然后将结果&str 放入quote! 对我有用。谢谢。
    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多