devela::code::result

Type Alias OptRes

Source
pub type OptRes<T, E> = Option<Result<T, E>>;
Expand description

An optional result for simple ternary logic.

Combines Option and Result to handle three outcomes: success (Ok), failure (Err), or no value (None).

It can simplify insertion, removal, and value presence management for collections lacking Clone or Default, by using Option::take, and enhance control flow in stateful or asynchronous contexts.

See also: sok and serr.

§Examples

use devela::{sok, serr, OptRes};

#[derive(Debug, PartialEq)]
struct V(i32);

fn process_results(results: &mut Vec<OptRes<V, &str>>) {
    println!("Processing...");
    let mut iter = results.iter_mut();
    while let Some(opt_res) = iter.next() {
        if let Some(res) = opt_res.take() {
            match res {
                Ok(mut data) => {
                    println!("  Ok({})", data.0);
                    data.0 += 1; // modify the value
                    *opt_res = sok(data); // and put it back
                }
                Err(err) => {
                    println!("  Err({err})");
                    // leave the current None value
                }
            }
        } else {
            println!("  None");
            *opt_res = serr("Beta"); // replace the None with an error
        }
    }
}

let mut results: Vec<OptRes<V, &str>> = Vec::new();
results.push(None);
results.push(sok(V(10)));
results.push(serr("Alpha"));
results.push(sok(V(20)));

assert_eq![results, vec![None, sok(V(10)), serr("Alpha"), sok(V(20))]];
process_results(&mut results);
assert_eq![results, vec![serr("Beta"), sok(V(11)), None, sok(V(21))]];
process_results(&mut results);
assert_eq![results, vec![None, sok(V(12)), serr("Beta"), sok(V(22))]];

It should print:

Processing...
  None
  Ok(10)
  Err(Alpha)
  Ok(20)
Processing...
  Err(Beta)
  Ok(11)
  None
  Ok(21)

Aliased Type§

enum OptRes<T, E> {
    None,
    Some(Result<T, E>),
}

Variants§

§1.0.0

None

No value.

§1.0.0

Some(Result<T, E>)

Some value of type T.

Trait Implementations§

Source§

impl<T, E> ExtOptRes<T, E> for OptRes<T, E>

Source§

fn transpose_result(self) -> Result<Option<T>, E>

Transposes Option<Result<T, E>> into Result<Option<T>, E>. Read more
Source§

fn unwrap_or_else_result<F: FnOnce() -> Result<T, E>>( self, f: F, ) -> Result<T, E>

Unwraps the result if the Option is Some, otherwise calls the provided closure. Read more
Source§

fn map_ok<U, F: FnOnce(T) -> U>(self, f: F) -> OptRes<U, E>

Applies a function to the Ok value inside Option<Result<T, E>>, if both are present. Read more
Source§

fn map_err<F, G: FnOnce(E) -> F>(self, f: G) -> OptRes<T, F>

Applies a function to the Err value inside Option<Result<T, E>>, if both are present. Read more
Source§

fn ok_or_default_err(self) -> Result<T, E>
where E: Default,

Provides a default error if the Option is None. Read more