如何基于动态变量进行匹配? [英] How do I match based on a dynamic variable?
本文介绍了如何基于动态变量进行匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以匹配动态变量而不是仅匹配文字?
在此代码中,第一个match
应该与注释掉的match
(number[0]
Being0
和number[1]
Being1
)相同:
const NUMBERS: [i8; 2] = [0, 1];
fn test() {
let current = 5;
let string = match current % 2 {
NUMBERS[0] => "even", // This does not work
NUMBERS[1] => "odd", // This does not work
_ => unreachable!(),
};
// let string = match current % 2 {
// 0 => "even",
// 1 => "odd",
// _ => unreachable!()
// };
}
推荐答案
您可以使用Match guards。
let string = match current % 2 {
even if even == numbers[0] => "even",
odd if odd == numbers[1] => "odd",
_ => unreachable!()
};
这篇关于如何基于动态变量进行匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文