]> git.lizzy.rs Git - rust.git/blob - library/core/src/option.rs
add modify-in-place methods to option overview
[rust.git] / library / core / src / option.rs
1 //! Optional values.
2 //!
3 //! Type [`Option`] represents an optional value: every [`Option`]
4 //! is either [`Some`] and contains a value, or [`None`], and
5 //! does not. [`Option`] types are very common in Rust code, as
6 //! they have a number of uses:
7 //!
8 //! * Initial values
9 //! * Return values for functions that are not defined
10 //!   over their entire input range (partial functions)
11 //! * Return value for otherwise reporting simple errors, where [`None`] is
12 //!   returned on error
13 //! * Optional struct fields
14 //! * Struct fields that can be loaned or "taken"
15 //! * Optional function arguments
16 //! * Nullable pointers
17 //! * Swapping things out of difficult situations
18 //!
19 //! [`Option`]s are commonly paired with pattern matching to query the presence
20 //! of a value and take action, always accounting for the [`None`] case.
21 //!
22 //! ```
23 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
24 //!     if denominator == 0.0 {
25 //!         None
26 //!     } else {
27 //!         Some(numerator / denominator)
28 //!     }
29 //! }
30 //!
31 //! // The return value of the function is an option
32 //! let result = divide(2.0, 3.0);
33 //!
34 //! // Pattern match to retrieve the value
35 //! match result {
36 //!     // The division was valid
37 //!     Some(x) => println!("Result: {}", x),
38 //!     // The division was invalid
39 //!     None    => println!("Cannot divide by 0"),
40 //! }
41 //! ```
42 //!
43 //
44 // FIXME: Show how `Option` is used in practice, with lots of methods
45 //
46 //! # Options and pointers ("nullable" pointers)
47 //!
48 //! Rust's pointer types must always point to a valid location; there are
49 //! no "null" references. Instead, Rust has *optional* pointers, like
50 //! the optional owned box, [`Option`]`<`[`Box<T>`]`>`.
51 //!
52 //! The following example uses [`Option`] to create an optional box of
53 //! [`i32`]. Notice that in order to use the inner [`i32`] value, the
54 //! `check_optional` function first needs to use pattern matching to
55 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
56 //! not ([`None`]).
57 //!
58 //! ```
59 //! let optional = None;
60 //! check_optional(optional);
61 //!
62 //! let optional = Some(Box::new(9000));
63 //! check_optional(optional);
64 //!
65 //! fn check_optional(optional: Option<Box<i32>>) {
66 //!     match optional {
67 //!         Some(p) => println!("has value {}", p),
68 //!         None => println!("has no value"),
69 //!     }
70 //! }
71 //! ```
72 //!
73 //! # Representation
74 //!
75 //! Rust guarantees to optimize the following types `T` such that
76 //! [`Option<T>`] has the same size as `T`:
77 //!
78 //! * [`Box<U>`]
79 //! * `&U`
80 //! * `&mut U`
81 //! * `fn`, `extern "C" fn`
82 //! * [`num::NonZero*`]
83 //! * [`ptr::NonNull<U>`]
84 //! * `#[repr(transparent)]` struct around one of the types in this list.
85 //!
86 //! This is called the "null pointer optimization" or NPO.
87 //!
88 //! It is further guaranteed that, for the cases above, one can
89 //! [`mem::transmute`] from all valid values of `T` to `Option<T>` and
90 //! from `Some::<T>(_)` to `T` (but transmuting `None::<T>` to `T`
91 //! is undefined behaviour).
92 //!
93 //! # Method overview
94 //!
95 //! In addition to working with pattern matching, [`Option`] provides a wide
96 //! variety of different methods.
97 //!
98 //! ## Querying the variant
99 //!
100 //! The [`is_some`] and [`is_none`] methods return [`true`] if the [`Option`]
101 //! is [`Some`] or [`None`], respectively.
102 //!
103 //! [`is_some`]: Option::is_some
104 //! [`is_none`]: Option::is_none
105 //!
106 //! ## Adapters for working with references
107 //!
108 //! * [`as_ref`] converts from `&Option<T>` to `Option<&T>`
109 //! * [`as_mut`] converts from `&mut Option<T>` to `Option<&mut T>`
110 //! * [`as_deref`] converts from `&Option<T>` to `Option<&T::Target>`
111 //! * [`as_deref_mut`] converts from `&mut Option<T>` to `Option<&mut T::Target>`
112 //! * [`as_pin_ref`] converts from [`&Pin`]`<Option<T>>` to `Option<`[`Pin`]`<&T>>`
113 //! * [`as_pin_mut`] converts from [`&mut Pin`]`<Option<T>>` to `Option<`[`Pin`]`<&mut T>>`
114 //!
115 //! [`&mut Pin`]: crate::pin::Pin
116 //! [`&Pin`]: crate::pin::Pin
117 //! [`as_deref`]: Option::as_deref
118 //! [`as_deref_mut`]: Option::as_deref_mut
119 //! [`as_mut`]: Option::as_mut
120 //! [`as_pin_ref`]: Option::as_pin_ref
121 //! [`as_pin_mut`]: Option::as_pin_mut
122 //! [`as_ref`]: Option::as_ref
123 //! [`Pin`]: crate::pin::Pin
124 //!
125 //! ## Extracting the contained value
126 //!
127 //! These methods extract the contained value in an [`Option`] when it is
128 //! the [`Some`] variant. If the [`Option`] is [`None`]:
129 //!
130 //! * [`expect`] panics with a provided custom message
131 //! * [`unwrap`] panics with a generic message
132 //! * [`unwrap_or`] returns the provided default value
133 //! * [`unwrap_or_default`] returns the default value of the type `T`
134 //!   (which must implement the [`Default`] trait)
135 //! * [`unwrap_or_else`] evaluates a provided function
136 //!
137 //! [`Default`]: crate::default::Default
138 //! [`expect`]: Option::expect
139 //! [`unwrap`]: Option::unwrap
140 //! [`unwrap_or`]: Option::unwrap_or
141 //! [`unwrap_or_default`]: Option::unwrap_or_default
142 //! [`unwrap_or_else`]: Option::unwrap_or_else
143 //!
144 //! ## Transforming contained values
145 //!
146 //! * [`flatten`] removes one level of nesting from an
147 //!   [`Option<Option<T>>`]
148 //! * [`map`] transforms [`Some<T>`] to [`Some<U>`] using the provided
149 //!   function
150 //! * [`map_or`] transforms [`Some<T>`] to a value of `U` using the
151 //!   provided function, or transforms [`None`] to a provided default value
152 //!   of `U`
153 //! * [`map_or_else`] transforms [`Some<T>`] to a value of `U` using the
154 //!   provided function, or transforms [`None`] to a value of `U` using
155 //!   another provided function
156 //! * [`ok_or`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
157 //!   [`Err(err)`] using the provided default `err` value
158 //! * [`ok_or_else`] transforms [`Some(v)`] to [`Ok(v)`], and [`None`] to
159 //!   a value of [`Err<E>`] using the provided function
160 //! * [`transpose`] transposes an [`Option`] of a [`Result`] into a
161 //!   [`Result`] of an [`Option`]
162 //!
163 //! [`Err(err)`]: Err
164 //! [`flatten`]: Option::flatten
165 //! [`map`]: Option::map
166 //! [`map_or`]: Option::map_or
167 //! [`map_or_else`]: Option::map_or_else
168 //! [`Ok(v)`]: Ok
169 //! [`ok_or`]: Option::ok_or
170 //! [`ok_or_else`]: Option::ok_or_else
171 //! [`Some(v)`]: Some
172 //! [`transpose`]: Option::transpose
173 //!
174 //! ## Boolean operators
175 //!
176 //! These methods treat the [`Option`] as a boolean value, where [`Some`]
177 //! acts like [`true`] and [`None`] acts like [`false`]. There are two
178 //! categories of these methods: ones that take an [`Option`] as input, and
179 //! ones that take a function as input (to be lazily evaluated).
180 //!
181 //! The [`and`], [`or`], and [`xor`] methods take another [`Option`] as
182 //! input, and produce an [`Option`] as output. Only the [`and`] method can
183 //! produce an [`Option<U>`] value having a different inner type `U` than
184 //! [`Option<T>`].
185 //!
186 //! | method  | self      | input     | output    |
187 //! |---------|-----------|-----------|-----------|
188 //! | [`and`] | `None`    | (ignored) | `None`    |
189 //! | [`and`] | `Some(x)` | `None`    | `None`    |
190 //! | [`and`] | `Some(x)` | `Some(y)` | `Some(y)` |
191 //! | [`or`]  | `None`    | `None`    | `None`    |
192 //! | [`or`]  | `None`    | `Some(y)` | `Some(y)` |
193 //! | [`or`]  | `Some(x)` | (ignored) | `Some(x)` |
194 //! | [`xor`] | `None`    | `None`    | `None`    |
195 //! | [`xor`] | `None`    | `Some(y)` | `Some(y)` |
196 //! | [`xor`] | `Some(x)` | `None`    | `Some(x)` |
197 //! | [`xor`] | `Some(x)` | `Some(y)` | `None`    |
198 //!
199 //! The [`and_then`], [`filter`], and [`or_else`] methods take a function
200 //! as input, and only evaluate the function when they need to produce a
201 //! new value. [`and_then`] and [`or_else`] take a function that produces
202 //! another [`Option`] value, while [`filter`] takes a predicate that is
203 //! used to decide whether to pass the [`Some`] value through. Only the
204 //! [`and_then`] method can produce an [`Option<U>`] value having a
205 //! different inner type `U` than [`Option<T>`].
206 //!
207 //! | method       | self      | function input | function result | output    |
208 //! |--------------|-----------|----------------|-----------------|-----------|
209 //! | [`and_then`] | `None`    | (not provided) | (not evaluated) | `None`    |
210 //! | [`and_then`] | `Some(x)` | `x`            | `None`          | `None`    |
211 //! | [`and_then`] | `Some(x)` | `x`            | `Some(y)`       | `Some(y)` |
212 //! | [`filter`]   | `None`    | (not provided) | (not evaluated) | `None`    |
213 //! | [`filter`]   | `Some(x)` | `x`            | `false`         | `None`    |
214 //! | [`filter`]   | `Some(x)` | `x`            | `true`          | `Some(x)` |
215 //! | [`or_else`]  | `None`    | (not provided) | `None`          | `None`    |
216 //! | [`or_else`]  | `None`    | (not provided) | `Some(y)`       | `Some(y)` |
217 //! | [`or_else`]  | `Some(x)` | (not provided) | (not evaluated) | `Some(x)` |
218 //!
219 //! [`and`]: Option::and
220 //! [`and_then`]: Option::and_then
221 //! [`filter`]: Option::filter
222 //! [`or`]: Option::or
223 //! [`or_else`]: Option::or_else
224 //! [`xor`]: Option::xor
225 //!
226 //! ## Iterators
227 //!
228 //! An [`Option`] can be iterated over. This can be helpful if you need an
229 //! iterator that is conditionally empty. The iterator will either produce
230 //! a single value (when the [`Option`] is [`Some`]), or produce no values
231 //! (when the [`Option`] is [`None`]). For example, [`into_iter`] acts like
232 //! [`once(v)`] if the [`Option`] is [`Some(v)`], and like [`empty()`] if
233 //! the [`Option`] is [`None`].
234 //!
235 //! Iterators over [`Option`] come in three types:
236 //!
237 //! * [`into_iter`] consumes the [`Option`] and produces the contained
238 //!   value
239 //! * [`iter`] produces an immutable reference of type `&T` to the
240 //!   contained value
241 //! * [`iter_mut`] produces a mutable reference of type `&mut T` to the
242 //!   contained value
243 //!
244 //! [`Option`] implements the [`FromIterator`] trait, which allows an
245 //! iterator over [`Option`] values to be collected into an [`Option`] of a
246 //! collection of each contained value of the original [`Option`] values,
247 //! or [`None`] if any of the elements was [`None`].
248 //!
249 //! [`empty()`]: crate::iter::empty
250 //! [`FromIterator`]: Option#impl-FromIterator%3COption%3CA%3E%3E
251 //! [`into_iter`]: Option::into_iter
252 //! [`iter`]: Option::iter
253 //! [`iter_mut`]: Option::iter_mut
254 //! [`once(v)`]: crate::iter::once
255 //! [`Some(v)`]: Some
256 //!
257 //! An iterator over [`Option`] can be useful when chaining iterators:
258 //!
259 //! ```
260 //! let yep = Some(42);
261 //! let nope = None;
262 //! let nums: Vec<i32> = (0..4).chain(yep.into_iter()).chain(4..8).collect();
263 //! assert_eq!(nums, [0, 1, 2, 3, 42, 4, 5, 6, 7]);
264 //! let nums: Vec<i32> = (0..4).chain(nope.into_iter()).chain(4..8).collect();
265 //! assert_eq!(nums, [0, 1, 2, 3, 4, 5, 6, 7]);
266 //! ```
267 //!
268 //! One reason to chain iterators in this way is that a function returning
269 //! `impl Iterator` must have all possible return values be of the same
270 //! concrete type. Chaining an iterated [`Option`] can help with that.
271 //!
272 //! ```
273 //! let yep = Some(42);
274 //! let nope = None;
275 //!
276 //! fn make_iter(opt: Option<i32>) -> impl Iterator<Item = i32> {
277 //!     (0..4).chain(opt.into_iter()).chain(4..8)
278 //! }
279 //! println!("{:?}", make_iter(yep).collect::<Vec<_>>());
280 //! println!("{:?}", make_iter(nope).collect::<Vec<_>>());
281 //! ```
282 //!
283 //! If we try to do the same thing, but using pattern matching, we can't
284 //! return `impl Iterator` anymore because the concrete types of the return
285 //! values differ.
286 //!
287 //! ```compile_fail,E0308
288 //! # use std::iter::{empty, once};
289 //! // This won't compile because all possible returns from the function
290 //! // must have the same concrete type.
291 //! fn make_iter(opt: Option<i32>) -> impl Iterator<Item = i32> {
292 //!     match opt {
293 //!         Some(x) => return (0..4).chain(once(x)).chain(4..8),
294 //!         None => return (0..4).chain(empty()).chain(4..8)
295 //!     }
296 //! }
297 //! ```
298 //!
299 //! ## Modifying an [`Option`] in-place
300 //!
301 //! These methods return a mutable reference to the contained value of a
302 //! [`Some`].
303 //!
304 //! * [`insert`] inserts a value, dropping any old contents
305 //! * [`get_or_insert`] gets the current value, inserting a provided
306 //!   default value if it is [`None`]
307 //! * [`get_or_insert_default`] gets the current value, inserting the
308 //!   default value of type `T` if it is [`None`]
309 //! * [`get_or_insert_with`] gets the current value, inserting a default
310 //!   computed by the provided function if it is [`None`]
311 //!
312 //! [`insert`]: Option::insert
313 //! [`get_or_insert`]: Option::get_or_insert
314 //! [`get_or_insert_default`]: Option::get_or_insert_default
315 //! [`get_or_insert_with`]: Option::get_or_insert_with
316 //!
317 //! These methods transfer ownership of the [`Option`].
318 //!
319 //! * [`take`] takes ownership of the [`Option`], including any contained
320 //!   value, replacing it with [`None`]
321 //! * [`replace`] takes ownership of the [`Option`], including any
322 //!   contained value, replacing it with a [`Some`] containing the provided
323 //!   value
324 //!
325 //! [`take`]: Option::take
326 //! [`replace`]: Option::replace
327 //!
328 //! # Examples
329 //!
330 //! Basic pattern matching on [`Option`]:
331 //!
332 //! ```
333 //! let msg = Some("howdy");
334 //!
335 //! // Take a reference to the contained string
336 //! if let Some(m) = &msg {
337 //!     println!("{}", *m);
338 //! }
339 //!
340 //! // Remove the contained string, destroying the Option
341 //! let unwrapped_msg = msg.unwrap_or("default message");
342 //! ```
343 //!
344 //! Initialize a result to [`None`] before a loop:
345 //!
346 //! ```
347 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
348 //!
349 //! // A list of data to search through.
350 //! let all_the_big_things = [
351 //!     Kingdom::Plant(250, "redwood"),
352 //!     Kingdom::Plant(230, "noble fir"),
353 //!     Kingdom::Plant(229, "sugar pine"),
354 //!     Kingdom::Animal(25, "blue whale"),
355 //!     Kingdom::Animal(19, "fin whale"),
356 //!     Kingdom::Animal(15, "north pacific right whale"),
357 //! ];
358 //!
359 //! // We're going to search for the name of the biggest animal,
360 //! // but to start with we've just got `None`.
361 //! let mut name_of_biggest_animal = None;
362 //! let mut size_of_biggest_animal = 0;
363 //! for big_thing in &all_the_big_things {
364 //!     match *big_thing {
365 //!         Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
366 //!             // Now we've found the name of some big animal
367 //!             size_of_biggest_animal = size;
368 //!             name_of_biggest_animal = Some(name);
369 //!         }
370 //!         Kingdom::Animal(..) | Kingdom::Plant(..) => ()
371 //!     }
372 //! }
373 //!
374 //! match name_of_biggest_animal {
375 //!     Some(name) => println!("the biggest animal is {}", name),
376 //!     None => println!("there are no animals :("),
377 //! }
378 //! ```
379 //!
380 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
381 //! [`Box<U>`]: ../../std/boxed/struct.Box.html
382 //! [`num::NonZero*`]: crate::num
383 //! [`ptr::NonNull<U>`]: crate::ptr::NonNull
384
385 #![stable(feature = "rust1", since = "1.0.0")]
386
387 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
388 use crate::pin::Pin;
389 use crate::{
390     convert, hint, mem,
391     ops::{self, ControlFlow, Deref, DerefMut},
392 };
393
394 /// The `Option` type. See [the module level documentation](self) for more.
395 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
396 #[rustc_diagnostic_item = "option_type"]
397 #[stable(feature = "rust1", since = "1.0.0")]
398 pub enum Option<T> {
399     /// No value
400     #[lang = "None"]
401     #[stable(feature = "rust1", since = "1.0.0")]
402     None,
403     /// Some value `T`
404     #[lang = "Some"]
405     #[stable(feature = "rust1", since = "1.0.0")]
406     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
407 }
408
409 /////////////////////////////////////////////////////////////////////////////
410 // Type implementation
411 /////////////////////////////////////////////////////////////////////////////
412
413 impl<T> Option<T> {
414     /////////////////////////////////////////////////////////////////////////
415     // Querying the contained values
416     /////////////////////////////////////////////////////////////////////////
417
418     /// Returns `true` if the option is a [`Some`] value.
419     ///
420     /// # Examples
421     ///
422     /// ```
423     /// let x: Option<u32> = Some(2);
424     /// assert_eq!(x.is_some(), true);
425     ///
426     /// let x: Option<u32> = None;
427     /// assert_eq!(x.is_some(), false);
428     /// ```
429     #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
430     #[inline]
431     #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
432     #[stable(feature = "rust1", since = "1.0.0")]
433     pub const fn is_some(&self) -> bool {
434         matches!(*self, Some(_))
435     }
436
437     /// Returns `true` if the option is a [`None`] value.
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// let x: Option<u32> = Some(2);
443     /// assert_eq!(x.is_none(), false);
444     ///
445     /// let x: Option<u32> = None;
446     /// assert_eq!(x.is_none(), true);
447     /// ```
448     #[must_use = "if you intended to assert that this doesn't have a value, consider \
449                   `.and_then(|_| panic!(\"`Option` had a value when expected `None`\"))` instead"]
450     #[inline]
451     #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
452     #[stable(feature = "rust1", since = "1.0.0")]
453     pub const fn is_none(&self) -> bool {
454         !self.is_some()
455     }
456
457     /// Returns `true` if the option is a [`Some`] value containing the given value.
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// #![feature(option_result_contains)]
463     ///
464     /// let x: Option<u32> = Some(2);
465     /// assert_eq!(x.contains(&2), true);
466     ///
467     /// let x: Option<u32> = Some(3);
468     /// assert_eq!(x.contains(&2), false);
469     ///
470     /// let x: Option<u32> = None;
471     /// assert_eq!(x.contains(&2), false);
472     /// ```
473     #[must_use]
474     #[inline]
475     #[unstable(feature = "option_result_contains", issue = "62358")]
476     pub fn contains<U>(&self, x: &U) -> bool
477     where
478         U: PartialEq<T>,
479     {
480         match self {
481             Some(y) => x == y,
482             None => false,
483         }
484     }
485
486     /////////////////////////////////////////////////////////////////////////
487     // Adapter for working with references
488     /////////////////////////////////////////////////////////////////////////
489
490     /// Converts from `&Option<T>` to `Option<&T>`.
491     ///
492     /// # Examples
493     ///
494     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
495     /// The [`map`] method takes the `self` argument by value, consuming the original,
496     /// so this technique uses `as_ref` to first take an `Option` to a reference
497     /// to the value inside the original.
498     ///
499     /// [`map`]: Option::map
500     /// [`String`]: ../../std/string/struct.String.html
501     ///
502     /// ```
503     /// let text: Option<String> = Some("Hello, world!".to_string());
504     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
505     /// // then consume *that* with `map`, leaving `text` on the stack.
506     /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
507     /// println!("still can print text: {:?}", text);
508     /// ```
509     #[inline]
510     #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
511     #[stable(feature = "rust1", since = "1.0.0")]
512     pub const fn as_ref(&self) -> Option<&T> {
513         match *self {
514             Some(ref x) => Some(x),
515             None => None,
516         }
517     }
518
519     /// Converts from `&mut Option<T>` to `Option<&mut T>`.
520     ///
521     /// # Examples
522     ///
523     /// ```
524     /// let mut x = Some(2);
525     /// match x.as_mut() {
526     ///     Some(v) => *v = 42,
527     ///     None => {},
528     /// }
529     /// assert_eq!(x, Some(42));
530     /// ```
531     #[inline]
532     #[stable(feature = "rust1", since = "1.0.0")]
533     pub fn as_mut(&mut self) -> Option<&mut T> {
534         match *self {
535             Some(ref mut x) => Some(x),
536             None => None,
537         }
538     }
539
540     /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
541     #[inline]
542     #[stable(feature = "pin", since = "1.33.0")]
543     pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
544         // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
545         // which is pinned.
546         unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
547     }
548
549     /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
550     #[inline]
551     #[stable(feature = "pin", since = "1.33.0")]
552     pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
553         // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
554         // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
555         unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
556     }
557
558     /////////////////////////////////////////////////////////////////////////
559     // Getting to contained values
560     /////////////////////////////////////////////////////////////////////////
561
562     /// Returns the contained [`Some`] value, consuming the `self` value.
563     ///
564     /// # Panics
565     ///
566     /// Panics if the value is a [`None`] with a custom panic message provided by
567     /// `msg`.
568     ///
569     /// # Examples
570     ///
571     /// ```
572     /// let x = Some("value");
573     /// assert_eq!(x.expect("fruits are healthy"), "value");
574     /// ```
575     ///
576     /// ```should_panic
577     /// let x: Option<&str> = None;
578     /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
579     /// ```
580     #[inline]
581     #[track_caller]
582     #[stable(feature = "rust1", since = "1.0.0")]
583     pub fn expect(self, msg: &str) -> T {
584         match self {
585             Some(val) => val,
586             None => expect_failed(msg),
587         }
588     }
589
590     /// Returns the contained [`Some`] value, consuming the `self` value.
591     ///
592     /// Because this function may panic, its use is generally discouraged.
593     /// Instead, prefer to use pattern matching and handle the [`None`]
594     /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
595     /// [`unwrap_or_default`].
596     ///
597     /// [`unwrap_or`]: Option::unwrap_or
598     /// [`unwrap_or_else`]: Option::unwrap_or_else
599     /// [`unwrap_or_default`]: Option::unwrap_or_default
600     ///
601     /// # Panics
602     ///
603     /// Panics if the self value equals [`None`].
604     ///
605     /// # Examples
606     ///
607     /// ```
608     /// let x = Some("air");
609     /// assert_eq!(x.unwrap(), "air");
610     /// ```
611     ///
612     /// ```should_panic
613     /// let x: Option<&str> = None;
614     /// assert_eq!(x.unwrap(), "air"); // fails
615     /// ```
616     #[inline]
617     #[track_caller]
618     #[stable(feature = "rust1", since = "1.0.0")]
619     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
620     pub const fn unwrap(self) -> T {
621         match self {
622             Some(val) => val,
623             None => panic!("called `Option::unwrap()` on a `None` value"),
624         }
625     }
626
627     /// Returns the contained [`Some`] value or a provided default.
628     ///
629     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
630     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
631     /// which is lazily evaluated.
632     ///
633     /// [`unwrap_or_else`]: Option::unwrap_or_else
634     ///
635     /// # Examples
636     ///
637     /// ```
638     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
639     /// assert_eq!(None.unwrap_or("bike"), "bike");
640     /// ```
641     #[inline]
642     #[stable(feature = "rust1", since = "1.0.0")]
643     pub fn unwrap_or(self, default: T) -> T {
644         match self {
645             Some(x) => x,
646             None => default,
647         }
648     }
649
650     /// Returns the contained [`Some`] value or computes it from a closure.
651     ///
652     /// # Examples
653     ///
654     /// ```
655     /// let k = 10;
656     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
657     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
658     /// ```
659     #[inline]
660     #[stable(feature = "rust1", since = "1.0.0")]
661     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
662         match self {
663             Some(x) => x,
664             None => f(),
665         }
666     }
667
668     /// Returns the contained [`Some`] value, consuming the `self` value,
669     /// without checking that the value is not [`None`].
670     ///
671     /// # Safety
672     ///
673     /// Calling this method on [`None`] is *[undefined behavior]*.
674     ///
675     /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// #![feature(option_result_unwrap_unchecked)]
681     /// let x = Some("air");
682     /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air");
683     /// ```
684     ///
685     /// ```no_run
686     /// #![feature(option_result_unwrap_unchecked)]
687     /// let x: Option<&str> = None;
688     /// assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior!
689     /// ```
690     #[inline]
691     #[track_caller]
692     #[unstable(feature = "option_result_unwrap_unchecked", reason = "newly added", issue = "81383")]
693     pub unsafe fn unwrap_unchecked(self) -> T {
694         debug_assert!(self.is_some());
695         match self {
696             Some(val) => val,
697             // SAFETY: the safety contract must be upheld by the caller.
698             None => unsafe { hint::unreachable_unchecked() },
699         }
700     }
701
702     /////////////////////////////////////////////////////////////////////////
703     // Transforming contained values
704     /////////////////////////////////////////////////////////////////////////
705
706     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
707     ///
708     /// # Examples
709     ///
710     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
711     ///
712     /// [`String`]: ../../std/string/struct.String.html
713     /// ```
714     /// let maybe_some_string = Some(String::from("Hello, World!"));
715     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
716     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
717     ///
718     /// assert_eq!(maybe_some_len, Some(13));
719     /// ```
720     #[inline]
721     #[stable(feature = "rust1", since = "1.0.0")]
722     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
723         match self {
724             Some(x) => Some(f(x)),
725             None => None,
726         }
727     }
728
729     /// Returns the provided default result (if none),
730     /// or applies a function to the contained value (if any).
731     ///
732     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
733     /// the result of a function call, it is recommended to use [`map_or_else`],
734     /// which is lazily evaluated.
735     ///
736     /// [`map_or_else`]: Option::map_or_else
737     ///
738     /// # Examples
739     ///
740     /// ```
741     /// let x = Some("foo");
742     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
743     ///
744     /// let x: Option<&str> = None;
745     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
746     /// ```
747     #[inline]
748     #[stable(feature = "rust1", since = "1.0.0")]
749     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
750         match self {
751             Some(t) => f(t),
752             None => default,
753         }
754     }
755
756     /// Computes a default function result (if none), or
757     /// applies a different function to the contained value (if any).
758     ///
759     /// # Examples
760     ///
761     /// ```
762     /// let k = 21;
763     ///
764     /// let x = Some("foo");
765     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
766     ///
767     /// let x: Option<&str> = None;
768     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
769     /// ```
770     #[inline]
771     #[stable(feature = "rust1", since = "1.0.0")]
772     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
773         match self {
774             Some(t) => f(t),
775             None => default(),
776         }
777     }
778
779     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
780     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
781     ///
782     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
783     /// result of a function call, it is recommended to use [`ok_or_else`], which is
784     /// lazily evaluated.
785     ///
786     /// [`Ok(v)`]: Ok
787     /// [`Err(err)`]: Err
788     /// [`Some(v)`]: Some
789     /// [`ok_or_else`]: Option::ok_or_else
790     ///
791     /// # Examples
792     ///
793     /// ```
794     /// let x = Some("foo");
795     /// assert_eq!(x.ok_or(0), Ok("foo"));
796     ///
797     /// let x: Option<&str> = None;
798     /// assert_eq!(x.ok_or(0), Err(0));
799     /// ```
800     #[inline]
801     #[stable(feature = "rust1", since = "1.0.0")]
802     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
803         match self {
804             Some(v) => Ok(v),
805             None => Err(err),
806         }
807     }
808
809     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
810     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
811     ///
812     /// [`Ok(v)`]: Ok
813     /// [`Err(err())`]: Err
814     /// [`Some(v)`]: Some
815     ///
816     /// # Examples
817     ///
818     /// ```
819     /// let x = Some("foo");
820     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
821     ///
822     /// let x: Option<&str> = None;
823     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
824     /// ```
825     #[inline]
826     #[stable(feature = "rust1", since = "1.0.0")]
827     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
828         match self {
829             Some(v) => Ok(v),
830             None => Err(err()),
831         }
832     }
833
834     /////////////////////////////////////////////////////////////////////////
835     // Iterator constructors
836     /////////////////////////////////////////////////////////////////////////
837
838     /// Returns an iterator over the possibly contained value.
839     ///
840     /// # Examples
841     ///
842     /// ```
843     /// let x = Some(4);
844     /// assert_eq!(x.iter().next(), Some(&4));
845     ///
846     /// let x: Option<u32> = None;
847     /// assert_eq!(x.iter().next(), None);
848     /// ```
849     #[inline]
850     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
851     #[stable(feature = "rust1", since = "1.0.0")]
852     pub const fn iter(&self) -> Iter<'_, T> {
853         Iter { inner: Item { opt: self.as_ref() } }
854     }
855
856     /// Returns a mutable iterator over the possibly contained value.
857     ///
858     /// # Examples
859     ///
860     /// ```
861     /// let mut x = Some(4);
862     /// match x.iter_mut().next() {
863     ///     Some(v) => *v = 42,
864     ///     None => {},
865     /// }
866     /// assert_eq!(x, Some(42));
867     ///
868     /// let mut x: Option<u32> = None;
869     /// assert_eq!(x.iter_mut().next(), None);
870     /// ```
871     #[inline]
872     #[stable(feature = "rust1", since = "1.0.0")]
873     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
874         IterMut { inner: Item { opt: self.as_mut() } }
875     }
876
877     /////////////////////////////////////////////////////////////////////////
878     // Boolean operations on the values, eager and lazy
879     /////////////////////////////////////////////////////////////////////////
880
881     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
882     ///
883     /// # Examples
884     ///
885     /// ```
886     /// let x = Some(2);
887     /// let y: Option<&str> = None;
888     /// assert_eq!(x.and(y), None);
889     ///
890     /// let x: Option<u32> = None;
891     /// let y = Some("foo");
892     /// assert_eq!(x.and(y), None);
893     ///
894     /// let x = Some(2);
895     /// let y = Some("foo");
896     /// assert_eq!(x.and(y), Some("foo"));
897     ///
898     /// let x: Option<u32> = None;
899     /// let y: Option<&str> = None;
900     /// assert_eq!(x.and(y), None);
901     /// ```
902     #[inline]
903     #[stable(feature = "rust1", since = "1.0.0")]
904     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
905         match self {
906             Some(_) => optb,
907             None => None,
908         }
909     }
910
911     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
912     /// wrapped value and returns the result.
913     ///
914     /// Some languages call this operation flatmap.
915     ///
916     /// # Examples
917     ///
918     /// ```
919     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
920     /// fn nope(_: u32) -> Option<u32> { None }
921     ///
922     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
923     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
924     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
925     /// assert_eq!(None.and_then(sq).and_then(sq), None);
926     /// ```
927     #[inline]
928     #[stable(feature = "rust1", since = "1.0.0")]
929     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
930         match self {
931             Some(x) => f(x),
932             None => None,
933         }
934     }
935
936     /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
937     /// with the wrapped value and returns:
938     ///
939     /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
940     ///   value), and
941     /// - [`None`] if `predicate` returns `false`.
942     ///
943     /// This function works similar to [`Iterator::filter()`]. You can imagine
944     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
945     /// lets you decide which elements to keep.
946     ///
947     /// # Examples
948     ///
949     /// ```rust
950     /// fn is_even(n: &i32) -> bool {
951     ///     n % 2 == 0
952     /// }
953     ///
954     /// assert_eq!(None.filter(is_even), None);
955     /// assert_eq!(Some(3).filter(is_even), None);
956     /// assert_eq!(Some(4).filter(is_even), Some(4));
957     /// ```
958     ///
959     /// [`Some(t)`]: Some
960     #[inline]
961     #[stable(feature = "option_filter", since = "1.27.0")]
962     pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
963         if let Some(x) = self {
964             if predicate(&x) {
965                 return Some(x);
966             }
967         }
968         None
969     }
970
971     /// Returns the option if it contains a value, otherwise returns `optb`.
972     ///
973     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
974     /// result of a function call, it is recommended to use [`or_else`], which is
975     /// lazily evaluated.
976     ///
977     /// [`or_else`]: Option::or_else
978     ///
979     /// # Examples
980     ///
981     /// ```
982     /// let x = Some(2);
983     /// let y = None;
984     /// assert_eq!(x.or(y), Some(2));
985     ///
986     /// let x = None;
987     /// let y = Some(100);
988     /// assert_eq!(x.or(y), Some(100));
989     ///
990     /// let x = Some(2);
991     /// let y = Some(100);
992     /// assert_eq!(x.or(y), Some(2));
993     ///
994     /// let x: Option<u32> = None;
995     /// let y = None;
996     /// assert_eq!(x.or(y), None);
997     /// ```
998     #[inline]
999     #[stable(feature = "rust1", since = "1.0.0")]
1000     pub fn or(self, optb: Option<T>) -> Option<T> {
1001         match self {
1002             Some(_) => self,
1003             None => optb,
1004         }
1005     }
1006
1007     /// Returns the option if it contains a value, otherwise calls `f` and
1008     /// returns the result.
1009     ///
1010     /// # Examples
1011     ///
1012     /// ```
1013     /// fn nobody() -> Option<&'static str> { None }
1014     /// fn vikings() -> Option<&'static str> { Some("vikings") }
1015     ///
1016     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
1017     /// assert_eq!(None.or_else(vikings), Some("vikings"));
1018     /// assert_eq!(None.or_else(nobody), None);
1019     /// ```
1020     #[inline]
1021     #[stable(feature = "rust1", since = "1.0.0")]
1022     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
1023         match self {
1024             Some(_) => self,
1025             None => f(),
1026         }
1027     }
1028
1029     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
1030     ///
1031     /// # Examples
1032     ///
1033     /// ```
1034     /// let x = Some(2);
1035     /// let y: Option<u32> = None;
1036     /// assert_eq!(x.xor(y), Some(2));
1037     ///
1038     /// let x: Option<u32> = None;
1039     /// let y = Some(2);
1040     /// assert_eq!(x.xor(y), Some(2));
1041     ///
1042     /// let x = Some(2);
1043     /// let y = Some(2);
1044     /// assert_eq!(x.xor(y), None);
1045     ///
1046     /// let x: Option<u32> = None;
1047     /// let y: Option<u32> = None;
1048     /// assert_eq!(x.xor(y), None);
1049     /// ```
1050     #[inline]
1051     #[stable(feature = "option_xor", since = "1.37.0")]
1052     pub fn xor(self, optb: Option<T>) -> Option<T> {
1053         match (self, optb) {
1054             (Some(a), None) => Some(a),
1055             (None, Some(b)) => Some(b),
1056             _ => None,
1057         }
1058     }
1059
1060     /////////////////////////////////////////////////////////////////////////
1061     // Entry-like operations to insert a value and return a reference
1062     /////////////////////////////////////////////////////////////////////////
1063
1064     /// Inserts `value` into the option then returns a mutable reference to it.
1065     ///
1066     /// If the option already contains a value, the old value is dropped.
1067     ///
1068     /// See also [`Option::get_or_insert`], which doesn't update the value if
1069     /// the option already contains [`Some`].
1070     ///
1071     /// # Example
1072     ///
1073     /// ```
1074     /// let mut opt = None;
1075     /// let val = opt.insert(1);
1076     /// assert_eq!(*val, 1);
1077     /// assert_eq!(opt.unwrap(), 1);
1078     /// let val = opt.insert(2);
1079     /// assert_eq!(*val, 2);
1080     /// *val = 3;
1081     /// assert_eq!(opt.unwrap(), 3);
1082     /// ```
1083     #[inline]
1084     #[stable(feature = "option_insert", since = "1.53.0")]
1085     pub fn insert(&mut self, value: T) -> &mut T {
1086         *self = Some(value);
1087
1088         match self {
1089             Some(v) => v,
1090             // SAFETY: the code above just filled the option
1091             None => unsafe { hint::unreachable_unchecked() },
1092         }
1093     }
1094
1095     /// Inserts `value` into the option if it is [`None`], then
1096     /// returns a mutable reference to the contained value.
1097     ///
1098     /// See also [`Option::insert`], which updates the value even if
1099     /// the option already contains [`Some`].
1100     ///
1101     /// # Examples
1102     ///
1103     /// ```
1104     /// let mut x = None;
1105     ///
1106     /// {
1107     ///     let y: &mut u32 = x.get_or_insert(5);
1108     ///     assert_eq!(y, &5);
1109     ///
1110     ///     *y = 7;
1111     /// }
1112     ///
1113     /// assert_eq!(x, Some(7));
1114     /// ```
1115     #[inline]
1116     #[stable(feature = "option_entry", since = "1.20.0")]
1117     pub fn get_or_insert(&mut self, value: T) -> &mut T {
1118         self.get_or_insert_with(|| value)
1119     }
1120
1121     /// Inserts the default value into the option if it is [`None`], then
1122     /// returns a mutable reference to the contained value.
1123     ///
1124     /// # Examples
1125     ///
1126     /// ```
1127     /// #![feature(option_get_or_insert_default)]
1128     ///
1129     /// let mut x = None;
1130     ///
1131     /// {
1132     ///     let y: &mut u32 = x.get_or_insert_default();
1133     ///     assert_eq!(y, &0);
1134     ///
1135     ///     *y = 7;
1136     /// }
1137     ///
1138     /// assert_eq!(x, Some(7));
1139     /// ```
1140     #[inline]
1141     #[unstable(feature = "option_get_or_insert_default", issue = "82901")]
1142     pub fn get_or_insert_default(&mut self) -> &mut T
1143     where
1144         T: Default,
1145     {
1146         self.get_or_insert_with(Default::default)
1147     }
1148
1149     /// Inserts a value computed from `f` into the option if it is [`None`],
1150     /// then returns a mutable reference to the contained value.
1151     ///
1152     /// # Examples
1153     ///
1154     /// ```
1155     /// let mut x = None;
1156     ///
1157     /// {
1158     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
1159     ///     assert_eq!(y, &5);
1160     ///
1161     ///     *y = 7;
1162     /// }
1163     ///
1164     /// assert_eq!(x, Some(7));
1165     /// ```
1166     #[inline]
1167     #[stable(feature = "option_entry", since = "1.20.0")]
1168     pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
1169         if let None = *self {
1170             *self = Some(f());
1171         }
1172
1173         match self {
1174             Some(v) => v,
1175             // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
1176             // variant in the code above.
1177             None => unsafe { hint::unreachable_unchecked() },
1178         }
1179     }
1180
1181     /////////////////////////////////////////////////////////////////////////
1182     // Misc
1183     /////////////////////////////////////////////////////////////////////////
1184
1185     /// Takes the value out of the option, leaving a [`None`] in its place.
1186     ///
1187     /// # Examples
1188     ///
1189     /// ```
1190     /// let mut x = Some(2);
1191     /// let y = x.take();
1192     /// assert_eq!(x, None);
1193     /// assert_eq!(y, Some(2));
1194     ///
1195     /// let mut x: Option<u32> = None;
1196     /// let y = x.take();
1197     /// assert_eq!(x, None);
1198     /// assert_eq!(y, None);
1199     /// ```
1200     #[inline]
1201     #[stable(feature = "rust1", since = "1.0.0")]
1202     pub fn take(&mut self) -> Option<T> {
1203         mem::take(self)
1204     }
1205
1206     /// Replaces the actual value in the option by the value given in parameter,
1207     /// returning the old value if present,
1208     /// leaving a [`Some`] in its place without deinitializing either one.
1209     ///
1210     /// # Examples
1211     ///
1212     /// ```
1213     /// let mut x = Some(2);
1214     /// let old = x.replace(5);
1215     /// assert_eq!(x, Some(5));
1216     /// assert_eq!(old, Some(2));
1217     ///
1218     /// let mut x = None;
1219     /// let old = x.replace(3);
1220     /// assert_eq!(x, Some(3));
1221     /// assert_eq!(old, None);
1222     /// ```
1223     #[inline]
1224     #[stable(feature = "option_replace", since = "1.31.0")]
1225     pub fn replace(&mut self, value: T) -> Option<T> {
1226         mem::replace(self, Some(value))
1227     }
1228
1229     /// Zips `self` with another `Option`.
1230     ///
1231     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
1232     /// Otherwise, `None` is returned.
1233     ///
1234     /// # Examples
1235     ///
1236     /// ```
1237     /// let x = Some(1);
1238     /// let y = Some("hi");
1239     /// let z = None::<u8>;
1240     ///
1241     /// assert_eq!(x.zip(y), Some((1, "hi")));
1242     /// assert_eq!(x.zip(z), None);
1243     /// ```
1244     #[stable(feature = "option_zip_option", since = "1.46.0")]
1245     pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
1246         match (self, other) {
1247             (Some(a), Some(b)) => Some((a, b)),
1248             _ => None,
1249         }
1250     }
1251
1252     /// Zips `self` and another `Option` with function `f`.
1253     ///
1254     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
1255     /// Otherwise, `None` is returned.
1256     ///
1257     /// # Examples
1258     ///
1259     /// ```
1260     /// #![feature(option_zip)]
1261     ///
1262     /// #[derive(Debug, PartialEq)]
1263     /// struct Point {
1264     ///     x: f64,
1265     ///     y: f64,
1266     /// }
1267     ///
1268     /// impl Point {
1269     ///     fn new(x: f64, y: f64) -> Self {
1270     ///         Self { x, y }
1271     ///     }
1272     /// }
1273     ///
1274     /// let x = Some(17.5);
1275     /// let y = Some(42.7);
1276     ///
1277     /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
1278     /// assert_eq!(x.zip_with(None, Point::new), None);
1279     /// ```
1280     #[unstable(feature = "option_zip", issue = "70086")]
1281     pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
1282     where
1283         F: FnOnce(T, U) -> R,
1284     {
1285         Some(f(self?, other?))
1286     }
1287 }
1288
1289 impl<T: Copy> Option<&T> {
1290     /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
1291     /// option.
1292     ///
1293     /// # Examples
1294     ///
1295     /// ```
1296     /// let x = 12;
1297     /// let opt_x = Some(&x);
1298     /// assert_eq!(opt_x, Some(&12));
1299     /// let copied = opt_x.copied();
1300     /// assert_eq!(copied, Some(12));
1301     /// ```
1302     #[stable(feature = "copied", since = "1.35.0")]
1303     pub fn copied(self) -> Option<T> {
1304         self.map(|&t| t)
1305     }
1306 }
1307
1308 impl<T: Copy> Option<&mut T> {
1309     /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
1310     /// option.
1311     ///
1312     /// # Examples
1313     ///
1314     /// ```
1315     /// let mut x = 12;
1316     /// let opt_x = Some(&mut x);
1317     /// assert_eq!(opt_x, Some(&mut 12));
1318     /// let copied = opt_x.copied();
1319     /// assert_eq!(copied, Some(12));
1320     /// ```
1321     #[stable(feature = "copied", since = "1.35.0")]
1322     pub fn copied(self) -> Option<T> {
1323         self.map(|&mut t| t)
1324     }
1325 }
1326
1327 impl<T: Clone> Option<&T> {
1328     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
1329     /// option.
1330     ///
1331     /// # Examples
1332     ///
1333     /// ```
1334     /// let x = 12;
1335     /// let opt_x = Some(&x);
1336     /// assert_eq!(opt_x, Some(&12));
1337     /// let cloned = opt_x.cloned();
1338     /// assert_eq!(cloned, Some(12));
1339     /// ```
1340     #[stable(feature = "rust1", since = "1.0.0")]
1341     pub fn cloned(self) -> Option<T> {
1342         self.map(|t| t.clone())
1343     }
1344 }
1345
1346 impl<T: Clone> Option<&mut T> {
1347     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1348     /// option.
1349     ///
1350     /// # Examples
1351     ///
1352     /// ```
1353     /// let mut x = 12;
1354     /// let opt_x = Some(&mut x);
1355     /// assert_eq!(opt_x, Some(&mut 12));
1356     /// let cloned = opt_x.cloned();
1357     /// assert_eq!(cloned, Some(12));
1358     /// ```
1359     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1360     pub fn cloned(self) -> Option<T> {
1361         self.map(|t| t.clone())
1362     }
1363 }
1364
1365 impl<T: Default> Option<T> {
1366     /// Returns the contained [`Some`] value or a default
1367     ///
1368     /// Consumes the `self` argument then, if [`Some`], returns the contained
1369     /// value, otherwise if [`None`], returns the [default value] for that
1370     /// type.
1371     ///
1372     /// # Examples
1373     ///
1374     /// Converts a string to an integer, turning poorly-formed strings
1375     /// into 0 (the default value for integers). [`parse`] converts
1376     /// a string to any other type that implements [`FromStr`], returning
1377     /// [`None`] on error.
1378     ///
1379     /// ```
1380     /// let good_year_from_input = "1909";
1381     /// let bad_year_from_input = "190blarg";
1382     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1383     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1384     ///
1385     /// assert_eq!(1909, good_year);
1386     /// assert_eq!(0, bad_year);
1387     /// ```
1388     ///
1389     /// [default value]: Default::default
1390     /// [`parse`]: str::parse
1391     /// [`FromStr`]: crate::str::FromStr
1392     #[inline]
1393     #[stable(feature = "rust1", since = "1.0.0")]
1394     pub fn unwrap_or_default(self) -> T {
1395         match self {
1396             Some(x) => x,
1397             None => Default::default(),
1398         }
1399     }
1400 }
1401
1402 impl<T: Deref> Option<T> {
1403     /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1404     ///
1405     /// Leaves the original Option in-place, creating a new one with a reference
1406     /// to the original one, additionally coercing the contents via [`Deref`].
1407     ///
1408     /// # Examples
1409     ///
1410     /// ```
1411     /// let x: Option<String> = Some("hey".to_owned());
1412     /// assert_eq!(x.as_deref(), Some("hey"));
1413     ///
1414     /// let x: Option<String> = None;
1415     /// assert_eq!(x.as_deref(), None);
1416     /// ```
1417     #[stable(feature = "option_deref", since = "1.40.0")]
1418     pub fn as_deref(&self) -> Option<&T::Target> {
1419         self.as_ref().map(|t| t.deref())
1420     }
1421 }
1422
1423 impl<T: DerefMut> Option<T> {
1424     /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1425     ///
1426     /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1427     /// the inner type's `Deref::Target` type.
1428     ///
1429     /// # Examples
1430     ///
1431     /// ```
1432     /// let mut x: Option<String> = Some("hey".to_owned());
1433     /// assert_eq!(x.as_deref_mut().map(|x| {
1434     ///     x.make_ascii_uppercase();
1435     ///     x
1436     /// }), Some("HEY".to_owned().as_mut_str()));
1437     /// ```
1438     #[stable(feature = "option_deref", since = "1.40.0")]
1439     pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1440         self.as_mut().map(|t| t.deref_mut())
1441     }
1442 }
1443
1444 impl<T, E> Option<Result<T, E>> {
1445     /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1446     ///
1447     /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1448     /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1449     /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1450     ///
1451     /// # Examples
1452     ///
1453     /// ```
1454     /// #[derive(Debug, Eq, PartialEq)]
1455     /// struct SomeErr;
1456     ///
1457     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1458     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1459     /// assert_eq!(x, y.transpose());
1460     /// ```
1461     #[inline]
1462     #[stable(feature = "transpose_result", since = "1.33.0")]
1463     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1464     pub const fn transpose(self) -> Result<Option<T>, E> {
1465         match self {
1466             Some(Ok(x)) => Ok(Some(x)),
1467             Some(Err(e)) => Err(e),
1468             None => Ok(None),
1469         }
1470     }
1471 }
1472
1473 // This is a separate function to reduce the code size of .expect() itself.
1474 #[inline(never)]
1475 #[cold]
1476 #[track_caller]
1477 fn expect_failed(msg: &str) -> ! {
1478     panic!("{}", msg)
1479 }
1480
1481 /////////////////////////////////////////////////////////////////////////////
1482 // Trait implementations
1483 /////////////////////////////////////////////////////////////////////////////
1484
1485 #[stable(feature = "rust1", since = "1.0.0")]
1486 impl<T: Clone> Clone for Option<T> {
1487     #[inline]
1488     fn clone(&self) -> Self {
1489         match self {
1490             Some(x) => Some(x.clone()),
1491             None => None,
1492         }
1493     }
1494
1495     #[inline]
1496     fn clone_from(&mut self, source: &Self) {
1497         match (self, source) {
1498             (Some(to), Some(from)) => to.clone_from(from),
1499             (to, from) => *to = from.clone(),
1500         }
1501     }
1502 }
1503
1504 #[stable(feature = "rust1", since = "1.0.0")]
1505 impl<T> Default for Option<T> {
1506     /// Returns [`None`][Option::None].
1507     ///
1508     /// # Examples
1509     ///
1510     /// ```
1511     /// let opt: Option<u32> = Option::default();
1512     /// assert!(opt.is_none());
1513     /// ```
1514     #[inline]
1515     fn default() -> Option<T> {
1516         None
1517     }
1518 }
1519
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<T> IntoIterator for Option<T> {
1522     type Item = T;
1523     type IntoIter = IntoIter<T>;
1524
1525     /// Returns a consuming iterator over the possibly contained value.
1526     ///
1527     /// # Examples
1528     ///
1529     /// ```
1530     /// let x = Some("string");
1531     /// let v: Vec<&str> = x.into_iter().collect();
1532     /// assert_eq!(v, ["string"]);
1533     ///
1534     /// let x = None;
1535     /// let v: Vec<&str> = x.into_iter().collect();
1536     /// assert!(v.is_empty());
1537     /// ```
1538     #[inline]
1539     fn into_iter(self) -> IntoIter<T> {
1540         IntoIter { inner: Item { opt: self } }
1541     }
1542 }
1543
1544 #[stable(since = "1.4.0", feature = "option_iter")]
1545 impl<'a, T> IntoIterator for &'a Option<T> {
1546     type Item = &'a T;
1547     type IntoIter = Iter<'a, T>;
1548
1549     fn into_iter(self) -> Iter<'a, T> {
1550         self.iter()
1551     }
1552 }
1553
1554 #[stable(since = "1.4.0", feature = "option_iter")]
1555 impl<'a, T> IntoIterator for &'a mut Option<T> {
1556     type Item = &'a mut T;
1557     type IntoIter = IterMut<'a, T>;
1558
1559     fn into_iter(self) -> IterMut<'a, T> {
1560         self.iter_mut()
1561     }
1562 }
1563
1564 #[stable(since = "1.12.0", feature = "option_from")]
1565 impl<T> From<T> for Option<T> {
1566     /// Copies `val` into a new `Some`.
1567     ///
1568     /// # Examples
1569     ///
1570     /// ```
1571     /// let o: Option<u8> = Option::from(67);
1572     ///
1573     /// assert_eq!(Some(67), o);
1574     /// ```
1575     fn from(val: T) -> Option<T> {
1576         Some(val)
1577     }
1578 }
1579
1580 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1581 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1582     /// Converts from `&Option<T>` to `Option<&T>`.
1583     ///
1584     /// # Examples
1585     ///
1586     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1587     /// The [`map`] method takes the `self` argument by value, consuming the original,
1588     /// so this technique uses `from` to first take an `Option` to a reference
1589     /// to the value inside the original.
1590     ///
1591     /// [`map`]: Option::map
1592     /// [`String`]: ../../std/string/struct.String.html
1593     ///
1594     /// ```
1595     /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1596     /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1597     ///
1598     /// println!("Can still print s: {:?}", s);
1599     ///
1600     /// assert_eq!(o, Some(18));
1601     /// ```
1602     fn from(o: &'a Option<T>) -> Option<&'a T> {
1603         o.as_ref()
1604     }
1605 }
1606
1607 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1608 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1609     /// Converts from `&mut Option<T>` to `Option<&mut T>`
1610     ///
1611     /// # Examples
1612     ///
1613     /// ```
1614     /// let mut s = Some(String::from("Hello"));
1615     /// let o: Option<&mut String> = Option::from(&mut s);
1616     ///
1617     /// match o {
1618     ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
1619     ///     None => (),
1620     /// }
1621     ///
1622     /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1623     /// ```
1624     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1625         o.as_mut()
1626     }
1627 }
1628
1629 /////////////////////////////////////////////////////////////////////////////
1630 // The Option Iterators
1631 /////////////////////////////////////////////////////////////////////////////
1632
1633 #[derive(Clone, Debug)]
1634 struct Item<A> {
1635     opt: Option<A>,
1636 }
1637
1638 impl<A> Iterator for Item<A> {
1639     type Item = A;
1640
1641     #[inline]
1642     fn next(&mut self) -> Option<A> {
1643         self.opt.take()
1644     }
1645
1646     #[inline]
1647     fn size_hint(&self) -> (usize, Option<usize>) {
1648         match self.opt {
1649             Some(_) => (1, Some(1)),
1650             None => (0, Some(0)),
1651         }
1652     }
1653 }
1654
1655 impl<A> DoubleEndedIterator for Item<A> {
1656     #[inline]
1657     fn next_back(&mut self) -> Option<A> {
1658         self.opt.take()
1659     }
1660 }
1661
1662 impl<A> ExactSizeIterator for Item<A> {}
1663 impl<A> FusedIterator for Item<A> {}
1664 unsafe impl<A> TrustedLen for Item<A> {}
1665
1666 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1667 ///
1668 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1669 ///
1670 /// This `struct` is created by the [`Option::iter`] function.
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 #[derive(Debug)]
1673 pub struct Iter<'a, A: 'a> {
1674     inner: Item<&'a A>,
1675 }
1676
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<'a, A> Iterator for Iter<'a, A> {
1679     type Item = &'a A;
1680
1681     #[inline]
1682     fn next(&mut self) -> Option<&'a A> {
1683         self.inner.next()
1684     }
1685     #[inline]
1686     fn size_hint(&self) -> (usize, Option<usize>) {
1687         self.inner.size_hint()
1688     }
1689 }
1690
1691 #[stable(feature = "rust1", since = "1.0.0")]
1692 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1693     #[inline]
1694     fn next_back(&mut self) -> Option<&'a A> {
1695         self.inner.next_back()
1696     }
1697 }
1698
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<A> ExactSizeIterator for Iter<'_, A> {}
1701
1702 #[stable(feature = "fused", since = "1.26.0")]
1703 impl<A> FusedIterator for Iter<'_, A> {}
1704
1705 #[unstable(feature = "trusted_len", issue = "37572")]
1706 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1707
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<A> Clone for Iter<'_, A> {
1710     #[inline]
1711     fn clone(&self) -> Self {
1712         Iter { inner: self.inner.clone() }
1713     }
1714 }
1715
1716 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1717 ///
1718 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1719 ///
1720 /// This `struct` is created by the [`Option::iter_mut`] function.
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 #[derive(Debug)]
1723 pub struct IterMut<'a, A: 'a> {
1724     inner: Item<&'a mut A>,
1725 }
1726
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl<'a, A> Iterator for IterMut<'a, A> {
1729     type Item = &'a mut A;
1730
1731     #[inline]
1732     fn next(&mut self) -> Option<&'a mut A> {
1733         self.inner.next()
1734     }
1735     #[inline]
1736     fn size_hint(&self) -> (usize, Option<usize>) {
1737         self.inner.size_hint()
1738     }
1739 }
1740
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1743     #[inline]
1744     fn next_back(&mut self) -> Option<&'a mut A> {
1745         self.inner.next_back()
1746     }
1747 }
1748
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1751
1752 #[stable(feature = "fused", since = "1.26.0")]
1753 impl<A> FusedIterator for IterMut<'_, A> {}
1754 #[unstable(feature = "trusted_len", issue = "37572")]
1755 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1756
1757 /// An iterator over the value in [`Some`] variant of an [`Option`].
1758 ///
1759 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1760 ///
1761 /// This `struct` is created by the [`Option::into_iter`] function.
1762 #[derive(Clone, Debug)]
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 pub struct IntoIter<A> {
1765     inner: Item<A>,
1766 }
1767
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<A> Iterator for IntoIter<A> {
1770     type Item = A;
1771
1772     #[inline]
1773     fn next(&mut self) -> Option<A> {
1774         self.inner.next()
1775     }
1776     #[inline]
1777     fn size_hint(&self) -> (usize, Option<usize>) {
1778         self.inner.size_hint()
1779     }
1780 }
1781
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<A> DoubleEndedIterator for IntoIter<A> {
1784     #[inline]
1785     fn next_back(&mut self) -> Option<A> {
1786         self.inner.next_back()
1787     }
1788 }
1789
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<A> ExactSizeIterator for IntoIter<A> {}
1792
1793 #[stable(feature = "fused", since = "1.26.0")]
1794 impl<A> FusedIterator for IntoIter<A> {}
1795
1796 #[unstable(feature = "trusted_len", issue = "37572")]
1797 unsafe impl<A> TrustedLen for IntoIter<A> {}
1798
1799 /////////////////////////////////////////////////////////////////////////////
1800 // FromIterator
1801 /////////////////////////////////////////////////////////////////////////////
1802
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1805     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1806     /// no further elements are taken, and the [`None`][Option::None] is
1807     /// returned. Should no [`None`][Option::None] occur, a container with the
1808     /// values of each [`Option`] is returned.
1809     ///
1810     /// # Examples
1811     ///
1812     /// Here is an example which increments every integer in a vector.
1813     /// We use the checked variant of `add` that returns `None` when the
1814     /// calculation would result in an overflow.
1815     ///
1816     /// ```
1817     /// let items = vec![0_u16, 1, 2];
1818     ///
1819     /// let res: Option<Vec<u16>> = items
1820     ///     .iter()
1821     ///     .map(|x| x.checked_add(1))
1822     ///     .collect();
1823     ///
1824     /// assert_eq!(res, Some(vec![1, 2, 3]));
1825     /// ```
1826     ///
1827     /// As you can see, this will return the expected, valid items.
1828     ///
1829     /// Here is another example that tries to subtract one from another list
1830     /// of integers, this time checking for underflow:
1831     ///
1832     /// ```
1833     /// let items = vec![2_u16, 1, 0];
1834     ///
1835     /// let res: Option<Vec<u16>> = items
1836     ///     .iter()
1837     ///     .map(|x| x.checked_sub(1))
1838     ///     .collect();
1839     ///
1840     /// assert_eq!(res, None);
1841     /// ```
1842     ///
1843     /// Since the last element is zero, it would underflow. Thus, the resulting
1844     /// value is `None`.
1845     ///
1846     /// Here is a variation on the previous example, showing that no
1847     /// further elements are taken from `iter` after the first `None`.
1848     ///
1849     /// ```
1850     /// let items = vec![3_u16, 2, 1, 10];
1851     ///
1852     /// let mut shared = 0;
1853     ///
1854     /// let res: Option<Vec<u16>> = items
1855     ///     .iter()
1856     ///     .map(|x| { shared += x; x.checked_sub(2) })
1857     ///     .collect();
1858     ///
1859     /// assert_eq!(res, None);
1860     /// assert_eq!(shared, 6);
1861     /// ```
1862     ///
1863     /// Since the third element caused an underflow, no further elements were taken,
1864     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1865     #[inline]
1866     fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1867         // FIXME(#11084): This could be replaced with Iterator::scan when this
1868         // performance bug is closed.
1869
1870         iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1871     }
1872 }
1873
1874 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1875 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1876 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1877 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1878 #[rustc_diagnostic_item = "none_error"]
1879 #[unstable(feature = "try_trait", issue = "42327")]
1880 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1881 #[cfg(bootstrap)]
1882 pub struct NoneError;
1883
1884 #[unstable(feature = "try_trait", issue = "42327")]
1885 #[cfg(bootstrap)]
1886 impl<T> ops::TryV1 for Option<T> {
1887     type Output = T;
1888     type Error = NoneError;
1889
1890     #[inline]
1891     fn into_result(self) -> Result<T, NoneError> {
1892         self.ok_or(NoneError)
1893     }
1894
1895     #[inline]
1896     fn from_ok(v: T) -> Self {
1897         Some(v)
1898     }
1899
1900     #[inline]
1901     fn from_error(_: NoneError) -> Self {
1902         None
1903     }
1904 }
1905
1906 #[unstable(feature = "try_trait_v2", issue = "84277")]
1907 impl<T> ops::TryV2 for Option<T> {
1908     type Output = T;
1909     type Residual = Option<convert::Infallible>;
1910
1911     #[inline]
1912     fn from_output(output: Self::Output) -> Self {
1913         Some(output)
1914     }
1915
1916     #[inline]
1917     fn branch(self) -> ControlFlow<Self::Residual, Self::Output> {
1918         match self {
1919             Some(v) => ControlFlow::Continue(v),
1920             None => ControlFlow::Break(None),
1921         }
1922     }
1923 }
1924
1925 #[unstable(feature = "try_trait_v2", issue = "84277")]
1926 impl<T> ops::FromResidual for Option<T> {
1927     #[inline]
1928     fn from_residual(residual: Option<convert::Infallible>) -> Self {
1929         match residual {
1930             None => None,
1931         }
1932     }
1933 }
1934
1935 impl<T> Option<Option<T>> {
1936     /// Converts from `Option<Option<T>>` to `Option<T>`
1937     ///
1938     /// # Examples
1939     ///
1940     /// Basic usage:
1941     ///
1942     /// ```
1943     /// let x: Option<Option<u32>> = Some(Some(6));
1944     /// assert_eq!(Some(6), x.flatten());
1945     ///
1946     /// let x: Option<Option<u32>> = Some(None);
1947     /// assert_eq!(None, x.flatten());
1948     ///
1949     /// let x: Option<Option<u32>> = None;
1950     /// assert_eq!(None, x.flatten());
1951     /// ```
1952     ///
1953     /// Flattening only removes one level of nesting at a time:
1954     ///
1955     /// ```
1956     /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1957     /// assert_eq!(Some(Some(6)), x.flatten());
1958     /// assert_eq!(Some(6), x.flatten().flatten());
1959     /// ```
1960     #[inline]
1961     #[stable(feature = "option_flattening", since = "1.40.0")]
1962     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
1963     pub const fn flatten(self) -> Option<T> {
1964         match self {
1965             Some(inner) => inner,
1966             None => None,
1967         }
1968     }
1969 }