Created
June 22, 2019 01:45
-
-
Save rust-play/a06a83589cefcf16ebb490f1a9b2b1d7 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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