Hi everyone! I have the problem with the next snippet. I am trying to read a line from a text file and count how many times the words are repeated.
use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::path::Path;
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where P: AsRef<Path>, {
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn main(){
println!("Contador de palabras");
let lines = read_lines("./palabras.txt");
match lines {
Ok(lines) => {
let mut words_matches: HashMap<&str, i32> = HashMap::new();
for line in lines {
if let Ok(text) = line {
let lower_case_text: String = text.to_lowercase();
let words = lower_case_text.split(" ");
for word in words {
//https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry
let matches = words_matches.entry(word).or_insert(0);
*matches += 1;
}
println!("{:?}", words_matches);
}
}
},
Err(err) => println!("Error, {}", err)
}
}
The compiler throw the next error:
let words = lower_case_text.split(" ");
| ^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
28 | let matches = words_matches.entry(word).or_insert(0);
| ------------- borrow later used here
...
32 | }
| - `lower_case_text` dropped here while still borrowed
I'm confused about the borrowing here. I don't see how freeing lower_case_text
is a problem in the hashmap.
Thanks!