Rust Result Enum

Rust has a built-in enum called Result that has two variants: Ok(T) and Err(E). Result is ideal as a return type when a function may encounter an error. Its two variants represent success (Ok) and failure (Err).

As a built-in enum that is part of the standard library, it can be called without first being defined. Within the standard library, it looks like this:

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

Let’s break this down:

pub – Keyword denoting a public enum, meaning that Result is accessible from external modules.

enum – Keyword specifying an enum – a custom data type with several variants.

Result – The name of the enum.

<T, E> – Return types of Ok(T) and Err(E), respectively.

Ok(T) – Variant of Result that is returned when the success condition is met.

Err(E) – Variant of Result that is returned when the result is a failure.

fn check_true(arg:bool) -> Result<bool,bool> {
   if arg {
      Ok(true)
   } else { 
      Err(false)
   }
}

fn main() {
   println!("{:?}",check_true(true)); 
   println!("{:?}",check_true(false));
}

Standard Output:

Ok(true)
Err(false)