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