根据密钥是否存在在HashMap上执行操作

时间:2016-10-18 19:41:50

标签: hashmap rust optional

我写了一个结构Edge,它代表一个点元组,由ID作为u16类型给出。

#[derive(Debug)]
struct Edge {
    left: u16,
    right: u16,
}

在我的主要功能中,我有Vector个边缘和HashMap,它将每个点ID映射到Vector所有边缘的left对象

要填充HashMap,我会迭代Vector个边缘,检查边缘的left值是否已成为HashMap中的关键字,如果所以,我只是将边添加到边Vector,如果没有,我插入新的键和值。

let mut map = HashMap::<u16, Vec<Edge>>::new();
let edge_list: Vec<Edge> = vec![];  // emptiness of this vector should not affect the code

for edge in edge_list.iter() {
    match map.get(&edge.left) {
        Some(x) => x.push(*edge),
        None => map.insert(edge.left, vec![*edge]),
    }       
}

但是,编译器不喜欢我的代码:

error[E0308]: match arms have incompatible types
  --> src/main.rs:14:9
   |
14 |         match map.get(&edge.left) {
   |         ^ expected (), found enum `std::option::Option`
   |
   = note: expected type `()`
   = note:    found type `std::option::Option<std::vec::Vec<Edge>>`
note: match arm with an incompatible type
  --> src/main.rs:16:21
   |
16 |             None => map.insert(edge.left, vec![*edge]),
   |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

我不知道它的期望。 map.get(...)应返回Option,即Some(x)None,我正在评估这两种情况。我见过一些案例match被用来解构Option。为什么match期待()?可能有什么不对?

0 个答案:

没有答案