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