Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created June 22, 2019 01:45
Show Gist options
  • Save rust-play/a06a83589cefcf16ebb490f1a9b2b1d7 to your computer and use it in GitHub Desktop.
Save rust-play/a06a83589cefcf16ebb490f1a9b2b1d7 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
trait Truthy: Sized {
fn is_truthy(&self) -> bool;
fn as_option(self) -> Option<Self> {
if self.is_truthy() {
Some(self)
} else {
None
}
}
}
impl Truthy for &str {
fn is_truthy(&self) -> bool {
!self.is_empty()
}
}
impl Truthy for String {
fn is_truthy(&self) -> bool {
!self.is_empty()
}
}
macro_rules! truthy_zero {
{$($Type:ident)*} => {$(
impl Truthy for $Type {
fn is_truthy(&self) -> bool {
*self == Self::default()
}
}
)*}
}
truthy_zero!{
i8 i16 i32 i64 isize
u8 u16 u32 u64 usize
f32 f64
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment