Macro try_conditional

Source
macro_rules! try_conditional {
    ($enum:ident, $( $variant:ident => $op:expr ),+ $(,)?) => { ... };
}
Expand description

Creates a TryOp that conditionally dispatches to one of multiple sub-ops based on the variant of the input enum, returning a Result.

Important Requirements:

  1. The enum must be defined as a single-type-parameter wrapper, e.g.
    enum MyEnum<T> {
        VariantA(T),
        VariantB(T),
    }
    This allows all variants to share the same inner type (T).
  2. All sub-ops must have the same Input type (this T) and the same Output. That is, for each variant, the corresponding op must implement TryOp<Input = T, Output = Out, Error = E>.

ยงExample

use rig::pipeline::*;
use rig::try_conditional;
use tokio;

#[tokio::main]
async fn main() {
    #[derive(Debug)]
    enum ExampleEnum<T> {
        Variant1(T),
        Variant2(T),
    }

    // Creates a pipeline TryOp that adds 1 or doubles, returning Ok(...) or Err(...)
    let op1 = map(|x: i32| Ok::<_, String>(x + 1));
    let op2 = map(|x: i32| Ok::<_, String>(x * 2));

    let try_conditional = try_conditional!(ExampleEnum,
        Variant1 => op1,
        Variant2 => op2,
    );

    let result = try_conditional.try_call(ExampleEnum::Variant1(2)).await;
    assert_eq!(result, Ok(3));
}