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

问题描述:

我按照代码从 Rust by Example 打开文件:

I followed the code to open a file from 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
    }
}

但是,我收到这样的消息:

However, I got a message like this:

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>`

我在做什么错了?

让我们看看您的错误消息:

Let's look at your error message:

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>`

错误消息几乎是它在罐子上所说的-类型 结果 具有方法 read_to_string 。这实际上是关于特征的方法阅读

The error message is pretty much what it says on the tin - the type Result does not have the method read_to_string. That's actually a method on the trait Read.

您有一个结果,因为 File :: open(& path)可能失败。失败用 Result 类型表示。 结果可以是 Ok (这是成功案例),或者是 Err ,失败案例。

You have a Result because File::open(&path) can fail. Failure is represented with the Result type. A Result may be either an Ok, which is the success case, or an Err, the failure case.

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

You need to handle the failure case somehow. The easiest is to just die on failure, using expect:

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

您还需要携带 Read 可以访问 read_to_string

You'll also need to bring Read into scope to have access to read_to_string:

use std::io::Read;

我会强烈推荐通读 Rust编程语言 并处理示例。 具有的可恢复错误结果 将非常相关。我认为这些文档是一流的!

I'd highly recommend reading through The Rust Programming Language and working the examples. The chapter Recoverable Errors with Result will be highly relevant. I think these docs are top-notch!