I'm trying to read text through a buffer and then calculate how many times each single word appears in the text:
let mut word_map: HashMap<&str, isize> = HashMap::new();
let reader = BufReader::new(file);
for line in reader.lines() {
for mut curr in line.unwrap().split_whitespace() {
match word_map.entry(curr) {
Entry::Occupied(entry) => {
*entry.into_mut() += 1;
}
Entry::Vacant(entry) => {
entry.insert(1);
}
}
}
}
I'm trying to use a HashMap
with words as keys and their frequencies in text as value. If a new word is found its value is one otherwise its value gets incremented.
I'm constantly getting this error and cannot find a way out. I've tried to use let
before the inner loop, but I still get the same error stating that temporary value
error[E0597]: `line` does not live long enough
--> src\main.rs:32:2
|
26 | for mut curr in line.as_ref().unwrap().split_whitespace(){
| ---- borrow occurs here
...
32 | }
| ^ `line` dropped here while still borrowed
33 |
34 | }
| - borrowed value needs to live until here
I'm having trouble finding why line
has to live until the end of main and why it gets dropped while still borrowed. Why am I having this error?