将字符串转换为 TokenStream

gar*_*ing 3 rust rust-macros rust-proc-macros

给定一个字符串 ( str),如何TokenStream在 Rust 中将其转换为 a ?

我试过使用quote!宏。

let str = "4";
let tokens = quote! { let num = #str; }; // #str is a str not i32
Run Code Online (Sandbox Code Playgroud)

这里的目标是为一些未知的代码字符串生成令牌。

let thing = "4";
let tokens = quote! { let thing = #thing }; // i32
Run Code Online (Sandbox Code Playgroud)

或者

let thing = ""4"";
let tokens = quote! { let thing = #thing }; // str
Run Code Online (Sandbox Code Playgroud)

She*_*ter 9

如何将 [a string] 转换为 TokenStream

锈有将字符串转换成数值时转换可能会失败,一个共同的特点:FromStr。这通常通过parseon 方法访问&str

proc_macro2::TokenStream

use proc_macro2; // 0.4.24

fn example(s: &str) {
    let stream: proc_macro2::TokenStream = s.parse().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

proc_macro::TokenStream

extern crate proc_macro;

fn example(s: &str) {
    let stream: proc_macro::TokenStream = s.parse().unwrap();
}
Run Code Online (Sandbox Code Playgroud)

您应该知道,此代码不能在实际过程宏的调用之外运行。