Я пытаюсь построить 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
Как я могу заставить это работать?
HashMap<_, &mut _>
)? - person Shepmaster   schedule 04.03.2018None
. - person Shepmaster   schedule 04.03.2018