Crates.io | try-guard |
lib.rs | try-guard |
version | 0.2.0 |
source | src |
created_at | 2019-05-07 14:42:07.392449 |
updated_at | 2019-06-07 08:31:33.447793 |
description | A guard! macro inspired by the guard Alternative function from Haskell. |
homepage | https://github.com/phaazon/try-guard |
repository | https://github.com/phaazon/try-guard |
max_upload_size | |
id | 132600 |
size | 12,967 |
guard
Haskell Alternative
function brought to RustThe guard!
macro.
The guard!
macro implements a control-flow sugar that occurs very often in common Rust code:
fn foo(cond: bool) -> Option<i32> {
if !cond {
return None;
}
// do something useful
Some(42)
}
This pattern of testing arguments and early-returning with an error is very typical.
Unfortunately, the ?
operator doesn’t help us here because we want to early-return on a
boolean value, not an error value.
A not very idiomatic and weird way to rewrite that:
fn foo(cond: bool) -> Option<i32> {
if cond { Some(()) } else { None }?;
Some(42)
}
This crate provides the guard!
macro — analoguous to the guard
Haskell Alternative
function — that helps early-return from a function if a predicate is false
:
use try_guard::guard;
fn foo(cond: bool) -> Option<i32> {
guard!(cond);
Some(42)
}
This crate also allows you to guard to any thing that implements Try<Error = NoneError>
.
For instance, the following works:
use std::ops::Try;
use std::option::NoneError;
use try_guard::guard;
enum MyGuard<T> {
Just(T),
Nothing
}
impl<T> MyGuard<T> {
fn new(x: T) -> Self {
MyGuard::Just(x)
}
fn none() -> Self {
MyGuard::Nothing
}
}
impl<T> Try for MyGuard<T> {
type Ok = T;
type Error = NoneError;
fn from_error(_: Self::Error) -> Self {
MyGuard::none()
}
fn from_ok(x: Self::Ok) -> Self {
MyGuard::new(x)
}
fn into_result(self) -> Result<Self::Ok, Self::Error> {
match self {
MyGuard::Just(x) => Ok(x),
MyGuard::Nothing => Err(NoneError)
}
}
}
fn foo(cond: bool) -> MyGuard<i32> {
guard!(cond);
MyGuard::new(42)
}
test-nightly
feature flag can be used to test nightly-related features that come
freely and don’t require a nightly build of rustc to compile this crate but require one at
use site.