Skip to content

Instantly share code, notes, and snippets.

@Lucretiel
Forked from rust-play/playground.rs
Created June 22, 2019 01:48
Show Gist options
  • Save Lucretiel/eca69ffa73ae7237cdc49ca8834511cd to your computer and use it in GitHub Desktop.
Save Lucretiel/eca69ffa73ae7237cdc49ca8834511cd 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