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