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