pub enum Option<T> {
None,
Some(T),
}
Expand description
The Option
type. See the module level documentation for more.
Variants§
Implementations§
Source§impl<T> Option<T>
impl<T> Option<T>
1.70.0 (const: unstable) · Sourcepub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool
pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool
Returns true
if the option is a Some
and the value inside of it matches a predicate.
§Examples
let x: Option<u32> = Some(2);
assert_eq!(x.is_some_and(|x| x > 1), true);
let x: Option<u32> = Some(0);
assert_eq!(x.is_some_and(|x| x > 1), false);
let x: Option<u32> = None;
assert_eq!(x.is_some_and(|x| x > 1), false);
let x: Option<String> = Some("ownership".to_string());
assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true);
println!("still alive {:?}", x);
1.82.0 (const: unstable) · Sourcepub fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool
pub fn is_none_or(self, f: impl FnOnce(T) -> bool) -> bool
Returns true
if the option is a None
or the value inside of it matches a predicate.
§Examples
let x: Option<u32> = Some(2);
assert_eq!(x.is_none_or(|x| x > 1), true);
let x: Option<u32> = Some(0);
assert_eq!(x.is_none_or(|x| x > 1), false);
let x: Option<u32> = None;
assert_eq!(x.is_none_or(|x| x > 1), true);
let x: Option<String> = Some("ownership".to_string());
assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true);
println!("still alive {:?}", x);
1.0.0 (const: 1.48.0) · Sourcepub const fn as_ref(&self) -> Option<&T>
pub const fn as_ref(&self) -> Option<&T>
Converts from &Option<T>
to Option<&T>
.
§Examples
Calculates the length of an Option<String>
as an Option<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 Option
to a
reference to the value inside the original.
let text: Option<String> = Some("Hello, world!".to_string());
// First, cast `Option<String>` to `Option<&String>` with `as_ref`,
// then consume *that* with `map`, leaving `text` on the stack.
let text_length: Option<usize> = text.as_ref().map(|s| s.len());
println!("still can print text: {text:?}");
1.0.0 (const: 1.83.0) · Sourcepub const fn as_mut(&mut self) -> Option<&mut T>
pub const fn as_mut(&mut self) -> Option<&mut T>
Converts from &mut Option<T>
to Option<&mut T>
.
§Examples
1.0.0 (const: unstable) · Sourcepub fn unwrap_or(self, default: T) -> Twhere
T:,
pub fn unwrap_or(self, default: T) -> Twhere
T:,
Returns the contained Some
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
1.0.0 (const: unstable) · 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,
1.0.0 (const: unstable) · Sourcepub fn unwrap_or_default(self) -> Twhere
T: Default,
pub fn unwrap_or_default(self) -> Twhere
T: Default,
Returns the contained Some
value or a default.
Consumes the self
argument then, if Some
, returns the contained
value, otherwise if None
, returns the default value for that
type.
§Examples
1.0.0 (const: unstable) · Sourcepub fn map<U, F>(self, f: F) -> Option<U>where
F: FnOnce(T) -> U,
pub fn map<U, F>(self, f: F) -> Option<U>where
F: FnOnce(T) -> U,
1.76.0 (const: unstable) · Sourcepub fn inspect<F>(self, f: F) -> Self
pub fn inspect<F>(self, f: F) -> Self
1.0.0 (const: unstable) · Sourcepub fn map_or<U, F>(self, default: U, f: F) -> Uwhere
F: FnOnce(T) -> U,
U:,
pub fn map_or<U, F>(self, default: U, f: F) -> Uwhere
F: FnOnce(T) -> U,
U:,
Returns the provided default result (if none), 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
1.0.0 (const: unstable) · 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 none), or applies a different function to the contained value (if any).
§Basic examples
let k = 21;
let x = Some("foo");
assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
let x: Option<&str> = None;
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
.
Sourcepub const fn map_or_default<U, F>(self, f: F) -> U
🔬This is a nightly-only experimental API. (result_option_map_or_default
#138099)
pub const fn map_or_default<U, F>(self, f: F) -> U
result_option_map_or_default
#138099)Maps an Option<T>
to a U
by applying function f
to the contained
value if the option is Some
, otherwise if None
, returns the
default value for the type U
.
§Examples
1.0.0 (const: unstable) · Sourcepub fn ok_or<E>(self, err: E) -> Result<T, E>
pub fn ok_or<E>(self, err: E) -> Result<T, E>
Transforms the Option<T>
into a Result<T, E>
, mapping Some(v)
to
Ok(v)
and None
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
1.0.0 (const: unstable) · 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 Option<T>
into a Result<T, E>
, mapping Some(v)
to
Ok(v)
and None
to Err(err())
.
§Examples
1.40.0 (const: unstable) · Sourcepub fn as_deref(&self) -> Option<&T::Target>where
T: Deref,
pub fn as_deref(&self) -> Option<&T::Target>where
T: Deref,
1.40.0 (const: unstable) · Sourcepub fn as_deref_mut(&mut self) -> Option<&mut T::Target>where
T: DerefMut,
pub fn as_deref_mut(&mut self) -> Option<&mut T::Target>where
T: DerefMut,
Converts from Option<T>
(or &mut Option<T>
) to Option<&mut T::Target>
.
Leaves the original Option
in-place, creating a new one containing a mutable reference to
the inner type’s Deref::Target
type.
§Examples
1.0.0 · Sourcepub fn iter(&self) -> Iter<'_, T>
pub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the possibly contained value.
§Examples
1.0.0 · Sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
pub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns a mutable iterator over the possibly contained value.
§Examples
1.0.0 (const: unstable) · Sourcepub fn and<U>(self, optb: Option<U>) -> Option<U>where
T:,
U:,
pub fn and<U>(self, optb: Option<U>) -> Option<U>where
T:,
U:,
Returns None
if the option is None
, 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 = Some(2);
let y: Option<&str> = None;
assert_eq!(x.and(y), None);
let x: Option<u32> = None;
let y = Some("foo");
assert_eq!(x.and(y), None);
let x = Some(2);
let y = Some("foo");
assert_eq!(x.and(y), Some("foo"));
let x: Option<u32> = None;
let y: Option<&str> = None;
assert_eq!(x.and(y), None);
1.0.0 (const: unstable) · Sourcepub fn and_then<U, F>(self, f: F) -> Option<U>
pub fn and_then<U, F>(self, f: F) -> Option<U>
Returns None
if the option is None
, otherwise calls f
with the
wrapped value and returns the result.
Some languages call this operation flatmap.
§Examples
fn sq_then_to_string(x: u32) -> Option<String> {
x.checked_mul(x).map(|sq| sq.to_string())
}
assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
assert_eq!(None.and_then(sq_then_to_string), None);
Often used to chain fallible operations that may return None
.
1.27.0 (const: unstable) · Sourcepub fn filter<P>(self, predicate: P) -> Self
pub fn filter<P>(self, predicate: P) -> Self
Returns None
if the option is None
, otherwise calls predicate
with the wrapped value and returns:
Some(t)
ifpredicate
returnstrue
(wheret
is the wrapped value), andNone
ifpredicate
returnsfalse
.
This function works similar to [Iterator::filter()
]. You can imagine
the Option<T>
being an iterator over one or zero elements. filter()
lets you decide which elements to keep.
§Examples
1.0.0 (const: unstable) · Sourcepub fn or(self, optb: Option<T>) -> Option<T>where
T:,
pub fn or(self, optb: Option<T>) -> Option<T>where
T:,
1.0.0 (const: unstable) · Sourcepub fn or_else<F>(self, f: F) -> Option<T>
pub fn or_else<F>(self, f: F) -> Option<T>
Returns the option if it contains a value, otherwise calls f
and
returns the result.
§Examples
1.37.0 (const: unstable) · Sourcepub fn xor(self, optb: Option<T>) -> Option<T>where
T:,
pub fn xor(self, optb: Option<T>) -> Option<T>where
T:,
1.46.0 (const: unstable) · Sourcepub fn zip<U>(self, other: Option<U>) -> Option<(T, U)>where
T:,
U:,
pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)>where
T:,
U:,
Zips self
with another Option
.
If self
is Some(s)
and other
is Some(o)
, this method returns Some((s, o))
.
Otherwise, None
is returned.
§Examples
Sourcepub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
🔬This is a nightly-only experimental API. (option_reduce
#144273)
pub fn reduce<U, R, F>(self, other: Option<U>, f: F) -> Option<R>
option_reduce
#144273)Reduces two options into one, using the provided function if both are Some
.
If self
is Some(s)
and other
is Some(o)
, this method returns Some(f(s, o))
.
Otherwise, if only one of self
and other
is Some
, that one is returned.
If both self
and other
are None
, None
is returned.
§Examples
Source§impl<T, U> Option<(T, U)>
impl<T, U> Option<(T, U)>
Source§impl<T> Option<&T>
impl<T> Option<&T>
Source§impl<T> Option<&mut T>
impl<T> Option<&mut T>
Source§impl<T, E> Option<Result<T, E>>
impl<T, E> Option<Result<T, E>>
Source§impl<T> Option<Option<T>>
impl<T> Option<Option<T>>
1.40.0 (const: 1.83.0) · Sourcepub const fn flatten(self) -> Option<T>
pub const fn flatten(self) -> Option<T>
Converts from Option<Option<T>>
to Option<T>
.
§Examples
Basic usage:
let x: Option<Option<u32>> = Some(Some(6));
assert_eq!(Some(6), x.flatten());
let x: Option<Option<u32>> = Some(None);
assert_eq!(None, x.flatten());
let x: Option<Option<u32>> = None;
assert_eq!(None, x.flatten());
Flattening only removes one level of nesting at a time: