rust - 这是从文件中读取行并将它们拆分为 Rust 中的单词的正确方法吗?

标签 rust

Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code. Updated versions of this code produce different errors, but the answers still contain valuable information.

我已经实现了以下方法,以二维数据结构的形式返回文件中的单词:

fn read_terms() -> Vec<Vec<String>> {
    let path = Path::new("terms.txt");
    let mut file = BufferedReader::new(File::open(&path));
    return file.lines().map(|x| x.unwrap().as_slice().words().map(|x| x.to_string()).collect()).collect();
}

这是 Rust 中正确、惯用且高效的方法吗?我想知道是否需要如此频繁地调用collect(),是否需要在这里调用to_string()来分配内存。也许返回类型应该以不同的方式定义,以更加惯用和高效?

最佳答案

有一种更短、更易读的方法可以从文本文件中获取单词。

use std::io::{BufRead, BufReader};
use std::fs::File;

let reader = BufReader::new(File::open("file.txt").expect("Cannot open file.txt"));

for line in reader.lines() {
    for word in line.unwrap().split_whitespace() {
        println!("word '{}'", word);
    }
}

关于rust - 这是从文件中读取行并将它们拆分为 Rust 中的单词的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25581463/

相关文章:

arrays - 在 Rust 中将数组值推送到向量

docker - 无法使用 Docker : "could not determine the current user" 创建新的 Rust 项目

rust - 理解枚举 Rust 的 move 语义

serialization - 将枚举值向量转换为另一个向量

rust - 有没有一种方法可以简化没有宏将Option转换为Result的方法?

multithreading - 使用非重叠向量 block ,并合并结果

parsing - Rust-如何解析nom中的UTF-8字母字符?

rust - 如何删除传递给 futures-cpupool 的闭包环境?

rust - 替换 Rust Vec 中的部分 &str

rust - 编译错误 : can't find crate for `core`