Tei*_*iem 9 pattern-matching rust
是否可以匹配动态变量而不仅仅是文字?
在此代码中,第一个match应该执行与注释掉的相同的操作match(number[0]being0和number[1]being 1):
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!()
// };
}
Run Code Online (Sandbox Code Playgroud)
Abd*_*P M 17
您可以使用比赛守卫。
let string = match current % 2 {
even if even == numbers[0] => "even",
odd if odd == numbers[1] => "odd",
_ => unreachable!()
};Run Code Online (Sandbox Code Playgroud)
Rust 是否可以匹配动态变量
不会。顾名思义,模式匹配基于模式,而不是表达式或值。
你可以从语法中看到这一点:MatchArm是OuterAttribute* Pattern MatchArmGuard?,模式是特定构造的枚举集。主要是文字、标识符、路径以及组合这些的方法(结构、元组、切片……模式)。
| 归档时间: |
|
| 查看次数: |
4392 次 |
| 最近记录: |