![](/img/trans.png)
[英]Is it possible to write a Rust macro “has_trait!(<type>,<ident>|<expr>)”?
[英]How to split an ident into letters in Rust macro?
我需要編寫一個multiply
宏,將 ident 轉換為單個字母 idents 並將它們相乘。
let a = 4;
let b = 7;
println!("{}", multiply!(abbabbb));
// println!("{}", (a * b * b * a * b * b * b))
但我不知道如何匹配單個字母。
我想做這樣的事情:
macro_rules! multiply {
($id:letter$other:tt) => {
$id * multiply!($other)
};
($id:ident) => {
$id
}
}
您不能在模式匹配宏中執行此操作(如您的示例所示),只能在過程宏中執行。
即使在程序宏中,解決您的問題也很麻煩。 在 Rust 中,縮進是 AST 的一個不可分割的元素,因此要將一個縮進轉換為多個縮進,您首先必須將其轉換為String
,將其分成字符並將字符轉換回縮進。
您不能在macro_rules
宏中執行此操作。 最接近的做法是在標識之間添加空格:
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.