<ao> | Adetunji's Blog

Result, Something might succeed or maybe not

Similar to Option, Result is also an enum with signature:

enum Result<T, E>{
    OK(T),
    Err(E),
}

Result and Option are often seen together, consider the scenario of a connecting to a web server, we write a function to to connect, if connection fails or not - we have a Result and after connecting we might not have a data might not exist, Option - a case of Option wrapped in Result.

Just like Option result has function that help confirm results if it's an error or if it's OK.

Just like any generic OK and Err can be of any type, String is mostly use as Err type, returning why a function or operation failed.

fn main(){
    println!("{:?}",is_even(4).unwrap());
}

fn is_even(value: i32) -> Result<bool, String>{
    match value % 2 {
	0 => Ok(true),
	_ => Err(format!("Sorry, got a {}", value))
    }
}

But just as with option we can't unwrap an Err, we can handle that with an if else statement or a match

#note #rust