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