【发布时间】:2017-08-27 08:25:20
【问题描述】:
我对 Rust 还很陌生,无法理解这个令人困惑的错误。
我只是想匹配HashMap 的get 函数返回的Option。如果返回一个值,我想增加它,否则我想向地图添加一个新元素。
代码如下:
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 都是同一个枚举类型的一部分。谁能解释编译器对我的代码有什么问题?
【问题讨论】:
标签: hashmap rust pattern-matching optional