rust - 是否可以在 Rust 中编写链式比较宏?
问题描述
在 rust 中,只要参数是s ,就可以在宏参数中传递>
or etc。<=
ident
是否可以创建一个允许您链接比较运算符的宏?
let x = 3;
let y = 1;
let z = -3;
assert_eq!(cond!(z <= x > y), true);
解决方案
是的你可以。您需要tt
用于运算符类型:
macro_rules! cond {
(@rec ($head:expr) $last:ident $op:tt $next:ident $($tail:tt)*) => {
cond!(@rec (($head) && ($last $op $next)) $next $($tail)*)
};
(@rec ($head:expr) $last:ident) => { $head };
($first:ident $op:tt $next:ident $($tail:tt)*) => {
cond!(@rec ($first $op $next) $next $($tail)*)
}
}
fn main() {
let x = 3;
let y = 1;
let z = -3;
println!("(z <= x > y) = {}", cond!(z <= x > y));
}
您还可以阅读Rust Macros 小书,了解更高级的宏模式。
推荐阅读
- c# - 用于国际网络的剑道 DatePickerFor 中的日期时间格式
- python - XGBoost - 输出提升回合
- php - 当我使用 .htaccess 重定向所有内容时,Bootstrap css 不起作用
- java - 类型不匹配,无法从元素 Object 转换为 String
- php - Laravel socket 尝试使用 pusher 和 Laravel Echo 加入私人频道时出现错误 401
- java - Spring WebClient - 错误底层HTTP客户端完成而没有发出响应
- macos - 在 Pycharm 上运行 Pyspark
- typescript - 如何使用 Typedoc 链接到另一个模块
- reactjs - ReactWrapper::state() 只能在类组件单元测试 Jest 和 Enzyme 上调用
- c++ - 如何将所有元素合二为一?