相关疑难解决方法(0)

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

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

我究竟做错了什么?

error-handling rust

9
推荐指数
1
解决办法
6073
查看次数

标签 统计

error-handling ×1

rust ×1