Crates.io | if_empty |
lib.rs | if_empty |
version | 0.3.0 |
source | src |
created_at | 2021-06-19 00:14:14.780389 |
updated_at | 2021-07-30 22:54:14.330312 |
description | Replace if/else checks for emptyness with a simple method call |
homepage | https://github.com/cschlosser/IfEmpty#ifempty |
repository | https://github.com/cschlosser/IfEmpty |
max_upload_size | |
id | 411920 |
size | 34,509 |
A crate to use for defensive programming where context specific defaults are needed.
While using an Option
is preferrably in most circumstances there are situations where a function call
doesn't return a Option
and the Default
of a type isn't helpful either.
You now have the option to wrap this special function call or write something along these lines:
let foo = {
let b = bar();
if b.is_empty() {
Bar {
// set the default values for your context here
}
} else {
b
}
};
Using this crate you can reduce this down to:
let foo = bar().if_empty(Bar { /* ... */ });
In order to take advantage of this feature you have to implement this behavior for your types:
use if_empty::*;
struct Foo {
val: bool,
}
impl IfEmpty for Foo {
fn if_empty(self, value: Foo) -> Foo {
if self.is_empty() {
value
} else {
self
}
}
}
See derive_macro for how to use the #[derive]
macro.
The crate provides this functionality for String
, OsString
, &str
and &OsStr
.