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