core/
option.rs

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