-
-
Save Lucretiel/9a1670d19a59672f69693058a30727d5 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 | |
} | |
} | |
fn or(self, default: Self) -> Self { | |
self.or_else(move || default) | |
} | |
fn or_else(self, default: impl FnOnce() -> Self) { | |
self.as_option().unwrap_or_else(default) | |
} | |
} | |
// A truthy value is a value that does not equal its default | |
impl<T: Default + PartialEq> Truthy for T { | |
fn is_truthy(&self) -> bool { | |
*self !== Self::default() | |
} | |
} | |
fn main() { | |
let x = "Hello"; | |
let y = ""; | |
assert_eq!(x.or("Default"), "Hello"); | |
assert_eq!(y.or("Default"), "Default"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment