无法将文件内容读取到字符串 - Result未在名为`read_to_string`的作用域中实现任何方法

use*_*985 9 error-handling rust

我按照代码从Rust打开一个文件示例:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我得到了这样的消息:

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);
   |              ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

She*_*ter 24

让我们看看你的错误信息:

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);
   |              ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

该错误消息是差不多就是它在锡说-类型Result没有有法read_to_string.这实际上是一种特质方法Read.

你有一个Result因为File::open(&path)可能会失败.失败用Result类型表示.A Result可以是a Ok,这是成功案例,也可以是a ,Err失败案例.

你需要以某种方式处理失败案例.最简单的方法是在失败时死亡,使用expect:

let mut file = File::open(&path).expect("Unable to open");
Run Code Online (Sandbox Code Playgroud)

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

use std::io::Read;
Run Code Online (Sandbox Code Playgroud)

强烈建议您阅读Rust编程语言并阅读示例." 可恢复错误Result "一章将具有高度相关性.我认为这些文档是一流的!

  • https://doc.rust-lang.org/std/fs/struct.File.html:这里确实说 File 有一个 read_to_string 方法。为什么我不能像第一个示例代码那样在这里访问它? (2认同)
  • @user3918985 `File` 实现了 `Read`,它提供了 `read_to_string`。我不明白你说的“这里”是什么意思。您必须“使用”该特征(如我所示)才能在范围内使用这些方法。 (2认同)