代码之家  ›  专栏  ›  技术社区  ›  Ender

如何实现阅读特质?[副本]

  •  3
  • Ender  · 技术社区  · 2 月前

    error[E0277]: the trait bound `Result<File, std::io::Error>: std::io::Read` is not satisfied
        --> src/main.rs:77:39
         |
    77   |     let yaml = serde_yml::from_reader(f)?;
         |                ---------------------- ^ the trait `std::io::Read` is not implemented for `Result<File, std::io::Error>`
         |                |
         |                required by a bound introduced by this call
         |
    note: required by a bound in `from_reader`
        --> /home/pepp/.cargo/registry/src/index.crates.io-1949cf2c6b52557f/serde_yml-0.0.12/src/de.rs:2326:8
         |
    2324 | pub fn from_reader<R, T>(rdr: R) -> Result<T>
         |        ----------- required by a bound in this function
    2325 | where
    2326 |     R: io::Read,
         |        ^^^^^^^^ required by this bound in `from_reader`
    
    For more information about this error, try `rustc --explain E0277`.
    

    fn parse_yml(conf: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    
        println!("conf: {:?}", conf);
    
        let f = File::open(conf);
    
        let yaml = serde_yml::from_reader(f)?;
    
        println!("yaml: {}", yaml);
    
        Ok(())
    }
    

    我的理解是File已经包含了read trait,所以当我阅读E0277时,我对在它已经拥有的东西上实现trait感到困惑。E0277似乎是关于实现用户定义的特性。

    1 回复  |  直到 2 月前
        1
  •  4
  •   user4815162342    2 月前

    File::open() 返回a Result<File, io::Error> ,你需要处理。由于您的函数已经返回了一个通用错误,因此处理错误的最简单方法是使用 File::open(conf)? ? ),如果一切正常,它将解包结果,否则将传播错误。

    File serde_yml::from_reader() 结果<文件,io::错误>

    BufReader::new(f) 从而缓冲从文件读取。