gpt4 book ai didi

rust - 错误[E0277] : the trait bound `Vec: ToTokens` is not satisfied

转载 作者:行者123 更新时间:2023-12-03 11:47:08 24 4
gpt4 key购买 nike

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

假设我有一些代码 (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<proc_macro2::TokenStream>

最佳答案

由于某些原因,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,
},
]

关于rust - 错误[E0277] : the trait bound `Vec<TokenStream2>: ToTokens` is not satisfied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65353488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com