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/