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