我是个新手,刚开始了解所有权和借款判断的工作原理
我写了这个小函数
pub fn count_words(file_path: &str) -> Result<usize, Error> {
return File::open(file_path).map(|file| {
let reader = BufReader::new(file);
return reader
.lines()
.map(|line| line.unwrap())
.flat_map(|line| line.split_whitespace())
.count();
});
}
我得到了这个错误
error[E0515]: cannot return value referencing function parameter `line`
--> src/lib.rs:19:30
|
19 | .flat_map(|line| line.split_whitespace())
| ----^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| `line` is borrowed here
|
= help: use `.collect()` to allocate the iterator
我不确定我是否理解这里发生的事情(因为在哪个实体正在borrow 行,所以我不能调用Split空白).
我设法运行了这个版本
pub fn count_words(file_path: &str) -> Result<usize, io::Error> {
return File::open(file_path).map(|file| {
let reader = BufReader::new(file);
let lines = reader.lines();
let mut num_words = 0;
for line in lines {
num_words += line.unwrap().split_whitespace().count();
}
return num_words
});
}