无法将文件内容读取为字符串 - 结果未在名为“read_to_string”的范围内实现任何方法

Unable to read file contents to string - Result does not implement any method in scope named `read_to_string`

我按照代码从 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>`

错误消息与罐头上所说的差不多 - 类型 Result does not have the method read_to_string. That's actually a method on the trait Read

你有一个 Result 因为 File::open(&path) 可以 失败 。失败用 Result 类型表示。 Result 可能是 Ok, which is the success case, or an Err,失败案例。

您需要以某种方式处理失败案例。最简单的就是死于失败,使用 expect:

let mut file = File::open(&path).expect("Unable to open");

您还需要将 Read 纳入范围才能访问 read_to_string:

use std::io::Read;

强烈推荐通读 The Rust Programming Language and working the examples. The chapter Recoverable Errors with Result 将非常相关。我认为这些文档是一流的!

如果您的方法 returns Result<String, io::Error>,您可以在 return a Result:

的函数上使用 ?
fn read_username_from_file() -> Result<String, io::Error> {
    let mut f = File::open("hello.txt")?;
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

如果您不能 return 一个 Result<String, io::Error> 那么您必须使用 中提到的 expect 或匹配 Result 来处理错误情况和恐慌:

let file = File::open(&opt_raw.config);

let file = match file {
    Ok(file) => file,
    Err(error) => {
        panic!("Problem opening the file: {:?}", error)
    }
};                                                                  

更多信息请参考Recoverable Errors with Result