提问者:小点点

无法将文件内容读取到字符串-结果未实现名为`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
    }
}

然而,我得到了这样一条信息:

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

我做错了什么?


共2个答案

匿名用户

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

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

错误消息与tin上所说的差不多--result类型没有read_to_string方法。 这实际上是特征read上的一个方法。

您有一个结果,因为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;

我强烈建议您通读Rust编程语言并使用示例。 具有result的可恢复错误章节将高度相关。 我觉得这些医生都是一流的!

匿名用户

你也可以用“?” 同时,

let mut file = File::open(&path)?;

但是在这种情况下,您的方法应该返回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)
}

如果无法返回result,则必须使用expect(在接受的答案中提到)或使用以下方式处理错误情况,

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

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

有关更多信息,请参阅此链接