在下面的简化示例中,编译器抱怨语句的一个分支match
返回bool
,而另一个分支返回()
。
use std::collections::{HashMap, HashSet};
fn main() {
let available = HashMap::from_iter([(2, "b"), (3, "c"), (4, "d")]);
let mut set = HashSet::new();
for i in [1, 2, 3, 4, 5] {
match available.get(&i) {
Some(s) => set.insert(*s),
None => ()
}
}
}
但这会导致错误:
error[E0308]: `match` arms have incompatible types
--> src/main.rs:10:21
|
8 | / match available.get(&i) {
9 | | Some(s) => set.insert(*s),
| | -------------- this is found to be of type `bool`
10 | | None => ()
| | ^^ expected `bool`, found `()`
11 | | }
| |_________- `match` arms have incompatible types
如何通知编译器 match 语句应该 return ()
,并且bool
返回的 frominsert
应该被忽略?
通常的方法是将手臂放在一个块中并用 来覆盖它
;
,因为这会抑制表达式的结果:一个可能不太常见的替代方案是将值提供给函数,将其“转换”为
()
例如drop
或者,您可以完全忽略第二个分支:
或者使用高阶函数来解决这种副作用,虽然这不是最常见的:
您可以将这两个块都转换为语句:
或者您可以将 转换
match
为if
-let
:另一种选择是利用 is
Option
可迭代和&str
isCopy
,因此您可以将返回的选项传递给available.get()
toExtend::extend()
:请注意,在这种特殊情况下,这需要额外的类型注释。
for 循环可以用函数式风格重写为