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