我试图读取一个名为enable.txt的文件,它与我的main.rs位于同一个dir中,我的代码如下所示:
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::error::Error;
fn main() {
let path = Path::new("enable.txt");
let display = path.display();
let mut file = File::open(&path);
let mut contents = String::new();
file.read_to_string(&mut contents);
println!("{}", contents);
}当我用cargo run或rustc src/main.rs编译它时,我会得到以下错误消息:
error: no method named `read_to_string` found for type `std::result::Result<std::fs::File, std::io::Error>` in the current scope
--> src/main.rs:10:10
|
10 | file.read_to_string(&mut contents);
| ^^^^^^^^^^^^^^发布于 2017-06-03 05:44:42
问题是,File::open()返回一个需要以某种方式展开的std::result::Result<std::fs::File, std::io::Error>,以便访问该文件。我喜欢这样做的方式是像这样使用expect():
...
fn main() {
...
let mut file = File::open(&path).expect("Error opening File");
...
file.read_to_string(&mut contents).expect("Unable to read to string");
...
}这将返回预期值或提供错误消息的panic,这取决于操作是否成功。
https://stackoverflow.com/questions/44340721
复制相似问题