Skip to content

Instantly share code, notes, and snippets.

Created October 23, 2015 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/ca48a102e7dda5c5a0db to your computer and use it in GitHub Desktop.
Save anonymous/ca48a102e7dda5c5a0db to your computer and use it in GitHub Desktop.
Shared via Rust Playground
#[derive(Debug)]
struct Foo(u32);
fn foo(val: u32) -> Foo { Foo(val) }
impl Foo {
fn new() -> Self { Foo(3) }
}
trait BoolExt {
fn into_option<F, T>(self, f: F) -> Option<T>
where F: Fn() -> T, Self: Sized;
}
impl BoolExt for bool {
fn into_option<F, T>(self, f: F) -> Option<T>
where F: Fn() -> T, Self: Sized
{
if self { Some(f()) } else { None }
}
}
fn main() {
println!("{:?}", true.into_option(Foo::new));
println!("{:?}", false.into_option(|| foo(3)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment