我按照代码从 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);
| ^^^^^^^^^^^^^^ method not found in `std::result::Result<std::fs::File, std::io::Error>`
我做错了什么?
最佳答案
让我们看看您的错误消息:
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);
| ^^^^^^^^^^^^^^ method not found in `std::result::Result<std::fs::File, std::io::Error>`
错误消息几乎就是它在 jar 上所说的 - 类型 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
将高度相关。我认为这些文档是一流的!
关于error-handling - 无法将文件内容读取为字符串 - 结果未在名为 `read_to_string` 的范围内实现任何方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29214963/