在下面的简化示例中,编译器抱怨语句的一个分支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
应该被忽略?