首页 > 解决方案 > 将字符串转换为 TokenStream

问题描述

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

我试过使用quote!宏。

let str = "4";
let tokens = quote! { let num = #str; }; // #str is a str not i32

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

let thing = "4";
let tokens = quote! { let thing = #thing }; // i32

或者

let thing = ""4"";
let tokens = quote! { let thing = #thing }; // str

标签: rustrust-macrosrust-proc-macros

解决方案


如何将 [a string] 转换为TokenStream

当转换可能失败时,Rust 具有将字符串转换为值的共同特征:FromStr. 这通常通过parseon 方法访问&str

proc_macro2::TokenStream

use proc_macro2; // 0.4.24

fn example(s: &str) {
    let stream: proc_macro2::TokenStream = s.parse().unwrap();
}

proc_macro::TokenStream

extern crate proc_macro;

fn example(s: &str) {
    let stream: proc_macro::TokenStream = s.parse().unwrap();
}

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


推荐阅读