我按照代码从Rust by Example打开一个文件:
use std::{env, fs::File, path::Path};
fn main() {
let args: Vec<_> = env::args().collect();
let pattern = &args[1];
if let Some(a) = env::args().nth(2) {
let path = Path::new(&a);
let mut file = File::open(&path);
let mut s = String::new();
file.read_to_string(&mut s);
println!("{:?}", s);
} else {
//do something
}
}
但是,我得到了这样的消息:
error[E0599]: 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:11:14
|
11 | file.read_to_string(&mut s);
| ^^^^^^^^^^^^^^
我究竟做错了什么?
让我们看看你的错误信息:
error[E0599]: 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:11:14
|
11 | file.read_to_string(&mut s);
| ^^^^^^^^^^^^^^
错误消息几乎就是它在锡上所说的 - 类型Result
没有方法read_to_string
。那实际上是a method on the trait Read
。
你有一个Result
因为File::open(&path)
可能会失败。失败用Result
类型表示。一个Result
可能是Ok
,这是成功案例,或Err
,失败案例。
你需要以某种方式处理失败案例。使用expect
最简单的方法是在失败时死亡:
let mut file = File::open(&path).expect("Unable to open");
您还需要将Read
带入范围才能访问read_to_string
:
use std::io::Read;
我强烈建议您阅读The Rust Programming Language并阅读示例。 Recoverable Errors with Result
这一章将具有高度相关性。我认为这些文档是一流的!