由于Rust比较新,我看到了很多阅读和编写文件的方法.许多人为他们的博客提出了非常混乱的片段,我发现的99%的例子(即使在Stack Overflow上)来自不稳定的构建,不再有效.现在Rust是稳定的,什么是简单,可读,非恐慌的读取或写入文件片段?
这是我最接近阅读文本文件的东西,但它仍然没有编译,即使我很确定我已经包含了我应该拥有的一切.这是基于我在所有地方的Google+上发现的一个片段,我唯一改变的是旧BufferedReader的现在只是BufReader:
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
fn main() {
let path = Path::new("./textfile");
let mut file = BufReader::new(File::open(&path));
for line in file.lines() {
println!("{}", line);
}
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
error: the trait bound `std::result::Result<std::fs::File, std::io::Error>: std::io::Read` is not satisfied [--explain E0277]
--> src/main.rs:7:20
|>
7 |> let mut file = BufReader::new(File::open(&path));
|> ^^^^^^^^^^^^^^
note: required by `std::io::BufReader::new`
error: no method named `lines` found for type `std::io::BufReader<std::result::Result<std::fs::File, std::io::Error>>` in the current scope
--> src/main.rs:8:22
|> …Run Code Online (Sandbox Code Playgroud) 我的Rust程序旨在逐行读取非常大(最多几GB)的简单文本文件.问题是,此文件太大而无法立即读取,或将所有行传输到a Vec<String>.
在Rust中处理这个问题的惯用方法是什么?
考虑这段代码来读取 rust 中的用户输入
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("error: unable to read user input");
println!("{}", input);
}
Run Code Online (Sandbox Code Playgroud)
为什么没有办法这样做?
use std::io;
fn main() {
let mut input = io::stdin()
.read_line()
.expect("error: unable to read user input");
println!("{}", input);
}
Run Code Online (Sandbox Code Playgroud)
其他语言会更方便