Hi!
I'm trying to read the content of a file and count the occurrence of each words.
When I do
let reader = BufReader::new(my_file);
// Go through every word and create a HashMap with the number of occurrence for each words
for line in reader.lines() {
println!("Line: {:?}", line);
for word in line.unwrap().split_whitespace() {
println!("Word: {:?}", &word);
}
}
I get :
Line: Ok("one one one two three two")
Word: "one"
Word: "one"
Word: "one"
Word: "two"
Word: "three"
Word: "two"
Line: Ok("one one one two three two")
Word: "one"
Word: "one"
Word: "one"
Word: "two"
Word: "three"
Word: "two"
Which is correct, my test file has 2 lines are are identical.
When I try to use word
as the key for my HashMap as such :
let reader = BufReader::new(my_file);
// Go through every word and create a HashMap with the number of occurence for each words
for line in reader.lines() {
//println!("Line: {:?}", line);
for word in line.unwrap().split_whitespace() {
let item: &mut i128 = all_words.entry(&word).or_insert(0);
*item += 1;
}
}
I get the following error :
|
42 | for word in line.unwrap().split_whitespace() {
| ^^^^^^^^^^^^^ creates a temporary value which is freed while still in use
...
45 | let item: &mut i128 = all_words.entry(&word).or_insert(0);
| --------- borrow later used here
...
48 | }
| - temporary value is freed at the end of this statement
|
= note: consider using a `let` binding to create a longer lived value
I tried cloning word
to key
and using that instead but I get the same error.
For more reference:
cat a.txt
one one one two three two
one one one two three two
So I'm expecting my HashMap to be
"one", 6
"two", 4
"three", 2
Everything is in the main function for now to make it even easier.
I'm pretty new to Rust (and programming in general) so sorry if this is obvious. I tried to look at other posts here with the same error but none gave an answer that worked for my code.
Thank you.