gpt4 book ai didi

rust - 是否可以在 Rust 中编写链式比较宏?

转载 作者:行者123 更新时间:2023-12-01 11:11:23 25 4
gpt4 key购买 nike

在 Rust 中,可以通过 ><=只要参数是 ident,宏参数中的 etc s。

是否可以创建一个宏来让您链接比较运算符?

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));
}

Playground

您也可以阅读 The little book of Rust Macros对于更高级的宏模式。

关于rust - 是否可以在 Rust 中编写链式比较宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59942857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com