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