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