Macro maybe

Source
macro_rules! maybe {
    ( // Returns either Some(<$T>::default()) or `None`.
      default: $implements_default:stmt, $T:ty ) => { ... };
    (
      // Returns either Some(<$value: $T>.clone()) or `None`.
      clone: $implements_clone:stmt, $T:ty, $value:expr ) => { ... };
}
Expand description

Helper for using optionally implemented traits, like Default or Clone.

The first boolean argument says whether $T implements the given trait.

§Examples

assert_eq![maybe![default:true, u8], Some(0)];
assert_eq![maybe![default:true, &str], Some("")];
assert_eq![maybe![default:false, u8], None];
assert_eq![maybe![default:false, NonZeroU8], None];

let s1 = String::from("string1");
let s2 = maybe![clone:true, String, &s1].expect("cloned");
let s3 = maybe![clone:true, String, &s1].expect("cloned");
assert_eq_all![&s1, &s2, &s3];
let _ = maybe![default:true, NonZeroU8];