[英]How to split an ident into letters in Rust macro?
I need to write an multiply
macro which converts ident into single letter idents and multiply them.我需要编写一个
multiply
宏,将 ident 转换为单个字母 idents 并将它们相乘。
let a = 4;
let b = 7;
println!("{}", multiply!(abbabbb));
// println!("{}", (a * b * b * a * b * b * b))
but I dont know how to match a single letter.但我不知道如何匹配单个字母。
I want to do something like this:我想做这样的事情:
macro_rules! multiply {
($id:letter$other:tt) => {
$id * multiply!($other)
};
($id:ident) => {
$id
}
}
You can't do it in pattern-matching macros (as in your example), only in procedural macros.您不能在模式匹配宏中执行此操作(如您的示例所示),只能在过程宏中执行。
Even in procedural macros solving your problem will be quite hacky.即使在程序宏中,解决您的问题也很麻烦。 In Rust an indent is a single indivisible element of AST, so to convert one indent to many you'll first have to convert it to
String
, divide it into characters and convert the characters back to indents.在 Rust 中,缩进是 AST 的一个不可分割的元素,因此要将一个缩进转换为多个缩进,您首先必须将其转换为
String
,将其分成字符并将字符转换回缩进。
You can't do it in a macro_rules
macro.您不能在
macro_rules
宏中执行此操作。 The closest you can do is to add spaces between the idents:最接近的做法是在标识之间添加空格:
macro_rules! multiply {
($($id:ident)*) => {
1 $(* $id)*
}
}
fn main() {
let a = 4;
let b = 7;
println!("{}", multiply!(a b b a b b b));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.