1//! Optional values.
2//!
3//! Type [`Option`] represents an optional value: every [`Option`]
4//! is either [`Some`] and contains a value, or [`None`], and
5//! does not. [`Option`] types are very common in Rust code, as
6//! they have a number of uses:
7//!
8//! * Initial values
9//! * Return values for functions that are not defined
10//! over their entire input range (partial functions)
11//! * Return value for otherwise reporting simple errors, where [`None`] is
12//! returned on error
13//! * Optional struct fields
14//! * Struct fields that can be loaned or "taken"
15//! * Optional function arguments
16//! * Nullable pointers
17//! * Swapping things out of difficult situations
18//!
19//! [`Option`]s are commonly paired with pattern matching to query the presence
20//! of a value and take action, always accounting for the [`None`] case.
21//!
22//! ```
23//! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24//! if denominator == 0.0 {
25//! None
26//! } else {
27//! Some(numerator / denominator)
28//! }
29//! }
30//!
31//! // The return value of the function is an option
32//! let result = divide(2.0, 3.0);
33//!
34//! // Pattern match to retrieve the value
35//! match result {
36//! // The division was valid
37//! Some(x) => println!("Result: {x}"),
38//! // The division was invalid
39//! None => println!("Cannot divide by 0"),
40//! }
41//! ```
42//!
43//
44// FIXME: Show how `Option` is used in practice, with lots of methods
45//
46//! # Options and pointers ("nullable" pointers)
47//!
48//! Rust's pointer types must always point to a valid location; there are
49//! no "null" references. Instead, Rust has *optional* pointers, like
50//! the optional owned box, <code>[Option]<[Box\<T>]></code>.
51//!
52//! [Box\<T>]: ../../std/boxed/struct.Box.html
53//!
54//! The following example uses [`Option`] to create an optional box of
55//! [`i32`]. Notice that in order to use the inner [`i32`] value, the
56//! `check_optional` function first needs to use pattern matching to
57//! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
58//! not ([`None`]).
59//!
60//! ```
61//! let optional = None;
62//! check_optional(optional);
63//!
64//! let optional = Some(Box::new(9000));
65//! check_optional(optional);
66//!
67//! fn check_optional(optional: Option<Box<i32>>) {
68//! match optional {
69//! Some(p) => println!("has value {p}"),
70//! None => println!("has no value"),
71//! }
72//! }
73//! ```
74//!
75//! # The question mark operator, `?`
76//!
77//! Similar to the [`Result`] type, when writing code that calls many functions that return the
78//! [`Option`] type, handling `Some`/`None` can be tedious. The question mark
79//! operator, [`?`], hides some of the boilerplate of propagating values
80//! up the call stack.
81//!
82//! It replaces this:
83//!
84//! ```
85//! # #![allow(dead_code)]
86//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
87//! let a = stack.pop();
88//! let b = stack.pop();
89//!
90//! match (a, b) {
91//! (Some(x), Some(y)) => Some(x + y),
92//! _ => None,
93//! }
94//! }
95//!
96//! ```
97//!
98//! With this:
99//!
100//! ```
101//! # #![allow(dead_code)]
102//! fn add_last_numbers(stack: &mut Vec<i32>) -> Option<i32> {
103//! Some(stack.pop()? + stack.pop()?)
104//! }
105//! ```
106//!
107//! *It's much nicer!*
108//!
109//! Ending the expression with [`?`] will result in the [`Some`]'s unwrapped value, unless the
110//! result is [`None`], in which case [`None`] is returned early from the enclosing function.
111//!
112//! [`?`] can be used in functions that return [`Option`] because of the
113//! early return of [`None`] that it provides.
114//!
115//! [`?`]: crate::ops::Try
116//! [`Some`]: Some
117//! [`None`]: None
118//!
119//! # Representation
120//!
121//! Rust guarantees to optimize the following types `T` such that
122//! [`Option<T>`] has the same size, alignment, and [function call ABI] as `T`. In some
123//! of these cases, Rust further guarantees that
124//! `transmute::<_, Option<T>>([0u8; size_of::<T>()])` is sound and
125//! produces `Option::<T>::None`. These cases are identified by the
126//! second column:
127//!
128//! | `T` | `transmute::<_, Option<T>>([0u8; size_of::<T>()])` sound? |
129//! |---------------------------------------------------------------------|----------------------------------------------------------------------|
130//! | [`Box<U>`] (specifically, only `Box<U, Global>`) | when `U: Sized` |
131//! | `&U` | when `U: Sized` |
132//! | `&mut U` | when `U: Sized` |
133//! | `fn`, `extern "C" fn`[^extern_fn] | always |
134//! | [`num::NonZero*`] | always |
135//! | [`ptr::NonNull<U>`] | when `U: Sized` |
136//! | `#[repr(transparent)]` struct around one of the types in this list. | when it holds for the inner type |
137//!
138//! [^extern_fn]: this remains true for any argument/return types and any other ABI: `extern "abi" fn` (_e.g._, `extern "system" fn`)
139//!
140//! [`Box<U>`]: ../../std/boxed/struct.Box.html
141//! [`num::NonZero*`]: crate::num
142//! [`ptr::NonNull<U>`]: crate::ptr::NonNull
143//! [function call ABI]: ../primitive.fn.html#abi-compatibility
144//!
145//! This is called the "null pointer optimization" or NPO.
146//!
147//! It is further guaranteed that, for the cases above, one can
148//! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
149//! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
150//! is undefined behaviour).
151//!
152//! # Method overview
153//!
154//! In addition to working with pattern matching, [`Option`] provides a wide
155//! variety of different methods.
156//!
157//! ## Querying the variant
158//!
159//! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
160//! is [`Some`] or [`None`], respectively.
161//!
162//! [`is_none`]: Option::is_none
163//! [`is_some`]: Option::is_some
164//!
165//! ## Adapters for working with references
166//!
167//! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code>
168//! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code>
169//! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to
170//! <code>[Option]<[&]T::[Target]></code>
171//! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to
172//! <code>[Option]<[&mut] T::[Target]></code>
173//! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to
174//! <code>[Option]<[Pin]<[&]T>></code>
175//! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
176//! <code>[Option]<[Pin]<[&mut] T>></code>
177//!
178//! [&]: reference "shared reference"
179//! [&mut]: reference "mutable reference"
180//! [Target]: Deref::Target "ops::Deref::Target"
181//! [`as_deref`]: Option::as_deref
182//! [`as_deref_mut`]: Option::as_deref_mut
183//! [`as_mut`]: Option::as_mut
184//! [`as_pin_mut`]: Option::as_pin_mut
185//! [`as_pin_ref`]: Option::as_pin_ref
186//! [`as_ref`]: Option::as_ref
187//!
188//! ## Extracting the contained value
189//!
190//! These methods extract the contained value in an [`Option<T>`] when it
191//! is the [`Some`] variant. If the [`Option`] is [`None`]:
192//!
193//! * [`expect`] panics with a provided custom message
194//! * [`unwrap`] panics with a generic message
195//! * [`unwrap_or`] returns the provided default value
196//! * [`unwrap_or_default`] returns the default value of the type `T`
197//! (which must implement the [`Default`] trait)
198//! * [`unwrap_or_else`] returns the result of evaluating the provided
199//! function
200//!
201//! [`expect`]: Option::expect
202//! [`unwrap`]: Option::unwrap
203//! [`unwrap_or`]: Option::unwrap_or
204//! [`unwrap_or_default`]: Option::unwrap_or_default
205//! [`unwrap_or_else`]: Option::unwrap_or_else
206//!
207//! ## Transforming contained values
208//!
209//! These methods transform [`Option`] to [`Result`]:
210//!
211//! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
212//! [`Err(err)`] using the provided default `err` value
213//! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
214//! a value of [`Err`] using the provided function
215//! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
216//! [`Result`] of an [`Option`]
217//!
218//! [`Err(err)`]: Err
219//! [`Ok(v)`]: Ok
220//! [`Some(v)`]: Some
221//! [`ok_or`]: Option::ok_or
222//! [`ok_or_else`]: Option::ok_or_else
223//! [`transpose`]: Option::transpose
224//!
225//! These methods transform the [`Some`] variant:
226//!
227//! * [`filter`] calls the provided predicate function on the contained
228//! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
229//! if the function returns `true`; otherwise, returns [`None`]
230//! * [`flatten`] removes one level of nesting from an
231//! [`Option<Option<T>>`]
232//! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
233//! provided function to the contained value of [`Some`] and leaving
234//! [`None`] values unchanged
235//!
236//! [`Some(t)`]: Some
237//! [`filter`]: Option::filter
238//! [`flatten`]: Option::flatten
239//! [`map`]: Option::map
240//!
241//! These methods transform [`Option<T>`] to a value of a possibly
242//! different type `U`:
243//!
244//! * [`map_or`] applies the provided function to the contained value of
245//! [`Some`], or returns the provided default value if the [`Option`] is
246//! [`None`]
247//! * [`map_or_else`] applies the provided function to the contained value
248//! of [`Some`], or returns the result of evaluating the provided
249//! fallback function if the [`Option`] is [`None`]
250//!
251//! [`map_or`]: Option::map_or
252//! [`map_or_else`]: Option::map_or_else
253//!
254//! These methods combine the [`Some`] variants of two [`Option`] values:
255//!
256//! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
257//! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
258//! * [`zip_with`] calls the provided function `f` and returns
259//! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
260//! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
261//!
262//! [`Some(f(s, o))`]: Some
263//! [`Some(o)`]: Some
264//! [`Some(s)`]: Some
265//! [`Some((s, o))`]: Some
266//! [`zip`]: Option::zip
267//! [`zip_with`]: Option::zip_with
268//!
269//! ## Boolean operators
270//!
271//! These methods treat the [`Option`] as a boolean value, where [`Some`]
272//! acts like [`true`] and [`None`] acts like [`false`]. There are two
273//! categories of these methods: ones that take an [`Option`] as input, and
274//! ones that take a function as input (to be lazily evaluated).
275//!
276//! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
277//! input, and produce an [`Option`] as output. Only the [`and`] method can
278//! produce an [`Option<U>`] value having a different inner type `U` than
279//! [`Option<T>`].
280//!
281//! | method | self | input | output |
282//! |---------|-----------|-----------|-----------|
283//! | [`and`] | `None` | (ignored) | `None` |
284//! | [`and`] | `Some(x)` | `None` | `None` |
285//! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
286//! | [`or`] | `None` | `None` | `None` |
287//! | [`or`] | `None` | `Some(y)` | `Some(y)` |
288//! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
289//! | [`xor`] | `None` | `None` | `None` |
290//! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
291//! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
292//! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
293//!
294//! [`and`]: Option::and
295//! [`or`]: Option::or
296//! [`xor`]: Option::xor
297//!
298//! The [`and_then`] and [`or_else`] methods take a function as input, and
299//! only evaluate the function when they need to produce a new value. Only
300//! the [`and_then`] method can produce an [`Option<U>`] value having a
301//! different inner type `U` than [`Option<T>`].
302//!
303//! | method | self | function input | function result | output |
304//! |--------------|-----------|----------------|-----------------|-----------|
305//! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
306//! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
307//! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
308//! | [`or_else`] | `None` | (not provided) | `None` | `None` |
309//! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
310//! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
311//!
312//! [`and_then`]: Option::and_then
313//! [`or_else`]: Option::or_else
314//!
315//! This is an example of using methods like [`and_then`] and [`or`] in a
316//! pipeline of method calls. Early stages of the pipeline pass failure
317//! values ([`None`]) through unchanged, and continue processing on
318//! success values ([`Some`]). Toward the end, [`or`] substitutes an error
319//! message if it receives [`None`].
320//!
321//! ```
322//! # use std::collections::BTreeMap;
323//! let mut bt = BTreeMap::new();
324//! bt.insert(20u8, "foo");
325//! bt.insert(42u8, "bar");
326//! let res = [0u8, 1, 11, 200, 22]
327//! .into_iter()
328//! .map(|x| {
329//! // `checked_sub()` returns `None` on error
330//! x.checked_sub(1)
331//! // same with `checked_mul()`
332//! .and_then(|x| x.checked_mul(2))
333//! // `BTreeMap::get` returns `None` on error
334//! .and_then(|x| bt.get(&x))
335//! // Substitute an error message if we have `None` so far
336//! .or(Some(&"error!"))
337//! .copied()
338//! // Won't panic because we unconditionally used `Some` above
339//! .unwrap()
340//! })
341//! .collect::<Vec<_>>();
342//! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
343//! ```
344//!
345//! ## Comparison operators
346//!
347//! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its
348//! [`PartialOrd`] implementation. With this order, [`None`] compares as
349//! less than any [`Some`], and two [`Some`] compare the same way as their
350//! contained values would in `T`. If `T` also implements
351//! [`Ord`], then so does [`Option<T>`].
352//!
353//! ```
354//! assert!(None < Some(0));
355//! assert!(Some(0) < Some(1));
356//! ```
357//!
358//! ## Iterating over `Option`
359//!
360//! An [`Option`] can be iterated over. This can be helpful if you need an
361//! iterator that is conditionally empty. The iterator will either produce
362//! a single value (when the [`Option`] is [`Some`]), or produce no values
363//! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
364//! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
365//! the [`Option`] is [`None`].
366//!
367//! [`Some(v)`]: Some
368//! [`empty()`]: crate::iter::empty
369//! [`once(v)`]: crate::iter::once
370//!
371//! Iterators over [`Option<T>`] come in three types:
372//!
373//! * [`into_iter`] consumes the [`Option`] and produces the contained
374//! value
375//! * [`iter`] produces an immutable reference of type `&T` to the
376//! contained value
377//! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
378//! contained value
379//!
380//! [`into_iter`]: Option::into_iter
381//! [`iter`]: Option::iter
382//! [`iter_mut`]: Option::iter_mut
383//!
384//! An iterator over [`Option`] can be useful when chaining iterators, for
385//! example, to conditionally insert items. (It's not always necessary to
386//! explicitly call an iterator constructor: many [`Iterator`] methods that
387//! accept other iterators will also accept iterable types that implement
388//! [`IntoIterator`], which includes [`Option`].)
389//!
390//! ```
391//! let yep = Some(42);
392//! let nope = None;
393//! // chain() already calls into_iter(), so we don't have to do so
394//! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
395//! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
396//! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
397//! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
398//! ```
399//!
400//! One reason to chain iterators in this way is that a function returning
401//! `impl Iterator` must have all possible return values be of the same
402//! concrete type. Chaining an iterated [`Option`] can help with that.
403//!
404//! ```
405//! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
406//! // Explicit returns to illustrate return types matching
407//! match do_insert {
408//! true => return (0..4).chain(Some(42)).chain(4..8),
409//! false => return (0..4).chain(None).chain(4..8),
410//! }
411//! }
412//! println!("{:?}", make_iter(true).collect::<Vec<_>>());
413//! println!("{:?}", make_iter(false).collect::<Vec<_>>());
414//! ```
415//!
416//! If we try to do the same thing, but using [`once()`] and [`empty()`],
417//! we can't return `impl Iterator` anymore because the concrete types of
418//! the return values differ.
419//!
420//! [`empty()`]: crate::iter::empty
421//! [`once()`]: crate::iter::once
422//!
423//! ```compile_fail,E0308
424//! # use std::iter::{empty, once};
425//! // This won't compile because all possible returns from the function
426//! // must have the same concrete type.
427//! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
428//! // Explicit returns to illustrate return types not matching
429//! match do_insert {
430//! true => return (0..4).chain(once(42)).chain(4..8),
431//! false => return (0..4).chain(empty()).chain(4..8),
432//! }
433//! }
434//! ```
435//!
436//! ## Collecting into `Option`
437//!
438//! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
439//! which allows an iterator over [`Option`] values to be collected into an
440//! [`Option`] of a collection of each contained value of the original
441//! [`Option`] values, or [`None`] if any of the elements was [`None`].
442//!
443//! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E-for-Option%3CV%3E
444//!
445//! ```
446//! let v = [Some(2), Some(4), None, Some(8)];
447//! let res: Option<Vec<_>> = v.into_iter().collect();
448//! assert_eq!(res, None);
449//! let v = [Some(2), Some(4), Some(8)];
450//! let res: Option<Vec<_>> = v.into_iter().collect();
451//! assert_eq!(res, Some(vec![2, 4, 8]));
452//! ```
453//!
454//! [`Option`] also implements the [`Product`][impl-Product] and
455//! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
456//! to provide the [`product`][Iterator::product] and
457//! [`sum`][Iterator::sum] methods.
458//!
459//! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E-for-Option%3CT%3E
460//! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E-for-Option%3CT%3E
461//!
462//! ```
463//! let v = [None, Some(1), Some(2), Some(3)];
464//! let res: Option<i32> = v.into_iter().sum();
465//! assert_eq!(res, None);
466//! let v = [Some(1), Some(2), Some(21)];
467//! let res: Option<i32> = v.into_iter().product();
468//! assert_eq!(res, Some(42));
469//! ```
470//!
471//! ## Modifying an [`Option`] in-place
472//!
473//! These methods return a mutable reference to the contained value of an
474//! [`Option<T>`]:
475//!
476//! * [`insert`] inserts a value, dropping any old contents
477//! * [`get_or_insert`] gets the current value, inserting a provided
478//! default value if it is [`None`]
479//! * [`get_or_insert_default`] gets the current value, inserting the
480//! default value of type `T` (which must implement [`Default`]) if it is
481//! [`None`]
482//! * [`get_or_insert_with`] gets the current value, inserting a default
483//! computed by the provided function if it is [`None`]
484//!
485//! [`get_or_insert`]: Option::get_or_insert
486//! [`get_or_insert_default`]: Option::get_or_insert_default
487//! [`get_or_insert_with`]: Option::get_or_insert_with
488//! [`insert`]: Option::insert
489//!
490//! These methods transfer ownership of the contained value of an
491//! [`Option`]:
492//!
493//! * [`take`] takes ownership of the contained value of an [`Option`], if
494//! any, replacing the [`Option`] with [`None`]
495//! * [`replace`] takes ownership of the contained value of an [`Option`],
496//! if any, replacing the [`Option`] with a [`Some`] containing the
497//! provided value
498//!
499//! [`replace`]: Option::replace
500//! [`take`]: Option::take
501//!
502//! # Examples
503//!
504//! Basic pattern matching on [`Option`]:
505//!
506//! ```
507//! let msg = Some("howdy");
508//!
509//! // Take a reference to the contained string
510//! if let Some(m) = &msg {
511//! println!("{}", *m);
512//! }
513//!
514//! // Remove the contained string, destroying the Option
515//! let unwrapped_msg = msg.unwrap_or("default message");
516//! ```
517//!
518//! Initialize a result to [`None`] before a loop:
519//!
520//! ```
521//! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
522//!
523//! // A list of data to search through.
524//! let all_the_big_things = [
525//! Kingdom::Plant(250, "redwood"),
526//! Kingdom::Plant(230, "noble fir"),
527//! Kingdom::Plant(229, "sugar pine"),
528//! Kingdom::Animal(25, "blue whale"),
529//! Kingdom::Animal(19, "fin whale"),
530//! Kingdom::Animal(15, "north pacific right whale"),
531//! ];
532//!
533//! // We're going to search for the name of the biggest animal,
534//! // but to start with we've just got `None`.
535//! let mut name_of_biggest_animal = None;
536//! let mut size_of_biggest_animal = 0;
537//! for big_thing in &all_the_big_things {
538//! match *big_thing {
539//! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
540//! // Now we've found the name of some big animal
541//! size_of_biggest_animal = size;
542//! name_of_biggest_animal = Some(name);
543//! }
544//! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
545//! }
546//! }
547//!
548//! match name_of_biggest_animal {
549//! Some(name) => println!("the biggest animal is {name}"),
550//! None => println!("there are no animals :("),
551//! }
552//! ```
553
554#![stable(feature = "rust1", since = "1.0.0")]
555
556use crate::iter::{self, FusedIterator, TrustedLen};
557use crate::panicking::{panic, panic_display};
558use crate::pin::Pin;
559use crate::{
560 cmp, convert, hint, mem,
561 ops::{self, ControlFlow, Deref, DerefMut},
562 slice,
563};
564
565/// The `Option` type. See [the module level documentation](self) for more.
566#[derive(Copy, Eq, Debug, Hash)]
567#[rustc_diagnostic_item = "Option"]
568#[lang = "Option"]
569#[stable(feature = "rust1", since = "1.0.0")]
570#[allow(clippy::derived_hash_with_manual_eq)] // PartialEq is manually implemented equivalently
571pub enum Option<T> {
572 /// No value.
573 #[lang = "None"]
574 #[stable(feature = "rust1", since = "1.0.0")]
575 None,
576 /// Some value of type `T`.
577 #[lang = "Some"]
578 #[stable(feature = "rust1", since = "1.0.0")]
579 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
580}
581
582/////////////////////////////////////////////////////////////////////////////
583// Type implementation
584/////////////////////////////////////////////////////////////////////////////
585
586impl<T> Option<T> {
587 /////////////////////////////////////////////////////////////////////////
588 // Querying the contained values
589 /////////////////////////////////////////////////////////////////////////
590
591 /// Returns `true` if the option is a [`Some`] value.
592 ///
593 /// # Examples
594 ///
595 /// ```
596 /// let x: Option<u32> = Some(2);
597 /// assert_eq!(x.is_some(), true);
598 ///
599 /// let x: Option<u32> = None;
600 /// assert_eq!(x.is_some(), false);
601 /// ```
602 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
603 #[inline]
604 #[stable(feature = "rust1", since = "1.0.0")]
605 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
606 pub const fn is_some(&self) -> bool {
607 matches!(*self, Some(_))
608 }
609
610 /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate.
611 ///
612 /// # Examples
613 ///
614 /// ```
615 /// let x: Option<u32> = Some(2);
616 /// assert_eq!(x.is_some_and(|x| x > 1), true);
617 ///
618 /// let x: Option<u32> = Some(0);
619 /// assert_eq!(x.is_some_and(|x| x > 1), false);
620 ///
621 /// let x: Option<u32> = None;
622 /// assert_eq!(x.is_some_and(|x| x > 1), false);
623 /// ```
624 #[must_use]
625 #[inline]
626 #[stable(feature = "is_some_and", since = "1.70.0")]
627 pub fn is_some_and(self, f: impl FnOnce(T) -> bool) -> bool {
628 match self {
629 None => false,
630 Some(x) => f(x),
631 }
632 }
633
634 /// Returns `true` if the option is a [`None`] value.
635 ///
636 /// # Examples
637 ///
638 /// ```
639 /// let x: Option<u32> = Some(2);
640 /// assert_eq!(x.is_none(), false);
641 ///
642 /// let x: Option<u32> = None;
643 /// assert_eq!(x.is_none(), true);
644 /// ```
645 #[must_use = "if you intended to assert that this doesn't have a value, consider \
646 wrapping this in an `assert!()` instead"]
647 #[inline]
648 #[stable(feature = "rust1", since = "1.0.0")]
649 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
650 pub const fn is_none(&self) -> bool {
651 !self.is_some()
652 }
653
654 /////////////////////////////////////////////////////////////////////////
655 // Adapter for working with references
656 /////////////////////////////////////////////////////////////////////////
657
658 /// Converts from `&Option<T>` to `Option<&T>`.
659 ///
660 /// # Examples
661 ///
662 /// Calculates the length of an <code>Option<[String]></code> as an <code>Option<[usize]></code>
663 /// without moving the [`String`]. The [`map`] method takes the `self` argument by value,
664 /// consuming the original, so this technique uses `as_ref` to first take an `Option` to a
665 /// reference to the value inside the original.
666 ///
667 /// [`map`]: Option::map
668 /// [String]: ../../std/string/struct.String.html "String"
669 /// [`String`]: ../../std/string/struct.String.html "String"
670 ///
671 /// ```
672 /// let text: Option<String> = Some("Hello, world!".to_string());
673 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
674 /// // then consume *that* with `map`, leaving `text` on the stack.
675 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
676 /// println!("still can print text: {text:?}");
677 /// ```
678 #[inline]
679 #[rustc_const_stable(feature = "const_option_basics", since = "1.48.0")]
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub const fn as_ref(&self) -> Option<&T> {
682 match *self {
683 Some(ref x) => Some(x),
684 None => None,
685 }
686 }
687
688 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
689 ///
690 /// # Examples
691 ///
692 /// ```
693 /// let mut x = Some(2);
694 /// match x.as_mut() {
695 /// Some(v) => *v = 42,
696 /// None => {},
697 /// }
698 /// assert_eq!(x, Some(42));
699 /// ```
700 #[inline]
701 #[stable(feature = "rust1", since = "1.0.0")]
702 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
703 pub const fn as_mut(&mut self) -> Option<&mut T> {
704 match *self {
705 Some(ref mut x) => Some(x),
706 None => None,
707 }
708 }
709
710 /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
711 ///
712 /// [&]: reference "shared reference"
713 #[inline]
714 #[must_use]
715 #[stable(feature = "pin", since = "1.33.0")]
716 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
717 pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
718 match Pin::get_ref(self).as_ref() {
719 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
720 // which is pinned.
721 Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
722 None => None,
723 }
724 }
725
726 /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
727 ///
728 /// [&mut]: reference "mutable reference"
729 #[inline]
730 #[must_use]
731 #[stable(feature = "pin", since = "1.33.0")]
732 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
733 pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
734 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
735 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
736 unsafe {
737 match Pin::get_unchecked_mut(self).as_mut() {
738 Some(x) => Some(Pin::new_unchecked(x)),
739 None => None,
740 }
741 }
742 }
743
744 /// Returns a slice of the contained value, if any. If this is `None`, an
745 /// empty slice is returned. This can be useful to have a single type of
746 /// iterator over an `Option` or slice.
747 ///
748 /// Note: Should you have an `Option<&T>` and wish to get a slice of `T`,
749 /// you can unpack it via `opt.map_or(&[], std::slice::from_ref)`.
750 ///
751 /// # Examples
752 ///
753 /// ```rust
754 /// assert_eq!(
755 /// [Some(1234).as_slice(), None.as_slice()],
756 /// [&[1234][..], &[][..]],
757 /// );
758 /// ```
759 ///
760 /// The inverse of this function is (discounting
761 /// borrowing) [`[_]::first`](slice::first):
762 ///
763 /// ```rust
764 /// for i in [Some(1234_u16), None] {
765 /// assert_eq!(i.as_ref(), i.as_slice().first());
766 /// }
767 /// ```
768 #[inline]
769 #[must_use]
770 #[stable(feature = "option_as_slice", since = "1.75.0")]
771 pub fn as_slice(&self) -> &[T] {
772 // SAFETY: When the `Option` is `Some`, we're using the actual pointer
773 // to the payload, with a length of 1, so this is equivalent to
774 // `slice::from_ref`, and thus is safe.
775 // When the `Option` is `None`, the length used is 0, so to be safe it
776 // just needs to be aligned, which it is because `&self` is aligned and
777 // the offset used is a multiple of alignment.
778 //
779 // In the new version, the intrinsic always returns a pointer to an
780 // in-bounds and correctly aligned position for a `T` (even if in the
781 // `None` case it's just padding).
782 unsafe {
783 slice::from_raw_parts(
784 (self as *const Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(),
785 usize::from(self.is_some()),
786 )
787 }
788 }
789
790 /// Returns a mutable slice of the contained value, if any. If this is
791 /// `None`, an empty slice is returned. This can be useful to have a
792 /// single type of iterator over an `Option` or slice.
793 ///
794 /// Note: Should you have an `Option<&mut T>` instead of a
795 /// `&mut Option<T>`, which this method takes, you can obtain a mutable
796 /// slice via `opt.map_or(&mut [], std::slice::from_mut)`.
797 ///
798 /// # Examples
799 ///
800 /// ```rust
801 /// assert_eq!(
802 /// [Some(1234).as_mut_slice(), None.as_mut_slice()],
803 /// [&mut [1234][..], &mut [][..]],
804 /// );
805 /// ```
806 ///
807 /// The result is a mutable slice of zero or one items that points into
808 /// our original `Option`:
809 ///
810 /// ```rust
811 /// let mut x = Some(1234);
812 /// x.as_mut_slice()[0] += 1;
813 /// assert_eq!(x, Some(1235));
814 /// ```
815 ///
816 /// The inverse of this method (discounting borrowing)
817 /// is [`[_]::first_mut`](slice::first_mut):
818 ///
819 /// ```rust
820 /// assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123))
821 /// ```
822 #[inline]
823 #[must_use]
824 #[stable(feature = "option_as_slice", since = "1.75.0")]
825 pub fn as_mut_slice(&mut self) -> &mut [T] {
826 // SAFETY: When the `Option` is `Some`, we're using the actual pointer
827 // to the payload, with a length of 1, so this is equivalent to
828 // `slice::from_mut`, and thus is safe.
829 // When the `Option` is `None`, the length used is 0, so to be safe it
830 // just needs to be aligned, which it is because `&self` is aligned and
831 // the offset used is a multiple of alignment.
832 //
833 // In the new version, the intrinsic creates a `*const T` from a
834 // mutable reference so it is safe to cast back to a mutable pointer
835 // here. As with `as_slice`, the intrinsic always returns a pointer to
836 // an in-bounds and correctly aligned position for a `T` (even if in
837 // the `None` case it's just padding).
838 unsafe {
839 slice::from_raw_parts_mut(
840 (self as *mut Self).byte_add(core::mem::offset_of!(Self, Some.0)).cast(),
841 usize::from(self.is_some()),
842 )
843 }
844 }
845
846 /////////////////////////////////////////////////////////////////////////
847 // Getting to contained values
848 /////////////////////////////////////////////////////////////////////////
849
850 /// Returns the contained [`Some`] value, consuming the `self` value.
851 ///
852 /// # Panics
853 ///
854 /// Panics if the value is a [`None`] with a custom panic message provided by
855 /// `msg`.
856 ///
857 /// # Examples
858 ///
859 /// ```
860 /// let x = Some("value");
861 /// assert_eq!(x.expect("fruits are healthy"), "value");
862 /// ```
863 ///
864 /// ```should_panic
865 /// let x: Option<&str> = None;
866 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
867 /// ```
868 ///
869 /// # Recommended Message Style
870 ///
871 /// We recommend that `expect` messages are used to describe the reason you
872 /// _expect_ the `Option` should be `Some`.
873 ///
874 /// ```should_panic
875 /// # let slice: &[u8] = &[];
876 /// let item = slice.get(0)
877 /// .expect("slice should not be empty");
878 /// ```
879 ///
880 /// **Hint**: If you're having trouble remembering how to phrase expect
881 /// error messages remember to focus on the word "should" as in "env
882 /// variable should be set by blah" or "the given binary should be available
883 /// and executable by the current user".
884 ///
885 /// For more detail on expect message styles and the reasoning behind our
886 /// recommendation please refer to the section on ["Common Message
887 /// Styles"](../../std/error/index.html#common-message-styles) in the [`std::error`](../../std/error/index.html) module docs.
888 #[inline]
889 #[track_caller]
890 #[stable(feature = "rust1", since = "1.0.0")]
891 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
892 pub const fn expect(self, msg: &str) -> T {
893 match self {
894 Some(val) => val,
895 None => expect_failed(msg),
896 }
897 }
898
899 /// Returns the contained [`Some`] value, consuming the `self` value.
900 ///
901 /// Because this function may panic, its use is generally discouraged.
902 /// Instead, prefer to use pattern matching and handle the [`None`]
903 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
904 /// [`unwrap_or_default`].
905 ///
906 /// [`unwrap_or`]: Option::unwrap_or
907 /// [`unwrap_or_else`]: Option::unwrap_or_else
908 /// [`unwrap_or_default`]: Option::unwrap_or_default
909 ///
910 /// # Panics
911 ///
912 /// Panics if the self value equals [`None`].
913 ///
914 /// # Examples
915 ///
916 /// ```
917 /// let x = Some("air");
918 /// assert_eq!(x.unwrap(), "air");
919 /// ```
920 ///
921 /// ```should_panic
922 /// let x: Option<&str> = None;
923 /// assert_eq!(x.unwrap(), "air"); // fails
924 /// ```
925 #[inline(always)]
926 #[track_caller]
927 #[stable(feature = "rust1", since = "1.0.0")]
928 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
929 pub const fn unwrap(self) -> T {
930 match self {
931 Some(val) => val,
932 None => unwrap_failed(),
933 }
934 }
935
936 /// Returns the contained [`Some`] value or a provided default.
937 ///
938 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
939 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
940 /// which is lazily evaluated.
941 ///
942 /// [`unwrap_or_else`]: Option::unwrap_or_else
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
948 /// assert_eq!(None.unwrap_or("bike"), "bike");
949 /// ```
950 #[inline]
951 #[stable(feature = "rust1", since = "1.0.0")]
952 pub fn unwrap_or(self, default: T) -> T {
953 match self {
954 Some(x) => x,
955 None => default,
956 }
957 }
958
959 /// Returns the contained [`Some`] value or computes it from a closure.
960 ///
961 /// # Examples
962 ///
963 /// ```
964 /// let k = 10;
965 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
966 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
967 /// ```
968 #[inline]
969 #[track_caller]
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn unwrap_or_else<F>(self, f: F) -> T
972 where
973 F: FnOnce() -> T,
974 {
975 match self {
976 Some(x) => x,
977 None => f(),
978 }
979 }
980
981 /// Returns the contained [`Some`] value or a default.
982 ///
983 /// Consumes the `self` argument then, if [`Some`], returns the contained
984 /// value, otherwise if [`None`], returns the [default value] for that
985 /// type.
986 ///
987 /// # Examples
988 ///
989 /// ```
990 /// let x: Option<u32> = None;
991 /// let y: Option<u32> = Some(12);
992 ///
993 /// assert_eq!(x.unwrap_or_default(), 0);
994 /// assert_eq!(y.unwrap_or_default(), 12);
995 /// ```
996 ///
997 /// [default value]: Default::default
998 /// [`parse`]: str::parse
999 /// [`FromStr`]: crate::str::FromStr
1000 #[inline]
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub fn unwrap_or_default(self) -> T
1003 where
1004 T: Default,
1005 {
1006 match self {
1007 Some(x) => x,
1008 None => T::default(),
1009 }
1010 }
1011
1012 /// Returns the contained [`Some`] value, consuming the `self` value,
1013 /// without checking that the value is not [`None`].
1014 ///
1015 /// # Safety
1016 ///
1017 /// Calling this method on [`None`] is *[undefined behavior]*.
1018 ///
1019 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1020 ///
1021 /// # Examples
1022 ///
1023 /// ```
1024 /// let x = Some("air");
1025 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
1026 /// ```
1027 ///
1028 /// ```no_run
1029 /// let x: Option<&str> = None;
1030 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
1031 /// ```
1032 #[inline]
1033 #[track_caller]
1034 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
1035 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1036 pub const unsafe fn unwrap_unchecked(self) -> T {
1037 match self {
1038 Some(val) => val,
1039 // SAFETY: the safety contract must be upheld by the caller.
1040 None => unsafe { hint::unreachable_unchecked() },
1041 }
1042 }
1043
1044 /////////////////////////////////////////////////////////////////////////
1045 // Transforming contained values
1046 /////////////////////////////////////////////////////////////////////////
1047
1048 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`) or returns `None` (if `None`).
1049 ///
1050 /// # Examples
1051 ///
1052 /// Calculates the length of an <code>Option<[String]></code> as an
1053 /// <code>Option<[usize]></code>, consuming the original:
1054 ///
1055 /// [String]: ../../std/string/struct.String.html "String"
1056 /// ```
1057 /// let maybe_some_string = Some(String::from("Hello, World!"));
1058 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
1059 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
1060 /// assert_eq!(maybe_some_len, Some(13));
1061 ///
1062 /// let x: Option<&str> = None;
1063 /// assert_eq!(x.map(|s| s.len()), None);
1064 /// ```
1065 #[inline]
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 pub fn map<U, F>(self, f: F) -> Option<U>
1068 where
1069 F: FnOnce(T) -> U,
1070 {
1071 match self {
1072 Some(x) => Some(f(x)),
1073 None => None,
1074 }
1075 }
1076
1077 /// Calls a function with a reference to the contained value if [`Some`].
1078 ///
1079 /// Returns the original option.
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```
1084 /// let list = vec![1, 2, 3];
1085 ///
1086 /// // prints "got: 2"
1087 /// let x = list
1088 /// .get(1)
1089 /// .inspect(|x| println!("got: {x}"))
1090 /// .expect("list should be long enough");
1091 ///
1092 /// // prints nothing
1093 /// list.get(5).inspect(|x| println!("got: {x}"));
1094 /// ```
1095 #[inline]
1096 #[stable(feature = "result_option_inspect", since = "1.76.0")]
1097 pub fn inspect<F: FnOnce(&T)>(self, f: F) -> Self {
1098 if let Some(ref x) = self {
1099 f(x);
1100 }
1101
1102 self
1103 }
1104
1105 /// Returns the provided default result (if none),
1106 /// or applies a function to the contained value (if any).
1107 ///
1108 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
1109 /// the result of a function call, it is recommended to use [`map_or_else`],
1110 /// which is lazily evaluated.
1111 ///
1112 /// [`map_or_else`]: Option::map_or_else
1113 ///
1114 /// # Examples
1115 ///
1116 /// ```
1117 /// let x = Some("foo");
1118 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
1119 ///
1120 /// let x: Option<&str> = None;
1121 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
1122 /// ```
1123 #[inline]
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 #[must_use = "if you don't need the returned value, use `if let` instead"]
1126 pub fn map_or<U, F>(self, default: U, f: F) -> U
1127 where
1128 F: FnOnce(T) -> U,
1129 {
1130 match self {
1131 Some(t) => f(t),
1132 None => default,
1133 }
1134 }
1135
1136 /// Computes a default function result (if none), or
1137 /// applies a different function to the contained value (if any).
1138 ///
1139 /// # Basic examples
1140 ///
1141 /// ```
1142 /// let k = 21;
1143 ///
1144 /// let x = Some("foo");
1145 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
1146 ///
1147 /// let x: Option<&str> = None;
1148 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
1149 /// ```
1150 ///
1151 /// # Handling a Result-based fallback
1152 ///
1153 /// A somewhat common occurrence when dealing with optional values
1154 /// in combination with [`Result<T, E>`] is the case where one wants to invoke
1155 /// a fallible fallback if the option is not present. This example
1156 /// parses a command line argument (if present), or the contents of a file to
1157 /// an integer. However, unlike accessing the command line argument, reading
1158 /// the file is fallible, so it must be wrapped with `Ok`.
1159 ///
1160 /// ```no_run
1161 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
1162 /// let v: u64 = std::env::args()
1163 /// .nth(1)
1164 /// .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)?
1165 /// .parse()?;
1166 /// # Ok(())
1167 /// # }
1168 /// ```
1169 #[inline]
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub fn map_or_else<U, D, F>(self, default: D, f: F) -> U
1172 where
1173 D: FnOnce() -> U,
1174 F: FnOnce(T) -> U,
1175 {
1176 match self {
1177 Some(t) => f(t),
1178 None => default(),
1179 }
1180 }
1181
1182 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1183 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
1184 ///
1185 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
1186 /// result of a function call, it is recommended to use [`ok_or_else`], which is
1187 /// lazily evaluated.
1188 ///
1189 /// [`Ok(v)`]: Ok
1190 /// [`Err(err)`]: Err
1191 /// [`Some(v)`]: Some
1192 /// [`ok_or_else`]: Option::ok_or_else
1193 ///
1194 /// # Examples
1195 ///
1196 /// ```
1197 /// let x = Some("foo");
1198 /// assert_eq!(x.ok_or(0), Ok("foo"));
1199 ///
1200 /// let x: Option<&str> = None;
1201 /// assert_eq!(x.ok_or(0), Err(0));
1202 /// ```
1203 #[inline]
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
1206 match self {
1207 Some(v) => Ok(v),
1208 None => Err(err),
1209 }
1210 }
1211
1212 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1213 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
1214 ///
1215 /// [`Ok(v)`]: Ok
1216 /// [`Err(err())`]: Err
1217 /// [`Some(v)`]: Some
1218 ///
1219 /// # Examples
1220 ///
1221 /// ```
1222 /// let x = Some("foo");
1223 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
1224 ///
1225 /// let x: Option<&str> = None;
1226 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
1227 /// ```
1228 #[inline]
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 pub fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
1231 where
1232 F: FnOnce() -> E,
1233 {
1234 match self {
1235 Some(v) => Ok(v),
1236 None => Err(err()),
1237 }
1238 }
1239
1240 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1241 ///
1242 /// Leaves the original Option in-place, creating a new one with a reference
1243 /// to the original one, additionally coercing the contents via [`Deref`].
1244 ///
1245 /// # Examples
1246 ///
1247 /// ```
1248 /// let x: Option<String> = Some("hey".to_owned());
1249 /// assert_eq!(x.as_deref(), Some("hey"));
1250 ///
1251 /// let x: Option<String> = None;
1252 /// assert_eq!(x.as_deref(), None);
1253 /// ```
1254 #[inline]
1255 #[stable(feature = "option_deref", since = "1.40.0")]
1256 pub fn as_deref(&self) -> Option<&T::Target>
1257 where
1258 T: Deref,
1259 {
1260 match self.as_ref() {
1261 Some(t) => Some(t.deref()),
1262 None => None,
1263 }
1264 }
1265
1266 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1267 ///
1268 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1269 /// the inner type's [`Deref::Target`] type.
1270 ///
1271 /// # Examples
1272 ///
1273 /// ```
1274 /// let mut x: Option<String> = Some("hey".to_owned());
1275 /// assert_eq!(x.as_deref_mut().map(|x| {
1276 /// x.make_ascii_uppercase();
1277 /// x
1278 /// }), Some("HEY".to_owned().as_mut_str()));
1279 /// ```
1280 #[inline]
1281 #[stable(feature = "option_deref", since = "1.40.0")]
1282 pub fn as_deref_mut(&mut self) -> Option<&mut T::Target>
1283 where
1284 T: DerefMut,
1285 {
1286 match self.as_mut() {
1287 Some(t) => Some(t.deref_mut()),
1288 None => None,
1289 }
1290 }
1291
1292 /////////////////////////////////////////////////////////////////////////
1293 // Iterator constructors
1294 /////////////////////////////////////////////////////////////////////////
1295
1296 /// Returns an iterator over the possibly contained value.
1297 ///
1298 /// # Examples
1299 ///
1300 /// ```
1301 /// let x = Some(4);
1302 /// assert_eq!(x.iter().next(), Some(&4));
1303 ///
1304 /// let x: Option<u32> = None;
1305 /// assert_eq!(x.iter().next(), None);
1306 /// ```
1307 #[inline]
1308 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 pub const fn iter(&self) -> Iter<'_, T> {
1311 Iter { inner: Item { opt: self.as_ref() } }
1312 }
1313
1314 /// Returns a mutable iterator over the possibly contained value.
1315 ///
1316 /// # Examples
1317 ///
1318 /// ```
1319 /// let mut x = Some(4);
1320 /// match x.iter_mut().next() {
1321 /// Some(v) => *v = 42,
1322 /// None => {},
1323 /// }
1324 /// assert_eq!(x, Some(42));
1325 ///
1326 /// let mut x: Option<u32> = None;
1327 /// assert_eq!(x.iter_mut().next(), None);
1328 /// ```
1329 #[inline]
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1332 IterMut { inner: Item { opt: self.as_mut() } }
1333 }
1334
1335 /////////////////////////////////////////////////////////////////////////
1336 // Boolean operations on the values, eager and lazy
1337 /////////////////////////////////////////////////////////////////////////
1338
1339 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
1340 ///
1341 /// Arguments passed to `and` are eagerly evaluated; if you are passing the
1342 /// result of a function call, it is recommended to use [`and_then`], which is
1343 /// lazily evaluated.
1344 ///
1345 /// [`and_then`]: Option::and_then
1346 ///
1347 /// # Examples
1348 ///
1349 /// ```
1350 /// let x = Some(2);
1351 /// let y: Option<&str> = None;
1352 /// assert_eq!(x.and(y), None);
1353 ///
1354 /// let x: Option<u32> = None;
1355 /// let y = Some("foo");
1356 /// assert_eq!(x.and(y), None);
1357 ///
1358 /// let x = Some(2);
1359 /// let y = Some("foo");
1360 /// assert_eq!(x.and(y), Some("foo"));
1361 ///
1362 /// let x: Option<u32> = None;
1363 /// let y: Option<&str> = None;
1364 /// assert_eq!(x.and(y), None);
1365 /// ```
1366 #[inline]
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
1369 match self {
1370 Some(_) => optb,
1371 None => None,
1372 }
1373 }
1374
1375 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1376 /// wrapped value and returns the result.
1377 ///
1378 /// Some languages call this operation flatmap.
1379 ///
1380 /// # Examples
1381 ///
1382 /// ```
1383 /// fn sq_then_to_string(x: u32) -> Option<String> {
1384 /// x.checked_mul(x).map(|sq| sq.to_string())
1385 /// }
1386 ///
1387 /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
1388 /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
1389 /// assert_eq!(None.and_then(sq_then_to_string), None);
1390 /// ```
1391 ///
1392 /// Often used to chain fallible operations that may return [`None`].
1393 ///
1394 /// ```
1395 /// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
1396 ///
1397 /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
1398 /// assert_eq!(item_0_1, Some(&"A1"));
1399 ///
1400 /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
1401 /// assert_eq!(item_2_0, None);
1402 /// ```
1403 #[doc(alias = "flatmap")]
1404 #[inline]
1405 #[stable(feature = "rust1", since = "1.0.0")]
1406 #[rustc_confusables("flat_map", "flatmap")]
1407 pub fn and_then<U, F>(self, f: F) -> Option<U>
1408 where
1409 F: FnOnce(T) -> Option<U>,
1410 {
1411 match self {
1412 Some(x) => f(x),
1413 None => None,
1414 }
1415 }
1416
1417 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1418 /// with the wrapped value and returns:
1419 ///
1420 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1421 /// value), and
1422 /// - [`None`] if `predicate` returns `false`.
1423 ///
1424 /// This function works similar to [`Iterator::filter()`]. You can imagine
1425 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1426 /// lets you decide which elements to keep.
1427 ///
1428 /// # Examples
1429 ///
1430 /// ```rust
1431 /// fn is_even(n: &i32) -> bool {
1432 /// n % 2 == 0
1433 /// }
1434 ///
1435 /// assert_eq!(None.filter(is_even), None);
1436 /// assert_eq!(Some(3).filter(is_even), None);
1437 /// assert_eq!(Some(4).filter(is_even), Some(4));
1438 /// ```
1439 ///
1440 /// [`Some(t)`]: Some
1441 #[inline]
1442 #[stable(feature = "option_filter", since = "1.27.0")]
1443 pub fn filter<P>(self, predicate: P) -> Self
1444 where
1445 P: FnOnce(&T) -> bool,
1446 {
1447 if let Some(x) = self {
1448 if predicate(&x) {
1449 return Some(x);
1450 }
1451 }
1452 None
1453 }
1454
1455 /// Returns the option if it contains a value, otherwise returns `optb`.
1456 ///
1457 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1458 /// result of a function call, it is recommended to use [`or_else`], which is
1459 /// lazily evaluated.
1460 ///
1461 /// [`or_else`]: Option::or_else
1462 ///
1463 /// # Examples
1464 ///
1465 /// ```
1466 /// let x = Some(2);
1467 /// let y = None;
1468 /// assert_eq!(x.or(y), Some(2));
1469 ///
1470 /// let x = None;
1471 /// let y = Some(100);
1472 /// assert_eq!(x.or(y), Some(100));
1473 ///
1474 /// let x = Some(2);
1475 /// let y = Some(100);
1476 /// assert_eq!(x.or(y), Some(2));
1477 ///
1478 /// let x: Option<u32> = None;
1479 /// let y = None;
1480 /// assert_eq!(x.or(y), None);
1481 /// ```
1482 #[inline]
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 pub fn or(self, optb: Option<T>) -> Option<T> {
1485 match self {
1486 x @ Some(_) => x,
1487 None => optb,
1488 }
1489 }
1490
1491 /// Returns the option if it contains a value, otherwise calls `f` and
1492 /// returns the result.
1493 ///
1494 /// # Examples
1495 ///
1496 /// ```
1497 /// fn nobody() -> Option<&'static str> { None }
1498 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1499 ///
1500 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1501 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1502 /// assert_eq!(None.or_else(nobody), None);
1503 /// ```
1504 #[inline]
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 pub fn or_else<F>(self, f: F) -> Option<T>
1507 where
1508 F: FnOnce() -> Option<T>,
1509 {
1510 match self {
1511 x @ Some(_) => x,
1512 None => f(),
1513 }
1514 }
1515
1516 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1517 ///
1518 /// # Examples
1519 ///
1520 /// ```
1521 /// let x = Some(2);
1522 /// let y: Option<u32> = None;
1523 /// assert_eq!(x.xor(y), Some(2));
1524 ///
1525 /// let x: Option<u32> = None;
1526 /// let y = Some(2);
1527 /// assert_eq!(x.xor(y), Some(2));
1528 ///
1529 /// let x = Some(2);
1530 /// let y = Some(2);
1531 /// assert_eq!(x.xor(y), None);
1532 ///
1533 /// let x: Option<u32> = None;
1534 /// let y: Option<u32> = None;
1535 /// assert_eq!(x.xor(y), None);
1536 /// ```
1537 #[inline]
1538 #[stable(feature = "option_xor", since = "1.37.0")]
1539 pub fn xor(self, optb: Option<T>) -> Option<T> {
1540 match (self, optb) {
1541 (a @ Some(_), None) => a,
1542 (None, b @ Some(_)) => b,
1543 _ => None,
1544 }
1545 }
1546
1547 /////////////////////////////////////////////////////////////////////////
1548 // Entry-like operations to insert a value and return a reference
1549 /////////////////////////////////////////////////////////////////////////
1550
1551 /// Inserts `value` into the option, then returns a mutable reference to it.
1552 ///
1553 /// If the option already contains a value, the old value is dropped.
1554 ///
1555 /// See also [`Option::get_or_insert`], which doesn't update the value if
1556 /// the option already contains [`Some`].
1557 ///
1558 /// # Example
1559 ///
1560 /// ```
1561 /// let mut opt = None;
1562 /// let val = opt.insert(1);
1563 /// assert_eq!(*val, 1);
1564 /// assert_eq!(opt.unwrap(), 1);
1565 /// let val = opt.insert(2);
1566 /// assert_eq!(*val, 2);
1567 /// *val = 3;
1568 /// assert_eq!(opt.unwrap(), 3);
1569 /// ```
1570 #[must_use = "if you intended to set a value, consider assignment instead"]
1571 #[inline]
1572 #[stable(feature = "option_insert", since = "1.53.0")]
1573 pub fn insert(&mut self, value: T) -> &mut T {
1574 *self = Some(value);
1575
1576 // SAFETY: the code above just filled the option
1577 unsafe { self.as_mut().unwrap_unchecked() }
1578 }
1579
1580 /// Inserts `value` into the option if it is [`None`], then
1581 /// returns a mutable reference to the contained value.
1582 ///
1583 /// See also [`Option::insert`], which updates the value even if
1584 /// the option already contains [`Some`].
1585 ///
1586 /// # Examples
1587 ///
1588 /// ```
1589 /// let mut x = None;
1590 ///
1591 /// {
1592 /// let y: &mut u32 = x.get_or_insert(5);
1593 /// assert_eq!(y, &5);
1594 ///
1595 /// *y = 7;
1596 /// }
1597 ///
1598 /// assert_eq!(x, Some(7));
1599 /// ```
1600 #[inline]
1601 #[stable(feature = "option_entry", since = "1.20.0")]
1602 pub fn get_or_insert(&mut self, value: T) -> &mut T {
1603 if let None = *self {
1604 *self = Some(value);
1605 }
1606
1607 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1608 // variant in the code above.
1609 unsafe { self.as_mut().unwrap_unchecked() }
1610 }
1611
1612 /// Inserts the default value into the option if it is [`None`], then
1613 /// returns a mutable reference to the contained value.
1614 ///
1615 /// # Examples
1616 ///
1617 /// ```
1618 /// #![feature(option_get_or_insert_default)]
1619 ///
1620 /// let mut x = None;
1621 ///
1622 /// {
1623 /// let y: &mut u32 = x.get_or_insert_default();
1624 /// assert_eq!(y, &0);
1625 ///
1626 /// *y = 7;
1627 /// }
1628 ///
1629 /// assert_eq!(x, Some(7));
1630 /// ```
1631 #[inline]
1632 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1633 pub fn get_or_insert_default(&mut self) -> &mut T
1634 where
1635 T: Default,
1636 {
1637 self.get_or_insert_with(T::default)
1638 }
1639
1640 /// Inserts a value computed from `f` into the option if it is [`None`],
1641 /// then returns a mutable reference to the contained value.
1642 ///
1643 /// # Examples
1644 ///
1645 /// ```
1646 /// let mut x = None;
1647 ///
1648 /// {
1649 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1650 /// assert_eq!(y, &5);
1651 ///
1652 /// *y = 7;
1653 /// }
1654 ///
1655 /// assert_eq!(x, Some(7));
1656 /// ```
1657 #[inline]
1658 #[stable(feature = "option_entry", since = "1.20.0")]
1659 pub fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
1660 where
1661 F: FnOnce() -> T,
1662 {
1663 if let None = self {
1664 *self = Some(f());
1665 }
1666
1667 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1668 // variant in the code above.
1669 unsafe { self.as_mut().unwrap_unchecked() }
1670 }
1671
1672 /////////////////////////////////////////////////////////////////////////
1673 // Misc
1674 /////////////////////////////////////////////////////////////////////////
1675
1676 /// Takes the value out of the option, leaving a [`None`] in its place.
1677 ///
1678 /// # Examples
1679 ///
1680 /// ```
1681 /// let mut x = Some(2);
1682 /// let y = x.take();
1683 /// assert_eq!(x, None);
1684 /// assert_eq!(y, Some(2));
1685 ///
1686 /// let mut x: Option<u32> = None;
1687 /// let y = x.take();
1688 /// assert_eq!(x, None);
1689 /// assert_eq!(y, None);
1690 /// ```
1691 #[inline]
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1694 pub const fn take(&mut self) -> Option<T> {
1695 // FIXME replace `mem::replace` by `mem::take` when the latter is const ready
1696 mem::replace(self, None)
1697 }
1698
1699 /// Takes the value out of the option, but only if the predicate evaluates to
1700 /// `true` on a mutable reference to the value.
1701 ///
1702 /// In other words, replaces `self` with `None` if the predicate returns `true`.
1703 /// This method operates similar to [`Option::take`] but conditional.
1704 ///
1705 /// # Examples
1706 ///
1707 /// ```
1708 /// #![feature(option_take_if)]
1709 ///
1710 /// let mut x = Some(42);
1711 ///
1712 /// let prev = x.take_if(|v| if *v == 42 {
1713 /// *v += 1;
1714 /// false
1715 /// } else {
1716 /// false
1717 /// });
1718 /// assert_eq!(x, Some(43));
1719 /// assert_eq!(prev, None);
1720 ///
1721 /// let prev = x.take_if(|v| *v == 43);
1722 /// assert_eq!(x, None);
1723 /// assert_eq!(prev, Some(43));
1724 /// ```
1725 #[inline]
1726 #[unstable(feature = "option_take_if", issue = "98934")]
1727 pub fn take_if<P>(&mut self, predicate: P) -> Option<T>
1728 where
1729 P: FnOnce(&mut T) -> bool,
1730 {
1731 if self.as_mut().map_or(false, predicate) { self.take() } else { None }
1732 }
1733
1734 /// Replaces the actual value in the option by the value given in parameter,
1735 /// returning the old value if present,
1736 /// leaving a [`Some`] in its place without deinitializing either one.
1737 ///
1738 /// # Examples
1739 ///
1740 /// ```
1741 /// let mut x = Some(2);
1742 /// let old = x.replace(5);
1743 /// assert_eq!(x, Some(5));
1744 /// assert_eq!(old, Some(2));
1745 ///
1746 /// let mut x = None;
1747 /// let old = x.replace(3);
1748 /// assert_eq!(x, Some(3));
1749 /// assert_eq!(old, None);
1750 /// ```
1751 #[inline]
1752 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1753 #[stable(feature = "option_replace", since = "1.31.0")]
1754 pub const fn replace(&mut self, value: T) -> Option<T> {
1755 mem::replace(self, Some(value))
1756 }
1757
1758 /// Zips `self` with another `Option`.
1759 ///
1760 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1761 /// Otherwise, `None` is returned.
1762 ///
1763 /// # Examples
1764 ///
1765 /// ```
1766 /// let x = Some(1);
1767 /// let y = Some("hi");
1768 /// let z = None::<u8>;
1769 ///
1770 /// assert_eq!(x.zip(y), Some((1, "hi")));
1771 /// assert_eq!(x.zip(z), None);
1772 /// ```
1773 #[stable(feature = "option_zip_option", since = "1.46.0")]
1774 pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1775 match (self, other) {
1776 (Some(a), Some(b)) => Some((a, b)),
1777 _ => None,
1778 }
1779 }
1780
1781 /// Zips `self` and another `Option` with function `f`.
1782 ///
1783 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1784 /// Otherwise, `None` is returned.
1785 ///
1786 /// # Examples
1787 ///
1788 /// ```
1789 /// #![feature(option_zip)]
1790 ///
1791 /// #[derive(Debug, PartialEq)]
1792 /// struct Point {
1793 /// x: f64,
1794 /// y: f64,
1795 /// }
1796 ///
1797 /// impl Point {
1798 /// fn new(x: f64, y: f64) -> Self {
1799 /// Self { x, y }
1800 /// }
1801 /// }
1802 ///
1803 /// let x = Some(17.5);
1804 /// let y = Some(42.7);
1805 ///
1806 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1807 /// assert_eq!(x.zip_with(None, Point::new), None);
1808 /// ```
1809 #[unstable(feature = "option_zip", issue = "70086")]
1810 pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1811 where
1812 F: FnOnce(T, U) -> R,
1813 {
1814 match (self, other) {
1815 (Some(a), Some(b)) => Some(f(a, b)),
1816 _ => None,
1817 }
1818 }
1819}
1820
1821impl<T, U> Option<(T, U)> {
1822 /// Unzips an option containing a tuple of two options.
1823 ///
1824 /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
1825 /// Otherwise, `(None, None)` is returned.
1826 ///
1827 /// # Examples
1828 ///
1829 /// ```
1830 /// let x = Some((1, "hi"));
1831 /// let y = None::<(u8, u32)>;
1832 ///
1833 /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
1834 /// assert_eq!(y.unzip(), (None, None));
1835 /// ```
1836 #[inline]
1837 #[stable(feature = "unzip_option", since = "1.66.0")]
1838 pub fn unzip(self) -> (Option<T>, Option<U>) {
1839 match self {
1840 Some((a: T, b: U)) => (Some(a), Some(b)),
1841 None => (None, None),
1842 }
1843 }
1844}
1845
1846impl<T> Option<&T> {
1847 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1848 /// option.
1849 ///
1850 /// # Examples
1851 ///
1852 /// ```
1853 /// let x = 12;
1854 /// let opt_x = Some(&x);
1855 /// assert_eq!(opt_x, Some(&12));
1856 /// let copied = opt_x.copied();
1857 /// assert_eq!(copied, Some(12));
1858 /// ```
1859 #[must_use = "`self` will be dropped if the result is not used"]
1860 #[stable(feature = "copied", since = "1.35.0")]
1861 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1862 pub const fn copied(self) -> Option<T>
1863 where
1864 T: Copy,
1865 {
1866 // FIXME: this implementation, which sidesteps using `Option::map` since it's not const
1867 // ready yet, should be reverted when possible to avoid code repetition
1868 match self {
1869 Some(&v) => Some(v),
1870 None => None,
1871 }
1872 }
1873
1874 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1875 /// option.
1876 ///
1877 /// # Examples
1878 ///
1879 /// ```
1880 /// let x = 12;
1881 /// let opt_x = Some(&x);
1882 /// assert_eq!(opt_x, Some(&12));
1883 /// let cloned = opt_x.cloned();
1884 /// assert_eq!(cloned, Some(12));
1885 /// ```
1886 #[must_use = "`self` will be dropped if the result is not used"]
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 pub fn cloned(self) -> Option<T>
1889 where
1890 T: Clone,
1891 {
1892 match self {
1893 Some(t) => Some(t.clone()),
1894 None => None,
1895 }
1896 }
1897}
1898
1899impl<T> Option<&mut T> {
1900 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1901 /// option.
1902 ///
1903 /// # Examples
1904 ///
1905 /// ```
1906 /// let mut x = 12;
1907 /// let opt_x = Some(&mut x);
1908 /// assert_eq!(opt_x, Some(&mut 12));
1909 /// let copied = opt_x.copied();
1910 /// assert_eq!(copied, Some(12));
1911 /// ```
1912 #[must_use = "`self` will be dropped if the result is not used"]
1913 #[stable(feature = "copied", since = "1.35.0")]
1914 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1915 pub const fn copied(self) -> Option<T>
1916 where
1917 T: Copy,
1918 {
1919 match self {
1920 Some(&mut t) => Some(t),
1921 None => None,
1922 }
1923 }
1924
1925 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1926 /// option.
1927 ///
1928 /// # Examples
1929 ///
1930 /// ```
1931 /// let mut x = 12;
1932 /// let opt_x = Some(&mut x);
1933 /// assert_eq!(opt_x, Some(&mut 12));
1934 /// let cloned = opt_x.cloned();
1935 /// assert_eq!(cloned, Some(12));
1936 /// ```
1937 #[must_use = "`self` will be dropped if the result is not used"]
1938 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1939 pub fn cloned(self) -> Option<T>
1940 where
1941 T: Clone,
1942 {
1943 match self {
1944 Some(t) => Some(t.clone()),
1945 None => None,
1946 }
1947 }
1948}
1949
1950impl<T, E> Option<Result<T, E>> {
1951 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1952 ///
1953 /// [`None`] will be mapped to <code>[Ok]\([None])</code>.
1954 /// <code>[Some]\([Ok]\(\_))</code> and <code>[Some]\([Err]\(\_))</code> will be mapped to
1955 /// <code>[Ok]\([Some]\(\_))</code> and <code>[Err]\(\_)</code>.
1956 ///
1957 /// # Examples
1958 ///
1959 /// ```
1960 /// #[derive(Debug, Eq, PartialEq)]
1961 /// struct SomeErr;
1962 ///
1963 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1964 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1965 /// assert_eq!(x, y.transpose());
1966 /// ```
1967 #[inline]
1968 #[stable(feature = "transpose_result", since = "1.33.0")]
1969 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1970 pub const fn transpose(self) -> Result<Option<T>, E> {
1971 match self {
1972 Some(Ok(x)) => Ok(Some(x)),
1973 Some(Err(e)) => Err(e),
1974 None => Ok(None),
1975 }
1976 }
1977}
1978
1979#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
1980#[cfg_attr(feature = "panic_immediate_abort", inline)]
1981#[cold]
1982#[track_caller]
1983const fn unwrap_failed() -> ! {
1984 panic(expr:"called `Option::unwrap()` on a `None` value")
1985}
1986
1987// This is a separate function to reduce the code size of .expect() itself.
1988#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
1989#[cfg_attr(feature = "panic_immediate_abort", inline)]
1990#[cold]
1991#[track_caller]
1992#[rustc_const_unstable(feature = "const_option", issue = "67441")]
1993const fn expect_failed(msg: &str) -> ! {
1994 panic_display(&msg)
1995}
1996
1997/////////////////////////////////////////////////////////////////////////////
1998// Trait implementations
1999/////////////////////////////////////////////////////////////////////////////
2000
2001#[stable(feature = "rust1", since = "1.0.0")]
2002impl<T> Clone for Option<T>
2003where
2004 T: Clone,
2005{
2006 #[inline]
2007 fn clone(&self) -> Self {
2008 match self {
2009 Some(x: &T) => Some(x.clone()),
2010 None => None,
2011 }
2012 }
2013
2014 #[inline]
2015 fn clone_from(&mut self, source: &Self) {
2016 match (self, source) {
2017 (Some(to: &mut T), Some(from: &T)) => to.clone_from(source:from),
2018 (to: &mut Option, from: &Option) => *to = from.clone(),
2019 }
2020 }
2021}
2022
2023#[stable(feature = "rust1", since = "1.0.0")]
2024impl<T> Default for Option<T> {
2025 /// Returns [`None`][Option::None].
2026 ///
2027 /// # Examples
2028 ///
2029 /// ```
2030 /// let opt: Option<u32> = Option::default();
2031 /// assert!(opt.is_none());
2032 /// ```
2033 #[inline]
2034 fn default() -> Option<T> {
2035 None
2036 }
2037}
2038
2039#[stable(feature = "rust1", since = "1.0.0")]
2040impl<T> IntoIterator for Option<T> {
2041 type Item = T;
2042 type IntoIter = IntoIter<T>;
2043
2044 /// Returns a consuming iterator over the possibly contained value.
2045 ///
2046 /// # Examples
2047 ///
2048 /// ```
2049 /// let x = Some("string");
2050 /// let v: Vec<&str> = x.into_iter().collect();
2051 /// assert_eq!(v, ["string"]);
2052 ///
2053 /// let x = None;
2054 /// let v: Vec<&str> = x.into_iter().collect();
2055 /// assert!(v.is_empty());
2056 /// ```
2057 #[inline]
2058 fn into_iter(self) -> IntoIter<T> {
2059 IntoIter { inner: Item { opt: self } }
2060 }
2061}
2062
2063#[stable(since = "1.4.0", feature = "option_iter")]
2064impl<'a, T> IntoIterator for &'a Option<T> {
2065 type Item = &'a T;
2066 type IntoIter = Iter<'a, T>;
2067
2068 fn into_iter(self) -> Iter<'a, T> {
2069 self.iter()
2070 }
2071}
2072
2073#[stable(since = "1.4.0", feature = "option_iter")]
2074impl<'a, T> IntoIterator for &'a mut Option<T> {
2075 type Item = &'a mut T;
2076 type IntoIter = IterMut<'a, T>;
2077
2078 fn into_iter(self) -> IterMut<'a, T> {
2079 self.iter_mut()
2080 }
2081}
2082
2083#[stable(since = "1.12.0", feature = "option_from")]
2084impl<T> From<T> for Option<T> {
2085 /// Moves `val` into a new [`Some`].
2086 ///
2087 /// # Examples
2088 ///
2089 /// ```
2090 /// let o: Option<u8> = Option::from(67);
2091 ///
2092 /// assert_eq!(Some(67), o);
2093 /// ```
2094 fn from(val: T) -> Option<T> {
2095 Some(val)
2096 }
2097}
2098
2099#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2100impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
2101 /// Converts from `&Option<T>` to `Option<&T>`.
2102 ///
2103 /// # Examples
2104 ///
2105 /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
2106 /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
2107 /// so this technique uses `from` to first take an [`Option`] to a reference
2108 /// to the value inside the original.
2109 ///
2110 /// [`map`]: Option::map
2111 /// [String]: ../../std/string/struct.String.html "String"
2112 ///
2113 /// ```
2114 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
2115 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
2116 ///
2117 /// println!("Can still print s: {s:?}");
2118 ///
2119 /// assert_eq!(o, Some(18));
2120 /// ```
2121 fn from(o: &'a Option<T>) -> Option<&'a T> {
2122 o.as_ref()
2123 }
2124}
2125
2126#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2127impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
2128 /// Converts from `&mut Option<T>` to `Option<&mut T>`
2129 ///
2130 /// # Examples
2131 ///
2132 /// ```
2133 /// let mut s = Some(String::from("Hello"));
2134 /// let o: Option<&mut String> = Option::from(&mut s);
2135 ///
2136 /// match o {
2137 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
2138 /// None => (),
2139 /// }
2140 ///
2141 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
2142 /// ```
2143 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
2144 o.as_mut()
2145 }
2146}
2147
2148// Ideally, LLVM should be able to optimize our derive code to this.
2149// Once https://github.com/llvm/llvm-project/issues/52622 is fixed, we can
2150// go back to deriving `PartialEq`.
2151#[stable(feature = "rust1", since = "1.0.0")]
2152impl<T> crate::marker::StructuralPartialEq for Option<T> {}
2153#[stable(feature = "rust1", since = "1.0.0")]
2154impl<T: PartialEq> PartialEq for Option<T> {
2155 #[inline]
2156 fn eq(&self, other: &Self) -> bool {
2157 // Spelling out the cases explicitly optimizes better than
2158 // `_ => false`
2159 match (self, other) {
2160 (Some(l: &T), Some(r: &T)) => *l == *r,
2161 (Some(_), None) => false,
2162 (None, Some(_)) => false,
2163 (None, None) => true,
2164 }
2165 }
2166}
2167
2168// Manually implementing here somewhat improves codegen for
2169// https://github.com/rust-lang/rust/issues/49892, although still
2170// not optimal.
2171#[stable(feature = "rust1", since = "1.0.0")]
2172impl<T: PartialOrd> PartialOrd for Option<T> {
2173 #[inline]
2174 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
2175 match (self, other) {
2176 (Some(l: &T), Some(r: &T)) => l.partial_cmp(r),
2177 (Some(_), None) => Some(cmp::Ordering::Greater),
2178 (None, Some(_)) => Some(cmp::Ordering::Less),
2179 (None, None) => Some(cmp::Ordering::Equal),
2180 }
2181 }
2182}
2183
2184#[stable(feature = "rust1", since = "1.0.0")]
2185impl<T: Ord> Ord for Option<T> {
2186 #[inline]
2187 fn cmp(&self, other: &Self) -> cmp::Ordering {
2188 match (self, other) {
2189 (Some(l: &T), Some(r: &T)) => l.cmp(r),
2190 (Some(_), None) => cmp::Ordering::Greater,
2191 (None, Some(_)) => cmp::Ordering::Less,
2192 (None, None) => cmp::Ordering::Equal,
2193 }
2194 }
2195}
2196
2197/////////////////////////////////////////////////////////////////////////////
2198// The Option Iterators
2199/////////////////////////////////////////////////////////////////////////////
2200
2201#[derive(Clone, Debug)]
2202struct Item<A> {
2203 opt: Option<A>,
2204}
2205
2206impl<A> Iterator for Item<A> {
2207 type Item = A;
2208
2209 #[inline]
2210 fn next(&mut self) -> Option<A> {
2211 self.opt.take()
2212 }
2213
2214 #[inline]
2215 fn size_hint(&self) -> (usize, Option<usize>) {
2216 match self.opt {
2217 Some(_) => (1, Some(1)),
2218 None => (0, Some(0)),
2219 }
2220 }
2221}
2222
2223impl<A> DoubleEndedIterator for Item<A> {
2224 #[inline]
2225 fn next_back(&mut self) -> Option<A> {
2226 self.opt.take()
2227 }
2228}
2229
2230impl<A> ExactSizeIterator for Item<A> {}
2231impl<A> FusedIterator for Item<A> {}
2232unsafe impl<A> TrustedLen for Item<A> {}
2233
2234/// An iterator over a reference to the [`Some`] variant of an [`Option`].
2235///
2236/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2237///
2238/// This `struct` is created by the [`Option::iter`] function.
2239#[stable(feature = "rust1", since = "1.0.0")]
2240#[derive(Debug)]
2241pub struct Iter<'a, A: 'a> {
2242 inner: Item<&'a A>,
2243}
2244
2245#[stable(feature = "rust1", since = "1.0.0")]
2246impl<'a, A> Iterator for Iter<'a, A> {
2247 type Item = &'a A;
2248
2249 #[inline]
2250 fn next(&mut self) -> Option<&'a A> {
2251 self.inner.next()
2252 }
2253 #[inline]
2254 fn size_hint(&self) -> (usize, Option<usize>) {
2255 self.inner.size_hint()
2256 }
2257}
2258
2259#[stable(feature = "rust1", since = "1.0.0")]
2260impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
2261 #[inline]
2262 fn next_back(&mut self) -> Option<&'a A> {
2263 self.inner.next_back()
2264 }
2265}
2266
2267#[stable(feature = "rust1", since = "1.0.0")]
2268impl<A> ExactSizeIterator for Iter<'_, A> {}
2269
2270#[stable(feature = "fused", since = "1.26.0")]
2271impl<A> FusedIterator for Iter<'_, A> {}
2272
2273#[unstable(feature = "trusted_len", issue = "37572")]
2274unsafe impl<A> TrustedLen for Iter<'_, A> {}
2275
2276#[stable(feature = "rust1", since = "1.0.0")]
2277impl<A> Clone for Iter<'_, A> {
2278 #[inline]
2279 fn clone(&self) -> Self {
2280 Iter { inner: self.inner.clone() }
2281 }
2282}
2283
2284/// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
2285///
2286/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2287///
2288/// This `struct` is created by the [`Option::iter_mut`] function.
2289#[stable(feature = "rust1", since = "1.0.0")]
2290#[derive(Debug)]
2291pub struct IterMut<'a, A: 'a> {
2292 inner: Item<&'a mut A>,
2293}
2294
2295#[stable(feature = "rust1", since = "1.0.0")]
2296impl<'a, A> Iterator for IterMut<'a, A> {
2297 type Item = &'a mut A;
2298
2299 #[inline]
2300 fn next(&mut self) -> Option<&'a mut A> {
2301 self.inner.next()
2302 }
2303 #[inline]
2304 fn size_hint(&self) -> (usize, Option<usize>) {
2305 self.inner.size_hint()
2306 }
2307}
2308
2309#[stable(feature = "rust1", since = "1.0.0")]
2310impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
2311 #[inline]
2312 fn next_back(&mut self) -> Option<&'a mut A> {
2313 self.inner.next_back()
2314 }
2315}
2316
2317#[stable(feature = "rust1", since = "1.0.0")]
2318impl<A> ExactSizeIterator for IterMut<'_, A> {}
2319
2320#[stable(feature = "fused", since = "1.26.0")]
2321impl<A> FusedIterator for IterMut<'_, A> {}
2322#[unstable(feature = "trusted_len", issue = "37572")]
2323unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2324
2325/// An iterator over the value in [`Some`] variant of an [`Option`].
2326///
2327/// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2328///
2329/// This `struct` is created by the [`Option::into_iter`] function.
2330#[derive(Clone, Debug)]
2331#[stable(feature = "rust1", since = "1.0.0")]
2332pub struct IntoIter<A> {
2333 inner: Item<A>,
2334}
2335
2336#[stable(feature = "rust1", since = "1.0.0")]
2337impl<A> Iterator for IntoIter<A> {
2338 type Item = A;
2339
2340 #[inline]
2341 fn next(&mut self) -> Option<A> {
2342 self.inner.next()
2343 }
2344 #[inline]
2345 fn size_hint(&self) -> (usize, Option<usize>) {
2346 self.inner.size_hint()
2347 }
2348}
2349
2350#[stable(feature = "rust1", since = "1.0.0")]
2351impl<A> DoubleEndedIterator for IntoIter<A> {
2352 #[inline]
2353 fn next_back(&mut self) -> Option<A> {
2354 self.inner.next_back()
2355 }
2356}
2357
2358#[stable(feature = "rust1", since = "1.0.0")]
2359impl<A> ExactSizeIterator for IntoIter<A> {}
2360
2361#[stable(feature = "fused", since = "1.26.0")]
2362impl<A> FusedIterator for IntoIter<A> {}
2363
2364#[unstable(feature = "trusted_len", issue = "37572")]
2365unsafe impl<A> TrustedLen for IntoIter<A> {}
2366
2367/////////////////////////////////////////////////////////////////////////////
2368// FromIterator
2369/////////////////////////////////////////////////////////////////////////////
2370
2371#[stable(feature = "rust1", since = "1.0.0")]
2372impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
2373 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
2374 /// no further elements are taken, and the [`None`][Option::None] is
2375 /// returned. Should no [`None`][Option::None] occur, a container of type
2376 /// `V` containing the values of each [`Option`] is returned.
2377 ///
2378 /// # Examples
2379 ///
2380 /// Here is an example which increments every integer in a vector.
2381 /// We use the checked variant of `add` that returns `None` when the
2382 /// calculation would result in an overflow.
2383 ///
2384 /// ```
2385 /// let items = vec![0_u16, 1, 2];
2386 ///
2387 /// let res: Option<Vec<u16>> = items
2388 /// .iter()
2389 /// .map(|x| x.checked_add(1))
2390 /// .collect();
2391 ///
2392 /// assert_eq!(res, Some(vec![1, 2, 3]));
2393 /// ```
2394 ///
2395 /// As you can see, this will return the expected, valid items.
2396 ///
2397 /// Here is another example that tries to subtract one from another list
2398 /// of integers, this time checking for underflow:
2399 ///
2400 /// ```
2401 /// let items = vec![2_u16, 1, 0];
2402 ///
2403 /// let res: Option<Vec<u16>> = items
2404 /// .iter()
2405 /// .map(|x| x.checked_sub(1))
2406 /// .collect();
2407 ///
2408 /// assert_eq!(res, None);
2409 /// ```
2410 ///
2411 /// Since the last element is zero, it would underflow. Thus, the resulting
2412 /// value is `None`.
2413 ///
2414 /// Here is a variation on the previous example, showing that no
2415 /// further elements are taken from `iter` after the first `None`.
2416 ///
2417 /// ```
2418 /// let items = vec![3_u16, 2, 1, 10];
2419 ///
2420 /// let mut shared = 0;
2421 ///
2422 /// let res: Option<Vec<u16>> = items
2423 /// .iter()
2424 /// .map(|x| { shared += x; x.checked_sub(2) })
2425 /// .collect();
2426 ///
2427 /// assert_eq!(res, None);
2428 /// assert_eq!(shared, 6);
2429 /// ```
2430 ///
2431 /// Since the third element caused an underflow, no further elements were taken,
2432 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2433 #[inline]
2434 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
2435 // FIXME(#11084): This could be replaced with Iterator::scan when this
2436 // performance bug is closed.
2437
2438 iter::try_process(iter.into_iter(), |i| i.collect())
2439 }
2440}
2441
2442#[unstable(feature = "try_trait_v2", issue = "84277")]
2443impl<T> ops::Try for Option<T> {
2444 type Output = T;
2445 type Residual = Option<convert::Infallible>;
2446
2447 #[inline]
2448 fn from_output(output: Self::Output) -> Self {
2449 Some(output)
2450 }
2451
2452 #[inline]
2453 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2454 match self {
2455 Some(v: T) => ControlFlow::Continue(v),
2456 None => ControlFlow::Break(None),
2457 }
2458 }
2459}
2460
2461#[unstable(feature = "try_trait_v2", issue = "84277")]
2462impl<T> ops::FromResidual for Option<T> {
2463 #[inline]
2464 fn from_residual(residual: Option<convert::Infallible>) -> Self {
2465 match residual {
2466 None => None,
2467 }
2468 }
2469}
2470
2471#[unstable(feature = "try_trait_v2_yeet", issue = "96374")]
2472impl<T> ops::FromResidual<ops::Yeet<()>> for Option<T> {
2473 #[inline]
2474 fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self {
2475 None
2476 }
2477}
2478
2479#[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2480impl<T> ops::Residual<T> for Option<convert::Infallible> {
2481 type TryType = Option<T>;
2482}
2483
2484impl<T> Option<Option<T>> {
2485 /// Converts from `Option<Option<T>>` to `Option<T>`.
2486 ///
2487 /// # Examples
2488 ///
2489 /// Basic usage:
2490 ///
2491 /// ```
2492 /// let x: Option<Option<u32>> = Some(Some(6));
2493 /// assert_eq!(Some(6), x.flatten());
2494 ///
2495 /// let x: Option<Option<u32>> = Some(None);
2496 /// assert_eq!(None, x.flatten());
2497 ///
2498 /// let x: Option<Option<u32>> = None;
2499 /// assert_eq!(None, x.flatten());
2500 /// ```
2501 ///
2502 /// Flattening only removes one level of nesting at a time:
2503 ///
2504 /// ```
2505 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2506 /// assert_eq!(Some(Some(6)), x.flatten());
2507 /// assert_eq!(Some(6), x.flatten().flatten());
2508 /// ```
2509 #[inline]
2510 #[stable(feature = "option_flattening", since = "1.40.0")]
2511 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
2512 pub const fn flatten(self) -> Option<T> {
2513 match self {
2514 Some(inner) => inner,
2515 None => None,
2516 }
2517 }
2518}
2519