| Crates.io | guard-clause |
| lib.rs | guard-clause |
| version | 1.0.0 |
| created_at | 2024-12-17 01:43:25.864038+00 |
| updated_at | 2025-05-12 17:20:27.913904+00 |
| description | Syntactic sugar for writing simple guard clauses. |
| homepage | |
| repository | https://github.com/Radiator-Labs/guard-clause-rs |
| max_upload_size | |
| id | 1485688 |
| size | 32,624 |
Guard-clause library, providing syntactic sugar to improve readability of guard-clauses in Rust code.
The Rust programming language provides the assert
macro in the core library (starting in 1.6.0; assert was originally in the standard library.)
The assert allows values to be checked and, if not as desired, panics the application.
Guard-clauses attempts to deliver a similar functionality, but causes the enclosing function to immediately return a value, instead of panicking.
Original Code:
if (value > threshold) {
return Err(Error::OverThreshold);
}
Code with guard-clause:
guard!(value <= threshold, Err(Error::OverThreshold));
This expresses the guard clause in a more concise manner, improving readability.
Note that the guard-clause is promising that the comparison is true after the guard, as is also the case for an assert. This is the reverse of the logic of an if statement. (I.E. it "guards" against the comparison being false.)
The guard-clause is intended to have no dependencies and operate in no-std code bases. (Dev-dependencies will be allowed, if necessary.)
Pedantic clippy is used to drive a more idiomatic codebase.
It has also been discussed to make the guard-clause even more tailored, with the following options:
guard_err(value <= threshold, Error::OverThreshold);
guard_none(value <= threshold);guard_str(value <= threshold, "Value is over threshold");
The current thinking is that these options do not offer enough benefit over the version that just returns a generic type.
Work creating this library was performed as part of commercial development by Kelvin (formerly Radiator Labs), a green energy company dedicated to decarbonizing the world's legacy buildings.
This crate is guaranteed to compile on stable Rust 1.83 and up. It might compile with older versions but that may change in any new patch release. Changes in Clippy support are the main factor driving the version dependency.
See here for details on how the MSRV may be upgraded.
Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.