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