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