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, [`Option`]`<`[`Box<T>`]`>`.
52 //! The following example uses [`Option`] to create an optional box of
53 //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the
54 //! `check_optional` function needs to use pattern matching to
55 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
59 //! let optional = None;
60 //! check_optional(optional);
62 //! let optional = Some(Box::new(9000));
63 //! check_optional(optional);
65 //! fn check_optional(optional: Option<Box<i32>>) {
67 //! Some(p) => println!("has value {}", p),
68 //! None => println!("has no value"),
75 //! Rust guarantees to optimize the following types `T` such that
76 //! [`Option<T>`] has the same size as `T`:
81 //! * `fn`, `extern "C" fn`
82 //! * [`num::NonZero*`]
83 //! * [`ptr::NonNull<U>`]
84 //! * `#[repr(transparent)]` struct around one of the types in this list.
86 //! It is further guaranteed that, for the cases above, one can
87 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
88 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
89 //! is undefined behaviour).
93 //! Basic pattern matching on [`Option`]:
96 //! let msg = Some("howdy");
98 //! // Take a reference to the contained string
99 //! if let Some(m) = &msg {
100 //! println!("{}", *m);
103 //! // Remove the contained string, destroying the Option
104 //! let unwrapped_msg = msg.unwrap_or("default message");
107 //! Initialize a result to [`None`] before a loop:
110 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
112 //! // A list of data to search through.
113 //! let all_the_big_things = [
114 //! Kingdom::Plant(250, "redwood"),
115 //! Kingdom::Plant(230, "noble fir"),
116 //! Kingdom::Plant(229, "sugar pine"),
117 //! Kingdom::Animal(25, "blue whale"),
118 //! Kingdom::Animal(19, "fin whale"),
119 //! Kingdom::Animal(15, "north pacific right whale"),
122 //! // We're going to search for the name of the biggest animal,
123 //! // but to start with we've just got `None`.
124 //! let mut name_of_biggest_animal = None;
125 //! let mut size_of_biggest_animal = 0;
126 //! for big_thing in &all_the_big_things {
127 //! match *big_thing {
128 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
129 //! // Now we've found the name of some big animal
130 //! size_of_biggest_animal = size;
131 //! name_of_biggest_animal = Some(name);
133 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
137 //! match name_of_biggest_animal {
138 //! Some(name) => println!("the biggest animal is {}", name),
139 //! None => println!("there are no animals :("),
143 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
144 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
145 //! [`num::NonZero*`]: crate::num
146 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
148 #![stable(feature = "rust1", since = "1.0.0")]
150 use crate::iter
::{FromIterator, FusedIterator, TrustedLen}
;
154 ops
::{self, Deref, DerefMut}
,
157 /// The `Option` type. See [the module level documentation](self) for more.
158 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
159 #[rustc_diagnostic_item = "option_type"]
160 #[stable(feature = "rust1", since = "1.0.0")]
164 #[stable(feature = "rust1", since = "1.0.0")]
168 #[stable(feature = "rust1", since = "1.0.0")]
169 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
172 /////////////////////////////////////////////////////////////////////////////
173 // Type implementation
174 /////////////////////////////////////////////////////////////////////////////
177 /////////////////////////////////////////////////////////////////////////
178 // Querying the contained values
179 /////////////////////////////////////////////////////////////////////////
181 /// Returns `true` if the option is a [`Some`] value.
186 /// let x: Option<u32> = Some(2);
187 /// assert_eq!(x.is_some(), true);
189 /// let x: Option<u32> = None;
190 /// assert_eq!(x.is_some(), false);
192 #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
194 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
195 #[stable(feature = "rust1", since = "1.0.0")]
196 pub const fn is_some(&self) -> bool
{
197 matches
!(*self, Some(_
))
200 /// Returns `true` if the option is a [`None`] value.
205 /// let x: Option<u32> = Some(2);
206 /// assert_eq!(x.is_none(), false);
208 /// let x: Option<u32> = None;
209 /// assert_eq!(x.is_none(), true);
211 #[must_use = "if you intended to assert that this doesn't have a value, consider \
212 `.and_then(|| panic!(\"`Option` had a value when expected `None`\"))` instead"]
214 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
215 #[stable(feature = "rust1", since = "1.0.0")]
216 pub const fn is_none(&self) -> bool
{
220 /// Returns `true` if the option is a [`Some`] value containing the given value.
225 /// #![feature(option_result_contains)]
227 /// let x: Option<u32> = Some(2);
228 /// assert_eq!(x.contains(&2), true);
230 /// let x: Option<u32> = Some(3);
231 /// assert_eq!(x.contains(&2), false);
233 /// let x: Option<u32> = None;
234 /// assert_eq!(x.contains(&2), false);
238 #[unstable(feature = "option_result_contains", issue = "62358")]
239 pub fn contains
<U
>(&self, x
: &U
) -> bool
249 /////////////////////////////////////////////////////////////////////////
250 // Adapter for working with references
251 /////////////////////////////////////////////////////////////////////////
253 /// Converts from `&Option<T>` to `Option<&T>`.
257 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
258 /// The [`map`] method takes the `self` argument by value, consuming the original,
259 /// so this technique uses `as_ref` to first take an `Option` to a reference
260 /// to the value inside the original.
262 /// [`map`]: Option::map
263 /// [`String`]: ../../std/string/struct.String.html
266 /// let text: Option<String> = Some("Hello, world!".to_string());
267 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
268 /// // then consume *that* with `map`, leaving `text` on the stack.
269 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
270 /// println!("still can print text: {:?}", text);
273 #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
274 #[stable(feature = "rust1", since = "1.0.0")]
275 pub const fn as_ref(&self) -> Option
<&T
> {
277 Some(ref x
) => Some(x
),
282 /// Converts from `&mut Option<T>` to `Option<&mut T>`.
287 /// let mut x = Some(2);
288 /// match x.as_mut() {
289 /// Some(v) => *v = 42,
292 /// assert_eq!(x, Some(42));
295 #[stable(feature = "rust1", since = "1.0.0")]
296 pub fn as_mut(&mut self) -> Option
<&mut T
> {
298 Some(ref mut x
) => Some(x
),
303 /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
305 #[stable(feature = "pin", since = "1.33.0")]
306 pub fn as_pin_ref(self: Pin
<&Self>) -> Option
<Pin
<&T
>> {
307 // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
309 unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
312 /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
314 #[stable(feature = "pin", since = "1.33.0")]
315 pub fn as_pin_mut(self: Pin
<&mut Self>) -> Option
<Pin
<&mut T
>> {
316 // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
317 // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
318 unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
321 /////////////////////////////////////////////////////////////////////////
322 // Getting to contained values
323 /////////////////////////////////////////////////////////////////////////
325 /// Returns the contained [`Some`] value, consuming the `self` value.
329 /// Panics if the value is a [`None`] with a custom panic message provided by
335 /// let x = Some("value");
336 /// assert_eq!(x.expect("fruits are healthy"), "value");
340 /// let x: Option<&str> = None;
341 /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
345 #[stable(feature = "rust1", since = "1.0.0")]
346 pub fn expect(self, msg
: &str) -> T
{
349 None
=> expect_failed(msg
),
353 /// Returns the contained [`Some`] value, consuming the `self` value.
355 /// Because this function may panic, its use is generally discouraged.
356 /// Instead, prefer to use pattern matching and handle the [`None`]
357 /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
358 /// [`unwrap_or_default`].
360 /// [`unwrap_or`]: Option::unwrap_or
361 /// [`unwrap_or_else`]: Option::unwrap_or_else
362 /// [`unwrap_or_default`]: Option::unwrap_or_default
366 /// Panics if the self value equals [`None`].
371 /// let x = Some("air");
372 /// assert_eq!(x.unwrap(), "air");
376 /// let x: Option<&str> = None;
377 /// assert_eq!(x.unwrap(), "air"); // fails
381 #[stable(feature = "rust1", since = "1.0.0")]
382 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
383 pub const fn unwrap(self) -> T
{
386 None
=> panic
!("called `Option::unwrap()` on a `None` value"),
390 /// Returns the contained [`Some`] value or a provided default.
392 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
393 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
394 /// which is lazily evaluated.
396 /// [`unwrap_or_else`]: Option::unwrap_or_else
401 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
402 /// assert_eq!(None.unwrap_or("bike"), "bike");
405 #[stable(feature = "rust1", since = "1.0.0")]
406 pub fn unwrap_or(self, default: T
) -> T
{
413 /// Returns the contained [`Some`] value or computes it from a closure.
419 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
420 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn unwrap_or_else
<F
: FnOnce() -> T
>(self, f
: F
) -> T
{
431 /// Returns the contained [`Some`] value, consuming the `self` value,
432 /// without checking that the value is not [`None`].
436 /// Calling this method on [`None`] is *[undefined behavior]*.
438 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
443 /// #![feature(option_result_unwrap_unchecked)]
444 /// let x = Some("air");
445 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
449 /// #![feature(option_result_unwrap_unchecked)]
450 /// let x: Option<&str> = None;
451 /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
455 #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
456 pub unsafe fn unwrap_unchecked(self) -> T
{
457 debug_assert
!(self.is_some());
460 // SAFETY: the safety contract must be upheld by the caller.
461 None
=> unsafe { hint::unreachable_unchecked() }
,
465 /////////////////////////////////////////////////////////////////////////
466 // Transforming contained values
467 /////////////////////////////////////////////////////////////////////////
469 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
473 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
475 /// [`String`]: ../../std/string/struct.String.html
477 /// let maybe_some_string = Some(String::from("Hello, World!"));
478 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
479 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
481 /// assert_eq!(maybe_some_len, Some(13));
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn map
<U
, F
: FnOnce(T
) -> U
>(self, f
: F
) -> Option
<U
> {
487 Some(x
) => Some(f(x
)),
492 /// Applies a function to the contained value (if any),
493 /// or returns the provided default (if not).
495 /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
496 /// the result of a function call, it is recommended to use [`map_or_else`],
497 /// which is lazily evaluated.
499 /// [`map_or_else`]: Option::map_or_else
504 /// let x = Some("foo");
505 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
507 /// let x: Option<&str> = None;
508 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
511 #[stable(feature = "rust1", since = "1.0.0")]
512 pub fn map_or
<U
, F
: FnOnce(T
) -> U
>(self, default: U
, f
: F
) -> U
{
519 /// Applies a function to the contained value (if any),
520 /// or computes a default (if not).
527 /// let x = Some("foo");
528 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
530 /// let x: Option<&str> = None;
531 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn map_or_else
<U
, D
: FnOnce() -> U
, F
: FnOnce(T
) -> U
>(self, default: D
, f
: F
) -> U
{
542 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
543 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
545 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
546 /// result of a function call, it is recommended to use [`ok_or_else`], which is
547 /// lazily evaluated.
550 /// [`Err(err)`]: Err
551 /// [`Some(v)`]: Some
552 /// [`ok_or_else`]: Option::ok_or_else
557 /// let x = Some("foo");
558 /// assert_eq!(x.ok_or(0), Ok("foo"));
560 /// let x: Option<&str> = None;
561 /// assert_eq!(x.ok_or(0), Err(0));
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn ok_or
<E
>(self, err
: E
) -> Result
<T
, E
> {
572 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
573 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
576 /// [`Err(err())`]: Err
577 /// [`Some(v)`]: Some
582 /// let x = Some("foo");
583 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
585 /// let x: Option<&str> = None;
586 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn ok_or_else
<E
, F
: FnOnce() -> E
>(self, err
: F
) -> Result
<T
, E
> {
597 /// Inserts `value` into the option then returns a mutable reference to it.
599 /// If the option already contains a value, the old value is dropped.
604 /// #![feature(option_insert)]
606 /// let mut opt = None;
607 /// let val = opt.insert(1);
608 /// assert_eq!(*val, 1);
609 /// assert_eq!(opt.unwrap(), 1);
610 /// let val = opt.insert(2);
611 /// assert_eq!(*val, 2);
613 /// assert_eq!(opt.unwrap(), 3);
616 #[unstable(feature = "option_insert", reason = "newly added", issue = "78271")]
617 pub fn insert(&mut self, value
: T
) -> &mut T
{
622 // SAFETY: the code above just filled the option
623 None
=> unsafe { hint::unreachable_unchecked() }
,
627 /////////////////////////////////////////////////////////////////////////
628 // Iterator constructors
629 /////////////////////////////////////////////////////////////////////////
631 /// Returns an iterator over the possibly contained value.
637 /// assert_eq!(x.iter().next(), Some(&4));
639 /// let x: Option<u32> = None;
640 /// assert_eq!(x.iter().next(), None);
643 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub const fn iter(&self) -> Iter
<'_
, T
> {
646 Iter { inner: Item { opt: self.as_ref() }
}
649 /// Returns a mutable iterator over the possibly contained value.
654 /// let mut x = Some(4);
655 /// match x.iter_mut().next() {
656 /// Some(v) => *v = 42,
659 /// assert_eq!(x, Some(42));
661 /// let mut x: Option<u32> = None;
662 /// assert_eq!(x.iter_mut().next(), None);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn iter_mut(&mut self) -> IterMut
<'_
, T
> {
667 IterMut { inner: Item { opt: self.as_mut() }
}
670 /////////////////////////////////////////////////////////////////////////
671 // Boolean operations on the values, eager and lazy
672 /////////////////////////////////////////////////////////////////////////
674 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
680 /// let y: Option<&str> = None;
681 /// assert_eq!(x.and(y), None);
683 /// let x: Option<u32> = None;
684 /// let y = Some("foo");
685 /// assert_eq!(x.and(y), None);
688 /// let y = Some("foo");
689 /// assert_eq!(x.and(y), Some("foo"));
691 /// let x: Option<u32> = None;
692 /// let y: Option<&str> = None;
693 /// assert_eq!(x.and(y), None);
696 #[stable(feature = "rust1", since = "1.0.0")]
697 pub fn and
<U
>(self, optb
: Option
<U
>) -> Option
<U
> {
704 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
705 /// wrapped value and returns the result.
707 /// Some languages call this operation flatmap.
712 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
713 /// fn nope(_: u32) -> Option<u32> { None }
715 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
716 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
717 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
718 /// assert_eq!(None.and_then(sq).and_then(sq), None);
721 #[stable(feature = "rust1", since = "1.0.0")]
722 pub fn and_then
<U
, F
: FnOnce(T
) -> Option
<U
>>(self, f
: F
) -> Option
<U
> {
729 /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
730 /// with the wrapped value and returns:
732 /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
734 /// - [`None`] if `predicate` returns `false`.
736 /// This function works similar to [`Iterator::filter()`]. You can imagine
737 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
738 /// lets you decide which elements to keep.
743 /// fn is_even(n: &i32) -> bool {
747 /// assert_eq!(None.filter(is_even), None);
748 /// assert_eq!(Some(3).filter(is_even), None);
749 /// assert_eq!(Some(4).filter(is_even), Some(4));
752 /// [`Some(t)`]: Some
754 #[stable(feature = "option_filter", since = "1.27.0")]
755 pub fn filter
<P
: FnOnce(&T
) -> bool
>(self, predicate
: P
) -> Self {
756 if let Some(x
) = self {
764 /// Returns the option if it contains a value, otherwise returns `optb`.
766 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
767 /// result of a function call, it is recommended to use [`or_else`], which is
768 /// lazily evaluated.
770 /// [`or_else`]: Option::or_else
777 /// assert_eq!(x.or(y), Some(2));
780 /// let y = Some(100);
781 /// assert_eq!(x.or(y), Some(100));
784 /// let y = Some(100);
785 /// assert_eq!(x.or(y), Some(2));
787 /// let x: Option<u32> = None;
789 /// assert_eq!(x.or(y), None);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub fn or(self, optb
: Option
<T
>) -> Option
<T
> {
800 /// Returns the option if it contains a value, otherwise calls `f` and
801 /// returns the result.
806 /// fn nobody() -> Option<&'static str> { None }
807 /// fn vikings() -> Option<&'static str> { Some("vikings") }
809 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
810 /// assert_eq!(None.or_else(vikings), Some("vikings"));
811 /// assert_eq!(None.or_else(nobody), None);
814 #[stable(feature = "rust1", since = "1.0.0")]
815 pub fn or_else
<F
: FnOnce() -> Option
<T
>>(self, f
: F
) -> Option
<T
> {
822 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
828 /// let y: Option<u32> = None;
829 /// assert_eq!(x.xor(y), Some(2));
831 /// let x: Option<u32> = None;
833 /// assert_eq!(x.xor(y), Some(2));
837 /// assert_eq!(x.xor(y), None);
839 /// let x: Option<u32> = None;
840 /// let y: Option<u32> = None;
841 /// assert_eq!(x.xor(y), None);
844 #[stable(feature = "option_xor", since = "1.37.0")]
845 pub fn xor(self, optb
: Option
<T
>) -> Option
<T
> {
847 (Some(a
), None
) => Some(a
),
848 (None
, Some(b
)) => Some(b
),
853 /////////////////////////////////////////////////////////////////////////
854 // Entry-like operations to insert if None and return a reference
855 /////////////////////////////////////////////////////////////////////////
857 /// Inserts `value` into the option if it is [`None`], then
858 /// returns a mutable reference to the contained value.
863 /// let mut x = None;
866 /// let y: &mut u32 = x.get_or_insert(5);
867 /// assert_eq!(y, &5);
872 /// assert_eq!(x, Some(7));
875 #[stable(feature = "option_entry", since = "1.20.0")]
876 pub fn get_or_insert(&mut self, value
: T
) -> &mut T
{
877 self.get_or_insert_with(|| value
)
880 /// Inserts the default value into the option if it is [`None`], then
881 /// returns a mutable reference to the contained value.
886 /// #![feature(option_get_or_insert_default)]
888 /// let mut x = None;
891 /// let y: &mut u32 = x.get_or_insert_default();
892 /// assert_eq!(y, &0);
897 /// assert_eq!(x, Some(7));
900 #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
901 pub fn get_or_insert_default(&mut self) -> &mut T
905 self.get_or_insert_with(Default
::default)
908 /// Inserts a value computed from `f` into the option if it is [`None`],
909 /// then returns a mutable reference to the contained value.
914 /// let mut x = None;
917 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
918 /// assert_eq!(y, &5);
923 /// assert_eq!(x, Some(7));
926 #[stable(feature = "option_entry", since = "1.20.0")]
927 pub fn get_or_insert_with
<F
: FnOnce() -> T
>(&mut self, f
: F
) -> &mut T
{
928 if let None
= *self {
934 // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
935 // variant in the code above.
936 None
=> unsafe { hint::unreachable_unchecked() }
,
940 /////////////////////////////////////////////////////////////////////////
942 /////////////////////////////////////////////////////////////////////////
944 /// Takes the value out of the option, leaving a [`None`] in its place.
949 /// let mut x = Some(2);
950 /// let y = x.take();
951 /// assert_eq!(x, None);
952 /// assert_eq!(y, Some(2));
954 /// let mut x: Option<u32> = None;
955 /// let y = x.take();
956 /// assert_eq!(x, None);
957 /// assert_eq!(y, None);
960 #[stable(feature = "rust1", since = "1.0.0")]
961 pub fn take(&mut self) -> Option
<T
> {
965 /// Replaces the actual value in the option by the value given in parameter,
966 /// returning the old value if present,
967 /// leaving a [`Some`] in its place without deinitializing either one.
972 /// let mut x = Some(2);
973 /// let old = x.replace(5);
974 /// assert_eq!(x, Some(5));
975 /// assert_eq!(old, Some(2));
977 /// let mut x = None;
978 /// let old = x.replace(3);
979 /// assert_eq!(x, Some(3));
980 /// assert_eq!(old, None);
983 #[stable(feature = "option_replace", since = "1.31.0")]
984 pub fn replace(&mut self, value
: T
) -> Option
<T
> {
985 mem
::replace(self, Some(value
))
988 /// Zips `self` with another `Option`.
990 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
991 /// Otherwise, `None` is returned.
997 /// let y = Some("hi");
998 /// let z = None::<u8>;
1000 /// assert_eq!(x.zip(y), Some((1, "hi")));
1001 /// assert_eq!(x.zip(z), None);
1003 #[stable(feature = "option_zip_option", since = "1.46.0")]
1004 pub fn zip
<U
>(self, other
: Option
<U
>) -> Option
<(T
, U
)> {
1005 match (self, other
) {
1006 (Some(a
), Some(b
)) => Some((a
, b
)),
1011 /// Zips `self` and another `Option` with function `f`.
1013 /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1014 /// Otherwise, `None` is returned.
1019 /// #![feature(option_zip)]
1021 /// #[derive(Debug, PartialEq)]
1028 /// fn new(x: f64, y: f64) -> Self {
1033 /// let x = Some(17.5);
1034 /// let y = Some(42.7);
1036 /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1037 /// assert_eq!(x.zip_with(None, Point::new), None);
1039 #[unstable(feature = "option_zip", issue = "70086")]
1040 pub fn zip_with
<U
, F
, R
>(self, other
: Option
<U
>, f
: F
) -> Option
<R
>
1042 F
: FnOnce(T
, U
) -> R
,
1044 Some(f(self?
, other?
))
1048 impl<T
: Copy
> Option
<&T
> {
1049 /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1056 /// let opt_x = Some(&x);
1057 /// assert_eq!(opt_x, Some(&12));
1058 /// let copied = opt_x.copied();
1059 /// assert_eq!(copied, Some(12));
1061 #[stable(feature = "copied", since = "1.35.0")]
1062 pub fn copied(self) -> Option
<T
> {
1067 impl<T
: Copy
> Option
<&mut T
> {
1068 /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1075 /// let opt_x = Some(&mut x);
1076 /// assert_eq!(opt_x, Some(&mut 12));
1077 /// let copied = opt_x.copied();
1078 /// assert_eq!(copied, Some(12));
1080 #[stable(feature = "copied", since = "1.35.0")]
1081 pub fn copied(self) -> Option
<T
> {
1082 self.map(|&mut t
| t
)
1086 impl<T
: Clone
> Option
<&T
> {
1087 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1094 /// let opt_x = Some(&x);
1095 /// assert_eq!(opt_x, Some(&12));
1096 /// let cloned = opt_x.cloned();
1097 /// assert_eq!(cloned, Some(12));
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 pub fn cloned(self) -> Option
<T
> {
1101 self.map(|t
| t
.clone())
1105 impl<T
: Clone
> Option
<&mut T
> {
1106 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1113 /// let opt_x = Some(&mut x);
1114 /// assert_eq!(opt_x, Some(&mut 12));
1115 /// let cloned = opt_x.cloned();
1116 /// assert_eq!(cloned, Some(12));
1118 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1119 pub fn cloned(self) -> Option
<T
> {
1120 self.map(|t
| t
.clone())
1124 impl<T
: fmt
::Debug
> Option
<T
> {
1125 /// Consumes `self` while expecting [`None`] and returning nothing.
1129 /// Panics if the value is a [`Some`], with a panic message including the
1130 /// passed message, and the content of the [`Some`].
1135 /// #![feature(option_expect_none)]
1137 /// use std::collections::HashMap;
1138 /// let mut squares = HashMap::new();
1139 /// for i in -10..=10 {
1140 /// // This will not panic, since all keys are unique.
1141 /// squares.insert(i, i * i).expect_none("duplicate key");
1146 /// #![feature(option_expect_none)]
1148 /// use std::collections::HashMap;
1149 /// let mut sqrts = HashMap::new();
1150 /// for i in -10..=10 {
1151 /// // This will panic, since both negative and positive `i` will
1152 /// // insert the same `i * i` key, returning the old `Some(i)`.
1153 /// sqrts.insert(i * i, i).expect_none("duplicate key");
1158 #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1159 pub fn expect_none(self, msg
: &str) {
1160 if let Some(val
) = self {
1161 expect_none_failed(msg
, &val
);
1165 /// Consumes `self` while expecting [`None`] and returning nothing.
1169 /// Panics if the value is a [`Some`], with a custom panic message provided
1170 /// by the [`Some`]'s value.
1172 /// [`Some(v)`]: Some
1177 /// #![feature(option_unwrap_none)]
1179 /// use std::collections::HashMap;
1180 /// let mut squares = HashMap::new();
1181 /// for i in -10..=10 {
1182 /// // This will not panic, since all keys are unique.
1183 /// squares.insert(i, i * i).unwrap_none();
1188 /// #![feature(option_unwrap_none)]
1190 /// use std::collections::HashMap;
1191 /// let mut sqrts = HashMap::new();
1192 /// for i in -10..=10 {
1193 /// // This will panic, since both negative and positive `i` will
1194 /// // insert the same `i * i` key, returning the old `Some(i)`.
1195 /// sqrts.insert(i * i, i).unwrap_none();
1200 #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1201 pub fn unwrap_none(self) {
1202 if let Some(val
) = self {
1203 expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val
);
1208 impl<T
: Default
> Option
<T
> {
1209 /// Returns the contained [`Some`] value or a default
1211 /// Consumes the `self` argument then, if [`Some`], returns the contained
1212 /// value, otherwise if [`None`], returns the [default value] for that
1217 /// Converts a string to an integer, turning poorly-formed strings
1218 /// into 0 (the default value for integers). [`parse`] converts
1219 /// a string to any other type that implements [`FromStr`], returning
1220 /// [`None`] on error.
1223 /// let good_year_from_input = "1909";
1224 /// let bad_year_from_input = "190blarg";
1225 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1226 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1228 /// assert_eq!(1909, good_year);
1229 /// assert_eq!(0, bad_year);
1232 /// [default value]: Default::default
1233 /// [`parse`]: str::parse
1234 /// [`FromStr`]: crate::str::FromStr
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn unwrap_or_default(self) -> T
{
1240 None
=> Default
::default(),
1245 impl<T
: Deref
> Option
<T
> {
1246 /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1248 /// Leaves the original Option in-place, creating a new one with a reference
1249 /// to the original one, additionally coercing the contents via [`Deref`].
1254 /// let x: Option<String> = Some("hey".to_owned());
1255 /// assert_eq!(x.as_deref(), Some("hey"));
1257 /// let x: Option<String> = None;
1258 /// assert_eq!(x.as_deref(), None);
1260 #[stable(feature = "option_deref", since = "1.40.0")]
1261 pub fn as_deref(&self) -> Option
<&T
::Target
> {
1262 self.as_ref().map(|t
| t
.deref())
1266 impl<T
: DerefMut
> Option
<T
> {
1267 /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1269 /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1270 /// the inner type's `Deref::Target` type.
1275 /// let mut x: Option<String> = Some("hey".to_owned());
1276 /// assert_eq!(x.as_deref_mut().map(|x| {
1277 /// x.make_ascii_uppercase();
1279 /// }), Some("HEY".to_owned().as_mut_str()));
1281 #[stable(feature = "option_deref", since = "1.40.0")]
1282 pub fn as_deref_mut(&mut self) -> Option
<&mut T
::Target
> {
1283 self.as_mut().map(|t
| t
.deref_mut())
1287 impl<T
, E
> Option
<Result
<T
, E
>> {
1288 /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1290 /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1291 /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1292 /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1297 /// #[derive(Debug, Eq, PartialEq)]
1300 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1301 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1302 /// assert_eq!(x, y.transpose());
1305 #[stable(feature = "transpose_result", since = "1.33.0")]
1306 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1307 pub const fn transpose(self) -> Result
<Option
<T
>, E
> {
1309 Some(Ok(x
)) => Ok(Some(x
)),
1310 Some(Err(e
)) => Err(e
),
1316 // This is a separate function to reduce the code size of .expect() itself.
1320 fn expect_failed(msg
: &str) -> ! {
1324 // This is a separate function to reduce the code size of .expect_none() itself.
1328 fn expect_none_failed(msg
: &str, value
: &dyn fmt
::Debug
) -> ! {
1329 panic
!("{}: {:?}", msg
, value
)
1332 /////////////////////////////////////////////////////////////////////////////
1333 // Trait implementations
1334 /////////////////////////////////////////////////////////////////////////////
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<T
: Clone
> Clone
for Option
<T
> {
1339 fn clone(&self) -> Self {
1341 Some(x
) => Some(x
.clone()),
1347 fn clone_from(&mut self, source
: &Self) {
1348 match (self, source
) {
1349 (Some(to
), Some(from
)) => to
.clone_from(from
),
1350 (to
, from
) => *to
= from
.clone(),
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<T
> Default
for Option
<T
> {
1357 /// Returns [`None`][Option::None].
1362 /// let opt: Option<u32> = Option::default();
1363 /// assert!(opt.is_none());
1366 fn default() -> Option
<T
> {
1371 #[stable(feature = "rust1", since = "1.0.0")]
1372 impl<T
> IntoIterator
for Option
<T
> {
1374 type IntoIter
= IntoIter
<T
>;
1376 /// Returns a consuming iterator over the possibly contained value.
1381 /// let x = Some("string");
1382 /// let v: Vec<&str> = x.into_iter().collect();
1383 /// assert_eq!(v, ["string"]);
1386 /// let v: Vec<&str> = x.into_iter().collect();
1387 /// assert!(v.is_empty());
1390 fn into_iter(self) -> IntoIter
<T
> {
1391 IntoIter { inner: Item { opt: self }
}
1395 #[stable(since = "1.4.0", feature = "option_iter")]
1396 impl<'a
, T
> IntoIterator
for &'a Option
<T
> {
1398 type IntoIter
= Iter
<'a
, T
>;
1400 fn into_iter(self) -> Iter
<'a
, T
> {
1405 #[stable(since = "1.4.0", feature = "option_iter")]
1406 impl<'a
, T
> IntoIterator
for &'a
mut Option
<T
> {
1407 type Item
= &'a
mut T
;
1408 type IntoIter
= IterMut
<'a
, T
>;
1410 fn into_iter(self) -> IterMut
<'a
, T
> {
1415 #[stable(since = "1.12.0", feature = "option_from")]
1416 impl<T
> From
<T
> for Option
<T
> {
1417 /// Copies `val` into a new `Some`.
1422 /// let o: Option<u8> = Option::from(67);
1424 /// assert_eq!(Some(67), o);
1426 fn from(val
: T
) -> Option
<T
> {
1431 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1432 impl<'a
, T
> From
<&'a Option
<T
>> for Option
<&'a T
> {
1433 /// Converts from `&Option<T>` to `Option<&T>`.
1437 /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1438 /// The [`map`] method takes the `self` argument by value, consuming the original,
1439 /// so this technique uses `as_ref` to first take an `Option` to a reference
1440 /// to the value inside the original.
1442 /// [`map`]: Option::map
1443 /// [`String`]: ../../std/string/struct.String.html
1446 /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1447 /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1449 /// println!("Can still print s: {:?}", s);
1451 /// assert_eq!(o, Some(18));
1453 fn from(o
: &'a Option
<T
>) -> Option
<&'a T
> {
1458 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1459 impl<'a
, T
> From
<&'a
mut Option
<T
>> for Option
<&'a
mut T
> {
1460 /// Converts from `&mut Option<T>` to `Option<&mut T>`
1465 /// let mut s = Some(String::from("Hello"));
1466 /// let o: Option<&mut String> = Option::from(&mut s);
1469 /// Some(t) => *t = String::from("Hello, Rustaceans!"),
1473 /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1475 fn from(o
: &'a
mut Option
<T
>) -> Option
<&'a
mut T
> {
1480 /////////////////////////////////////////////////////////////////////////////
1481 // The Option Iterators
1482 /////////////////////////////////////////////////////////////////////////////
1484 #[derive(Clone, Debug)]
1489 impl<A
> Iterator
for Item
<A
> {
1493 fn next(&mut self) -> Option
<A
> {
1498 fn size_hint(&self) -> (usize, Option
<usize>) {
1500 Some(_
) => (1, Some(1)),
1501 None
=> (0, Some(0)),
1506 impl<A
> DoubleEndedIterator
for Item
<A
> {
1508 fn next_back(&mut self) -> Option
<A
> {
1513 impl<A
> ExactSizeIterator
for Item
<A
> {}
1514 impl<A
> FusedIterator
for Item
<A
> {}
1515 unsafe impl<A
> TrustedLen
for Item
<A
> {}
1517 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1519 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1521 /// This `struct` is created by the [`Option::iter`] function.
1522 #[stable(feature = "rust1", since = "1.0.0")]
1524 pub struct Iter
<'a
, A
: 'a
> {
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 impl<'a
, A
> Iterator
for Iter
<'a
, A
> {
1533 fn next(&mut self) -> Option
<&'a A
> {
1537 fn size_hint(&self) -> (usize, Option
<usize>) {
1538 self.inner
.size_hint()
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl<'a
, A
> DoubleEndedIterator
for Iter
<'a
, A
> {
1545 fn next_back(&mut self) -> Option
<&'a A
> {
1546 self.inner
.next_back()
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl<A
> ExactSizeIterator
for Iter
<'_
, A
> {}
1553 #[stable(feature = "fused", since = "1.26.0")]
1554 impl<A
> FusedIterator
for Iter
<'_
, A
> {}
1556 #[unstable(feature = "trusted_len", issue = "37572")]
1557 unsafe impl<A
> TrustedLen
for Iter
<'_
, A
> {}
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<A
> Clone
for Iter
<'_
, A
> {
1562 fn clone(&self) -> Self {
1563 Iter { inner: self.inner.clone() }
1567 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1569 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1571 /// This `struct` is created by the [`Option::iter_mut`] function.
1572 #[stable(feature = "rust1", since = "1.0.0")]
1574 pub struct IterMut
<'a
, A
: 'a
> {
1575 inner
: Item
<&'a
mut A
>,
1578 #[stable(feature = "rust1", since = "1.0.0")]
1579 impl<'a
, A
> Iterator
for IterMut
<'a
, A
> {
1580 type Item
= &'a
mut A
;
1583 fn next(&mut self) -> Option
<&'a
mut A
> {
1587 fn size_hint(&self) -> (usize, Option
<usize>) {
1588 self.inner
.size_hint()
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<'a
, A
> DoubleEndedIterator
for IterMut
<'a
, A
> {
1595 fn next_back(&mut self) -> Option
<&'a
mut A
> {
1596 self.inner
.next_back()
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<A
> ExactSizeIterator
for IterMut
<'_
, A
> {}
1603 #[stable(feature = "fused", since = "1.26.0")]
1604 impl<A
> FusedIterator
for IterMut
<'_
, A
> {}
1605 #[unstable(feature = "trusted_len", issue = "37572")]
1606 unsafe impl<A
> TrustedLen
for IterMut
<'_
, A
> {}
1608 /// An iterator over the value in [`Some`] variant of an [`Option`].
1610 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1612 /// This `struct` is created by the [`Option::into_iter`] function.
1613 #[derive(Clone, Debug)]
1614 #[stable(feature = "rust1", since = "1.0.0")]
1615 pub struct IntoIter
<A
> {
1619 #[stable(feature = "rust1", since = "1.0.0")]
1620 impl<A
> Iterator
for IntoIter
<A
> {
1624 fn next(&mut self) -> Option
<A
> {
1628 fn size_hint(&self) -> (usize, Option
<usize>) {
1629 self.inner
.size_hint()
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<A
> DoubleEndedIterator
for IntoIter
<A
> {
1636 fn next_back(&mut self) -> Option
<A
> {
1637 self.inner
.next_back()
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl<A
> ExactSizeIterator
for IntoIter
<A
> {}
1644 #[stable(feature = "fused", since = "1.26.0")]
1645 impl<A
> FusedIterator
for IntoIter
<A
> {}
1647 #[unstable(feature = "trusted_len", issue = "37572")]
1648 unsafe impl<A
> TrustedLen
for IntoIter
<A
> {}
1650 /////////////////////////////////////////////////////////////////////////////
1652 /////////////////////////////////////////////////////////////////////////////
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl<A
, V
: FromIterator
<A
>> FromIterator
<Option
<A
>> for Option
<V
> {
1656 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1657 /// no further elements are taken, and the [`None`][Option::None] is
1658 /// returned. Should no [`None`][Option::None] occur, a container with the
1659 /// values of each [`Option`] is returned.
1663 /// Here is an example which increments every integer in a vector.
1664 /// We use the checked variant of `add` that returns `None` when the
1665 /// calculation would result in an overflow.
1668 /// let items = vec![0_u16, 1, 2];
1670 /// let res: Option<Vec<u16>> = items
1672 /// .map(|x| x.checked_add(1))
1675 /// assert_eq!(res, Some(vec![1, 2, 3]));
1678 /// As you can see, this will return the expected, valid items.
1680 /// Here is another example that tries to subtract one from another list
1681 /// of integers, this time checking for underflow:
1684 /// let items = vec![2_u16, 1, 0];
1686 /// let res: Option<Vec<u16>> = items
1688 /// .map(|x| x.checked_sub(1))
1691 /// assert_eq!(res, None);
1694 /// Since the last element is zero, it would underflow. Thus, the resulting
1695 /// value is `None`.
1697 /// Here is a variation on the previous example, showing that no
1698 /// further elements are taken from `iter` after the first `None`.
1701 /// let items = vec![3_u16, 2, 1, 10];
1703 /// let mut shared = 0;
1705 /// let res: Option<Vec<u16>> = items
1707 /// .map(|x| { shared += x; x.checked_sub(2) })
1710 /// assert_eq!(res, None);
1711 /// assert_eq!(shared, 6);
1714 /// Since the third element caused an underflow, no further elements were taken,
1715 /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1717 fn from_iter
<I
: IntoIterator
<Item
= Option
<A
>>>(iter
: I
) -> Option
<V
> {
1718 // FIXME(#11084): This could be replaced with Iterator::scan when this
1719 // performance bug is closed.
1721 iter
.into_iter().map(|x
| x
.ok_or(())).collect
::<Result
<_
, _
>>().ok()
1725 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1726 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1727 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1728 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1729 #[rustc_diagnostic_item = "none_error"]
1730 #[unstable(feature = "try_trait", issue = "42327")]
1731 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1732 pub struct NoneError
;
1734 #[unstable(feature = "try_trait", issue = "42327")]
1735 impl<T
> ops
::Try
for Option
<T
> {
1737 type Error
= NoneError
;
1740 fn into_result(self) -> Result
<T
, NoneError
> {
1741 self.ok_or(NoneError
)
1745 fn from_ok(v
: T
) -> Self {
1750 fn from_error(_
: NoneError
) -> Self {
1755 impl<T
> Option
<Option
<T
>> {
1756 /// Converts from `Option<Option<T>>` to `Option<T>`
1763 /// let x: Option<Option<u32>> = Some(Some(6));
1764 /// assert_eq!(Some(6), x.flatten());
1766 /// let x: Option<Option<u32>> = Some(None);
1767 /// assert_eq!(None, x.flatten());
1769 /// let x: Option<Option<u32>> = None;
1770 /// assert_eq!(None, x.flatten());
1773 /// Flattening only removes one level of nesting at a time:
1776 /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1777 /// assert_eq!(Some(Some(6)), x.flatten());
1778 /// assert_eq!(Some(6), x.flatten().flatten());
1781 #[stable(feature = "option_flattening", since = "1.40.0")]
1782 #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1783 pub const fn flatten(self) -> Option
<T
> {
1785 Some(inner
) => inner
,