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

问题描述 投票:8回答:1

我按照代码从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-handling rust
1个回答
22
投票

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

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这一章将具有高度相关性。我认为这些文档是一流的!

© www.soinside.com 2019 - 2024. All rights reserved.