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