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
// 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
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
impl
fn none() -> Self { MyGuard::Nothing } }
impl
type Error = NoneError;
fn fromerror(: Self::Error) -> Self { MyGuard::none() }
fn from_ok(x: Self::Ok) -> Self { MyGuard::new(x) }
fn into_result(self) -> Result
fn foo(cond: bool) -> MyGuard
```
"try-trait"
flag allows to use guard!
with any type that implements
[Try<Error = NoneError>
]. Disabling this will make guard!
work only with
[Option
]. Enabled by default.