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