我指望一個單詞出現在麥克白次數:「借來的價值不活足夠長的時間」,似乎怪說錯話
use std::io::{BufRead, BufReader};
use std::fs::File;
use std::collections::HashMap;
fn main() {
let f = File::open("macbeth.txt").unwrap();
let reader = BufReader::new(f);
let mut counts = HashMap::new();
for l in reader.lines() {
for w in l.unwrap().split_whitespace() {
let count = counts.entry(w).or_insert(0);
*count += 1;
}
}
println!("{:?}", counts);
}
這個鏽barfs,他說:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:14:9
|
11 | for w in l.unwrap().split_whitespace() {
| ---------- temporary value created here
...
14 | }
| ^temporary value dropped here while still borrowed
...
18 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
實際的問題是w
是一個參考,所以將它改爲w.to_string()
可以解決它。我不明白爲什麼Rust編譯器指責l
,問題是w
。我該怎麼推斷w
是這裏的問題?