0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • When you do `word_map.entry(curr)` and then potentially insert that entry, you are borrowing `curr` for the lifetime of that `HashMap`. You will probably need to copy or own that value. (Disclaimer: I don't know rust) – Score_Under Dec 14 '17 at 01:31
  • @Score_Under close, but not quite. `split_whitespace` returns references to the original string, but that memory will be dropped at the end of loop. – Shepmaster Dec 14 '17 at 03:28
  • @Shepmaster thanks, that solved the problem. – Mehmet Hakan Kurtoğlu Dec 14 '17 at 10:30

0 Answers0