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