【问题标题】:error[E0277]: the trait bound `Vec<TokenStream2>: ToTokens` is not satisfied错误 [E0277]: 特征绑定 `Vec<TokenStream2>: ToTokens` 不满足
【发布时间】:2021-03-28 21:33:17
【问题描述】:

我遇到了这个错误,并认为我非常hacky的解决方法可能对某人有用。

假设我有一些代码(playground),看起来像这样:

#[macro_use]
extern crate quote;
extern crate syn;
extern crate proc_macro2; // 1.0.24

fn main() {
    let x = vec![
        quote! {let x = 1;},
        quote! {let x = 2;}
    ];
    println!("{:#?}", quote! {
        #x
    });
}

这不会编译。

   Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `Vec<TokenStream2>: ToTokens` is not satisfied
  --> src/main.rs:11:23
   |
11 |       println!("{:#?}", quote! {
   |  _______________________^
12 | |         #x
13 | |     });
   | |_____^ the trait `ToTokens` is not implemented for `Vec<TokenStream2>`
   |
   = note: required by `to_tokens`
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

如何使用quote! 连接Vec&lt;proc_macro2::TokenStream&gt;?

【问题讨论】:

    标签: rust


    【解决方案1】:

    由于某种原因,quote::ToTokens 没有为 proc_macro2::TokenStream 实现。

    新答案

    这可以使用quote! 宏的语法来实现:

    #[macro_use]
    extern crate quote;
    extern crate syn;
    extern crate proc_macro2; // 1.0.24
    
    fn main() {
        let x = vec![
            quote! {let x = 1;},
            quote! {let x = 2;}
        ];
        println!("{:#?}", quote! {
            #(#x)*
        });
    }
    

    旧答案

    要解决此问题,一种可能的解决方法是使用 fold (playground link)。

    #[macro_use]
    extern crate quote;
    extern crate syn;
    extern crate proc_macro2; // 1.0.24
    
    fn main() {
        let x = vec![
            quote! {let x = 1;},
            quote! {let x = 2;}
        ].iter().fold(quote! {}, |acc, new| quote! {#acc #new});
        println!("{:#?}", quote! {
            #x
        });
    }
    

    现在编译,产生预期的输出:

    TokenStream [
        Ident {
            sym: let,
        },
        Ident {
            sym: x,
        },
        Punct {
            char: '=',
            spacing: Alone,
        },
        Literal {
            lit: 1,
            span: bytes(1..2),
        },
        Punct {
            char: ';',
            spacing: Alone,
        },
        Ident {
            sym: let,
        },
        Ident {
            sym: x,
        },
        Punct {
            char: '=',
            spacing: Alone,
        },
        Literal {
            lit: 2,
            span: bytes(3..4),
        },
        Punct {
            char: ';',
            spacing: Alone,
        },
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-12-29
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-03-25
      • 2021-03-30
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多