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