I'm trying to build a HashMap
with vectors as values and I have problems with borrowing / lifetimes.
The task is to find the funniest words in a given text as ranked by the funny_score
method. I would like to store a list of words for each distinct score in a HashMap
.
I have the following code
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 }
And the compiler says
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
How can I make this work?