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