代码之家  ›  专栏  ›  技术社区  ›  joydeep bhattacharjee

客户端没有get方法[duplicate]

  •  0
  • joydeep bhattacharjee  · 技术社区  · 6 年前

    我按照代码打开了一个文件 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);
       |              ^^^^^^^^^^^^^^
    

    我做错什么了?

    1 回复  |  直到 6 年前
        1
  •  23
  •   Shepmaster Tim Diekmann    6 年前

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

    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);
       |              ^^^^^^^^^^^^^^
    

    错误信息和它在tin上写的差不多-类型 Result 有办法 read_to_string . 事实上 a method on the trait Read .

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

    你得设法处理这个失败的案子。最简单的方法就是失败而死 expect :

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

    你还需要带上 进入可访问的范围 读取字符串 :

    use std::io::Read;
    

    我想要 强烈推荐 通读 The Rust Programming Language 并举例说明。章 Recoverable Errors with Result 将是高度相关的。我认为这些医生是一流的!