我是个新手,刚开始了解所有权和借款判断的工作原理

我写了这个小函数

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
    });
}

推荐答案

Rust在这里遇到了麻烦,因为它创建了对您正在迭代的line的短暂引用,这些引用必须在定义该变量的范围之外持续存在.

因为您真的不关心行内容,所以只需直接使用Count:

BufReader::new(file)
    .lines()
    .map(|line| line.unwrap())
    .map(|line| line.split_whitespace().count())
    .sum()

在那里你可以简单地把所有的分割计数加起来.这大致就是您在更冗长的版本中所做的,但我认为这类代码就其 rust 性而言读起来更好.

很明显,您可以通过将这两个map()操作合并为一个操作来进一步减少这里的代码量,等等.

Rust相关问答推荐

在一个tauri协议处理程序中调用一个rectuc函数的推荐技术是什么?

如何最好地并行化修改同一Rust向量的多个切片的代码?

如何go 除铁 rust 中路径组件的第一项和最后一项?

将PathBuf转换为字符串

Gtk4-rs:将监视器作为gdk::monitor获取,而不是作为glib::对象获取

我应该将哪些文件放入我的GitHub存储库

在Rust中,Box:ed struct 与普通 struct 在删除顺序上有区别吗?

Tokio';s io::用Cursor拆分<;Vec<;u8>>;赢得';t get the full writted data

当我try 使用 SKI 演算中的S I I实现递归时,为什么 Rust 会失败?

在 Rust 中忽略 None 值的正确样式

Google chrome 和 Apple M1 中的计算着色器

`tokio::pin` 如何改变变量的类型?

在不安全的 Rust 中存储对 struct 内部数据的静态引用是否合法?

使用 lalrpop 在 rust 中解析由 " 引用的字符串

使用自定义 struct 收集 Vec

`移动||异步移动{...}`,如何知道哪个移动正在移动哪个?

只有一个字符被读入作为词法分析器的输入

使用泛型作为关联类型,没有幻像数据

有没有办法隐藏类型定义?

`if let` 只是另一种编写其他 `if` 语句的方式吗?