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