在 C 中,我习惯于:
if (ELEM(value, a, b, c)) { ... }
这是一个带有可变数量参数的宏,以避免输入错误
if (value == a || value == b || value == c) { ... }
一个 C 例子可以在 Varargs `ELEM` macro for use with C 中看到。 .
这在 Rust 中可能吗?我假设它会使用 match
。如果是这样,如何使用可变参数来实现这一目标?
最佳答案
macro_rules! cmp {
// Hack for Rust v1.11 and prior.
(@as_expr $e:expr) => { $e };
($lhs:expr, $cmp:tt any $($rhss:expr),*) => {
// We do this to bind `$lhs` to a name so we don't evaluate it multiple
// times. Use a leading underscore to avoid an unused variable warning
// in the degenerate case of no `rhs`s.
match $lhs { _lhs => {
false || $(
cmp!(@as_expr _lhs $cmp $rhss)
) || *
// ^- this is used as a *separator* between terms
}}
};
// Same, but for "all".
($lhs:expr, $cmp:tt all $($rhss:expr),*) => {
match $lhs { _lhs => {
true && $( cmp!(@as_expr _lhs $cmp $rhss) ) && *
}}
};
}
fn main() {
let value = 2;
if cmp!(value, == any 1, 2, 3) {
println!("true! value: {:?}", value);
}
if cmp!(value*2, != all 5, 7, 1<<7 - 1) {
println!("true! value: {:?}", value);
}
}
关于macros - 如何在 Rust 中编写宏来匹配集合中的任何元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38828920/