首页 > 解决方案 > 是否可以在 Rust 中编写链式比较宏?

问题描述

在 rust 中,只要参数是s ,就可以在宏参数中传递>or etc。<=ident

是否可以创建一个允许您链接比较运算符的宏?

let x = 3;
let y = 1;
let z = -3;

assert_eq!(cond!(z <= x > y), true);

标签: rustmacros

解决方案


是的你可以。您需要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 小书,了解更高级的宏模式。


推荐阅读