ward
This crate exports two macros, which are intended to replicate the functionality of Swift's
guard expression with Option<T>
.
The guard!
macro was created to emulate the guard let
statement in Swift. This macro is only
really useful for moving values out of Option<T>
s into variables.
The ward!
macro, on the other hand, doesn't force the creation of a variable, it only returns
the value that the guard!
variable would place into a variable. As such, it's a more flexible
version of the guard!
macro; and probably also somewhat more Rustic.
Examples
let sut = Some;
// This creates the variable res, which from an Option<T> will return a T if it is Some(T), and will
// otherwise return early from the function.
guard!;
assert_eq!;
The ward!
macro, by comparison, just returns the value, without forcing you to make a variable
from it (although we still do in this example):
let sut = Some;
let res = ward!;
assert_eq!;
Both macros also support an else
branch, which will run if the Option<T>
is None
:
let sut = None;
guard!;
unreachable!;
Both macros also support an alternative "early return statement", which will let you e.g.
break
within loops:
// Not that you couldn't (and probably should) do this case with `while let Some(res) = sut`...
let mut sut = Some;
loop
assert_eq!;