pub enum Perhaps<T> {
Dubious,
Certain(T),
}Expand description
The Perhaps type. See the module level documentation for more.
Variants§
Implementations§
Source§impl<T> Perhaps<T>
impl<T> Perhaps<T>
Sourcepub const fn is_certain(&self) -> bool
pub const fn is_certain(&self) -> bool
Returns true if the option is a [Certain] value.
§Examples
let x: Perhaps<u32> = Certain(2);
assert_eq!(x.is_certain(), true);
let x: Perhaps<u32> = Dubious;
assert_eq!(x.is_certain(), false);Sourcepub fn is_certain_and(self, f: impl FnOnce(T) -> bool) -> bool
pub fn is_certain_and(self, f: impl FnOnce(T) -> bool) -> bool
Returns true if the option is a [Certain] and the value inside of it matches a predicate.
§Examples
let x: Perhaps<u32> = Certain(2);
assert_eq!(x.is_certain_and(|x| x > 1), true);
let x: Perhaps<u32> = Certain(0);
assert_eq!(x.is_certain_and(|x| x > 1), false);
let x: Perhaps<u32> = Dubious;
assert_eq!(x.is_certain_and(|x| x > 1), false);Sourcepub const fn is_dubious(&self) -> bool
pub const fn is_dubious(&self) -> bool
Returns true if the option is a [Dubious] value.
§Examples
let x: Perhaps<u32> = Certain(2);
assert_eq!(x.is_dubious(), false);
let x: Perhaps<u32> = Dubious;
assert_eq!(x.is_dubious(), true);Sourcepub const fn as_ref(&self) -> Perhaps<&T>
pub const fn as_ref(&self) -> Perhaps<&T>
Converts from &Perhaps<T> to Perhaps<&T>.
§Examples
Calculates the length of an Perhaps<String> as an Perhaps<usize>
without moving the String. The map method takes the self argument by value,
consuming the original, so this technique uses as_ref to first take an Perhaps to a
reference to the value inside the original.
let text: Perhaps<String> = Certain("Hello, world!".to_string());
// First, cast `Perhaps<String>` to `Perhaps<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: Perhaps<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {text:?}");Sourcepub fn as_mut(&mut self) -> Perhaps<&mut T>
pub fn as_mut(&mut self) -> Perhaps<&mut T>
Converts from &mut Perhaps<T> to Perhaps<&mut T>.
§Examples
let mut x = Certain(2);
match x.as_mut() {
Certain(v) => *v = 42,
Dubious => {},
}
assert_eq!(x, Certain(42));Sourcepub fn expect(self, msg: &str) -> T
pub fn expect(self, msg: &str) -> T
Returns the contained [Certain] value, consuming the self value.
§Panics
Panics if the value is a [Dubious] with a custom panic message provided by
msg.
§Examples
let x = Certain("value");
assert_eq!(x.expect("fruits are healthy"), "value");let x: Perhaps<&str> = Dubious;
x.expect("fruits are healthy"); // panics with `fruits are healthy`§Recommended Message Style
We recommend that expect messages are used to describe the reason you
expect the Perhaps should be Certain.
let item = slice.get(0)
.expect("slice should not be empty");Hint: If you’re having trouble remembering how to phrase expect error messages remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”.
For more detail on expect message styles and the reasoning behind our
recommendation please refer to the section on “Common Message
Styles” in the std::error module docs.
Sourcepub fn unwrap(self) -> T
pub fn unwrap(self) -> T
Returns the contained [Certain] value, consuming the self value.
Because this function may panic, its use is generally discouraged.
Instead, prefer to use pattern matching and handle the [Dubious]
case explicitly, or call unwrap_or, unwrap_or_else, or
unwrap_or_default.
§Panics
Panics if the self value equals [Dubious].
§Examples
let x = Certain("air");
assert_eq!(x.unwrap(), "air");let x: Perhaps<&str> = Dubious;
assert_eq!(x.unwrap(), "air"); // failsSourcepub fn unwrap_or(self, default: T) -> T
pub fn unwrap_or(self, default: T) -> T
Returns the contained [Certain] value or a provided default.
Arguments passed to unwrap_or are eagerly evaluated; if you are passing
the result of a function call, it is recommended to use unwrap_or_else,
which is lazily evaluated.
§Examples
assert_eq!(Certain("car").unwrap_or("bike"), "car");
assert_eq!(Dubious.unwrap_or("bike"), "bike");Sourcepub fn unwrap_or_else<F>(self, f: F) -> Twhere
F: FnOnce() -> T,
pub fn unwrap_or_else<F>(self, f: F) -> Twhere
F: FnOnce() -> T,
Returns the contained [Certain] value or computes it from a closure.
§Examples
let k = 10;
assert_eq!(Certain(4).unwrap_or_else(|| 2 * k), 4);
assert_eq!(Dubious.unwrap_or_else(|| 2 * k), 20);Sourcepub fn unwrap_or_default(self) -> Twhere
T: Default,
pub fn unwrap_or_default(self) -> Twhere
T: Default,
Returns the contained [Certain] value or a default.
Consumes the self argument then, if [Certain], returns the contained
value, otherwise if [Dubious], returns the default value for that
type.
§Examples
let x: Perhaps<u32> = Dubious;
let y: Perhaps<u32> = Certain(12);
assert_eq!(x.unwrap_or_default(), 0);
assert_eq!(y.unwrap_or_default(), 12);Sourcepub unsafe fn unwrap_unchecked(self) -> T
pub unsafe fn unwrap_unchecked(self) -> T
Returns the contained [Certain] value, consuming the self value,
without checking that the value is not [Dubious].
§Safety
Calling this method on [Dubious] is undefined behavior.
§Examples
let x = Certain("air");
assert_eq!(unsafe { x.unwrap_unchecked() }, "air");let x: Perhaps<&str> = Dubious;
assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!Sourcepub fn map<U, F>(self, f: F) -> Perhaps<U>where
F: FnOnce(T) -> U,
pub fn map<U, F>(self, f: F) -> Perhaps<U>where
F: FnOnce(T) -> U,
Maps an Perhaps<T> to Perhaps<U> by applying a function to a contained value (if Certain) or returns Self::Dubious (if Dubious).
§Examples
Calculates the length of an Perhaps<String> as an
Perhaps<usize>, consuming the original:
let maybe_string = Certain(String::from("Hello, World!"));
// `Perhaps::map` takes self *by value*, consuming `maybe_some_string`
let maybe_len = maybe_string.map(|s| s.len());
assert_eq!(maybe_len, Certain(13));
let x: Perhaps<&str> = Dubious;
assert_eq!(x.map(|s| s.len()), Dubious);Sourcepub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self
pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self
Calls a function with a reference to the contained value if [Certain].
Returns the original option.
§Examples
let list = vec![1, 2, 3];
// prints "got: 2"
let x = list
.get(1)
.inspect(|x| println!("got: {x}"))
.expect("list should be long enough");
// prints nothing
list.get(5).inspect(|x| println!("got: {x}"));Sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere
F: FnOnce(T) -> U,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere
F: FnOnce(T) -> U,
Returns the provided default result (if dubious), or applies a function to the contained value (if any).
Arguments passed to map_or are eagerly evaluated; if you are passing
the result of a function call, it is recommended to use map_or_else,
which is lazily evaluated.
§Examples
let x = Certain("foo");
assert_eq!(x.map_or(42, |v| v.len()), 3);
let x: Perhaps<&str> = Dubious;
assert_eq!(x.map_or(42, |v| v.len()), 42);Sourcepub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
Computes a default function result (if dubious), or applies a different function to the contained value (if any).
§Basic examples
let k = 21;
let x = Certain("foo");
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
let x: Perhaps<&str> = Dubious;
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);§Handling a Result-based fallback
A somewhat common occurrence when dealing with optional values
in combination with Result<T, E> is the case where one wants to invoke
a fallible fallback if the option is not present. This example
parses a command line argument (if present), or the contents of a file to
an integer. However, unlike accessing the command line argument, reading
the file is fallible, so it must be wrapped with Ok.
let v: u64 = std::env::args()
.nth(1)
.map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
.parse()?;Sourcepub fn ok_or<E>(self, err: E) -> Result<T, E>
pub fn ok_or<E>(self, err: E) -> Result<T, E>
Transforms the Perhaps<T> into a Result<T, E>, mapping [Certain(v)] to
Ok(v) and [Dubious] to Err(err).
Arguments passed to ok_or are eagerly evaluated; if you are passing the
result of a function call, it is recommended to use ok_or_else, which is
lazily evaluated.
§Examples
let x = Certain("foo");
assert_eq!(x.ok_or(0), Ok("foo"));
let x: Perhaps<&str> = Dubious;
assert_eq!(x.ok_or(0), Err(0));Sourcepub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>where
F: FnOnce() -> E,
pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>where
F: FnOnce() -> E,
Transforms the Perhaps<T> into a Result<T, E>, mapping [Certain(v)] to
Ok(v) and [Dubious] to Err(err()).
§Examples
let x = Certain("foo");
assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
let x: Perhaps<&str> = Dubious;
assert_eq!(x.ok_or_else(|| 0), Err(0));Sourcepub fn as_deref(&self) -> Perhaps<&T::Target>where
T: Deref,
pub fn as_deref(&self) -> Perhaps<&T::Target>where
T: Deref,
Converts from Perhaps<T> (or &Perhaps<T>) to Perhaps<&T::Target>.
Leaves the original Perhaps in-place, creating a new one with a reference
to the original one, additionally coercing the contents via Deref.
§Examples
let x: Perhaps<String> = Certain("hey".to_owned());
assert_eq!(x.as_deref(), Certain("hey"));
let x: Perhaps<String> = Dubious;
assert_eq!(x.as_deref(), Dubious);Sourcepub fn as_deref_mut(&mut self) -> Perhaps<&mut T::Target>where
T: DerefMut,
pub fn as_deref_mut(&mut self) -> Perhaps<&mut T::Target>where
T: DerefMut,
Converts from Perhaps<T> (or &mut Perhaps<T>) to Perhaps<&mut T::Target>.
Leaves the original Perhaps in-place, creating a new one containing a mutable reference to
the inner type’s Deref::Target type.
§Examples
let mut x: Perhaps<String> = Certain("hey".to_owned());
assert_eq!(x.as_deref_mut().map(|x| {
x.make_ascii_uppercase();
x
}), Certain("HEY".to_owned().as_mut_str()));Sourcepub fn and<U>(self, optb: Perhaps<U>) -> Perhaps<U>
pub fn and<U>(self, optb: Perhaps<U>) -> Perhaps<U>
Returns Self::Dubious if the option is [Dubious], otherwise returns optb.
Arguments passed to and are eagerly evaluated; if you are passing the
result of a function call, it is recommended to use and_then, which is
lazily evaluated.
§Examples
let x = Certain(2);
let y: Perhaps<&str> = Dubious;
assert_eq!(x.and(y), Dubious);
let x: Perhaps<u32> = Dubious;
let y = Certain("foo");
assert_eq!(x.and(y), Dubious);
let x = Certain(2);
let y = Certain("foo");
assert_eq!(x.and(y), Certain("foo"));
let x: Perhaps<u32> = Dubious;
let y: Perhaps<&str> = Dubious;
assert_eq!(x.and(y), Dubious);Sourcepub fn and_then<U, F>(self, f: F) -> Perhaps<U>
pub fn and_then<U, F>(self, f: F) -> Perhaps<U>
Returns Self::Dubious if the option is [Dubious], otherwise calls f with the
wrapped value and returns the result.
Certain languages call this operation flatmap.
§Examples
fn sq_then_to_string(x: u32) -> Perhaps<String> {
x.checked_mul(x).map(|sq| sq.to_string())
}
assert_eq!(Self::Certain(2).and_then(sq_then_to_string), Certain(4.to_string()));
assert_eq!(Certain(1_000_000).and_then(sq_then_to_string), Dubious); // overflowed!
assert_eq!(Self::Dubious.and_then(sq_then_to_string), Dubious);Often used to chain fallible operations that may return [Dubious].
let arr_2d = [["A0", "A1"], ["B0", "B1"]];
let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
assert_eq!(item_0_1, Certain(&"A1"));
let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
assert_eq!(item_2_0, Dubious);Sourcepub fn filter<P>(self, predicate: P) -> Self
pub fn filter<P>(self, predicate: P) -> Self
Returns Self::Dubious if the option is [Dubious], otherwise calls predicate
with the wrapped value and returns:
- [
Certain(t)] ifpredicatereturnstrue(wheretis the wrapped value), and - [
Dubious] ifpredicatereturnsfalse.
This function works similar to Iterator::filter(). You can imagine
the Perhaps<T> being an iterator over one or zero elements. filter()
lets you decide which elements to keep.
§Examples
fn is_even(n: &i32) -> bool {
n % 2 == 0
}
assert_eq!(Self::Dubious.filter(is_even), Dubious);
assert_eq!(Certain(3).filter(is_even), Dubious);
assert_eq!(Self::Certain(4).filter(is_even), Certain(4));Sourcepub fn or(self, optb: Perhaps<T>) -> Perhaps<T>
pub fn or(self, optb: Perhaps<T>) -> Perhaps<T>
Returns the option if it contains a value, otherwise returns optb.
Arguments passed to or are eagerly evaluated; if you are passing the
result of a function call, it is recommended to use or_else, which is
lazily evaluated.
§Examples
let x = Certain(2);
let y = Dubious;
assert_eq!(x.or(y), Certain(2));
let x = Dubious;
let y = Certain(100);
assert_eq!(x.or(y), Certain(100));
let x = Certain(2);
let y = Certain(100);
assert_eq!(x.or(y), Certain(2));
let x: Perhaps<u32> = Dubious;
let y = Dubious;
assert_eq!(x.or(y), Dubious);Sourcepub fn or_else<F>(self, f: F) -> Perhaps<T>
pub fn or_else<F>(self, f: F) -> Perhaps<T>
Returns the option if it contains a value, otherwise calls f and
returns the result.
§Examples
fn nobody() -> Perhaps<&'static str> { Dubious }
fn vikings() -> Perhaps<&'static str> { Certain("vikings") }
assert_eq!(Self::Certain("barbarians").or_else(vikings), Certain("barbarians"));
assert_eq!(Dubious.or_else(vikings), Certain("vikings"));
assert_eq!(Self::Dubious.or_else(nobody), Dubious);Sourcepub fn xor(self, optb: Perhaps<T>) -> Perhaps<T>
pub fn xor(self, optb: Perhaps<T>) -> Perhaps<T>
Returns Self::Certain if exactly one of self, optb is [Certain], otherwise returns [Dubious].
§Examples
let x = Certain(2);
let y: Perhaps<u32> = Dubious;
assert_eq!(x.xor(y), Certain(2));
let x: Perhaps<u32> = Dubious;
let y = Certain(2);
assert_eq!(x.xor(y), Certain(2));
let x = Certain(2);
let y = Certain(2);
assert_eq!(x.xor(y), Dubious);
let x: Perhaps<u32> = Dubious;
let y: Perhaps<u32> = Dubious;
assert_eq!(x.xor(y), Dubious);Sourcepub fn insert(&mut self, value: T) -> &mut T
pub fn insert(&mut self, value: T) -> &mut T
Inserts value into the option, then returns a mutable reference to it.
If the option already contains a value, the old value is dropped.
See also Perhaps::get_or_insert, which doesn’t update the value if
the option already contains [Certain].
§Example
let mut opt = Dubious;
let val = opt.insert(1);
assert_eq!(*val, 1);
assert_eq!(opt.unwrap(), 1);
let val = opt.insert(2);
assert_eq!(*val, 2);
*val = 3;
assert_eq!(opt.unwrap(), 3);Sourcepub fn get_or_insert(&mut self, value: T) -> &mut T
pub fn get_or_insert(&mut self, value: T) -> &mut T
Inserts value into the option if it is [Dubious], then
returns a mutable reference to the contained value.
See also Perhaps::insert, which updates the value even if
the option already contains [Certain].
§Examples
let mut x = Dubious;
{
let y: &mut u32 = x.get_or_insert(5);
assert_eq!(y, &5);
*y = 7;
}
assert_eq!(x, Certain(7));Sourcepub fn get_or_insert_with<F>(&mut self, f: F) -> &mut Twhere
F: FnOnce() -> T,
pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut Twhere
F: FnOnce() -> T,
Inserts a value computed from f into the option if it is [Dubious],
then returns a mutable reference to the contained value.
§Examples
let mut x = Dubious;
{
let y: &mut u32 = x.get_or_insert_with(|| 5);
assert_eq!(y, &5);
*y = 7;
}
assert_eq!(x, Certain(7));Sourcepub fn take(&mut self) -> Perhaps<T>
pub fn take(&mut self) -> Perhaps<T>
Takes the value out of the option, leaving a [Dubious] in its place.
§Examples
let mut x = Certain(2);
let y = x.take();
assert_eq!(x, Dubious);
assert_eq!(y, Certain(2));
let mut x: Perhaps<u32> = Dubious;
let y = x.take();
assert_eq!(x, Dubious);
assert_eq!(y, Dubious);Sourcepub fn replace(&mut self, value: T) -> Perhaps<T>
pub fn replace(&mut self, value: T) -> Perhaps<T>
Replaces the actual value in the option by the value given in parameter,
returning the old value if present,
leaving a [Certain] in its place without deinitializing either one.
§Examples
let mut x = Certain(2);
let old = x.replace(5);
assert_eq!(x, Certain(5));
assert_eq!(old, Certain(2));
let mut x = Dubious;
let old = x.replace(3);
assert_eq!(x, Certain(3));
assert_eq!(old, Dubious);Sourcepub fn zip<U>(self, other: Perhaps<U>) -> Perhaps<(T, U)>
pub fn zip<U>(self, other: Perhaps<U>) -> Perhaps<(T, U)>
Zips self with another Perhaps.
If self is Self::Certain(s) and other is Self::Certain(o), this method returns Certain((s, o)).
Otherwise, Dubious is returned.
§Examples
let x = Certain(1);
let y = Certain("hi");
let z = Dubious::<u8>;
assert_eq!(x.zip(y), Certain((1, "hi")));
assert_eq!(x.zip(z), Dubious);Source§impl<T, U> Perhaps<(T, U)>
impl<T, U> Perhaps<(T, U)>
Sourcepub fn unzip(self) -> (Perhaps<T>, Perhaps<U>)
pub fn unzip(self) -> (Perhaps<T>, Perhaps<U>)
Unzips an option containing a tuple of two options.
If self is Self::Certain((a, b)) this method returns (Self::Certain(a), Certain(b)).
Otherwise, (Self::Dubious, Dubious) is returned.
§Examples
let x = Certain((1, "hi"));
let y = Dubious::<(u8, u32)>;
assert_eq!(x.unzip(), (Self::Certain(1), Certain("hi")));
assert_eq!(y.unzip(), (Self::Dubious, Dubious));Source§impl<T> Perhaps<&T>
impl<T> Perhaps<&T>
Source§impl<T> Perhaps<&mut T>
impl<T> Perhaps<&mut T>
Source§impl<T, E> Perhaps<Result<T, E>>
impl<T, E> Perhaps<Result<T, E>>
Sourcepub fn transpose(self) -> Result<Perhaps<T>, E>
pub fn transpose(self) -> Result<Perhaps<T>, E>
Transposes an Perhaps of a Result into a Result of an Perhaps.
Self::Dubious will be mapped to Ok([Dubious]).
Self::Certain(Ok(_)) and [Certain](Err(_)) will be mapped to
Ok([Certain](_)) and Err(_).
§Examples
#[derive(Debug, Eq, PartialEq)]
struct SomeErr;
let x: Result<Perhaps<i32>, SomeErr> = Ok(Certain(5));
let y: Perhaps<Result<i32, SomeErr>> = Certain(Ok(5));
assert_eq!(x, y.transpose());Source§impl<T> Perhaps<Perhaps<T>>
impl<T> Perhaps<Perhaps<T>>
Sourcepub fn flatten(self) -> Perhaps<T>
pub fn flatten(self) -> Perhaps<T>
Converts from Perhaps<Perhaps<T>> to Perhaps<T>.
§Examples
Basic usage:
let x: Perhaps<Perhaps<u32>> = Self::Certain(Certain(6));
assert_eq!(Certain(6), x.flatten());
let x: Perhaps<Perhaps<u32>> = Certain(Dubious);
assert_eq!(Dubious, x.flatten());
let x: Perhaps<Perhaps<u32>> = Dubious;
assert_eq!(Dubious, x.flatten());Flattening only removes one level of nesting at a time:
let x: Perhaps<Perhaps<Perhaps<u32>>> = Self::Certain(Self::Certain(Certain(6)));
assert_eq!(Self::Certain(Certain(6)), x.flatten());
assert_eq!(Certain(6), x.flatten().flatten());Trait Implementations§
Source§impl<'a, T> From<&'a Perhaps<T>> for Perhaps<&'a T>
impl<'a, T> From<&'a Perhaps<T>> for Perhaps<&'a T>
Source§fn from(o: &'a Perhaps<T>) -> Perhaps<&'a T>
fn from(o: &'a Perhaps<T>) -> Perhaps<&'a T>
Converts from &Perhaps<T> to Perhaps<&T>.
§Examples
Converts an Perhaps<String> into an Perhaps<usize>, preserving
the original. The map method takes the self argument by value, consuming the original,
so this technique uses from to first take an Perhaps to a reference
to the value inside the original.
let s: Perhaps<String> = Certain(String::from("Hello, Rustaceans!"));
let o: Perhaps<usize> = Perhaps::from(&s).map(|ss: &String| ss.len());
println!("Can still print s: {s:?}");
assert_eq!(o, Certain(18));Source§impl<'a, T> From<&'a mut Perhaps<T>> for Perhaps<&'a mut T>
impl<'a, T> From<&'a mut Perhaps<T>> for Perhaps<&'a mut T>
Source§fn from(o: &'a mut Perhaps<T>) -> Perhaps<&'a mut T>
fn from(o: &'a mut Perhaps<T>) -> Perhaps<&'a mut T>
Converts from &mut Perhaps<T> to Perhaps<&mut T>
§Examples
let mut s = Certain(String::from("Hello"));
let o: Perhaps<&mut String> = Perhaps::from(&mut s);
match o {
Certain(t) => *t = String::from("Hello, Rustaceans!"),
Dubious => (),
}
assert_eq!(s, Certain(String::from("Hello, Rustaceans!")));