在 Rust 中,匹配这样的值是可行的:
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
_ => println!("something else")
}
但是在 match
中使用向量中的值而不是硬编码的数字是行不通的:
let x = 1;
let list = vec![1, 2];
match x {
list[0] => println!("one"),
list[1] => println!("two"),
_ => println!("something else")
}
失败并显示消息:
error: expected one of `=>`, `@`, `if`, or `|`, found `[`
--> src/main.rs:6:9
|
6 | list[0] => println!("one"),
| ^ expected one of `=>`, `@`, `if`, or `|` here
为什么它不起作用?
最佳答案
火柴臂的图案是defined作为
Syntax
Pattern :
LiteralPattern
| IdentifierPattern
| WildcardPattern
| RangePattern
| ReferencePattern
| StructPattern
| TupleStructPattern
| TuplePattern
| GroupedPattern
| SlicePattern
| PathPattern
| MacroInvocation
它要么是常量(包括字面量),要么是结构性的,而不是计算出来的。定义为 list[0]
的值不匹配这些定义。
幸运的是,一个火柴臂也可能包含一个 guard expression ,这允许这样做:
let x = 1;
let list = vec![1, 2];
match x {
_ if x == list[0] => println!("one"),
_ if x == list[1] => println!("two"),
_ => println!("something else")
}
不过,使用 if else
会更简洁(或者如果您有更多情况,则使用不同的结构,例如 map 或索引)。
关于rust - 如何与 Rust 中的向量元素匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199125/