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