3 stable releases
| 1.0.2 | Feb 22, 2024 |
|---|---|
| 1.0.1 | Feb 19, 2024 |
#616 in Procedural macros
78 downloads per month
16KB
359 lines
guard_macros
This library provides a macro called guard! which replaces recurring
let-else and if statements.
For documentation, refer to Rustdoc:
lib.rs:
Usage
// returns when (expr) is evaluated to false
guard!( (expr) );
// returns when refuted (i.e. (expr) doesn't match (pat))
guard!( (pat) = (expr) );
// panics instead of returning (called "Refute Handler")
guard!( (expr) => panic!("false") );
guard!( (pat) = (expr) => panic!("refuted") );
guard! {
// can be repeated
(expr),
(pat) = (expr) => panic!("refuted"),
// can be scoped and nested
{
(expr),
(pat) = (expr),
{
(expr),
(pat) = (expr) => panic!("baz"),
} => _, // inherit refute handler
} => panic!("foo"),
}
Overview
guard_macros provides two macros:
guard!which replaces recurringlet-elseandifstatements.make_guard!which defines new guard macros with different default Refute Handlers.
Refute Handler
A "Refute Handler" is an expression that is executed when the condition of
a clause is not met. It can be specified by appending => followed by an
expression, either:
- to a single clause
guard! { (pat) = (expr) => panic!("refuted"), (expr) => panic!("false"), } - or to a group of clauses enclosed by
{}.guard! { { (pat) = (expr), (expr), } => panic!("unmet") }Note: By default, blocks create a new scope, but it can be disabled by prepending a
*to the opening brace.
Example
Specification
-
Syntax
GuardBody :
GuardDecl (,GuardDecl )*,?GuardDecl :
*?{GuardBody}RefuteHandlerInheritable
| GuardClause RefuteHandler?GuardClause :
PatternNoTopAlt=Expression
| ExpressionRefuteHandler :
=>ExpressionRefuteHandlerInheritable :
RefuteHandler
|=>_ -
Syntax
MakeGuardBody :
MakeGuardDecl (,MakeGuardDecl )*,?MakeGuardDecl :
Identifier RefuteHandler
Dependencies
~240–690KB
~16K SLoC