如何用矢量值修改HashMap?

时间:2018-03-04 17:48:42

标签: vector hashmap rust mutable mutability

我试图用向量作为值来构建HashMap,并且我在借用/生命周期时遇到了问题。

任务是找到按funny_score方法排名的给定文本中最有趣的单词。我想在HashMap中为每个不同的分数存储一个单词列表。

我有以下代码

use std::collections::HashMap;

fn main() {
    let text = "";
    let mut scores: HashMap<usize, &mut Vec<&str>> = HashMap::new();
    for word in text.split(' ') {
        let funny_score = funny_score(word);
        match scores.get_mut(&funny_score) {
            Some(list) => list.push(word),
            None => {
                let mut list = vec![word];
                scores.insert(funny_score, &mut list);
            }
        }
    }
}

fn funny_score(_: &str) -> usize { 0 }

编译器说

error[E0597]: `list` does not live long enough
  --> src/main.rs:12:49
   |
12 |                 scores.insert(funny_score, &mut list);
   |                                                 ^^^^ borrowed value does not live long enough
13 |             }
   |             - `list` dropped here while still borrowed
...
16 | }
   | - borrowed value needs to live until here

error[E0499]: cannot borrow `scores` as mutable more than once at a time
  --> src/main.rs:12:17
   |
8  |         match scores.get_mut(&funny_score) {
   |               ------ first mutable borrow occurs here
...
12 |                 scores.insert(funny_score, &mut list);
   |                 ^^^^^^ second mutable borrow occurs here
13 |             }
14 |         }
   |         - first borrow ends here

我该如何做到这一点?

0 个答案:

没有答案