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:
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
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
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.
23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24 //! if denominator == 0.0 {
27 //! Some(numerator / denominator)
31 //! // The return value of the function is an option
32 //! let result = divide(2.0, 3.0);
34 //! // Pattern match to retrieve the value
36 //! // The division was valid
37 //! Some(x) => println!("Result: {x}"),
38 //! // The division was invalid
39 //! None => println!("Cannot divide by 0"),
44 // FIXME: Show how `Option` is used in practice, with lots of methods
46 //! # Options and pointers ("nullable" pointers)
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>.
52 //! [Box\<T>]: ../../std/boxed/struct.Box.html
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
61 //! let optional = None;
62 //! check_optional(optional);
64 //! let optional = Some(Box::new(9000));
65 //! check_optional(optional);
67 //! fn check_optional(optional: Option<Box<i32>>) {
69 //! Some(p) => println!("has value {p}"),
70 //! None => println!("has no value"),
77 //! Rust guarantees to optimize the following types `T` such that
78 //! [`Option<T>`] has the same size as `T`:
83 //! * `fn`, `extern "C" fn`[^extern_fn]
84 //! * [`num::NonZero*`]
85 //! * [`ptr::NonNull<U>`]
86 //! * `#[repr(transparent)]` struct around one of the types in this list.
88 //! [^extern_fn]: this remains true for any other ABI: `extern "abi" fn` (_e.g._, `extern "system" fn`)
90 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
91 //! [`num::NonZero*`]: crate::num
92 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
94 //! This is called the "null pointer optimization" or NPO.
96 //! It is further guaranteed that, for the cases above, one can
97 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
98 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
99 //! is undefined behaviour).
101 //! # Method overview
103 //! In addition to working with pattern matching, [`Option`] provides a wide
104 //! variety of different methods.
106 //! ## Querying the variant
108 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
109 //! is [`Some`] or [`None`], respectively.
111 //! [`is_none`]: Option::is_none
112 //! [`is_some`]: Option::is_some
114 //! ## Adapters for working with references
116 //! * [`as_ref`] converts from <code>[&][][Option]\<T></code> to <code>[Option]<[&]T></code>
117 //! * [`as_mut`] converts from <code>[&mut] [Option]\<T></code> to <code>[Option]<[&mut] T></code>
118 //! * [`as_deref`] converts from <code>[&][][Option]\<T></code> to
119 //! <code>[Option]<[&]T::[Target]></code>
120 //! * [`as_deref_mut`] converts from <code>[&mut] [Option]\<T></code> to
121 //! <code>[Option]<[&mut] T::[Target]></code>
122 //! * [`as_pin_ref`] converts from <code>[Pin]<[&][][Option]\<T>></code> to
123 //! <code>[Option]<[Pin]<[&]T>></code>
124 //! * [`as_pin_mut`] converts from <code>[Pin]<[&mut] [Option]\<T>></code> to
125 //! <code>[Option]<[Pin]<[&mut] T>></code>
127 //! [&]: reference "shared reference"
128 //! [&mut]: reference "mutable reference"
129 //! [Target]: Deref::Target "ops::Deref::Target"
130 //! [`as_deref`]: Option::as_deref
131 //! [`as_deref_mut`]: Option::as_deref_mut
132 //! [`as_mut`]: Option::as_mut
133 //! [`as_pin_mut`]: Option::as_pin_mut
134 //! [`as_pin_ref`]: Option::as_pin_ref
135 //! [`as_ref`]: Option::as_ref
137 //! ## Extracting the contained value
139 //! These methods extract the contained value in an [`Option<T>`] when it
140 //! is the [`Some`] variant. If the [`Option`] is [`None`]:
142 //! * [`expect`] panics with a provided custom message
143 //! * [`unwrap`] panics with a generic message
144 //! * [`unwrap_or`] returns the provided default value
145 //! * [`unwrap_or_default`] returns the default value of the type `T`
146 //! (which must implement the [`Default`] trait)
147 //! * [`unwrap_or_else`] returns the result of evaluating the provided
150 //! [`expect`]: Option::expect
151 //! [`unwrap`]: Option::unwrap
152 //! [`unwrap_or`]: Option::unwrap_or
153 //! [`unwrap_or_default`]: Option::unwrap_or_default
154 //! [`unwrap_or_else`]: Option::unwrap_or_else
156 //! ## Transforming contained values
158 //! These methods transform [`Option`] to [`Result`]:
160 //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
161 //! [`Err(err)`] using the provided default `err` value
162 //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
163 //! a value of [`Err`] using the provided function
164 //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
165 //! [`Result`] of an [`Option`]
167 //! [`Err(err)`]: Err
169 //! [`Some(v)`]: Some
170 //! [`ok_or`]: Option::ok_or
171 //! [`ok_or_else`]: Option::ok_or_else
172 //! [`transpose`]: Option::transpose
174 //! These methods transform the [`Some`] variant:
176 //! * [`filter`] calls the provided predicate function on the contained
177 //! value `t` if the [`Option`] is [`Some(t)`], and returns [`Some(t)`]
178 //! if the function returns `true`; otherwise, returns [`None`]
179 //! * [`flatten`] removes one level of nesting from an
180 //! [`Option<Option<T>>`]
181 //! * [`map`] transforms [`Option<T>`] to [`Option<U>`] by applying the
182 //! provided function to the contained value of [`Some`] and leaving
183 //! [`None`] values unchanged
185 //! [`Some(t)`]: Some
186 //! [`filter`]: Option::filter
187 //! [`flatten`]: Option::flatten
188 //! [`map`]: Option::map
190 //! These methods transform [`Option<T>`] to a value of a possibly
191 //! different type `U`:
193 //! * [`map_or`] applies the provided function to the contained value of
194 //! [`Some`], or returns the provided default value if the [`Option`] is
196 //! * [`map_or_else`] applies the provided function to the contained value
197 //! of [`Some`], or returns the result of evaluating the provided
198 //! fallback function if the [`Option`] is [`None`]
200 //! [`map_or`]: Option::map_or
201 //! [`map_or_else`]: Option::map_or_else
203 //! These methods combine the [`Some`] variants of two [`Option`] values:
205 //! * [`zip`] returns [`Some((s, o))`] if `self` is [`Some(s)`] and the
206 //! provided [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
207 //! * [`zip_with`] calls the provided function `f` and returns
208 //! [`Some(f(s, o))`] if `self` is [`Some(s)`] and the provided
209 //! [`Option`] value is [`Some(o)`]; otherwise, returns [`None`]
211 //! [`Some(f(s, o))`]: Some
212 //! [`Some(o)`]: Some
213 //! [`Some(s)`]: Some
214 //! [`Some((s, o))`]: Some
215 //! [`zip`]: Option::zip
216 //! [`zip_with`]: Option::zip_with
218 //! ## Boolean operators
220 //! These methods treat the [`Option`] as a boolean value, where [`Some`]
221 //! acts like [`true`] and [`None`] acts like [`false`]. There are two
222 //! categories of these methods: ones that take an [`Option`] as input, and
223 //! ones that take a function as input (to be lazily evaluated).
225 //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
226 //! input, and produce an [`Option`] as output. Only the [`and`] method can
227 //! produce an [`Option<U>`] value having a different inner type `U` than
230 //! | method | self | input | output |
231 //! |---------|-----------|-----------|-----------|
232 //! | [`and`] | `None` | (ignored) | `None` |
233 //! | [`and`] | `Some(x)` | `None` | `None` |
234 //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
235 //! | [`or`] | `None` | `None` | `None` |
236 //! | [`or`] | `None` | `Some(y)` | `Some(y)` |
237 //! | [`or`] | `Some(x)` | (ignored) | `Some(x)` |
238 //! | [`xor`] | `None` | `None` | `None` |
239 //! | [`xor`] | `None` | `Some(y)` | `Some(y)` |
240 //! | [`xor`] | `Some(x)` | `None` | `Some(x)` |
241 //! | [`xor`] | `Some(x)` | `Some(y)` | `None` |
243 //! [`and`]: Option::and
244 //! [`or`]: Option::or
245 //! [`xor`]: Option::xor
247 //! The [`and_then`] and [`or_else`] methods take a function as input, and
248 //! only evaluate the function when they need to produce a new value. Only
249 //! the [`and_then`] method can produce an [`Option<U>`] value having a
250 //! different inner type `U` than [`Option<T>`].
252 //! | method | self | function input | function result | output |
253 //! |--------------|-----------|----------------|-----------------|-----------|
254 //! | [`and_then`] | `None` | (not provided) | (not evaluated) | `None` |
255 //! | [`and_then`] | `Some(x)` | `x` | `None` | `None` |
256 //! | [`and_then`] | `Some(x)` | `x` | `Some(y)` | `Some(y)` |
257 //! | [`or_else`] | `None` | (not provided) | `None` | `None` |
258 //! | [`or_else`] | `None` | (not provided) | `Some(y)` | `Some(y)` |
259 //! | [`or_else`] | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
261 //! [`and_then`]: Option::and_then
262 //! [`or_else`]: Option::or_else
264 //! This is an example of using methods like [`and_then`] and [`or`] in a
265 //! pipeline of method calls. Early stages of the pipeline pass failure
266 //! values ([`None`]) through unchanged, and continue processing on
267 //! success values ([`Some`]). Toward the end, [`or`] substitutes an error
268 //! message if it receives [`None`].
271 //! # use std::collections::BTreeMap;
272 //! let mut bt = BTreeMap::new();
273 //! bt.insert(20u8, "foo");
274 //! bt.insert(42u8, "bar");
275 //! let res = [0u8, 1, 11, 200, 22]
278 //! // `checked_sub()` returns `None` on error
280 //! // same with `checked_mul()`
281 //! .and_then(|x| x.checked_mul(2))
282 //! // `BTreeMap::get` returns `None` on error
283 //! .and_then(|x| bt.get(&x))
284 //! // Substitute an error message if we have `None` so far
285 //! .or(Some(&"error!"))
287 //! // Won't panic because we unconditionally used `Some` above
290 //! .collect::<Vec<_>>();
291 //! assert_eq!(res, ["error!", "error!", "foo", "error!", "bar"]);
294 //! ## Comparison operators
296 //! If `T` implements [`PartialOrd`] then [`Option<T>`] will derive its
297 //! [`PartialOrd`] implementation. With this order, [`None`] compares as
298 //! less than any [`Some`], and two [`Some`] compare the same way as their
299 //! contained values would in `T`. If `T` also implements
300 //! [`Ord`], then so does [`Option<T>`].
303 //! assert!(None < Some(0));
304 //! assert!(Some(0) < Some(1));
307 //! ## Iterating over `Option`
309 //! An [`Option`] can be iterated over. This can be helpful if you need an
310 //! iterator that is conditionally empty. The iterator will either produce
311 //! a single value (when the [`Option`] is [`Some`]), or produce no values
312 //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
313 //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
314 //! the [`Option`] is [`None`].
316 //! [`Some(v)`]: Some
317 //! [`empty()`]: crate::iter::empty
318 //! [`once(v)`]: crate::iter::once
320 //! Iterators over [`Option<T>`] come in three types:
322 //! * [`into_iter`] consumes the [`Option`] and produces the contained
324 //! * [`iter`] produces an immutable reference of type `&T` to the
326 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
329 //! [`into_iter`]: Option::into_iter
330 //! [`iter`]: Option::iter
331 //! [`iter_mut`]: Option::iter_mut
333 //! An iterator over [`Option`] can be useful when chaining iterators, for
334 //! example, to conditionally insert items. (It's not always necessary to
335 //! explicitly call an iterator constructor: many [`Iterator`] methods that
336 //! accept other iterators will also accept iterable types that implement
337 //! [`IntoIterator`], which includes [`Option`].)
340 //! let yep = Some(42);
342 //! // chain() already calls into_iter(), so we don't have to do so
343 //! let nums: Vec<i32> = (0..4).chain(yep).chain(4..8).collect();
344 //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
345 //! let nums: Vec<i32> = (0..4).chain(nope).chain(4..8).collect();
346 //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
349 //! One reason to chain iterators in this way is that a function returning
350 //! `impl Iterator` must have all possible return values be of the same
351 //! concrete type. Chaining an iterated [`Option`] can help with that.
354 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
355 //! // Explicit returns to illustrate return types matching
356 //! match do_insert {
357 //! true => return (0..4).chain(Some(42)).chain(4..8),
358 //! false => return (0..4).chain(None).chain(4..8),
361 //! println!("{:?}", make_iter(true).collect::<Vec<_>>());
362 //! println!("{:?}", make_iter(false).collect::<Vec<_>>());
365 //! If we try to do the same thing, but using [`once()`] and [`empty()`],
366 //! we can't return `impl Iterator` anymore because the concrete types of
367 //! the return values differ.
369 //! [`empty()`]: crate::iter::empty
370 //! [`once()`]: crate::iter::once
372 //! ```compile_fail,E0308
373 //! # use std::iter::{empty, once};
374 //! // This won't compile because all possible returns from the function
375 //! // must have the same concrete type.
376 //! fn make_iter(do_insert: bool) -> impl Iterator<Item = i32> {
377 //! // Explicit returns to illustrate return types not matching
378 //! match do_insert {
379 //! true => return (0..4).chain(once(42)).chain(4..8),
380 //! false => return (0..4).chain(empty()).chain(4..8),
385 //! ## Collecting into `Option`
387 //! [`Option`] implements the [`FromIterator`][impl-FromIterator] trait,
388 //! which allows an iterator over [`Option`] values to be collected into an
389 //! [`Option`] of a collection of each contained value of the original
390 //! [`Option`] values, or [`None`] if any of the elements was [`None`].
392 //! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E
395 //! let v = [Some(2), Some(4), None, Some(8)];
396 //! let res: Option<Vec<_>> = v.into_iter().collect();
397 //! assert_eq!(res, None);
398 //! let v = [Some(2), Some(4), Some(8)];
399 //! let res: Option<Vec<_>> = v.into_iter().collect();
400 //! assert_eq!(res, Some(vec![2, 4, 8]));
403 //! [`Option`] also implements the [`Product`][impl-Product] and
404 //! [`Sum`][impl-Sum] traits, allowing an iterator over [`Option`] values
405 //! to provide the [`product`][Iterator::product] and
406 //! [`sum`][Iterator::sum] methods.
408 //! [impl-Product]: Option#impl-Product%3COption%3CU%3E%3E
409 //! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E
412 //! let v = [None, Some(1), Some(2), Some(3)];
413 //! let res: Option<i32> = v.into_iter().sum();
414 //! assert_eq!(res, None);
415 //! let v = [Some(1), Some(2), Some(21)];
416 //! let res: Option<i32> = v.into_iter().product();
417 //! assert_eq!(res, Some(42));
420 //! ## Modifying an [`Option`] in-place
422 //! These methods return a mutable reference to the contained value of an
425 //! * [`insert`] inserts a value, dropping any old contents
426 //! * [`get_or_insert`] gets the current value, inserting a provided
427 //! default value if it is [`None`]
428 //! * [`get_or_insert_default`] gets the current value, inserting the
429 //! default value of type `T` (which must implement [`Default`]) if it is
431 //! * [`get_or_insert_with`] gets the current value, inserting a default
432 //! computed by the provided function if it is [`None`]
434 //! [`get_or_insert`]: Option::get_or_insert
435 //! [`get_or_insert_default`]: Option::get_or_insert_default
436 //! [`get_or_insert_with`]: Option::get_or_insert_with
437 //! [`insert`]: Option::insert
439 //! These methods transfer ownership of the contained value of an
442 //! * [`take`] takes ownership of the contained value of an [`Option`], if
443 //! any, replacing the [`Option`] with [`None`]
444 //! * [`replace`] takes ownership of the contained value of an [`Option`],
445 //! if any, replacing the [`Option`] with a [`Some`] containing the
448 //! [`replace`]: Option::replace
449 //! [`take`]: Option::take
453 //! Basic pattern matching on [`Option`]:
456 //! let msg = Some("howdy");
458 //! // Take a reference to the contained string
459 //! if let Some(m) = &msg {
460 //! println!("{}", *m);
463 //! // Remove the contained string, destroying the Option
464 //! let unwrapped_msg = msg.unwrap_or("default message");
467 //! Initialize a result to [`None`] before a loop:
470 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
472 //! // A list of data to search through.
473 //! let all_the_big_things = [
474 //! Kingdom::Plant(250, "redwood"),
475 //! Kingdom::Plant(230, "noble fir"),
476 //! Kingdom::Plant(229, "sugar pine"),
477 //! Kingdom::Animal(25, "blue whale"),
478 //! Kingdom::Animal(19, "fin whale"),
479 //! Kingdom::Animal(15, "north pacific right whale"),
482 //! // We're going to search for the name of the biggest animal,
483 //! // but to start with we've just got `None`.
484 //! let mut name_of_biggest_animal = None;
485 //! let mut size_of_biggest_animal = 0;
486 //! for big_thing in &all_the_big_things {
487 //! match *big_thing {
488 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
489 //! // Now we've found the name of some big animal
490 //! size_of_biggest_animal = size;
491 //! name_of_biggest_animal = Some(name);
493 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
497 //! match name_of_biggest_animal {
498 //! Some(name) => println!("the biggest animal is {name}"),
499 //! None => println!("there are no animals :("),
503 #![stable(feature = "rust1", since = "1.0.0")]
505 use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
506 use crate::marker::Destruct;
507 use crate::panicking::{panic, panic_str};
511 ops::{self, ControlFlow, Deref, DerefMut},
514 /// The `Option` type. See [the module level documentation](self) for more.
515 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
516 #[rustc_diagnostic_item = "Option"]
517 #[stable(feature = "rust1", since = "1.0.0")]
521 #[stable(feature = "rust1", since = "1.0.0")]
523 /// Some value of type `T`.
525 #[stable(feature = "rust1", since = "1.0.0")]
526 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
529 /////////////////////////////////////////////////////////////////////////////
530 // Type implementation
531 /////////////////////////////////////////////////////////////////////////////
534 /////////////////////////////////////////////////////////////////////////
535 // Querying the contained values
536 /////////////////////////////////////////////////////////////////////////
538 /// Returns `true` if the option is a [`Some`] value.
543 /// let x: Option<u32> = Some(2);
544 /// assert_eq!(x.is_some(), true);
546 /// let x: Option<u32> = None;
547 /// assert_eq!(x.is_some(), false);
549 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
551 #[stable(feature = "rust1", since = "1.0.0")]
552 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
553 pub const fn is_some(&self) -> bool {
554 matches!(*self, Some(_))
557 /// Returns `true` if the option is a [`Some`] and the value inside of it matches a predicate.
562 /// #![feature(is_some_with)]
564 /// let x: Option<u32> = Some(2);
565 /// assert_eq!(x.is_some_and(|&x| x > 1), true);
567 /// let x: Option<u32> = Some(0);
568 /// assert_eq!(x.is_some_and(|&x| x > 1), false);
570 /// let x: Option<u32> = None;
571 /// assert_eq!(x.is_some_and(|&x| x > 1), false);
575 #[unstable(feature = "is_some_with", issue = "93050")]
576 pub fn is_some_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
577 matches!(self, Some(x) if f(x))
580 /// Returns `true` if the option is a [`None`] value.
585 /// let x: Option<u32> = Some(2);
586 /// assert_eq!(x.is_none(), false);
588 /// let x: Option<u32> = None;
589 /// assert_eq!(x.is_none(), true);
591 #[must_use = "if you intended to assert that this doesn't have a value, consider \
592 `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
594 #[stable(feature = "rust1", since = "1.0.0")]
595 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
596 pub const fn is_none(&self) -> bool {
600 /////////////////////////////////////////////////////////////////////////
601 // Adapter for working with references
602 /////////////////////////////////////////////////////////////////////////
604 /// Converts from `&Option<T>` to `Option<&T>`.
608 /// Converts an <code>Option<[String]></code> into an <code>Option<[usize]></code>, preserving
609 /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
610 /// so this technique uses `as_ref` to first take an `Option` to a reference
611 /// to the value inside the original.
613 /// [`map`]: Option::map
614 /// [String]: ../../std/string/struct.String.html "String"
617 /// let text: Option<String> = Some("Hello, world!".to_string());
618 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
619 /// // then consume *that* with `map`, leaving `text` on the stack.
620 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
621 /// println!("still can print text: {text:?}");
624 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub const fn as_ref(&self) -> Option<&T> {
628 Some(ref x) => Some(x),
633 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
638 /// let mut x = Some(2);
639 /// match x.as_mut() {
640 /// Some(v) => *v = 42,
643 /// assert_eq!(x, Some(42));
646 #[stable(feature = "rust1", since = "1.0.0")]
647 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
648 pub const fn as_mut(&mut self) -> Option<&mut T> {
650 Some(ref mut x) => Some(x),
655 /// Converts from <code>[Pin]<[&]Option\<T>></code> to <code>Option<[Pin]<[&]T>></code>.
657 /// [&]: reference "shared reference"
660 #[stable(feature = "pin", since = "1.33.0")]
661 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
662 pub const fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
663 match Pin::get_ref(self).as_ref() {
664 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
666 Some(x) => unsafe { Some(Pin::new_unchecked(x)) },
671 /// Converts from <code>[Pin]<[&mut] Option\<T>></code> to <code>Option<[Pin]<[&mut] T>></code>.
673 /// [&mut]: reference "mutable reference"
676 #[stable(feature = "pin", since = "1.33.0")]
677 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
678 pub const fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
679 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
680 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
682 match Pin::get_unchecked_mut(self).as_mut() {
683 Some(x) => Some(Pin::new_unchecked(x)),
689 /////////////////////////////////////////////////////////////////////////
690 // Getting to contained values
691 /////////////////////////////////////////////////////////////////////////
693 /// Returns the contained [`Some`] value, consuming the `self` value.
697 /// Panics if the value is a [`None`] with a custom panic message provided by
703 /// let x = Some("value");
704 /// assert_eq!(x.expect("fruits are healthy"), "value");
708 /// let x: Option<&str> = None;
709 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
713 #[stable(feature = "rust1", since = "1.0.0")]
714 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
715 pub const fn expect(self, msg: &str) -> T {
718 None => expect_failed(msg),
722 /// Returns the contained [`Some`] value, consuming the `self` value.
724 /// Because this function may panic, its use is generally discouraged.
725 /// Instead, prefer to use pattern matching and handle the [`None`]
726 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
727 /// [`unwrap_or_default`].
729 /// [`unwrap_or`]: Option::unwrap_or
730 /// [`unwrap_or_else`]: Option::unwrap_or_else
731 /// [`unwrap_or_default`]: Option::unwrap_or_default
735 /// Panics if the self value equals [`None`].
740 /// let x = Some("air");
741 /// assert_eq!(x.unwrap(), "air");
745 /// let x: Option<&str> = None;
746 /// assert_eq!(x.unwrap(), "air"); // fails
750 #[stable(feature = "rust1", since = "1.0.0")]
751 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
752 pub const fn unwrap(self) -> T {
755 None => panic("called `Option::unwrap()` on a `None` value"),
759 /// Returns the contained [`Some`] value or a provided default.
761 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
762 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
763 /// which is lazily evaluated.
765 /// [`unwrap_or_else`]: Option::unwrap_or_else
770 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
771 /// assert_eq!(None.unwrap_or("bike"), "bike");
774 #[stable(feature = "rust1", since = "1.0.0")]
775 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
776 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
777 pub const fn unwrap_or(self, default: T) -> T
779 T: ~const Drop + ~const Destruct,
787 /// Returns the contained [`Some`] value or computes it from a closure.
793 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
794 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
797 #[stable(feature = "rust1", since = "1.0.0")]
798 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
799 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
800 pub const fn unwrap_or_else<F>(self, f: F) -> T
802 F: ~const FnOnce() -> T,
803 F: ~const Drop + ~const Destruct,
811 /// Returns the contained [`Some`] value or a default.
813 /// Consumes the `self` argument then, if [`Some`], returns the contained
814 /// value, otherwise if [`None`], returns the [default value] for that
819 /// Converts a string to an integer, turning poorly-formed strings
820 /// into 0 (the default value for integers). [`parse`] converts
821 /// a string to any other type that implements [`FromStr`], returning
822 /// [`None`] on error.
825 /// let good_year_from_input = "1909";
826 /// let bad_year_from_input = "190blarg";
827 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
828 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
830 /// assert_eq!(1909, good_year);
831 /// assert_eq!(0, bad_year);
834 /// [default value]: Default::default
835 /// [`parse`]: str::parse
836 /// [`FromStr`]: crate::str::FromStr
838 #[stable(feature = "rust1", since = "1.0.0")]
839 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
840 pub const fn unwrap_or_default(self) -> T
846 None => Default::default(),
850 /// Returns the contained [`Some`] value, consuming the `self` value,
851 /// without checking that the value is not [`None`].
855 /// Calling this method on [`None`] is *[undefined behavior]*.
857 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
862 /// let x = Some("air");
863 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
867 /// let x: Option<&str> = None;
868 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
872 #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
873 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
874 pub const unsafe fn unwrap_unchecked(self) -> T {
875 debug_assert!(self.is_some());
878 // SAFETY: the safety contract must be upheld by the caller.
879 None => unsafe { hint::unreachable_unchecked() },
883 /////////////////////////////////////////////////////////////////////////
884 // Transforming contained values
885 /////////////////////////////////////////////////////////////////////////
887 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
891 /// Converts an <code>Option<[String]></code> into an <code>Option<[usize]></code>, consuming
894 /// [String]: ../../std/string/struct.String.html "String"
896 /// let maybe_some_string = Some(String::from("Hello, World!"));
897 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
898 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
900 /// assert_eq!(maybe_some_len, Some(13));
903 #[stable(feature = "rust1", since = "1.0.0")]
904 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
905 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
906 pub const fn map<U, F>(self, f: F) -> Option<U>
908 F: ~const FnOnce(T) -> U,
909 F: ~const Drop + ~const Destruct,
912 Some(x) => Some(f(x)),
917 /// Calls the provided closure with a reference to the contained value (if [`Some`]).
922 /// #![feature(result_option_inspect)]
924 /// let v = vec![1, 2, 3, 4, 5];
926 /// // prints "got: 4"
927 /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));
929 /// // prints nothing
930 /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
933 #[unstable(feature = "result_option_inspect", issue = "91345")]
934 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
935 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
936 pub const fn inspect<F>(self, f: F) -> Self
938 F: ~const FnOnce(&T),
939 F: ~const Drop + ~const Destruct,
941 if let Some(ref x) = self {
948 /// Returns the provided default result (if none),
949 /// or applies a function to the contained value (if any).
951 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
952 /// the result of a function call, it is recommended to use [`map_or_else`],
953 /// which is lazily evaluated.
955 /// [`map_or_else`]: Option::map_or_else
960 /// let x = Some("foo");
961 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
963 /// let x: Option<&str> = None;
964 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
967 #[stable(feature = "rust1", since = "1.0.0")]
968 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
969 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
970 pub const fn map_or<U, F>(self, default: U, f: F) -> U
972 F: ~const FnOnce(T) -> U,
973 F: ~const Drop + ~const Destruct,
974 U: ~const Drop + ~const Destruct,
982 /// Computes a default function result (if none), or
983 /// applies a different function to the contained value (if any).
990 /// let x = Some("foo");
991 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
993 /// let x: Option<&str> = None;
994 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
997 #[stable(feature = "rust1", since = "1.0.0")]
998 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
999 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1000 pub const fn map_or_else<U, D, F>(self, default: D, f: F) -> U
1002 D: ~const FnOnce() -> U,
1003 D: ~const Drop + ~const Destruct,
1004 F: ~const FnOnce(T) -> U,
1005 F: ~const Drop + ~const Destruct,
1013 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1014 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
1016 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
1017 /// result of a function call, it is recommended to use [`ok_or_else`], which is
1018 /// lazily evaluated.
1021 /// [`Err(err)`]: Err
1022 /// [`Some(v)`]: Some
1023 /// [`ok_or_else`]: Option::ok_or_else
1028 /// let x = Some("foo");
1029 /// assert_eq!(x.ok_or(0), Ok("foo"));
1031 /// let x: Option<&str> = None;
1032 /// assert_eq!(x.ok_or(0), Err(0));
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1037 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1038 pub const fn ok_or<E>(self, err: E) -> Result<T, E>
1040 E: ~const Drop + ~const Destruct,
1048 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
1049 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
1052 /// [`Err(err())`]: Err
1053 /// [`Some(v)`]: Some
1058 /// let x = Some("foo");
1059 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
1061 /// let x: Option<&str> = None;
1062 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1067 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1068 pub const fn ok_or_else<E, F>(self, err: F) -> Result<T, E>
1070 F: ~const FnOnce() -> E,
1071 F: ~const Drop + ~const Destruct,
1079 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1081 /// Leaves the original Option in-place, creating a new one with a reference
1082 /// to the original one, additionally coercing the contents via [`Deref`].
1087 /// let x: Option<String> = Some("hey".to_owned());
1088 /// assert_eq!(x.as_deref(), Some("hey"));
1090 /// let x: Option<String> = None;
1091 /// assert_eq!(x.as_deref(), None);
1093 #[stable(feature = "option_deref", since = "1.40.0")]
1094 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1095 pub const fn as_deref(&self) -> Option<&T::Target>
1099 match self.as_ref() {
1100 Some(t) => Some(t.deref()),
1105 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1107 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1108 /// the inner type's [`Deref::Target`] type.
1113 /// let mut x: Option<String> = Some("hey".to_owned());
1114 /// assert_eq!(x.as_deref_mut().map(|x| {
1115 /// x.make_ascii_uppercase();
1117 /// }), Some("HEY".to_owned().as_mut_str()));
1119 #[stable(feature = "option_deref", since = "1.40.0")]
1120 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1121 pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target>
1125 match self.as_mut() {
1126 Some(t) => Some(t.deref_mut()),
1131 /////////////////////////////////////////////////////////////////////////
1132 // Iterator constructors
1133 /////////////////////////////////////////////////////////////////////////
1135 /// Returns an iterator over the possibly contained value.
1140 /// let x = Some(4);
1141 /// assert_eq!(x.iter().next(), Some(&4));
1143 /// let x: Option<u32> = None;
1144 /// assert_eq!(x.iter().next(), None);
1147 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 pub const fn iter(&self) -> Iter<'_, T> {
1150 Iter { inner: Item { opt: self.as_ref() } }
1153 /// Returns a mutable iterator over the possibly contained value.
1158 /// let mut x = Some(4);
1159 /// match x.iter_mut().next() {
1160 /// Some(v) => *v = 42,
1163 /// assert_eq!(x, Some(42));
1165 /// let mut x: Option<u32> = None;
1166 /// assert_eq!(x.iter_mut().next(), None);
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1171 IterMut { inner: Item { opt: self.as_mut() } }
1174 /////////////////////////////////////////////////////////////////////////
1175 // Boolean operations on the values, eager and lazy
1176 /////////////////////////////////////////////////////////////////////////
1178 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
1183 /// let x = Some(2);
1184 /// let y: Option<&str> = None;
1185 /// assert_eq!(x.and(y), None);
1187 /// let x: Option<u32> = None;
1188 /// let y = Some("foo");
1189 /// assert_eq!(x.and(y), None);
1191 /// let x = Some(2);
1192 /// let y = Some("foo");
1193 /// assert_eq!(x.and(y), Some("foo"));
1195 /// let x: Option<u32> = None;
1196 /// let y: Option<&str> = None;
1197 /// assert_eq!(x.and(y), None);
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1202 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1203 pub const fn and<U>(self, optb: Option<U>) -> Option<U>
1205 T: ~const Drop + ~const Destruct,
1206 U: ~const Drop + ~const Destruct,
1214 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
1215 /// wrapped value and returns the result.
1217 /// Some languages call this operation flatmap.
1222 /// fn sq_then_to_string(x: u32) -> Option<String> {
1223 /// x.checked_mul(x).map(|sq| sq.to_string())
1226 /// assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string()));
1227 /// assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed!
1228 /// assert_eq!(None.and_then(sq_then_to_string), None);
1231 /// Often used to chain fallible operations that may return [`None`].
1234 /// let arr_2d = [["A0", "A1"], ["B0", "B1"]];
1236 /// let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1));
1237 /// assert_eq!(item_0_1, Some(&"A1"));
1239 /// let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0));
1240 /// assert_eq!(item_2_0, None);
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1245 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1246 pub const fn and_then<U, F>(self, f: F) -> Option<U>
1248 F: ~const FnOnce(T) -> Option<U>,
1249 F: ~const Drop + ~const Destruct,
1257 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
1258 /// with the wrapped value and returns:
1260 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
1262 /// - [`None`] if `predicate` returns `false`.
1264 /// This function works similar to [`Iterator::filter()`]. You can imagine
1265 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
1266 /// lets you decide which elements to keep.
1271 /// fn is_even(n: &i32) -> bool {
1275 /// assert_eq!(None.filter(is_even), None);
1276 /// assert_eq!(Some(3).filter(is_even), None);
1277 /// assert_eq!(Some(4).filter(is_even), Some(4));
1280 /// [`Some(t)`]: Some
1282 #[stable(feature = "option_filter", since = "1.27.0")]
1283 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1284 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1285 pub const fn filter<P>(self, predicate: P) -> Self
1287 T: ~const Drop + ~const Destruct,
1288 P: ~const FnOnce(&T) -> bool,
1289 P: ~const Drop + ~const Destruct,
1291 if let Some(x) = self {
1299 /// Returns the option if it contains a value, otherwise returns `optb`.
1301 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
1302 /// result of a function call, it is recommended to use [`or_else`], which is
1303 /// lazily evaluated.
1305 /// [`or_else`]: Option::or_else
1310 /// let x = Some(2);
1312 /// assert_eq!(x.or(y), Some(2));
1315 /// let y = Some(100);
1316 /// assert_eq!(x.or(y), Some(100));
1318 /// let x = Some(2);
1319 /// let y = Some(100);
1320 /// assert_eq!(x.or(y), Some(2));
1322 /// let x: Option<u32> = None;
1324 /// assert_eq!(x.or(y), None);
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1329 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1330 pub const fn or(self, optb: Option<T>) -> Option<T>
1332 T: ~const Drop + ~const Destruct,
1340 /// Returns the option if it contains a value, otherwise calls `f` and
1341 /// returns the result.
1346 /// fn nobody() -> Option<&'static str> { None }
1347 /// fn vikings() -> Option<&'static str> { Some("vikings") }
1349 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1350 /// assert_eq!(None.or_else(vikings), Some("vikings"));
1351 /// assert_eq!(None.or_else(nobody), None);
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1356 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1357 pub const fn or_else<F>(self, f: F) -> Option<T>
1359 F: ~const FnOnce() -> Option<T>,
1360 F: ~const Drop + ~const Destruct,
1368 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1373 /// let x = Some(2);
1374 /// let y: Option<u32> = None;
1375 /// assert_eq!(x.xor(y), Some(2));
1377 /// let x: Option<u32> = None;
1378 /// let y = Some(2);
1379 /// assert_eq!(x.xor(y), Some(2));
1381 /// let x = Some(2);
1382 /// let y = Some(2);
1383 /// assert_eq!(x.xor(y), None);
1385 /// let x: Option<u32> = None;
1386 /// let y: Option<u32> = None;
1387 /// assert_eq!(x.xor(y), None);
1390 #[stable(feature = "option_xor", since = "1.37.0")]
1391 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1392 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1393 pub const fn xor(self, optb: Option<T>) -> Option<T>
1395 T: ~const Drop + ~const Destruct,
1397 match (self, optb) {
1398 (Some(a), None) => Some(a),
1399 (None, Some(b)) => Some(b),
1404 /////////////////////////////////////////////////////////////////////////
1405 // Entry-like operations to insert a value and return a reference
1406 /////////////////////////////////////////////////////////////////////////
1408 /// Inserts `value` into the option, then returns a mutable reference to it.
1410 /// If the option already contains a value, the old value is dropped.
1412 /// See also [`Option::get_or_insert`], which doesn't update the value if
1413 /// the option already contains [`Some`].
1418 /// let mut opt = None;
1419 /// let val = opt.insert(1);
1420 /// assert_eq!(*val, 1);
1421 /// assert_eq!(opt.unwrap(), 1);
1422 /// let val = opt.insert(2);
1423 /// assert_eq!(*val, 2);
1425 /// assert_eq!(opt.unwrap(), 3);
1427 #[must_use = "if you intended to set a value, consider assignment instead"]
1429 #[stable(feature = "option_insert", since = "1.53.0")]
1430 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1431 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1432 pub const fn insert(&mut self, value: T) -> &mut T
1434 T: ~const Drop + ~const Destruct,
1436 *self = Some(value);
1438 // SAFETY: the code above just filled the option
1439 unsafe { self.as_mut().unwrap_unchecked() }
1442 /// Inserts `value` into the option if it is [`None`], then
1443 /// returns a mutable reference to the contained value.
1445 /// See also [`Option::insert`], which updates the value even if
1446 /// the option already contains [`Some`].
1451 /// let mut x = None;
1454 /// let y: &mut u32 = x.get_or_insert(5);
1455 /// assert_eq!(y, &5);
1460 /// assert_eq!(x, Some(7));
1463 #[stable(feature = "option_entry", since = "1.20.0")]
1464 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1465 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1466 pub const fn get_or_insert(&mut self, value: T) -> &mut T
1468 T: ~const Drop + ~const Destruct,
1470 if let None = *self {
1471 *self = Some(value);
1474 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1475 // variant in the code above.
1476 unsafe { self.as_mut().unwrap_unchecked() }
1479 /// Inserts the default value into the option if it is [`None`], then
1480 /// returns a mutable reference to the contained value.
1485 /// #![feature(option_get_or_insert_default)]
1487 /// let mut x = None;
1490 /// let y: &mut u32 = x.get_or_insert_default();
1491 /// assert_eq!(y, &0);
1496 /// assert_eq!(x, Some(7));
1499 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1500 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1501 pub const fn get_or_insert_default(&mut self) -> &mut T
1505 #[rustc_allow_const_fn_unstable(const_fn_trait_bound)]
1506 const fn default<T: ~const Default>() -> T {
1510 self.get_or_insert_with(default)
1513 /// Inserts a value computed from `f` into the option if it is [`None`],
1514 /// then returns a mutable reference to the contained value.
1519 /// let mut x = None;
1522 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
1523 /// assert_eq!(y, &5);
1528 /// assert_eq!(x, Some(7));
1531 #[stable(feature = "option_entry", since = "1.20.0")]
1532 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1533 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1534 pub const fn get_or_insert_with<F>(&mut self, f: F) -> &mut T
1536 F: ~const FnOnce() -> T,
1537 F: ~const Drop + ~const Destruct,
1539 if let None = *self {
1540 // the compiler isn't smart enough to know that we are not dropping a `T`
1541 // here and wants us to ensure `T` can be dropped at compile time.
1542 mem::forget(mem::replace(self, Some(f())))
1545 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1546 // variant in the code above.
1547 unsafe { self.as_mut().unwrap_unchecked() }
1550 /////////////////////////////////////////////////////////////////////////
1552 /////////////////////////////////////////////////////////////////////////
1554 /// Takes the value out of the option, leaving a [`None`] in its place.
1559 /// let mut x = Some(2);
1560 /// let y = x.take();
1561 /// assert_eq!(x, None);
1562 /// assert_eq!(y, Some(2));
1564 /// let mut x: Option<u32> = None;
1565 /// let y = x.take();
1566 /// assert_eq!(x, None);
1567 /// assert_eq!(y, None);
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1572 pub const fn take(&mut self) -> Option<T> {
1573 // FIXME replace `mem::replace` by `mem::take` when the latter is const ready
1574 mem::replace(self, None)
1577 /// Replaces the actual value in the option by the value given in parameter,
1578 /// returning the old value if present,
1579 /// leaving a [`Some`] in its place without deinitializing either one.
1584 /// let mut x = Some(2);
1585 /// let old = x.replace(5);
1586 /// assert_eq!(x, Some(5));
1587 /// assert_eq!(old, Some(2));
1589 /// let mut x = None;
1590 /// let old = x.replace(3);
1591 /// assert_eq!(x, Some(3));
1592 /// assert_eq!(old, None);
1595 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1596 #[stable(feature = "option_replace", since = "1.31.0")]
1597 pub const fn replace(&mut self, value: T) -> Option<T> {
1598 mem::replace(self, Some(value))
1601 /// Returns `true` if the option is a [`Some`] value containing the given value.
1606 /// #![feature(option_result_contains)]
1608 /// let x: Option<u32> = Some(2);
1609 /// assert_eq!(x.contains(&2), true);
1611 /// let x: Option<u32> = Some(3);
1612 /// assert_eq!(x.contains(&2), false);
1614 /// let x: Option<u32> = None;
1615 /// assert_eq!(x.contains(&2), false);
1619 #[unstable(feature = "option_result_contains", issue = "62358")]
1620 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1621 pub const fn contains<U>(&self, x: &U) -> bool
1623 U: ~const PartialEq<T>,
1631 /// Zips `self` with another `Option`.
1633 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1634 /// Otherwise, `None` is returned.
1639 /// let x = Some(1);
1640 /// let y = Some("hi");
1641 /// let z = None::<u8>;
1643 /// assert_eq!(x.zip(y), Some((1, "hi")));
1644 /// assert_eq!(x.zip(z), None);
1646 #[stable(feature = "option_zip_option", since = "1.46.0")]
1647 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1648 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1649 pub const fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
1651 T: ~const Drop + ~const Destruct,
1652 U: ~const Drop + ~const Destruct,
1654 match (self, other) {
1655 (Some(a), Some(b)) => Some((a, b)),
1660 /// Zips `self` and another `Option` with function `f`.
1662 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1663 /// Otherwise, `None` is returned.
1668 /// #![feature(option_zip)]
1670 /// #[derive(Debug, PartialEq)]
1677 /// fn new(x: f64, y: f64) -> Self {
1682 /// let x = Some(17.5);
1683 /// let y = Some(42.7);
1685 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1686 /// assert_eq!(x.zip_with(None, Point::new), None);
1688 #[unstable(feature = "option_zip", issue = "70086")]
1689 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1690 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1691 pub const fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1693 F: ~const FnOnce(T, U) -> R,
1694 F: ~const Drop + ~const Destruct,
1695 T: ~const Drop + ~const Destruct,
1696 U: ~const Drop + ~const Destruct,
1698 match (self, other) {
1699 (Some(a), Some(b)) => Some(f(a, b)),
1705 impl<T, U> Option<(T, U)> {
1706 /// Unzips an option containing a tuple of two options.
1708 /// If `self` is `Some((a, b))` this method returns `(Some(a), Some(b))`.
1709 /// Otherwise, `(None, None)` is returned.
1714 /// #![feature(unzip_option)]
1716 /// let x = Some((1, "hi"));
1717 /// let y = None::<(u8, u32)>;
1719 /// assert_eq!(x.unzip(), (Some(1), Some("hi")));
1720 /// assert_eq!(y.unzip(), (None, None));
1723 #[unstable(feature = "unzip_option", issue = "87800", reason = "recently added")]
1724 pub const fn unzip(self) -> (Option<T>, Option<U>) {
1726 Some((a, b)) => (Some(a), Some(b)),
1727 None => (None, None),
1732 impl<T> Option<&T> {
1733 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1740 /// let opt_x = Some(&x);
1741 /// assert_eq!(opt_x, Some(&12));
1742 /// let copied = opt_x.copied();
1743 /// assert_eq!(copied, Some(12));
1745 #[must_use = "`self` will be dropped if the result is not used"]
1746 #[stable(feature = "copied", since = "1.35.0")]
1747 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1748 pub const fn copied(self) -> Option<T>
1752 // FIXME: this implementation, which sidesteps using `Option::map` since it's not const
1753 // ready yet, should be reverted when possible to avoid code repetition
1755 Some(&v) => Some(v),
1760 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1767 /// let opt_x = Some(&x);
1768 /// assert_eq!(opt_x, Some(&12));
1769 /// let cloned = opt_x.cloned();
1770 /// assert_eq!(cloned, Some(12));
1772 #[must_use = "`self` will be dropped if the result is not used"]
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")]
1775 pub const fn cloned(self) -> Option<T>
1780 Some(t) => Some(t.clone()),
1786 impl<T> Option<&mut T> {
1787 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1794 /// let opt_x = Some(&mut x);
1795 /// assert_eq!(opt_x, Some(&mut 12));
1796 /// let copied = opt_x.copied();
1797 /// assert_eq!(copied, Some(12));
1799 #[must_use = "`self` will be dropped if the result is not used"]
1800 #[stable(feature = "copied", since = "1.35.0")]
1801 #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")]
1802 pub const fn copied(self) -> Option<T>
1807 Some(&mut t) => Some(t),
1812 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1819 /// let opt_x = Some(&mut x);
1820 /// assert_eq!(opt_x, Some(&mut 12));
1821 /// let cloned = opt_x.cloned();
1822 /// assert_eq!(cloned, Some(12));
1824 #[must_use = "`self` will be dropped if the result is not used"]
1825 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1826 #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")]
1827 pub const fn cloned(self) -> Option<T>
1832 Some(t) => Some(t.clone()),
1838 impl<T, E> Option<Result<T, E>> {
1839 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1841 /// [`None`] will be mapped to <code>[Ok]\([None])</code>.
1842 /// <code>[Some]\([Ok]\(\_))</code> and <code>[Some]\([Err]\(\_))</code> will be mapped to
1843 /// <code>[Ok]\([Some]\(\_))</code> and <code>[Err]\(\_)</code>.
1848 /// #[derive(Debug, Eq, PartialEq)]
1851 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1852 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1853 /// assert_eq!(x, y.transpose());
1856 #[stable(feature = "transpose_result", since = "1.33.0")]
1857 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1858 pub const fn transpose(self) -> Result<Option<T>, E> {
1860 Some(Ok(x)) => Ok(Some(x)),
1861 Some(Err(e)) => Err(e),
1867 // This is a separate function to reduce the code size of .expect() itself.
1868 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
1869 #[cfg_attr(feature = "panic_immediate_abort", inline)]
1872 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1873 const fn expect_failed(msg: &str) -> ! {
1877 /////////////////////////////////////////////////////////////////////////////
1878 // Trait implementations
1879 /////////////////////////////////////////////////////////////////////////////
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 #[rustc_const_unstable(feature = "const_clone", issue = "91805")]
1883 #[cfg_attr(not(bootstrap), allow(drop_bounds))] // FIXME remove `~const Drop` and this attr when bumping
1884 impl<T> const Clone for Option<T>
1886 T: ~const Clone + ~const Drop + ~const Destruct,
1889 fn clone(&self) -> Self {
1891 Some(x) => Some(x.clone()),
1897 fn clone_from(&mut self, source: &Self) {
1898 match (self, source) {
1899 (Some(to), Some(from)) => to.clone_from(from),
1900 (to, from) => *to = from.clone(),
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1907 impl<T> const Default for Option<T> {
1908 /// Returns [`None`][Option::None].
1913 /// let opt: Option<u32> = Option::default();
1914 /// assert!(opt.is_none());
1917 fn default() -> Option<T> {
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<T> IntoIterator for Option<T> {
1925 type IntoIter = IntoIter<T>;
1927 /// Returns a consuming iterator over the possibly contained value.
1932 /// let x = Some("string");
1933 /// let v: Vec<&str> = x.into_iter().collect();
1934 /// assert_eq!(v, ["string"]);
1937 /// let v: Vec<&str> = x.into_iter().collect();
1938 /// assert!(v.is_empty());
1941 fn into_iter(self) -> IntoIter<T> {
1942 IntoIter { inner: Item { opt: self } }
1946 #[stable(since = "1.4.0", feature = "option_iter")]
1947 impl<'a, T> IntoIterator for &'a Option<T> {
1949 type IntoIter = Iter<'a, T>;
1951 fn into_iter(self) -> Iter<'a, T> {
1956 #[stable(since = "1.4.0", feature = "option_iter")]
1957 impl<'a, T> IntoIterator for &'a mut Option<T> {
1958 type Item = &'a mut T;
1959 type IntoIter = IterMut<'a, T>;
1961 fn into_iter(self) -> IterMut<'a, T> {
1966 #[stable(since = "1.12.0", feature = "option_from")]
1967 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1968 impl<T> const From<T> for Option<T> {
1969 /// Moves `val` into a new [`Some`].
1974 /// let o: Option<u8> = Option::from(67);
1976 /// assert_eq!(Some(67), o);
1978 fn from(val: T) -> Option<T> {
1983 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1984 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1985 impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
1986 /// Converts from `&Option<T>` to `Option<&T>`.
1990 /// Converts an <code>[Option]<[String]></code> into an <code>[Option]<[usize]></code>, preserving
1991 /// the original. The [`map`] method takes the `self` argument by value, consuming the original,
1992 /// so this technique uses `from` to first take an [`Option`] to a reference
1993 /// to the value inside the original.
1995 /// [`map`]: Option::map
1996 /// [String]: ../../std/string/struct.String.html "String"
1999 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
2000 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
2002 /// println!("Can still print s: {s:?}");
2004 /// assert_eq!(o, Some(18));
2006 fn from(o: &'a Option<T>) -> Option<&'a T> {
2011 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
2012 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2013 impl<'a, T> const From<&'a mut Option<T>> for Option<&'a mut T> {
2014 /// Converts from `&mut Option<T>` to `Option<&mut T>`
2019 /// let mut s = Some(String::from("Hello"));
2020 /// let o: Option<&mut String> = Option::from(&mut s);
2023 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
2027 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
2029 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
2034 /////////////////////////////////////////////////////////////////////////////
2035 // The Option Iterators
2036 /////////////////////////////////////////////////////////////////////////////
2038 #[derive(Clone, Debug)]
2043 impl<A> Iterator for Item<A> {
2047 fn next(&mut self) -> Option<A> {
2052 fn size_hint(&self) -> (usize, Option<usize>) {
2054 Some(_) => (1, Some(1)),
2055 None => (0, Some(0)),
2060 impl<A> DoubleEndedIterator for Item<A> {
2062 fn next_back(&mut self) -> Option<A> {
2067 impl<A> ExactSizeIterator for Item<A> {}
2068 impl<A> FusedIterator for Item<A> {}
2069 unsafe impl<A> TrustedLen for Item<A> {}
2071 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
2073 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2075 /// This `struct` is created by the [`Option::iter`] function.
2076 #[stable(feature = "rust1", since = "1.0.0")]
2078 pub struct Iter<'a, A: 'a> {
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<'a, A> Iterator for Iter<'a, A> {
2087 fn next(&mut self) -> Option<&'a A> {
2091 fn size_hint(&self) -> (usize, Option<usize>) {
2092 self.inner.size_hint()
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
2099 fn next_back(&mut self) -> Option<&'a A> {
2100 self.inner.next_back()
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 impl<A> ExactSizeIterator for Iter<'_, A> {}
2107 #[stable(feature = "fused", since = "1.26.0")]
2108 impl<A> FusedIterator for Iter<'_, A> {}
2110 #[unstable(feature = "trusted_len", issue = "37572")]
2111 unsafe impl<A> TrustedLen for Iter<'_, A> {}
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl<A> Clone for Iter<'_, A> {
2116 fn clone(&self) -> Self {
2117 Iter { inner: self.inner.clone() }
2121 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
2123 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2125 /// This `struct` is created by the [`Option::iter_mut`] function.
2126 #[stable(feature = "rust1", since = "1.0.0")]
2128 pub struct IterMut<'a, A: 'a> {
2129 inner: Item<&'a mut A>,
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 impl<'a, A> Iterator for IterMut<'a, A> {
2134 type Item = &'a mut A;
2137 fn next(&mut self) -> Option<&'a mut A> {
2141 fn size_hint(&self) -> (usize, Option<usize>) {
2142 self.inner.size_hint()
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
2149 fn next_back(&mut self) -> Option<&'a mut A> {
2150 self.inner.next_back()
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl<A> ExactSizeIterator for IterMut<'_, A> {}
2157 #[stable(feature = "fused", since = "1.26.0")]
2158 impl<A> FusedIterator for IterMut<'_, A> {}
2159 #[unstable(feature = "trusted_len", issue = "37572")]
2160 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
2162 /// An iterator over the value in [`Some`] variant of an [`Option`].
2164 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
2166 /// This `struct` is created by the [`Option::into_iter`] function.
2167 #[derive(Clone, Debug)]
2168 #[stable(feature = "rust1", since = "1.0.0")]
2169 pub struct IntoIter<A> {
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 impl<A> Iterator for IntoIter<A> {
2178 fn next(&mut self) -> Option<A> {
2182 fn size_hint(&self) -> (usize, Option<usize>) {
2183 self.inner.size_hint()
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 impl<A> DoubleEndedIterator for IntoIter<A> {
2190 fn next_back(&mut self) -> Option<A> {
2191 self.inner.next_back()
2195 #[stable(feature = "rust1", since = "1.0.0")]
2196 impl<A> ExactSizeIterator for IntoIter<A> {}
2198 #[stable(feature = "fused", since = "1.26.0")]
2199 impl<A> FusedIterator for IntoIter<A> {}
2201 #[unstable(feature = "trusted_len", issue = "37572")]
2202 unsafe impl<A> TrustedLen for IntoIter<A> {}
2204 /////////////////////////////////////////////////////////////////////////////
2206 /////////////////////////////////////////////////////////////////////////////
2208 #[stable(feature = "rust1", since = "1.0.0")]
2209 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
2210 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
2211 /// no further elements are taken, and the [`None`][Option::None] is
2212 /// returned. Should no [`None`][Option::None] occur, a container of type
2213 /// `V` containing the values of each [`Option`] is returned.
2217 /// Here is an example which increments every integer in a vector.
2218 /// We use the checked variant of `add` that returns `None` when the
2219 /// calculation would result in an overflow.
2222 /// let items = vec![0_u16, 1, 2];
2224 /// let res: Option<Vec<u16>> = items
2226 /// .map(|x| x.checked_add(1))
2229 /// assert_eq!(res, Some(vec![1, 2, 3]));
2232 /// As you can see, this will return the expected, valid items.
2234 /// Here is another example that tries to subtract one from another list
2235 /// of integers, this time checking for underflow:
2238 /// let items = vec![2_u16, 1, 0];
2240 /// let res: Option<Vec<u16>> = items
2242 /// .map(|x| x.checked_sub(1))
2245 /// assert_eq!(res, None);
2248 /// Since the last element is zero, it would underflow. Thus, the resulting
2249 /// value is `None`.
2251 /// Here is a variation on the previous example, showing that no
2252 /// further elements are taken from `iter` after the first `None`.
2255 /// let items = vec![3_u16, 2, 1, 10];
2257 /// let mut shared = 0;
2259 /// let res: Option<Vec<u16>> = items
2261 /// .map(|x| { shared += x; x.checked_sub(2) })
2264 /// assert_eq!(res, None);
2265 /// assert_eq!(shared, 6);
2268 /// Since the third element caused an underflow, no further elements were taken,
2269 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
2271 fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
2272 // FIXME(#11084): This could be replaced with Iterator::scan when this
2273 // performance bug is closed.
2275 iter::try_process(iter.into_iter(), |i| i.collect())
2279 #[unstable(feature = "try_trait_v2", issue = "84277")]
2280 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2281 impl<T> const ops::Try for Option<T> {
2283 type Residual = Option<convert::Infallible>;
2286 fn from_output(output: Self::Output) -> Self {
2291 fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
2293 Some(v) => ControlFlow::Continue(v),
2294 None => ControlFlow::Break(None),
2299 #[unstable(feature = "try_trait_v2", issue = "84277")]
2300 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
2301 impl<T> const ops::FromResidual for Option<T> {
2303 fn from_residual(residual: Option<convert::Infallible>) -> Self {
2310 #[unstable(feature = "try_trait_v2_residual", issue = "91285")]
2311 impl<T> ops::Residual<T> for Option<convert::Infallible> {
2312 type TryType = Option<T>;
2315 impl<T> Option<Option<T>> {
2316 /// Converts from `Option<Option<T>>` to `Option<T>`.
2323 /// let x: Option<Option<u32>> = Some(Some(6));
2324 /// assert_eq!(Some(6), x.flatten());
2326 /// let x: Option<Option<u32>> = Some(None);
2327 /// assert_eq!(None, x.flatten());
2329 /// let x: Option<Option<u32>> = None;
2330 /// assert_eq!(None, x.flatten());
2333 /// Flattening only removes one level of nesting at a time:
2336 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
2337 /// assert_eq!(Some(Some(6)), x.flatten());
2338 /// assert_eq!(Some(6), x.flatten().flatten());
2341 #[stable(feature = "option_flattening", since = "1.40.0")]
2342 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
2343 pub const fn flatten(self) -> Option<T> {
2345 Some(inner) => inner,