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