Grazosi
Grazosi

Reputation: 723

Unable to return an error in function that returns result?

I'm trying to learn how to use results, and want to make a function that throws an error from one. So if I create this:

use std::io::{Read, Write,Error};


fn func(n:u8) -> Result<u8, Error> {
    if (n == 2){
        Error::new(ErrorKind::Other, "oh no!")
    } else {
        return Ok(n)
    }
}

This will not compile, because the function expects a result, and not a actual error. But I thought that I would be able to do this, as just the error that the function returns. It gives this error:

note: expected enum `std::result::Result<u8, std::io::Error>`
       found struct `std::io::Error`rustc(E0308)

Why does this fail? and How do I actually get to return the error?

Upvotes: 1

Views: 1286

Answers (1)

simeondermaats
simeondermaats

Reputation: 443

Much like you need to wrap the value n in Ok first, you need to wrap your Error in Err like this:

fn func(n: u8) -> Result<u8, Error> {
    if n == 2 {
        Err(Error::new(ErrorKind::Other, "oh no!"))
    } else {
        Ok(n)
    }
}

The reason for this is simple: Result is an enum that's either an Ok or an Err. If you simply return an Error, the type doesn't match.

Upvotes: 5

Related Questions