]> git.lizzy.rs Git - rust.git/blob - library/core/src/option.rs
Rollup merge of #75892 - ArekPiekarz:unstable_book_tls_model_typo, r=petrochenkov
[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 first, the
54 //! `check_optional` function needs to use pattern matching to
55 //! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or
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 //! This usage of [`Option`] to create safe nullable pointers is so
74 //! common that Rust does special optimizations to make the
75 //! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
76 //! in Rust are stored as efficiently as any other pointer type.
77 //!
78 //! # Examples
79 //!
80 //! Basic pattern matching on [`Option`]:
81 //!
82 //! ```
83 //! let msg = Some("howdy");
84 //!
85 //! // Take a reference to the contained string
86 //! if let Some(m) = &msg {
87 //!     println!("{}", *m);
88 //! }
89 //!
90 //! // Remove the contained string, destroying the Option
91 //! let unwrapped_msg = msg.unwrap_or("default message");
92 //! ```
93 //!
94 //! Initialize a result to [`None`] before a loop:
95 //!
96 //! ```
97 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
98 //!
99 //! // A list of data to search through.
100 //! let all_the_big_things = [
101 //!     Kingdom::Plant(250, "redwood"),
102 //!     Kingdom::Plant(230, "noble fir"),
103 //!     Kingdom::Plant(229, "sugar pine"),
104 //!     Kingdom::Animal(25, "blue whale"),
105 //!     Kingdom::Animal(19, "fin whale"),
106 //!     Kingdom::Animal(15, "north pacific right whale"),
107 //! ];
108 //!
109 //! // We're going to search for the name of the biggest animal,
110 //! // but to start with we've just got `None`.
111 //! let mut name_of_biggest_animal = None;
112 //! let mut size_of_biggest_animal = 0;
113 //! for big_thing in &all_the_big_things {
114 //!     match *big_thing {
115 //!         Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
116 //!             // Now we've found the name of some big animal
117 //!             size_of_biggest_animal = size;
118 //!             name_of_biggest_animal = Some(name);
119 //!         }
120 //!         Kingdom::Animal(..) | Kingdom::Plant(..) => ()
121 //!     }
122 //! }
123 //!
124 //! match name_of_biggest_animal {
125 //!     Some(name) => println!("the biggest animal is {}", name),
126 //!     None => println!("there are no animals :("),
127 //! }
128 //! ```
129 //!
130 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
131
132 #![stable(feature = "rust1", since = "1.0.0")]
133
134 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
135 use crate::pin::Pin;
136 use crate::{
137     convert, fmt, hint, mem,
138     ops::{self, Deref, DerefMut},
139 };
140
141 /// The `Option` type. See [the module level documentation](self) for more.
142 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
143 #[rustc_diagnostic_item = "option_type"]
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub enum Option<T> {
146     /// No value
147     #[lang = "None"]
148     #[stable(feature = "rust1", since = "1.0.0")]
149     None,
150     /// Some value `T`
151     #[lang = "Some"]
152     #[stable(feature = "rust1", since = "1.0.0")]
153     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
154 }
155
156 /////////////////////////////////////////////////////////////////////////////
157 // Type implementation
158 /////////////////////////////////////////////////////////////////////////////
159
160 impl<T> Option<T> {
161     /////////////////////////////////////////////////////////////////////////
162     // Querying the contained values
163     /////////////////////////////////////////////////////////////////////////
164
165     /// Returns `true` if the option is a [`Some`] value.
166     ///
167     /// # Examples
168     ///
169     /// ```
170     /// let x: Option<u32> = Some(2);
171     /// assert_eq!(x.is_some(), true);
172     ///
173     /// let x: Option<u32> = None;
174     /// assert_eq!(x.is_some(), false);
175     /// ```
176     #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"]
177     #[inline]
178     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
179     #[stable(feature = "rust1", since = "1.0.0")]
180     pub const fn is_some(&self) -> bool {
181         matches!(*self, Some(_))
182     }
183
184     /// Returns `true` if the option is a [`None`] value.
185     ///
186     /// # Examples
187     ///
188     /// ```
189     /// let x: Option<u32> = Some(2);
190     /// assert_eq!(x.is_none(), false);
191     ///
192     /// let x: Option<u32> = None;
193     /// assert_eq!(x.is_none(), true);
194     /// ```
195     #[must_use = "if you intended to assert that this doesn't have a value, consider \
196                   `.and_then(|| panic!(\"`Option` had a value when expected `None`\"))` instead"]
197     #[inline]
198     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
199     #[stable(feature = "rust1", since = "1.0.0")]
200     pub const fn is_none(&self) -> bool {
201         !self.is_some()
202     }
203
204     /// Returns `true` if the option is a [`Some`] value containing the given value.
205     ///
206     /// # Examples
207     ///
208     /// ```
209     /// #![feature(option_result_contains)]
210     ///
211     /// let x: Option<u32> = Some(2);
212     /// assert_eq!(x.contains(&2), true);
213     ///
214     /// let x: Option<u32> = Some(3);
215     /// assert_eq!(x.contains(&2), false);
216     ///
217     /// let x: Option<u32> = None;
218     /// assert_eq!(x.contains(&2), false);
219     /// ```
220     #[must_use]
221     #[inline]
222     #[unstable(feature = "option_result_contains", issue = "62358")]
223     pub fn contains<U>(&self, x: &U) -> bool
224     where
225         U: PartialEq<T>,
226     {
227         match self {
228             Some(y) => x == y,
229             None => false,
230         }
231     }
232
233     /////////////////////////////////////////////////////////////////////////
234     // Adapter for working with references
235     /////////////////////////////////////////////////////////////////////////
236
237     /// Converts from `&Option<T>` to `Option<&T>`.
238     ///
239     /// # Examples
240     ///
241     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
242     /// The [`map`] method takes the `self` argument by value, consuming the original,
243     /// so this technique uses `as_ref` to first take an `Option` to a reference
244     /// to the value inside the original.
245     ///
246     /// [`map`]: Option::map
247     /// [`String`]: ../../std/string/struct.String.html
248     ///
249     /// ```
250     /// let text: Option<String> = Some("Hello, world!".to_string());
251     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
252     /// // then consume *that* with `map`, leaving `text` on the stack.
253     /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
254     /// println!("still can print text: {:?}", text);
255     /// ```
256     #[inline]
257     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
258     #[stable(feature = "rust1", since = "1.0.0")]
259     pub const fn as_ref(&self) -> Option<&T> {
260         match *self {
261             Some(ref x) => Some(x),
262             None => None,
263         }
264     }
265
266     /// Converts from `&mut Option<T>` to `Option<&mut T>`.
267     ///
268     /// # Examples
269     ///
270     /// ```
271     /// let mut x = Some(2);
272     /// match x.as_mut() {
273     ///     Some(v) => *v = 42,
274     ///     None => {},
275     /// }
276     /// assert_eq!(x, Some(42));
277     /// ```
278     #[inline]
279     #[stable(feature = "rust1", since = "1.0.0")]
280     pub fn as_mut(&mut self) -> Option<&mut T> {
281         match *self {
282             Some(ref mut x) => Some(x),
283             None => None,
284         }
285     }
286
287     /// Converts from [`Pin`]`<&Option<T>>` to `Option<`[`Pin`]`<&T>>`.
288     #[inline]
289     #[stable(feature = "pin", since = "1.33.0")]
290     pub fn as_pin_ref(self: Pin<&Self>) -> Option<Pin<&T>> {
291         // SAFETY: `x` is guaranteed to be pinned because it comes from `self`
292         // which is pinned.
293         unsafe { Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x)) }
294     }
295
296     /// Converts from [`Pin`]`<&mut Option<T>>` to `Option<`[`Pin`]`<&mut T>>`.
297     #[inline]
298     #[stable(feature = "pin", since = "1.33.0")]
299     pub fn as_pin_mut(self: Pin<&mut Self>) -> Option<Pin<&mut T>> {
300         // SAFETY: `get_unchecked_mut` is never used to move the `Option` inside `self`.
301         // `x` is guaranteed to be pinned because it comes from `self` which is pinned.
302         unsafe { Pin::get_unchecked_mut(self).as_mut().map(|x| Pin::new_unchecked(x)) }
303     }
304
305     /////////////////////////////////////////////////////////////////////////
306     // Getting to contained values
307     /////////////////////////////////////////////////////////////////////////
308
309     /// Returns the contained [`Some`] value, consuming the `self` value.
310     ///
311     /// # Panics
312     ///
313     /// Panics if the value is a [`None`] with a custom panic message provided by
314     /// `msg`.
315     ///
316     /// # Examples
317     ///
318     /// ```
319     /// let x = Some("value");
320     /// assert_eq!(x.expect("fruits are healthy"), "value");
321     /// ```
322     ///
323     /// ```{.should_panic}
324     /// let x: Option<&str> = None;
325     /// x.expect("fruits are healthy"); // panics with `fruits are healthy`
326     /// ```
327     #[inline]
328     #[track_caller]
329     #[stable(feature = "rust1", since = "1.0.0")]
330     pub fn expect(self, msg: &str) -> T {
331         match self {
332             Some(val) => val,
333             None => expect_failed(msg),
334         }
335     }
336
337     /// Returns the contained [`Some`] value, consuming the `self` value.
338     ///
339     /// Because this function may panic, its use is generally discouraged.
340     /// Instead, prefer to use pattern matching and handle the [`None`]
341     /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
342     /// [`unwrap_or_default`].
343     ///
344     /// [`unwrap_or`]: Option::unwrap_or
345     /// [`unwrap_or_else`]: Option::unwrap_or_else
346     /// [`unwrap_or_default`]: Option::unwrap_or_default
347     ///
348     /// # Panics
349     ///
350     /// Panics if the self value equals [`None`].
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// let x = Some("air");
356     /// assert_eq!(x.unwrap(), "air");
357     /// ```
358     ///
359     /// ```{.should_panic}
360     /// let x: Option<&str> = None;
361     /// assert_eq!(x.unwrap(), "air"); // fails
362     /// ```
363     #[inline]
364     #[track_caller]
365     #[stable(feature = "rust1", since = "1.0.0")]
366     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
367     pub const fn unwrap(self) -> T {
368         match self {
369             Some(val) => val,
370             None => panic!("called `Option::unwrap()` on a `None` value"),
371         }
372     }
373
374     /// Returns the contained [`Some`] value or a provided default.
375     ///
376     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
377     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
378     /// which is lazily evaluated.
379     ///
380     /// [`unwrap_or_else`]: Option::unwrap_or_else
381     ///
382     /// # Examples
383     ///
384     /// ```
385     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
386     /// assert_eq!(None.unwrap_or("bike"), "bike");
387     /// ```
388     #[inline]
389     #[stable(feature = "rust1", since = "1.0.0")]
390     pub fn unwrap_or(self, default: T) -> T {
391         match self {
392             Some(x) => x,
393             None => default,
394         }
395     }
396
397     /// Returns the contained [`Some`] value or computes it from a closure.
398     ///
399     /// # Examples
400     ///
401     /// ```
402     /// let k = 10;
403     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
404     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
405     /// ```
406     #[inline]
407     #[stable(feature = "rust1", since = "1.0.0")]
408     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
409         match self {
410             Some(x) => x,
411             None => f(),
412         }
413     }
414
415     /////////////////////////////////////////////////////////////////////////
416     // Transforming contained values
417     /////////////////////////////////////////////////////////////////////////
418
419     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
420     ///
421     /// # Examples
422     ///
423     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
424     ///
425     /// [`String`]: ../../std/string/struct.String.html
426     /// ```
427     /// let maybe_some_string = Some(String::from("Hello, World!"));
428     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
429     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
430     ///
431     /// assert_eq!(maybe_some_len, Some(13));
432     /// ```
433     #[inline]
434     #[stable(feature = "rust1", since = "1.0.0")]
435     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
436         match self {
437             Some(x) => Some(f(x)),
438             None => None,
439         }
440     }
441
442     /// Applies a function to the contained value (if any),
443     /// or returns the provided default (if not).
444     ///
445     /// Arguments passed to `map_or` are eagerly evaluated; if you are passing
446     /// the result of a function call, it is recommended to use [`map_or_else`],
447     /// which is lazily evaluated.
448     ///
449     /// [`map_or_else`]: Option::map_or_else
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// let x = Some("foo");
455     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
456     ///
457     /// let x: Option<&str> = None;
458     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
459     /// ```
460     #[inline]
461     #[stable(feature = "rust1", since = "1.0.0")]
462     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
463         match self {
464             Some(t) => f(t),
465             None => default,
466         }
467     }
468
469     /// Applies a function to the contained value (if any),
470     /// or computes a default (if not).
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// let k = 21;
476     ///
477     /// let x = Some("foo");
478     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
479     ///
480     /// let x: Option<&str> = None;
481     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
482     /// ```
483     #[inline]
484     #[stable(feature = "rust1", since = "1.0.0")]
485     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
486         match self {
487             Some(t) => f(t),
488             None => default(),
489         }
490     }
491
492     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
493     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
494     ///
495     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
496     /// result of a function call, it is recommended to use [`ok_or_else`], which is
497     /// lazily evaluated.
498     ///
499     /// [`Result<T, E>`]: Result
500     /// [`Ok(v)`]: Ok
501     /// [`Err(err)`]: Err
502     /// [`Some(v)`]: Some
503     /// [`ok_or_else`]: Option::ok_or_else
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// let x = Some("foo");
509     /// assert_eq!(x.ok_or(0), Ok("foo"));
510     ///
511     /// let x: Option<&str> = None;
512     /// assert_eq!(x.ok_or(0), Err(0));
513     /// ```
514     #[inline]
515     #[stable(feature = "rust1", since = "1.0.0")]
516     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
517         match self {
518             Some(v) => Ok(v),
519             None => Err(err),
520         }
521     }
522
523     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
524     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
525     ///
526     /// [`Result<T, E>`]: Result
527     /// [`Ok(v)`]: Ok
528     /// [`Err(err())`]: Err
529     /// [`Some(v)`]: Some
530     ///
531     /// # Examples
532     ///
533     /// ```
534     /// let x = Some("foo");
535     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
536     ///
537     /// let x: Option<&str> = None;
538     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
539     /// ```
540     #[inline]
541     #[stable(feature = "rust1", since = "1.0.0")]
542     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
543         match self {
544             Some(v) => Ok(v),
545             None => Err(err()),
546         }
547     }
548
549     /////////////////////////////////////////////////////////////////////////
550     // Iterator constructors
551     /////////////////////////////////////////////////////////////////////////
552
553     /// Returns an iterator over the possibly contained value.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// let x = Some(4);
559     /// assert_eq!(x.iter().next(), Some(&4));
560     ///
561     /// let x: Option<u32> = None;
562     /// assert_eq!(x.iter().next(), None);
563     /// ```
564     #[inline]
565     #[rustc_const_unstable(feature = "const_option", issue = "67441")]
566     #[stable(feature = "rust1", since = "1.0.0")]
567     pub const fn iter(&self) -> Iter<'_, T> {
568         Iter { inner: Item { opt: self.as_ref() } }
569     }
570
571     /// Returns a mutable iterator over the possibly contained value.
572     ///
573     /// # Examples
574     ///
575     /// ```
576     /// let mut x = Some(4);
577     /// match x.iter_mut().next() {
578     ///     Some(v) => *v = 42,
579     ///     None => {},
580     /// }
581     /// assert_eq!(x, Some(42));
582     ///
583     /// let mut x: Option<u32> = None;
584     /// assert_eq!(x.iter_mut().next(), None);
585     /// ```
586     #[inline]
587     #[stable(feature = "rust1", since = "1.0.0")]
588     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
589         IterMut { inner: Item { opt: self.as_mut() } }
590     }
591
592     /////////////////////////////////////////////////////////////////////////
593     // Boolean operations on the values, eager and lazy
594     /////////////////////////////////////////////////////////////////////////
595
596     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
597     ///
598     /// # Examples
599     ///
600     /// ```
601     /// let x = Some(2);
602     /// let y: Option<&str> = None;
603     /// assert_eq!(x.and(y), None);
604     ///
605     /// let x: Option<u32> = None;
606     /// let y = Some("foo");
607     /// assert_eq!(x.and(y), None);
608     ///
609     /// let x = Some(2);
610     /// let y = Some("foo");
611     /// assert_eq!(x.and(y), Some("foo"));
612     ///
613     /// let x: Option<u32> = None;
614     /// let y: Option<&str> = None;
615     /// assert_eq!(x.and(y), None);
616     /// ```
617     #[inline]
618     #[stable(feature = "rust1", since = "1.0.0")]
619     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
620         match self {
621             Some(_) => optb,
622             None => None,
623         }
624     }
625
626     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
627     /// wrapped value and returns the result.
628     ///
629     /// Some languages call this operation flatmap.
630     ///
631     /// # Examples
632     ///
633     /// ```
634     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
635     /// fn nope(_: u32) -> Option<u32> { None }
636     ///
637     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
638     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
639     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
640     /// assert_eq!(None.and_then(sq).and_then(sq), None);
641     /// ```
642     #[inline]
643     #[stable(feature = "rust1", since = "1.0.0")]
644     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
645         match self {
646             Some(x) => f(x),
647             None => None,
648         }
649     }
650
651     /// Returns [`None`] if the option is [`None`], otherwise calls `predicate`
652     /// with the wrapped value and returns:
653     ///
654     /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped
655     ///   value), and
656     /// - [`None`] if `predicate` returns `false`.
657     ///
658     /// This function works similar to [`Iterator::filter()`]. You can imagine
659     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
660     /// lets you decide which elements to keep.
661     ///
662     /// # Examples
663     ///
664     /// ```rust
665     /// fn is_even(n: &i32) -> bool {
666     ///     n % 2 == 0
667     /// }
668     ///
669     /// assert_eq!(None.filter(is_even), None);
670     /// assert_eq!(Some(3).filter(is_even), None);
671     /// assert_eq!(Some(4).filter(is_even), Some(4));
672     /// ```
673     ///
674     #[inline]
675     #[stable(feature = "option_filter", since = "1.27.0")]
676     pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
677         if let Some(x) = self {
678             if predicate(&x) {
679                 return Some(x);
680             }
681         }
682         None
683     }
684
685     /// Returns the option if it contains a value, otherwise returns `optb`.
686     ///
687     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
688     /// result of a function call, it is recommended to use [`or_else`], which is
689     /// lazily evaluated.
690     ///
691     /// [`or_else`]: Option::or_else
692     ///
693     /// # Examples
694     ///
695     /// ```
696     /// let x = Some(2);
697     /// let y = None;
698     /// assert_eq!(x.or(y), Some(2));
699     ///
700     /// let x = None;
701     /// let y = Some(100);
702     /// assert_eq!(x.or(y), Some(100));
703     ///
704     /// let x = Some(2);
705     /// let y = Some(100);
706     /// assert_eq!(x.or(y), Some(2));
707     ///
708     /// let x: Option<u32> = None;
709     /// let y = None;
710     /// assert_eq!(x.or(y), None);
711     /// ```
712     #[inline]
713     #[stable(feature = "rust1", since = "1.0.0")]
714     pub fn or(self, optb: Option<T>) -> Option<T> {
715         match self {
716             Some(_) => self,
717             None => optb,
718         }
719     }
720
721     /// Returns the option if it contains a value, otherwise calls `f` and
722     /// returns the result.
723     ///
724     /// # Examples
725     ///
726     /// ```
727     /// fn nobody() -> Option<&'static str> { None }
728     /// fn vikings() -> Option<&'static str> { Some("vikings") }
729     ///
730     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
731     /// assert_eq!(None.or_else(vikings), Some("vikings"));
732     /// assert_eq!(None.or_else(nobody), None);
733     /// ```
734     #[inline]
735     #[stable(feature = "rust1", since = "1.0.0")]
736     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
737         match self {
738             Some(_) => self,
739             None => f(),
740         }
741     }
742
743     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`].
744     ///
745     /// # Examples
746     ///
747     /// ```
748     /// let x = Some(2);
749     /// let y: Option<u32> = None;
750     /// assert_eq!(x.xor(y), Some(2));
751     ///
752     /// let x: Option<u32> = None;
753     /// let y = Some(2);
754     /// assert_eq!(x.xor(y), Some(2));
755     ///
756     /// let x = Some(2);
757     /// let y = Some(2);
758     /// assert_eq!(x.xor(y), None);
759     ///
760     /// let x: Option<u32> = None;
761     /// let y: Option<u32> = None;
762     /// assert_eq!(x.xor(y), None);
763     /// ```
764     #[inline]
765     #[stable(feature = "option_xor", since = "1.37.0")]
766     pub fn xor(self, optb: Option<T>) -> Option<T> {
767         match (self, optb) {
768             (Some(a), None) => Some(a),
769             (None, Some(b)) => Some(b),
770             _ => None,
771         }
772     }
773
774     /////////////////////////////////////////////////////////////////////////
775     // Entry-like operations to insert if None and return a reference
776     /////////////////////////////////////////////////////////////////////////
777
778     /// Inserts `v` into the option if it is [`None`], then
779     /// returns a mutable reference to the contained value.
780     ///
781     /// # Examples
782     ///
783     /// ```
784     /// let mut x = None;
785     ///
786     /// {
787     ///     let y: &mut u32 = x.get_or_insert(5);
788     ///     assert_eq!(y, &5);
789     ///
790     ///     *y = 7;
791     /// }
792     ///
793     /// assert_eq!(x, Some(7));
794     /// ```
795     #[inline]
796     #[stable(feature = "option_entry", since = "1.20.0")]
797     pub fn get_or_insert(&mut self, v: T) -> &mut T {
798         self.get_or_insert_with(|| v)
799     }
800
801     /// Inserts a value computed from `f` into the option if it is [`None`], then
802     /// returns a mutable reference to the contained value.
803     ///
804     /// # Examples
805     ///
806     /// ```
807     /// let mut x = None;
808     ///
809     /// {
810     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
811     ///     assert_eq!(y, &5);
812     ///
813     ///     *y = 7;
814     /// }
815     ///
816     /// assert_eq!(x, Some(7));
817     /// ```
818     #[inline]
819     #[stable(feature = "option_entry", since = "1.20.0")]
820     pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
821         if let None = *self {
822             *self = Some(f());
823         }
824
825         match *self {
826             Some(ref mut v) => v,
827             // SAFETY: a `None` variant for `self` would have been replaced by a `Some`
828             // variant in the code above.
829             None => unsafe { hint::unreachable_unchecked() },
830         }
831     }
832
833     /////////////////////////////////////////////////////////////////////////
834     // Misc
835     /////////////////////////////////////////////////////////////////////////
836
837     /// Takes the value out of the option, leaving a [`None`] in its place.
838     ///
839     /// # Examples
840     ///
841     /// ```
842     /// let mut x = Some(2);
843     /// let y = x.take();
844     /// assert_eq!(x, None);
845     /// assert_eq!(y, Some(2));
846     ///
847     /// let mut x: Option<u32> = None;
848     /// let y = x.take();
849     /// assert_eq!(x, None);
850     /// assert_eq!(y, None);
851     /// ```
852     #[inline]
853     #[stable(feature = "rust1", since = "1.0.0")]
854     pub fn take(&mut self) -> Option<T> {
855         mem::take(self)
856     }
857
858     /// Replaces the actual value in the option by the value given in parameter,
859     /// returning the old value if present,
860     /// leaving a [`Some`] in its place without deinitializing either one.
861     ///
862     /// # Examples
863     ///
864     /// ```
865     /// let mut x = Some(2);
866     /// let old = x.replace(5);
867     /// assert_eq!(x, Some(5));
868     /// assert_eq!(old, Some(2));
869     ///
870     /// let mut x = None;
871     /// let old = x.replace(3);
872     /// assert_eq!(x, Some(3));
873     /// assert_eq!(old, None);
874     /// ```
875     #[inline]
876     #[stable(feature = "option_replace", since = "1.31.0")]
877     pub fn replace(&mut self, value: T) -> Option<T> {
878         mem::replace(self, Some(value))
879     }
880
881     /// Zips `self` with another `Option`.
882     ///
883     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some((s, o))`.
884     /// Otherwise, `None` is returned.
885     ///
886     /// # Examples
887     ///
888     /// ```
889     /// let x = Some(1);
890     /// let y = Some("hi");
891     /// let z = None::<u8>;
892     ///
893     /// assert_eq!(x.zip(y), Some((1, "hi")));
894     /// assert_eq!(x.zip(z), None);
895     /// ```
896     #[stable(feature = "option_zip_option", since = "1.46.0")]
897     pub fn zip<U>(self, other: Option<U>) -> Option<(T, U)> {
898         match (self, other) {
899             (Some(a), Some(b)) => Some((a, b)),
900             _ => None,
901         }
902     }
903
904     /// Zips `self` and another `Option` with function `f`.
905     ///
906     /// If `self` is `Some(s)` and `other` is `Some(o)`, this method returns `Some(f(s, o))`.
907     /// Otherwise, `None` is returned.
908     ///
909     /// # Examples
910     ///
911     /// ```
912     /// #![feature(option_zip)]
913     ///
914     /// #[derive(Debug, PartialEq)]
915     /// struct Point {
916     ///     x: f64,
917     ///     y: f64,
918     /// }
919     ///
920     /// impl Point {
921     ///     fn new(x: f64, y: f64) -> Self {
922     ///         Self { x, y }
923     ///     }
924     /// }
925     ///
926     /// let x = Some(17.5);
927     /// let y = Some(42.7);
928     ///
929     /// assert_eq!(x.zip_with(y, Point::new), Some(Point { x: 17.5, y: 42.7 }));
930     /// assert_eq!(x.zip_with(None, Point::new), None);
931     /// ```
932     #[unstable(feature = "option_zip", issue = "70086")]
933     pub fn zip_with<U, F, R>(self, other: Option<U>, f: F) -> Option<R>
934     where
935         F: FnOnce(T, U) -> R,
936     {
937         Some(f(self?, other?))
938     }
939 }
940
941 impl<T: Copy> Option<&T> {
942     /// Maps an `Option<&T>` to an `Option<T>` by copying the contents of the
943     /// option.
944     ///
945     /// # Examples
946     ///
947     /// ```
948     /// let x = 12;
949     /// let opt_x = Some(&x);
950     /// assert_eq!(opt_x, Some(&12));
951     /// let copied = opt_x.copied();
952     /// assert_eq!(copied, Some(12));
953     /// ```
954     #[stable(feature = "copied", since = "1.35.0")]
955     pub fn copied(self) -> Option<T> {
956         self.map(|&t| t)
957     }
958 }
959
960 impl<T: Copy> Option<&mut T> {
961     /// Maps an `Option<&mut T>` to an `Option<T>` by copying the contents of the
962     /// option.
963     ///
964     /// # Examples
965     ///
966     /// ```
967     /// let mut x = 12;
968     /// let opt_x = Some(&mut x);
969     /// assert_eq!(opt_x, Some(&mut 12));
970     /// let copied = opt_x.copied();
971     /// assert_eq!(copied, Some(12));
972     /// ```
973     #[stable(feature = "copied", since = "1.35.0")]
974     pub fn copied(self) -> Option<T> {
975         self.map(|&mut t| t)
976     }
977 }
978
979 impl<T: Clone> Option<&T> {
980     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
981     /// option.
982     ///
983     /// # Examples
984     ///
985     /// ```
986     /// let x = 12;
987     /// let opt_x = Some(&x);
988     /// assert_eq!(opt_x, Some(&12));
989     /// let cloned = opt_x.cloned();
990     /// assert_eq!(cloned, Some(12));
991     /// ```
992     #[stable(feature = "rust1", since = "1.0.0")]
993     pub fn cloned(self) -> Option<T> {
994         self.map(|t| t.clone())
995     }
996 }
997
998 impl<T: Clone> Option<&mut T> {
999     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
1000     /// option.
1001     ///
1002     /// # Examples
1003     ///
1004     /// ```
1005     /// let mut x = 12;
1006     /// let opt_x = Some(&mut x);
1007     /// assert_eq!(opt_x, Some(&mut 12));
1008     /// let cloned = opt_x.cloned();
1009     /// assert_eq!(cloned, Some(12));
1010     /// ```
1011     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
1012     pub fn cloned(self) -> Option<T> {
1013         self.map(|t| t.clone())
1014     }
1015 }
1016
1017 impl<T: fmt::Debug> Option<T> {
1018     /// Consumes `self` while expecting [`None`] and returning nothing.
1019     ///
1020     /// # Panics
1021     ///
1022     /// Panics if the value is a [`Some`], with a panic message including the
1023     /// passed message, and the content of the [`Some`].
1024     ///
1025     /// # Examples
1026     ///
1027     /// ```
1028     /// #![feature(option_expect_none)]
1029     ///
1030     /// use std::collections::HashMap;
1031     /// let mut squares = HashMap::new();
1032     /// for i in -10..=10 {
1033     ///     // This will not panic, since all keys are unique.
1034     ///     squares.insert(i, i * i).expect_none("duplicate key");
1035     /// }
1036     /// ```
1037     ///
1038     /// ```{.should_panic}
1039     /// #![feature(option_expect_none)]
1040     ///
1041     /// use std::collections::HashMap;
1042     /// let mut sqrts = HashMap::new();
1043     /// for i in -10..=10 {
1044     ///     // This will panic, since both negative and positive `i` will
1045     ///     // insert the same `i * i` key, returning the old `Some(i)`.
1046     ///     sqrts.insert(i * i, i).expect_none("duplicate key");
1047     /// }
1048     /// ```
1049     #[inline]
1050     #[track_caller]
1051     #[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1052     pub fn expect_none(self, msg: &str) {
1053         if let Some(val) = self {
1054             expect_none_failed(msg, &val);
1055         }
1056     }
1057
1058     /// Consumes `self` while expecting [`None`] and returning nothing.
1059     ///
1060     /// # Panics
1061     ///
1062     /// Panics if the value is a [`Some`], with a custom panic message provided
1063     /// by the [`Some`]'s value.
1064     ///
1065     /// [`Some(v)`]: Some
1066     ///
1067     /// # Examples
1068     ///
1069     /// ```
1070     /// #![feature(option_unwrap_none)]
1071     ///
1072     /// use std::collections::HashMap;
1073     /// let mut squares = HashMap::new();
1074     /// for i in -10..=10 {
1075     ///     // This will not panic, since all keys are unique.
1076     ///     squares.insert(i, i * i).unwrap_none();
1077     /// }
1078     /// ```
1079     ///
1080     /// ```{.should_panic}
1081     /// #![feature(option_unwrap_none)]
1082     ///
1083     /// use std::collections::HashMap;
1084     /// let mut sqrts = HashMap::new();
1085     /// for i in -10..=10 {
1086     ///     // This will panic, since both negative and positive `i` will
1087     ///     // insert the same `i * i` key, returning the old `Some(i)`.
1088     ///     sqrts.insert(i * i, i).unwrap_none();
1089     /// }
1090     /// ```
1091     #[inline]
1092     #[track_caller]
1093     #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1094     pub fn unwrap_none(self) {
1095         if let Some(val) = self {
1096             expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1097         }
1098     }
1099 }
1100
1101 impl<T: Default> Option<T> {
1102     /// Returns the contained [`Some`] value or a default
1103     ///
1104     /// Consumes the `self` argument then, if [`Some`], returns the contained
1105     /// value, otherwise if [`None`], returns the [default value] for that
1106     /// type.
1107     ///
1108     /// # Examples
1109     ///
1110     /// Converts a string to an integer, turning poorly-formed strings
1111     /// into 0 (the default value for integers). [`parse`] converts
1112     /// a string to any other type that implements [`FromStr`], returning
1113     /// [`None`] on error.
1114     ///
1115     /// ```
1116     /// let good_year_from_input = "1909";
1117     /// let bad_year_from_input = "190blarg";
1118     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
1119     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
1120     ///
1121     /// assert_eq!(1909, good_year);
1122     /// assert_eq!(0, bad_year);
1123     /// ```
1124     ///
1125     /// [default value]: Default::default
1126     /// [`parse`]: str::parse
1127     /// [`FromStr`]: crate::str::FromStr
1128     #[inline]
1129     #[stable(feature = "rust1", since = "1.0.0")]
1130     pub fn unwrap_or_default(self) -> T {
1131         match self {
1132             Some(x) => x,
1133             None => Default::default(),
1134         }
1135     }
1136 }
1137
1138 impl<T: Deref> Option<T> {
1139     /// Converts from `Option<T>` (or `&Option<T>`) to `Option<&T::Target>`.
1140     ///
1141     /// Leaves the original Option in-place, creating a new one with a reference
1142     /// to the original one, additionally coercing the contents via [`Deref`].
1143     ///
1144     /// # Examples
1145     ///
1146     /// ```
1147     /// let x: Option<String> = Some("hey".to_owned());
1148     /// assert_eq!(x.as_deref(), Some("hey"));
1149     ///
1150     /// let x: Option<String> = None;
1151     /// assert_eq!(x.as_deref(), None);
1152     /// ```
1153     #[stable(feature = "option_deref", since = "1.40.0")]
1154     pub fn as_deref(&self) -> Option<&T::Target> {
1155         self.as_ref().map(|t| t.deref())
1156     }
1157 }
1158
1159 impl<T: DerefMut> Option<T> {
1160     /// Converts from `Option<T>` (or `&mut Option<T>`) to `Option<&mut T::Target>`.
1161     ///
1162     /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to
1163     /// the inner type's `Deref::Target` type.
1164     ///
1165     /// # Examples
1166     ///
1167     /// ```
1168     /// let mut x: Option<String> = Some("hey".to_owned());
1169     /// assert_eq!(x.as_deref_mut().map(|x| {
1170     ///     x.make_ascii_uppercase();
1171     ///     x
1172     /// }), Some("HEY".to_owned().as_mut_str()));
1173     /// ```
1174     #[stable(feature = "option_deref", since = "1.40.0")]
1175     pub fn as_deref_mut(&mut self) -> Option<&mut T::Target> {
1176         self.as_mut().map(|t| t.deref_mut())
1177     }
1178 }
1179
1180 impl<T, E> Option<Result<T, E>> {
1181     /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`.
1182     ///
1183     /// [`None`] will be mapped to [`Ok`]`(`[`None`]`)`.
1184     /// [`Some`]`(`[`Ok`]`(_))` and [`Some`]`(`[`Err`]`(_))` will be mapped to
1185     /// [`Ok`]`(`[`Some`]`(_))` and [`Err`]`(_)`.
1186     ///
1187     /// # Examples
1188     ///
1189     /// ```
1190     /// #[derive(Debug, Eq, PartialEq)]
1191     /// struct SomeErr;
1192     ///
1193     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
1194     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
1195     /// assert_eq!(x, y.transpose());
1196     /// ```
1197     #[inline]
1198     #[stable(feature = "transpose_result", since = "1.33.0")]
1199     pub fn transpose(self) -> Result<Option<T>, E> {
1200         match self {
1201             Some(Ok(x)) => Ok(Some(x)),
1202             Some(Err(e)) => Err(e),
1203             None => Ok(None),
1204         }
1205     }
1206 }
1207
1208 // This is a separate function to reduce the code size of .expect() itself.
1209 #[inline(never)]
1210 #[cold]
1211 #[track_caller]
1212 fn expect_failed(msg: &str) -> ! {
1213     panic!("{}", msg)
1214 }
1215
1216 // This is a separate function to reduce the code size of .expect_none() itself.
1217 #[inline(never)]
1218 #[cold]
1219 #[track_caller]
1220 fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1221     panic!("{}: {:?}", msg, value)
1222 }
1223
1224 /////////////////////////////////////////////////////////////////////////////
1225 // Trait implementations
1226 /////////////////////////////////////////////////////////////////////////////
1227
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<T: Clone> Clone for Option<T> {
1230     #[inline]
1231     fn clone(&self) -> Self {
1232         match self {
1233             Some(x) => Some(x.clone()),
1234             None => None,
1235         }
1236     }
1237
1238     #[inline]
1239     fn clone_from(&mut self, source: &Self) {
1240         match (self, source) {
1241             (Some(to), Some(from)) => to.clone_from(from),
1242             (to, from) => *to = from.clone(),
1243         }
1244     }
1245 }
1246
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl<T> Default for Option<T> {
1249     /// Returns [`None`][Option::None].
1250     ///
1251     /// # Examples
1252     ///
1253     /// ```
1254     /// let opt: Option<u32> = Option::default();
1255     /// assert!(opt.is_none());
1256     /// ```
1257     #[inline]
1258     fn default() -> Option<T> {
1259         None
1260     }
1261 }
1262
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl<T> IntoIterator for Option<T> {
1265     type Item = T;
1266     type IntoIter = IntoIter<T>;
1267
1268     /// Returns a consuming iterator over the possibly contained value.
1269     ///
1270     /// # Examples
1271     ///
1272     /// ```
1273     /// let x = Some("string");
1274     /// let v: Vec<&str> = x.into_iter().collect();
1275     /// assert_eq!(v, ["string"]);
1276     ///
1277     /// let x = None;
1278     /// let v: Vec<&str> = x.into_iter().collect();
1279     /// assert!(v.is_empty());
1280     /// ```
1281     #[inline]
1282     fn into_iter(self) -> IntoIter<T> {
1283         IntoIter { inner: Item { opt: self } }
1284     }
1285 }
1286
1287 #[stable(since = "1.4.0", feature = "option_iter")]
1288 impl<'a, T> IntoIterator for &'a Option<T> {
1289     type Item = &'a T;
1290     type IntoIter = Iter<'a, T>;
1291
1292     fn into_iter(self) -> Iter<'a, T> {
1293         self.iter()
1294     }
1295 }
1296
1297 #[stable(since = "1.4.0", feature = "option_iter")]
1298 impl<'a, T> IntoIterator for &'a mut Option<T> {
1299     type Item = &'a mut T;
1300     type IntoIter = IterMut<'a, T>;
1301
1302     fn into_iter(self) -> IterMut<'a, T> {
1303         self.iter_mut()
1304     }
1305 }
1306
1307 #[stable(since = "1.12.0", feature = "option_from")]
1308 impl<T> From<T> for Option<T> {
1309     /// Copies `val` into a new `Some`.
1310     ///
1311     /// # Examples
1312     ///
1313     /// ```
1314     /// let o: Option<u8> = Option::from(67);
1315     ///
1316     /// assert_eq!(Some(67), o);
1317     /// ```
1318     fn from(val: T) -> Option<T> {
1319         Some(val)
1320     }
1321 }
1322
1323 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1324 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1325     /// Converts from `&Option<T>` to `Option<&T>`.
1326     ///
1327     /// # Examples
1328     ///
1329     /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1330     /// The [`map`] method takes the `self` argument by value, consuming the original,
1331     /// so this technique uses `as_ref` to first take an `Option` to a reference
1332     /// to the value inside the original.
1333     ///
1334     /// [`map`]: Option::map
1335     /// [`String`]: ../../std/string/struct.String.html
1336     ///
1337     /// ```
1338     /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1339     /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1340     ///
1341     /// println!("Can still print s: {:?}", s);
1342     ///
1343     /// assert_eq!(o, Some(18));
1344     /// ```
1345     fn from(o: &'a Option<T>) -> Option<&'a T> {
1346         o.as_ref()
1347     }
1348 }
1349
1350 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1351 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1352     /// Converts from `&mut Option<T>` to `Option<&mut T>`
1353     ///
1354     /// # Examples
1355     ///
1356     /// ```
1357     /// let mut s = Some(String::from("Hello"));
1358     /// let o: Option<&mut String> = Option::from(&mut s);
1359     ///
1360     /// match o {
1361     ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
1362     ///     None => (),
1363     /// }
1364     ///
1365     /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1366     /// ```
1367     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1368         o.as_mut()
1369     }
1370 }
1371
1372 /////////////////////////////////////////////////////////////////////////////
1373 // The Option Iterators
1374 /////////////////////////////////////////////////////////////////////////////
1375
1376 #[derive(Clone, Debug)]
1377 struct Item<A> {
1378     opt: Option<A>,
1379 }
1380
1381 impl<A> Iterator for Item<A> {
1382     type Item = A;
1383
1384     #[inline]
1385     fn next(&mut self) -> Option<A> {
1386         self.opt.take()
1387     }
1388
1389     #[inline]
1390     fn size_hint(&self) -> (usize, Option<usize>) {
1391         match self.opt {
1392             Some(_) => (1, Some(1)),
1393             None => (0, Some(0)),
1394         }
1395     }
1396 }
1397
1398 impl<A> DoubleEndedIterator for Item<A> {
1399     #[inline]
1400     fn next_back(&mut self) -> Option<A> {
1401         self.opt.take()
1402     }
1403 }
1404
1405 impl<A> ExactSizeIterator for Item<A> {}
1406 impl<A> FusedIterator for Item<A> {}
1407 unsafe impl<A> TrustedLen for Item<A> {}
1408
1409 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1410 ///
1411 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1412 ///
1413 /// This `struct` is created by the [`Option::iter`] function.
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 #[derive(Debug)]
1416 pub struct Iter<'a, A: 'a> {
1417     inner: Item<&'a A>,
1418 }
1419
1420 #[stable(feature = "rust1", since = "1.0.0")]
1421 impl<'a, A> Iterator for Iter<'a, A> {
1422     type Item = &'a A;
1423
1424     #[inline]
1425     fn next(&mut self) -> Option<&'a A> {
1426         self.inner.next()
1427     }
1428     #[inline]
1429     fn size_hint(&self) -> (usize, Option<usize>) {
1430         self.inner.size_hint()
1431     }
1432 }
1433
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1436     #[inline]
1437     fn next_back(&mut self) -> Option<&'a A> {
1438         self.inner.next_back()
1439     }
1440 }
1441
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<A> ExactSizeIterator for Iter<'_, A> {}
1444
1445 #[stable(feature = "fused", since = "1.26.0")]
1446 impl<A> FusedIterator for Iter<'_, A> {}
1447
1448 #[unstable(feature = "trusted_len", issue = "37572")]
1449 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1450
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<A> Clone for Iter<'_, A> {
1453     #[inline]
1454     fn clone(&self) -> Self {
1455         Iter { inner: self.inner.clone() }
1456     }
1457 }
1458
1459 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1460 ///
1461 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1462 ///
1463 /// This `struct` is created by the [`Option::iter_mut`] function.
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 #[derive(Debug)]
1466 pub struct IterMut<'a, A: 'a> {
1467     inner: Item<&'a mut A>,
1468 }
1469
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<'a, A> Iterator for IterMut<'a, A> {
1472     type Item = &'a mut A;
1473
1474     #[inline]
1475     fn next(&mut self) -> Option<&'a mut A> {
1476         self.inner.next()
1477     }
1478     #[inline]
1479     fn size_hint(&self) -> (usize, Option<usize>) {
1480         self.inner.size_hint()
1481     }
1482 }
1483
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1486     #[inline]
1487     fn next_back(&mut self) -> Option<&'a mut A> {
1488         self.inner.next_back()
1489     }
1490 }
1491
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1494
1495 #[stable(feature = "fused", since = "1.26.0")]
1496 impl<A> FusedIterator for IterMut<'_, A> {}
1497 #[unstable(feature = "trusted_len", issue = "37572")]
1498 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1499
1500 /// An iterator over the value in [`Some`] variant of an [`Option`].
1501 ///
1502 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1503 ///
1504 /// This `struct` is created by the [`Option::into_iter`] function.
1505 ///
1506 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1507 #[derive(Clone, Debug)]
1508 #[stable(feature = "rust1", since = "1.0.0")]
1509 pub struct IntoIter<A> {
1510     inner: Item<A>,
1511 }
1512
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 impl<A> Iterator for IntoIter<A> {
1515     type Item = A;
1516
1517     #[inline]
1518     fn next(&mut self) -> Option<A> {
1519         self.inner.next()
1520     }
1521     #[inline]
1522     fn size_hint(&self) -> (usize, Option<usize>) {
1523         self.inner.size_hint()
1524     }
1525 }
1526
1527 #[stable(feature = "rust1", since = "1.0.0")]
1528 impl<A> DoubleEndedIterator for IntoIter<A> {
1529     #[inline]
1530     fn next_back(&mut self) -> Option<A> {
1531         self.inner.next_back()
1532     }
1533 }
1534
1535 #[stable(feature = "rust1", since = "1.0.0")]
1536 impl<A> ExactSizeIterator for IntoIter<A> {}
1537
1538 #[stable(feature = "fused", since = "1.26.0")]
1539 impl<A> FusedIterator for IntoIter<A> {}
1540
1541 #[unstable(feature = "trusted_len", issue = "37572")]
1542 unsafe impl<A> TrustedLen for IntoIter<A> {}
1543
1544 /////////////////////////////////////////////////////////////////////////////
1545 // FromIterator
1546 /////////////////////////////////////////////////////////////////////////////
1547
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1550     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1551     /// no further elements are taken, and the [`None`][Option::None] is
1552     /// returned. Should no [`None`][Option::None] occur, a container with the
1553     /// values of each [`Option`] is returned.
1554     ///
1555     /// # Examples
1556     ///
1557     /// Here is an example which increments every integer in a vector.
1558     /// We use the checked variant of `add` that returns `None` when the
1559     /// calculation would result in an overflow.
1560     ///
1561     /// ```
1562     /// let items = vec![0_u16, 1, 2];
1563     ///
1564     /// let res: Option<Vec<u16>> = items
1565     ///     .iter()
1566     ///     .map(|x| x.checked_add(1))
1567     ///     .collect();
1568     ///
1569     /// assert_eq!(res, Some(vec![1, 2, 3]));
1570     /// ```
1571     ///
1572     /// As you can see, this will return the expected, valid items.
1573     ///
1574     /// Here is another example that tries to subtract one from another list
1575     /// of integers, this time checking for underflow:
1576     ///
1577     /// ```
1578     /// let items = vec![2_u16, 1, 0];
1579     ///
1580     /// let res: Option<Vec<u16>> = items
1581     ///     .iter()
1582     ///     .map(|x| x.checked_sub(1))
1583     ///     .collect();
1584     ///
1585     /// assert_eq!(res, None);
1586     /// ```
1587     ///
1588     /// Since the last element is zero, it would underflow. Thus, the resulting
1589     /// value is `None`.
1590     ///
1591     /// Here is a variation on the previous example, showing that no
1592     /// further elements are taken from `iter` after the first `None`.
1593     ///
1594     /// ```
1595     /// let items = vec![3_u16, 2, 1, 10];
1596     ///
1597     /// let mut shared = 0;
1598     ///
1599     /// let res: Option<Vec<u16>> = items
1600     ///     .iter()
1601     ///     .map(|x| { shared += x; x.checked_sub(2) })
1602     ///     .collect();
1603     ///
1604     /// assert_eq!(res, None);
1605     /// assert_eq!(shared, 6);
1606     /// ```
1607     ///
1608     /// Since the third element caused an underflow, no further elements were taken,
1609     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1610     #[inline]
1611     fn from_iter<I: IntoIterator<Item = Option<A>>>(iter: I) -> Option<V> {
1612         // FIXME(#11084): This could be replaced with Iterator::scan when this
1613         // performance bug is closed.
1614
1615         iter.into_iter().map(|x| x.ok_or(())).collect::<Result<_, _>>().ok()
1616     }
1617 }
1618
1619 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1620 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1621 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1622 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1623 #[rustc_diagnostic_item = "none_error"]
1624 #[unstable(feature = "try_trait", issue = "42327")]
1625 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1626 pub struct NoneError;
1627
1628 #[unstable(feature = "try_trait", issue = "42327")]
1629 impl<T> ops::Try for Option<T> {
1630     type Ok = T;
1631     type Error = NoneError;
1632
1633     #[inline]
1634     fn into_result(self) -> Result<T, NoneError> {
1635         self.ok_or(NoneError)
1636     }
1637
1638     #[inline]
1639     fn from_ok(v: T) -> Self {
1640         Some(v)
1641     }
1642
1643     #[inline]
1644     fn from_error(_: NoneError) -> Self {
1645         None
1646     }
1647 }
1648
1649 impl<T> Option<Option<T>> {
1650     /// Converts from `Option<Option<T>>` to `Option<T>`
1651     ///
1652     /// # Examples
1653     /// Basic usage:
1654     /// ```
1655     /// let x: Option<Option<u32>> = Some(Some(6));
1656     /// assert_eq!(Some(6), x.flatten());
1657     ///
1658     /// let x: Option<Option<u32>> = Some(None);
1659     /// assert_eq!(None, x.flatten());
1660     ///
1661     /// let x: Option<Option<u32>> = None;
1662     /// assert_eq!(None, x.flatten());
1663     /// ```
1664     /// Flattening once only removes one level of nesting:
1665     /// ```
1666     /// let x: Option<Option<Option<u32>>> = Some(Some(Some(6)));
1667     /// assert_eq!(Some(Some(6)), x.flatten());
1668     /// assert_eq!(Some(6), x.flatten().flatten());
1669     /// ```
1670     #[inline]
1671     #[stable(feature = "option_flattening", since = "1.40.0")]
1672     pub fn flatten(self) -> Option<T> {
1673         self.and_then(convert::identity)
1674     }
1675 }