rust - 将字符串转换为 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
解决方案
如何将 [a string] 转换为
TokenStream
当转换可能失败时,Rust 具有将字符串转换为值的共同特征:FromStr
. 这通常通过parse
on 方法访问&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();
}
您应该知道,此代码不能在实际过程宏的调用之外运行。
推荐阅读
- google-apps-script - 高保真 UI 原型到基于谷歌网络的应用程序
- scala - 在 scala (2.12.8) 中使用案例类时的 Apache flink (1.9.1) 运行时异常
- html - 是否可以通过在 URL 中使用变量来动态更改图像(即背景)?
- javascript - Ajax 数据未显示在控制台日志中,但给出错误“http://localhost/IFICSV3/public/sla/sla/getbranch/180 not found”
- linux - 在linux中根据第四列选择具有最小值的行并按第一列分组
- css - 网格单元格可以跨越每一列而不指定列数吗?
- java - 艾玛迪斯航班优惠搜索
- r - 在矩阵中找到最小的一行
- jquery - 无法在 jquery HighCharts 中显示 ModelMap 对象数据
- python - 通过python在Spyder中没有法庭线的数据文件的Aifoil plottin