Skip to content

Instantly share code, notes, and snippets.

@Lucretiel
Forked from rust-play/playground.rs
Last active October 7, 2020 06:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lucretiel/9a1670d19a59672f69693058a30727d5 to your computer and use it in GitHub Desktop.
Save Lucretiel/9a1670d19a59672f69693058a30727d5 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
}
}
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