Returns true
if the option is a Some
and the value inside of it matches a predicate.
let x: Option<u32> = Some(2);\nassert_eq!(x.is_some_and(|x| x > 1), true);\n\nlet x: Option<u32> = Some(0);\nassert_eq!(x.is_some_and(|x| x > 1), false);\n\nlet x: Option<u32> = None;\nassert_eq!(x.is_some_and(|x| x > 1), false);
Converts from &Option<T>
to Option<&T>
.
Calculates the length of an Option<String>
as an Option<usize>
\nwithout moving the String
. The map
method takes the self
argument by value,\nconsuming the original, so this technique uses as_ref
to first take an Option
to a\nreference to the value inside the original.
let text: Option<String> = Some(\"Hello, world!\".to_string());\n// First, cast `Option<String>` to `Option<&String>` with `as_ref`,\n// then consume *that* with `map`, leaving `text` on the stack.\nlet text_length: Option<usize> = text.as_ref().map(|s| s.len());\nprintln!(\"still can print text: {text:?}\");
Converts from &mut Option<T>
to Option<&mut T>
.
let mut x = Some(2);\nmatch x.as_mut() {\n Some(v) => *v = 42,\n None => {},\n}\nassert_eq!(x, Some(42));
Returns a slice of the contained value, if any. If this is None
, an\nempty slice is returned. This can be useful to have a single type of\niterator over an Option
or slice.
Note: Should you have an Option<&T>
and wish to get a slice of T
,\nyou can unpack it via opt.map_or(&[], std::slice::from_ref)
.
assert_eq!(\n [Some(1234).as_slice(), None.as_slice()],\n [&[1234][..], &[][..]],\n);
The inverse of this function is (discounting\nborrowing) [_]::first
:
for i in [Some(1234_u16), None] {\n assert_eq!(i.as_ref(), i.as_slice().first());\n}
Returns a mutable slice of the contained value, if any. If this is\nNone
, an empty slice is returned. This can be useful to have a\nsingle type of iterator over an Option
or slice.
Note: Should you have an Option<&mut T>
instead of a\n&mut Option<T>
, which this method takes, you can obtain a mutable\nslice via opt.map_or(&mut [], std::slice::from_mut)
.
assert_eq!(\n [Some(1234).as_mut_slice(), None.as_mut_slice()],\n [&mut [1234][..], &mut [][..]],\n);
The result is a mutable slice of zero or one items that points into\nour original Option
:
let mut x = Some(1234);\nx.as_mut_slice()[0] += 1;\nassert_eq!(x, Some(1235));
The inverse of this method (discounting borrowing)\nis [_]::first_mut
:
assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
Returns the contained Some
value, consuming the self
value.
Panics if the value is a None
with a custom panic message provided by\nmsg
.
let x = Some(\"value\");\nassert_eq!(x.expect(\"fruits are healthy\"), \"value\");
let x: Option<&str> = None;\nx.expect(\"fruits are healthy\"); // panics with `fruits are healthy`
We recommend that expect
messages are used to describe the reason you\nexpect the Option
should be Some
.
let item = slice.get(0)\n .expect(\"slice should not be empty\");
Hint: If you’re having trouble remembering how to phrase expect\nerror messages remember to focus on the word “should” as in “env\nvariable should be set by blah” or “the given binary should be available\nand executable by the current user”.
\nFor more detail on expect message styles and the reasoning behind our\nrecommendation please refer to the section on “Common Message\nStyles” in the std::error
module docs.
Returns the contained Some
value, consuming the self
value.
Because this function may panic, its use is generally discouraged.\nInstead, prefer to use pattern matching and handle the None
\ncase explicitly, or call unwrap_or
, unwrap_or_else
, or\nunwrap_or_default
.
Panics if the self value equals None
.
let x = Some(\"air\");\nassert_eq!(x.unwrap(), \"air\");
let x: Option<&str> = None;\nassert_eq!(x.unwrap(), \"air\"); // fails
Returns the contained Some
value or a provided default.
Arguments passed to unwrap_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use unwrap_or_else
,\nwhich is lazily evaluated.
assert_eq!(Some(\"car\").unwrap_or(\"bike\"), \"car\");\nassert_eq!(None.unwrap_or(\"bike\"), \"bike\");
Returns the contained Some
value or a default.
Consumes the self
argument then, if Some
, returns the contained\nvalue, otherwise if None
, returns the default value for that\ntype.
let x: Option<u32> = None;\nlet y: Option<u32> = Some(12);\n\nassert_eq!(x.unwrap_or_default(), 0);\nassert_eq!(y.unwrap_or_default(), 12);
Returns the contained Some
value, consuming the self
value,\nwithout checking that the value is not None
.
Calling this method on None
is undefined behavior.
let x = Some(\"air\");\nassert_eq!(unsafe { x.unwrap_unchecked() }, \"air\");
let x: Option<&str> = None;\nassert_eq!(unsafe { x.unwrap_unchecked() }, \"air\"); // Undefined behavior!
Maps an Option<T>
to Option<U>
by applying a function to a contained value (if Some
) or returns None
(if None
).
Calculates the length of an Option<String>
as an\nOption<usize>
, consuming the original:
let maybe_some_string = Some(String::from(\"Hello, World!\"));\n// `Option::map` takes self *by value*, consuming `maybe_some_string`\nlet maybe_some_len = maybe_some_string.map(|s| s.len());\nassert_eq!(maybe_some_len, Some(13));\n\nlet x: Option<&str> = None;\nassert_eq!(x.map(|s| s.len()), None);
Calls the provided closure with a reference to the contained value (if Some
).
let v = vec![1, 2, 3, 4, 5];\n\n// prints \"got: 4\"\nlet x: Option<&usize> = v.get(3).inspect(|x| println!(\"got: {x}\"));\n\n// prints nothing\nlet x: Option<&usize> = v.get(5).inspect(|x| println!(\"got: {x}\"));
Returns the provided default result (if none),\nor applies a function to the contained value (if any).
\nArguments passed to map_or
are eagerly evaluated; if you are passing\nthe result of a function call, it is recommended to use map_or_else
,\nwhich is lazily evaluated.
let x = Some(\"foo\");\nassert_eq!(x.map_or(42, |v| v.len()), 3);\n\nlet x: Option<&str> = None;\nassert_eq!(x.map_or(42, |v| v.len()), 42);
Computes a default function result (if none), or\napplies a different function to the contained value (if any).
\nlet k = 21;\n\nlet x = Some(\"foo\");\nassert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);\n\nlet x: Option<&str> = None;\nassert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
A somewhat common occurrence when dealing with optional values\nin combination with Result<T, E>
is the case where one wants to invoke\na fallible fallback if the option is not present. This example\nparses a command line argument (if present), or the contents of a file to\nan integer. However, unlike accessing the command line argument, reading\nthe file is fallible, so it must be wrapped with Ok
.
let v: u64 = std::env::args()\n .nth(1)\n .map_or_else(|| std::fs::read_to_string(\"/etc/someconfig.conf\"), Ok)?\n .parse()?;
Transforms the Option<T>
into a Result<T, E>
, mapping Some(v)
to\nOk(v)
and None
to Err(err)
.
Arguments passed to ok_or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use ok_or_else
, which is\nlazily evaluated.
let x = Some(\"foo\");\nassert_eq!(x.ok_or(0), Ok(\"foo\"));\n\nlet x: Option<&str> = None;\nassert_eq!(x.ok_or(0), Err(0));
Transforms the Option<T>
into a Result<T, E>
, mapping Some(v)
to\nOk(v)
and None
to Err(err())
.
let x = Some(\"foo\");\nassert_eq!(x.ok_or_else(|| 0), Ok(\"foo\"));\n\nlet x: Option<&str> = None;\nassert_eq!(x.ok_or_else(|| 0), Err(0));
Converts from Option<T>
(or &Option<T>
) to Option<&T::Target>
.
Leaves the original Option in-place, creating a new one with a reference\nto the original one, additionally coercing the contents via Deref
.
let x: Option<String> = Some(\"hey\".to_owned());\nassert_eq!(x.as_deref(), Some(\"hey\"));\n\nlet x: Option<String> = None;\nassert_eq!(x.as_deref(), None);
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\nthe inner type’s Deref::Target
type.
let mut x: Option<String> = Some(\"hey\".to_owned());\nassert_eq!(x.as_deref_mut().map(|x| {\n x.make_ascii_uppercase();\n x\n}), Some(\"HEY\".to_owned().as_mut_str()));
Returns an iterator over the possibly contained value.
\nlet x = Some(4);\nassert_eq!(x.iter().next(), Some(&4));\n\nlet x: Option<u32> = None;\nassert_eq!(x.iter().next(), None);
Returns a mutable iterator over the possibly contained value.
\nlet mut x = Some(4);\nmatch x.iter_mut().next() {\n Some(v) => *v = 42,\n None => {},\n}\nassert_eq!(x, Some(42));\n\nlet mut x: Option<u32> = None;\nassert_eq!(x.iter_mut().next(), None);
Returns None
if the option is None
, otherwise returns optb
.
Arguments passed to and
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use and_then
, which is\nlazily evaluated.
let x = Some(2);\nlet y: Option<&str> = None;\nassert_eq!(x.and(y), None);\n\nlet x: Option<u32> = None;\nlet y = Some(\"foo\");\nassert_eq!(x.and(y), None);\n\nlet x = Some(2);\nlet y = Some(\"foo\");\nassert_eq!(x.and(y), Some(\"foo\"));\n\nlet x: Option<u32> = None;\nlet y: Option<&str> = None;\nassert_eq!(x.and(y), None);
Returns None
if the option is None
, otherwise calls f
with the\nwrapped value and returns the result.
Some languages call this operation flatmap.
\nfn sq_then_to_string(x: u32) -> Option<String> {\n x.checked_mul(x).map(|sq| sq.to_string())\n}\n\nassert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));\nassert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!\nassert_eq!(None.and_then(sq_then_to_string), None);
Often used to chain fallible operations that may return None
.
let arr_2d = [[\"A0\", \"A1\"], [\"B0\", \"B1\"]];\n\nlet item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));\nassert_eq!(item_0_1, Some(&\"A1\"));\n\nlet item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));\nassert_eq!(item_2_0, None);
Returns None
if the option is None
, otherwise calls predicate
\nwith the wrapped value and returns:
Some(t)
if predicate
returns true
(where t
is the wrapped\nvalue), andNone
if predicate
returns false
.This function works similar to Iterator::filter()
. You can imagine\nthe Option<T>
being an iterator over one or zero elements. filter()
\nlets you decide which elements to keep.
fn is_even(n: &i32) -> bool {\n n % 2 == 0\n}\n\nassert_eq!(None.filter(is_even), None);\nassert_eq!(Some(3).filter(is_even), None);\nassert_eq!(Some(4).filter(is_even), Some(4));
Returns the option if it contains a value, otherwise returns optb
.
Arguments passed to or
are eagerly evaluated; if you are passing the\nresult of a function call, it is recommended to use or_else
, which is\nlazily evaluated.
let x = Some(2);\nlet y = None;\nassert_eq!(x.or(y), Some(2));\n\nlet x = None;\nlet y = Some(100);\nassert_eq!(x.or(y), Some(100));\n\nlet x = Some(2);\nlet y = Some(100);\nassert_eq!(x.or(y), Some(2));\n\nlet x: Option<u32> = None;\nlet y = None;\nassert_eq!(x.or(y), None);
Returns the option if it contains a value, otherwise calls f
and\nreturns the result.
fn nobody() -> Option<&'static str> { None }\nfn vikings() -> Option<&'static str> { Some(\"vikings\") }\n\nassert_eq!(Some(\"barbarians\").or_else(vikings), Some(\"barbarians\"));\nassert_eq!(None.or_else(vikings), Some(\"vikings\"));\nassert_eq!(None.or_else(nobody), None);
Returns Some
if exactly one of self
, optb
is Some
, otherwise returns None
.
let x = Some(2);\nlet y: Option<u32> = None;\nassert_eq!(x.xor(y), Some(2));\n\nlet x: Option<u32> = None;\nlet y = Some(2);\nassert_eq!(x.xor(y), Some(2));\n\nlet x = Some(2);\nlet y = Some(2);\nassert_eq!(x.xor(y), None);\n\nlet x: Option<u32> = None;\nlet y: Option<u32> = None;\nassert_eq!(x.xor(y), None);
Inserts value
into the option, then returns a mutable reference to it.
If the option already contains a value, the old value is dropped.
\nSee also Option::get_or_insert
, which doesn’t update the value if\nthe option already contains Some
.
let mut opt = None;\nlet val = opt.insert(1);\nassert_eq!(*val, 1);\nassert_eq!(opt.unwrap(), 1);\nlet val = opt.insert(2);\nassert_eq!(*val, 2);\n*val = 3;\nassert_eq!(opt.unwrap(), 3);
Inserts value
into the option if it is None
, then\nreturns a mutable reference to the contained value.
See also Option::insert
, which updates the value even if\nthe option already contains Some
.
let mut x = None;\n\n{\n let y: &mut u32 = x.get_or_insert(5);\n assert_eq!(y, &5);\n\n *y = 7;\n}\n\nassert_eq!(x, Some(7));
option_get_or_insert_default
)Inserts the default value into the option if it is None
, then\nreturns a mutable reference to the contained value.
#![feature(option_get_or_insert_default)]\n\nlet mut x = None;\n\n{\n let y: &mut u32 = x.get_or_insert_default();\n assert_eq!(y, &0);\n\n *y = 7;\n}\n\nassert_eq!(x, Some(7));
option_take_if
)Takes the value out of the option, but only if the predicate evaluates to\ntrue
on a mutable reference to the value.
In other words, replaces self
with None
if the predicate returns true
.\nThis method operates similar to Option::take
but conditional.
#![feature(option_take_if)]\n\nlet mut x = Some(42);\n\nlet prev = x.take_if(|v| if *v == 42 {\n *v += 1;\n false\n} else {\n false\n});\nassert_eq!(x, Some(43));\nassert_eq!(prev, None);\n\nlet prev = x.take_if(|v| *v == 43);\nassert_eq!(x, None);\nassert_eq!(prev, Some(43));
Replaces the actual value in the option by the value given in parameter,\nreturning the old value if present,\nleaving a Some
in its place without deinitializing either one.
let mut x = Some(2);\nlet old = x.replace(5);\nassert_eq!(x, Some(5));\nassert_eq!(old, Some(2));\n\nlet mut x = None;\nlet old = x.replace(3);\nassert_eq!(x, Some(3));\nassert_eq!(old, None);
Zips self
with another Option
.
If self
is Some(s)
and other
is Some(o)
, this method returns Some((s, o))
.\nOtherwise, None
is returned.
let x = Some(1);\nlet y = Some(\"hi\");\nlet z = None::<u8>;\n\nassert_eq!(x.zip(y), Some((1, \"hi\")));\nassert_eq!(x.zip(z), None);
option_zip
)Zips self
and another Option
with function f
.
If self
is Some(s)
and other
is Some(o)
, this method returns Some(f(s, o))
.\nOtherwise, None
is returned.
#![feature(option_zip)]\n\n#[derive(Debug, PartialEq)]\nstruct Point {\n x: f64,\n y: f64,\n}\n\nimpl Point {\n fn new(x: f64, y: f64) -> Self {\n Self { x, y }\n }\n}\n\nlet x = Some(17.5);\nlet y = Some(42.7);\n\nassert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));\nassert_eq!(x.zip_with(None, Point::new), None);
self
and other
) and is used by the <=
\noperator. Read moreTakes each element in the Iterator
: if it is a None
, no further\nelements are taken, and the None
is returned. Should no None
\noccur, the product of all elements is returned.
This multiplies each number in a vector of strings,\nif a string could not be parsed the operation returns None
:
let nums = vec![\"5\", \"10\", \"1\", \"2\"];\nlet total: Option<usize> = nums.iter().map(|w| w.parse::<usize>().ok()).product();\nassert_eq!(total, Some(100));\nlet nums = vec![\"5\", \"10\", \"one\", \"2\"];\nlet total: Option<usize> = nums.iter().map(|w| w.parse::<usize>().ok()).product();\nassert_eq!(total, None);