maybe_trait/lib.rs
1//! This crate provides the `Maybe` trait which is implemented for
2//! both `T` and `Option<T>`. The purpose is so that you can write functions
3//! like this:
4//! ```rs
5//! fn foo(param: impl Maybe<Foo>) {
6//! if let Some(value) = param.maybe() {
7//! do_something_with(value)
8//! } else {
9//! do_something_else()
10//! }
11//! }
12//! ```
13//! This way you never need to write `foo(Some(x))`.
14
15#![no_std]
16
17pub trait Maybe<T>: Sized {
18 fn maybe(self) -> Option<T>;
19}
20
21impl<T> Maybe<T> for T {
22 fn maybe(self) -> Option<T> {
23 Some(self)
24 }
25}
26
27impl<T> Maybe<T> for Option<T> {
28 fn maybe(self) -> Option<T> {
29 self
30 }
31}