#enums #monads #macro #result #options

result-like

Option/Result-like monad interface for your own enum

12 releases

0.5.0 Dec 29, 2023
0.4.6 Feb 23, 2023
0.4.5 Aug 7, 2022
0.4.3 Jun 7, 2022
0.1.0 Jan 4, 2020

#294 in Rust patterns

Download history 2873/week @ 2024-06-22 1906/week @ 2024-06-29 1583/week @ 2024-07-06 1909/week @ 2024-07-13 1520/week @ 2024-07-20 1955/week @ 2024-07-27 2090/week @ 2024-08-03 2008/week @ 2024-08-10 1584/week @ 2024-08-17 1535/week @ 2024-08-24 1430/week @ 2024-08-31 2329/week @ 2024-09-07 1113/week @ 2024-09-14 1426/week @ 2024-09-21 1078/week @ 2024-09-28 1024/week @ 2024-10-05

4,732 downloads per month
Used in 6 crates (via rustpython-vm)

BSD-2-Clause-Views

12KB
97 lines

OptionLike and ResultLike

Install: https://crates.io/crates/result-like

Define your own Option-like and Result-like enum types. Avoid to reimplement everything of option and result for your own enums.

Option example

use result_like::OptionLike;

// Simple case with single argument name to use Some and None
#[derive(OptionLike)]
enum MyOption<T> {
    Some(T),
    None,
}

let v = MyOption::Some(1);
// every option utilities are possible including unwrap, map, and, or etc.
assert_eq!(v.unwrap(), 1);

// convertable to option
let opt = v.into_option();
assert_eq!(opt, Some(1));

// enum with custom names instead of Some and None
#[derive(OptionLike)]
enum Number {
    Value(i64),
    Nan,
}

let v = Number::Value(10);
assert_ne!(v, Number::Nan);

Result example in same way

use result_like::ResultLike;

// typical
#[derive(ResultLike)]
enum MyResult<T, E> {
    Ok(T),
    Err(E),
}

// value-only
#[derive(ResultLike)]
enum Trial {
    Success(String),
    Failure(String),
}

Dependencies

~255–700KB
~17K SLoC