如何在匹配表达式中进行多重绑定或模式?
How to multibind or patterns in match expressions?
有没有办法绑定同名的一堆或匹配项?
因此,例如在下面的代码中,我希望 n
是任何匹配项,1
、2
或 3
.
fn main() {
match 2 {
n @ 1 | 2 | 3 => {
println!("{}", n);
}
_ => {},
}
}
它抱怨:
error[E0408]: variable `n` is not bound in all patterns
--> src/main.rs:3:17
|
3 | n @ 1 | 2 | 3 => {
| - ^ ^ pattern doesn't bind `n`
| | |
| | pattern doesn't bind `n`
| variable not in all patterns
用 ()
(括号)将 or
匹配包围起来就可以正确绑定:
fn main() {
match 2 {
n @ (1 | 2 | 3) => {
println!("{}", n);
}
_ => {},
}
}
有没有办法绑定同名的一堆或匹配项?
因此,例如在下面的代码中,我希望 n
是任何匹配项,1
、2
或 3
.
fn main() {
match 2 {
n @ 1 | 2 | 3 => {
println!("{}", n);
}
_ => {},
}
}
它抱怨:
error[E0408]: variable `n` is not bound in all patterns
--> src/main.rs:3:17
|
3 | n @ 1 | 2 | 3 => {
| - ^ ^ pattern doesn't bind `n`
| | |
| | pattern doesn't bind `n`
| variable not in all patterns
用 ()
(括号)将 or
匹配包围起来就可以正确绑定:
fn main() {
match 2 {
n @ (1 | 2 | 3) => {
println!("{}", n);
}
_ => {},
}
}