Crate result_like
source ·Expand description
OptionLike and ResultLike
Define your own Option-like and Result-like enum types. Avoid to reimplement everything of std::option::Option and std::result::Result for your own enums.
Option example
use result_like::OptionLike;
// Simple case with single argument name to use Some and None
#[derive(OptionLike, Clone, Copy)]
enum MyOption {
Some(u32),
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));
Result example in same way
use result_like::ResultLike;
#[derive(ResultLike)]
enum Trial<T, E> {
Success(T),
Failure(E),
}
BoolLike
BoolLike is comparably simpler than OptionLike and ResultLike.
use result_like::BoolLike;
#[derive(BoolLike, Clone, Copy, Debug, PartialEq, Eq)]
enum MyBool {
Enabled,
Disabled,
}
let v = MyBool::Enabled;
assert!(v.to_bool());
assert!(!MyBool::Disabled.to_bool());
assert_eq!(MyBool::from_bool(true), MyBool::Enabled);
assert_eq!(v.then(|| 1), Some(1));
assert_eq!(v.then_some(1), Some(1));
if MyBool::Enabled.into() {
// bool-like usage
}
#[derive(BoolLike)]
enum ValuedBool {
Something = 50,
Nothing = 10,
}
assert!(ValuedBool::Something.to_bool());
assert!(ValuedBool::Something as u8 == 50);