3

I'm trying to work through Rust and using serde_yml as opposed to serde_yaml which has caused me much great confusion, and can't seem to find examples for parsing yaml from a file. I've been running into this error ...

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

My function is ...

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(())
}

My understanding is that File already contains the read trait, so when I read E0277, I'm confused about implementing a trait on something it already has. E0277 seems to be about implementing a user defined trait.

2
  • Oh, my bad. If you want to make this an answer, I'll mark it. Also, what is this called where a function returns on error so I can read it in the rust book? I'm a C++ dev. Commented Nov 21 at 18:31
  • Done. The early return on error using ? is unimaginatively called "the ? operator". Take a look at chapter 9.2 of the book, in particular the section on ?. Commented Nov 21 at 18:43

1 Answer 1

4

File::open() returns a Result<File, io::Error>, which you need to handle. Since your function already returns a generic error, the easiest way to handle the error is by using File::open(conf)? (note the trailing ?), which will unwrap the result if ok, and propagate the error otherwise.

In your code you're not passing a File to serde_yml::from_reader(), but a Result<File, io::Error>, which it doesn't know what to do with (i.e. the latter "doesn't implement Read", as the error message tells you if you read it carefully).

Also, you probably want to pass BufReader::new(f) to serde_yml::from_reader() so that reading from file is buffered.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.