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