是否可以在 Rust 的匹配语句中包含现有变量?
Is it possible to include existing variables in Rust's match statement?
例如在 Elixir 的 case statement 中,以下代码是有效的并且将匹配 10 到 1:
x = 1
case 10 do
^x -> "Won't match"
_ -> "Will match"
end
然而,在 Rust 中,^ 不是这个用例的有效运算符。它只是给出一个错误,说类似“预期的模式,找到 ^”。我试过这样做:
let x = 1;
match 10 {
x => "Won't match",
_ => "Will match",
}
但是它将 10 绑定到 x 并且 returns“不匹配”(相当于“x @ _”)。有没有办法动态包含 x 以便无论 x 是什么,它都会与其值相匹配? (注意:我知道我可以只使用 if 语句,但我很好奇 match 语句是否提供了解决方案)
您可以在这种情况下使用火柴护臂。将匹配文字绑定到其他变量,比如 y
,然后检查守卫中的 y == x
。示例:
fn main() {
let x = 1;
let result = match 10 {
y if y == x => "10 matched x value",
_ => "10 didn't match x value",
};
println!("{}", result); // 10 didn't match x value
}
例如在 Elixir 的 case statement 中,以下代码是有效的并且将匹配 10 到 1:
x = 1
case 10 do
^x -> "Won't match"
_ -> "Will match"
end
然而,在 Rust 中,^ 不是这个用例的有效运算符。它只是给出一个错误,说类似“预期的模式,找到 ^”。我试过这样做:
let x = 1;
match 10 {
x => "Won't match",
_ => "Will match",
}
但是它将 10 绑定到 x 并且 returns“不匹配”(相当于“x @ _”)。有没有办法动态包含 x 以便无论 x 是什么,它都会与其值相匹配? (注意:我知道我可以只使用 if 语句,但我很好奇 match 语句是否提供了解决方案)
您可以在这种情况下使用火柴护臂。将匹配文字绑定到其他变量,比如 y
,然后检查守卫中的 y == x
。示例:
fn main() {
let x = 1;
let result = match 10 {
y if y == x => "10 matched x value",
_ => "10 didn't match x value",
};
println!("{}", result); // 10 didn't match x value
}