Using Result inside a map closure

31 points Creator13

Hello! I am a complete Rust noob, so sorry if this is a bit of a basic question. I did try googling but that didn't result in much...

I'm trying to create a simple parsing function. It reads a file and then parses all the lines inside that file to a generic T. This is what I came up with:

    pub fn read_and_parse<T: FromStr>() -> Result<Vec<T>, Error>  {
        let contents = fs::read_to_string("input.txt")?;

        let result = contents.lines()
            .map(|line| match line.parse::<T>() {
                Ok(x) => x,
                Err(_) => panic!("Parse error while reading file!")
            })
            .collect();

        Ok(result)
    }

To please the compiler, I had to match the parse function to unwrap the error (couldn't figure out how to do trait bounds that satisfied unwrap()) and panic! on an error. Instead I'd like to return the read_and_parse() function with the error returned by parse() from inside the closure. How might I do this?