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