我对Rust很新,无法理解这个令人困惑的错误。当模式匹配一个选项时引发与不兼容类型的匹配错误引发的错误
我只是试图匹配Option
返回的get
函数HashMap
。如果返回值,我想增加它,如果没有,我想添加一个新的元素到地图。
下面是代码:
let mut map = HashMap::new();
map.insert("a", 0);
let a = "a";
match map.get(&a) {
Some(count) => *count += 1,
None => map.insert(a, 0),
}
产生的错误:
error[E0308]: match arms have incompatible types
--> <anon>:7:5
|
7 | match map.get(&a) {
| _____^ starting here...
8 | | Some(count) => *count += 1,
9 | | None => map.insert(a, 0),
10 | | }
| |_____^ ...ending here: expected(), found enum `std::option::Option`
|
= note: expected type `()`
found type `std::option::Option<{integer}>`
note: match arm with an incompatible type
--> <anon>:9:17
|
9 | None => map.insert(a, 0),
| ^^^^^^^^^^^^^^^^
我真的不知道该编译器抱怨什么类型的约在这里,因为这两个Some
和None
是两部分相同的枚举类型。任何人都可以解释编译器与我的代码有什么问题吗?
感谢你,非常完美! 我会多看看'entry' API,它看起来非常有用。 –