Crate if_empty[][src]

Expand description

For use with 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 an Option and the Default of a type isn’t helpful either.

Examples

//  Converting
let foo = {
   let b = bar();
   if b.is_empty() {
       Bar {
           // set the default values for your context here
       }
   } else {
       b
   }
};
// into
use if_empty::IfEmpty;
impl IfEmpty for Bar {
     fn if_empty(self, value: Self) -> Self {
         // implement
     }
}

let foo = bar().if_empty(Bar { /* ... */ });

Implementation

In this example we’re using the obvious is_empty() function for Foo but we could also do more elaborate checks.

use if_empty::IfEmpty;

struct Foo {
   val: bool,
}

impl Foo {
    fn is_empty(&self) -> bool { !self.val }
}

impl IfEmpty for Foo {
   fn if_empty(self, value: Foo) -> Foo {
       if self.is_empty() {
           value
       } else {
           self
       }
   }
}

Traits

For checking IfEmpty on value semantics

For checking IfEmpty on borrowed objects

Derive Macros

Implement if_empty on types with is_empty functions