如何更改BTreeMap容器​​中的值

时间:2017-04-05 07:48:46

标签: reference rust

代码:

#[derive(Debug)]
struct Haha {
    data: i32,
}

use std::collections::BTreeMap;

fn main() {
    let mut map: BTreeMap<i8, Option<Box<Haha>>> = BTreeMap::new();
    map.insert(1, Some(Box::new(Haha { data: 3 })));
    map.insert(2, None);

    for (key, value) in map.iter_mut() {
        if value.is_none() {        // if find `None`, change it to a `Some(Haha)`
            value = Some(Box::new(Haha { data: 5 }));
        }
    }
}

我想创建一个函数,当我在None中得到值BTreeMap.value时,我将其更改为Some值,而不是引用。但它出了一个错误:

 error[E0308]: mismatched types
  --> Untitled.rs:15:12
   |
15 |            value = Some(Box::new(Haha{data: 5}));
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected mutable reference, found enum `std::option::Option`
   |
   = note: expected type `&mut std::option::Option<std::boxed::Box<Haha>>`
              found type `std::option::Option<std::boxed::Box<Haha>>`
   = help: here are some functions which might fulfill your needs:
           - .unwrap()

因为使用map.iter_mut()我只能获得参考。如何发送真值Some(Haha)但不是对mut引用value的引用?如果我改为value = & mut Some(Box::new(Haha { data: 5 }));因为Some(Box...)会被破坏,所以会出现另一个错误。

1 个答案:

答案 0 :(得分:1)

由于value是一个可变引用(由于iter_mut()),因此只需取消引用它:

*value = Some(Box::new(Haha{data: 5}));

它会很好用。