1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! Type [`Option`] represents an optional value: every [`Option`]
14 //! is either [`Some`] and contains a value, or [`None`], and
15 //! does not. [`Option`] types are very common in Rust code, as
16 //! they have a number of uses:
19 //! * Return values for functions that are not defined
20 //! over their entire input range (partial functions)
21 //! * Return value for otherwise reporting simple errors, where `None` is
23 //! * Optional struct fields
24 //! * Struct fields that can be loaned or "taken"
25 //! * Optional function arguments
26 //! * Nullable pointers
27 //! * Swapping things out of difficult situations
29 //! [`Option`]s are commonly paired with pattern matching to query the presence
30 //! of a value and take action, always accounting for the [`None`] case.
33 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
34 //! if denominator == 0.0 {
37 //! Some(numerator / denominator)
41 //! // The return value of the function is an option
42 //! let result = divide(2.0, 3.0);
44 //! // Pattern match to retrieve the value
46 //! // The division was valid
47 //! Some(x) => println!("Result: {}", x),
48 //! // The division was invalid
49 //! None => println!("Cannot divide by 0"),
54 // FIXME: Show how `Option` is used in practice, with lots of methods
56 //! # Options and pointers ("nullable" pointers)
58 //! Rust's pointer types must always point to a valid location; there are
59 //! no "null" pointers. Instead, Rust has *optional* pointers, like
60 //! the optional owned box, [`Option`]`<`[`Box<T>`]`>`.
62 //! The following example uses [`Option`] to create an optional box of
63 //! [`i32`]. Notice that in order to use the inner [`i32`] value first the
64 //! `check_optional` function needs to use pattern matching to
65 //! determine whether the box has a value (i.e. it is [`Some(...)`][`Some`]) or
69 //! let optional: Option<Box<i32>> = None;
70 //! check_optional(&optional);
72 //! let optional: Option<Box<i32>> = Some(Box::new(9000));
73 //! check_optional(&optional);
75 //! fn check_optional(optional: &Option<Box<i32>>) {
77 //! Some(ref p) => println!("have value {}", p),
78 //! None => println!("have no value"),
83 //! This usage of [`Option`] to create safe nullable pointers is so
84 //! common that Rust does special optimizations to make the
85 //! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
86 //! in Rust are stored as efficiently as any other pointer type.
90 //! Basic pattern matching on [`Option`]:
93 //! let msg = Some("howdy");
95 //! // Take a reference to the contained string
96 //! if let Some(ref m) = msg {
97 //! println!("{}", *m);
100 //! // Remove the contained string, destroying the Option
101 //! let unwrapped_msg = msg.unwrap_or("default message");
104 //! Initialize a result to [`None`] before a loop:
107 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
109 //! // A list of data to search through.
110 //! let all_the_big_things = [
111 //! Kingdom::Plant(250, "redwood"),
112 //! Kingdom::Plant(230, "noble fir"),
113 //! Kingdom::Plant(229, "sugar pine"),
114 //! Kingdom::Animal(25, "blue whale"),
115 //! Kingdom::Animal(19, "fin whale"),
116 //! Kingdom::Animal(15, "north pacific right whale"),
119 //! // We're going to search for the name of the biggest animal,
120 //! // but to start with we've just got `None`.
121 //! let mut name_of_biggest_animal = None;
122 //! let mut size_of_biggest_animal = 0;
123 //! for big_thing in &all_the_big_things {
124 //! match *big_thing {
125 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
126 //! // Now we've found the name of some big animal
127 //! size_of_biggest_animal = size;
128 //! name_of_biggest_animal = Some(name);
130 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
134 //! match name_of_biggest_animal {
135 //! Some(name) => println!("the biggest animal is {}", name),
136 //! None => println!("there are no animals :("),
140 //! [`Option`]: enum.Option.html
141 //! [`Some`]: enum.Option.html#variant.Some
142 //! [`None`]: enum.Option.html#variant.None
143 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
144 //! [`i32`]: ../../std/primitive.i32.html
146 #![stable(feature = "rust1", since = "1.0.0")]
148 use iter
::{FromIterator, FusedIterator}
;
151 // Note that this is not a lang item per se, but it has a hidden dependency on
152 // `Iterator`, which is one. The compiler assumes that the `next` method of
153 // `Iterator` is an enumeration with one type parameter and two variants,
154 // which basically means it must be `Option`.
156 /// The `Option` type. See [the module level documentation](index.html) for more.
157 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
158 #[stable(feature = "rust1", since = "1.0.0")]
161 #[stable(feature = "rust1", since = "1.0.0")]
164 #[stable(feature = "rust1", since = "1.0.0")]
165 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
168 /////////////////////////////////////////////////////////////////////////////
169 // Type implementation
170 /////////////////////////////////////////////////////////////////////////////
173 /////////////////////////////////////////////////////////////////////////
174 // Querying the contained values
175 /////////////////////////////////////////////////////////////////////////
177 /// Returns `true` if the option is a `Some` value.
182 /// let x: Option<u32> = Some(2);
183 /// assert_eq!(x.is_some(), true);
185 /// let x: Option<u32> = None;
186 /// assert_eq!(x.is_some(), false);
189 #[stable(feature = "rust1", since = "1.0.0")]
190 pub fn is_some(&self) -> bool
{
197 /// Returns `true` if the option is a `None` value.
202 /// let x: Option<u32> = Some(2);
203 /// assert_eq!(x.is_none(), false);
205 /// let x: Option<u32> = None;
206 /// assert_eq!(x.is_none(), true);
209 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn is_none(&self) -> bool
{
214 /////////////////////////////////////////////////////////////////////////
215 // Adapter for working with references
216 /////////////////////////////////////////////////////////////////////////
218 /// Converts from `Option<T>` to `Option<&T>`.
222 /// Convert an `Option<String>` into an `Option<usize>`, preserving the original.
223 /// The [`map`] method takes the `self` argument by value, consuming the original,
224 /// so this technique uses `as_ref` to first take an `Option` to a reference
225 /// to the value inside the original.
227 /// [`map`]: enum.Option.html#method.map
230 /// let num_as_str: Option<String> = Some("10".to_string());
231 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
232 /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
233 /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len());
234 /// println!("still can print num_as_str: {:?}", num_as_str);
237 #[stable(feature = "rust1", since = "1.0.0")]
238 pub fn as_ref(&self) -> Option
<&T
> {
240 Some(ref x
) => Some(x
),
245 /// Converts from `Option<T>` to `Option<&mut T>`.
250 /// let mut x = Some(2);
251 /// match x.as_mut() {
252 /// Some(v) => *v = 42,
255 /// assert_eq!(x, Some(42));
258 #[stable(feature = "rust1", since = "1.0.0")]
259 pub fn as_mut(&mut self) -> Option
<&mut T
> {
261 Some(ref mut x
) => Some(x
),
266 /////////////////////////////////////////////////////////////////////////
267 // Getting to contained values
268 /////////////////////////////////////////////////////////////////////////
270 /// Unwraps an option, yielding the content of a `Some`.
274 /// Panics if the value is a `None` with a custom panic message provided by
280 /// let x = Some("value");
281 /// assert_eq!(x.expect("the world is ending"), "value");
284 /// ```{.should_panic}
285 /// let x: Option<&str> = None;
286 /// x.expect("the world is ending"); // panics with `the world is ending`
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn expect(self, msg
: &str) -> T
{
293 None
=> expect_failed(msg
),
297 /// Moves the value `v` out of the `Option<T>` if it is `Some(v)`.
299 /// In general, because this function may panic, its use is discouraged.
300 /// Instead, prefer to use pattern matching and handle the `None`
305 /// Panics if the self value equals `None`.
310 /// let x = Some("air");
311 /// assert_eq!(x.unwrap(), "air");
314 /// ```{.should_panic}
315 /// let x: Option<&str> = None;
316 /// assert_eq!(x.unwrap(), "air"); // fails
319 #[stable(feature = "rust1", since = "1.0.0")]
320 pub fn unwrap(self) -> T
{
323 None
=> panic
!("called `Option::unwrap()` on a `None` value"),
327 /// Returns the contained value or a default.
332 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
333 /// assert_eq!(None.unwrap_or("bike"), "bike");
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn unwrap_or(self, def
: T
) -> T
{
344 /// Returns the contained value or computes it from a closure.
350 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
351 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn unwrap_or_else
<F
: FnOnce() -> T
>(self, f
: F
) -> T
{
362 /////////////////////////////////////////////////////////////////////////
363 // Transforming contained values
364 /////////////////////////////////////////////////////////////////////////
366 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
370 /// Convert an `Option<String>` into an `Option<usize>`, consuming the original:
373 /// let maybe_some_string = Some(String::from("Hello, World!"));
374 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
375 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
377 /// assert_eq!(maybe_some_len, Some(13));
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn map
<U
, F
: FnOnce(T
) -> U
>(self, f
: F
) -> Option
<U
> {
383 Some(x
) => Some(f(x
)),
388 /// Applies a function to the contained value (if any),
389 /// or returns a `default` (if not).
394 /// let x = Some("foo");
395 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
397 /// let x: Option<&str> = None;
398 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn map_or
<U
, F
: FnOnce(T
) -> U
>(self, default: U
, f
: F
) -> U
{
409 /// Applies a function to the contained value (if any),
410 /// or computes a `default` (if not).
417 /// let x = Some("foo");
418 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
420 /// let x: Option<&str> = None;
421 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn map_or_else
<U
, D
: FnOnce() -> U
, F
: FnOnce(T
) -> U
>(self, default: D
, f
: F
) -> U
{
432 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping `Some(v)` to
433 /// [`Ok(v)`] and `None` to [`Err(err)`][Err].
435 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
436 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
437 /// [Err]: ../../std/result/enum.Result.html#variant.Err
442 /// let x = Some("foo");
443 /// assert_eq!(x.ok_or(0), Ok("foo"));
445 /// let x: Option<&str> = None;
446 /// assert_eq!(x.ok_or(0), Err(0));
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn ok_or
<E
>(self, err
: E
) -> Result
<T
, E
> {
457 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping `Some(v)` to
458 /// [`Ok(v)`] and `None` to [`Err(err())`][Err].
460 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
461 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
462 /// [Err]: ../../std/result/enum.Result.html#variant.Err
467 /// let x = Some("foo");
468 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
470 /// let x: Option<&str> = None;
471 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn ok_or_else
<E
, F
: FnOnce() -> E
>(self, err
: F
) -> Result
<T
, E
> {
482 /////////////////////////////////////////////////////////////////////////
483 // Iterator constructors
484 /////////////////////////////////////////////////////////////////////////
486 /// Returns an iterator over the possibly contained value.
492 /// assert_eq!(x.iter().next(), Some(&4));
494 /// let x: Option<u32> = None;
495 /// assert_eq!(x.iter().next(), None);
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn iter(&self) -> Iter
<T
> {
500 Iter { inner: Item { opt: self.as_ref() }
}
503 /// Returns a mutable iterator over the possibly contained value.
508 /// let mut x = Some(4);
509 /// match x.iter_mut().next() {
510 /// Some(v) => *v = 42,
513 /// assert_eq!(x, Some(42));
515 /// let mut x: Option<u32> = None;
516 /// assert_eq!(x.iter_mut().next(), None);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn iter_mut(&mut self) -> IterMut
<T
> {
521 IterMut { inner: Item { opt: self.as_mut() }
}
524 /////////////////////////////////////////////////////////////////////////
525 // Boolean operations on the values, eager and lazy
526 /////////////////////////////////////////////////////////////////////////
528 /// Returns `None` if the option is `None`, otherwise returns `optb`.
534 /// let y: Option<&str> = None;
535 /// assert_eq!(x.and(y), None);
537 /// let x: Option<u32> = None;
538 /// let y = Some("foo");
539 /// assert_eq!(x.and(y), None);
542 /// let y = Some("foo");
543 /// assert_eq!(x.and(y), Some("foo"));
545 /// let x: Option<u32> = None;
546 /// let y: Option<&str> = None;
547 /// assert_eq!(x.and(y), None);
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn and
<U
>(self, optb
: Option
<U
>) -> Option
<U
> {
558 /// Returns `None` if the option is `None`, otherwise calls `f` with the
559 /// wrapped value and returns the result.
561 /// Some languages call this operation flatmap.
566 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
567 /// fn nope(_: u32) -> Option<u32> { None }
569 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
570 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
571 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
572 /// assert_eq!(None.and_then(sq).and_then(sq), None);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn and_then
<U
, F
: FnOnce(T
) -> Option
<U
>>(self, f
: F
) -> Option
<U
> {
583 /// Returns the option if it contains a value, otherwise returns `optb`.
590 /// assert_eq!(x.or(y), Some(2));
593 /// let y = Some(100);
594 /// assert_eq!(x.or(y), Some(100));
597 /// let y = Some(100);
598 /// assert_eq!(x.or(y), Some(2));
600 /// let x: Option<u32> = None;
602 /// assert_eq!(x.or(y), None);
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn or(self, optb
: Option
<T
>) -> Option
<T
> {
613 /// Returns the option if it contains a value, otherwise calls `f` and
614 /// returns the result.
619 /// fn nobody() -> Option<&'static str> { None }
620 /// fn vikings() -> Option<&'static str> { Some("vikings") }
622 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
623 /// assert_eq!(None.or_else(vikings), Some("vikings"));
624 /// assert_eq!(None.or_else(nobody), None);
627 #[stable(feature = "rust1", since = "1.0.0")]
628 pub fn or_else
<F
: FnOnce() -> Option
<T
>>(self, f
: F
) -> Option
<T
> {
635 /////////////////////////////////////////////////////////////////////////
637 /////////////////////////////////////////////////////////////////////////
639 /// Takes the value out of the option, leaving a `None` in its place.
644 /// let mut x = Some(2);
646 /// assert_eq!(x, None);
648 /// let mut x: Option<u32> = None;
650 /// assert_eq!(x, None);
653 #[stable(feature = "rust1", since = "1.0.0")]
654 pub fn take(&mut self) -> Option
<T
> {
655 mem
::replace(self, None
)
659 impl<'a
, T
: Clone
> Option
<&'a T
> {
660 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub fn cloned(self) -> Option
<T
> {
664 self.map(|t
| t
.clone())
668 impl<T
: Default
> Option
<T
> {
669 /// Returns the contained value or a default
671 /// Consumes the `self` argument then, if `Some`, returns the contained
672 /// value, otherwise if `None`, returns the default value for that
677 /// Convert a string to an integer, turning poorly-formed strings
678 /// into 0 (the default value for integers). `parse` converts
679 /// a string to any other type that implements `FromStr`, returning
683 /// let good_year_from_input = "1909";
684 /// let bad_year_from_input = "190blarg";
685 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
686 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
688 /// assert_eq!(1909, good_year);
689 /// assert_eq!(0, bad_year);
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn unwrap_or_default(self) -> T
{
696 None
=> Default
::default(),
701 // This is a separate function to reduce the code size of .expect() itself.
704 fn expect_failed(msg
: &str) -> ! {
709 /////////////////////////////////////////////////////////////////////////////
710 // Trait implementations
711 /////////////////////////////////////////////////////////////////////////////
713 #[stable(feature = "rust1", since = "1.0.0")]
714 impl<T
> Default
for Option
<T
> {
717 fn default() -> Option
<T
> { None }
720 #[stable(feature = "rust1", since = "1.0.0")]
721 impl<T
> IntoIterator
for Option
<T
> {
723 type IntoIter
= IntoIter
<T
>;
725 /// Returns a consuming iterator over the possibly contained value.
730 /// let x = Some("string");
731 /// let v: Vec<&str> = x.into_iter().collect();
732 /// assert_eq!(v, ["string"]);
735 /// let v: Vec<&str> = x.into_iter().collect();
736 /// assert!(v.is_empty());
739 fn into_iter(self) -> IntoIter
<T
> {
740 IntoIter { inner: Item { opt: self }
}
744 #[stable(since = "1.4.0", feature = "option_iter")]
745 impl<'a
, T
> IntoIterator
for &'a Option
<T
> {
747 type IntoIter
= Iter
<'a
, T
>;
749 fn into_iter(self) -> Iter
<'a
, T
> {
754 #[stable(since = "1.4.0", feature = "option_iter")]
755 impl<'a
, T
> IntoIterator
for &'a
mut Option
<T
> {
756 type Item
= &'a
mut T
;
757 type IntoIter
= IterMut
<'a
, T
>;
759 fn into_iter(mut self) -> IterMut
<'a
, T
> {
764 #[stable(since = "1.12.0", feature = "option_from")]
765 impl<T
> From
<T
> for Option
<T
> {
766 fn from(val
: T
) -> Option
<T
> {
771 /////////////////////////////////////////////////////////////////////////////
772 // The Option Iterators
773 /////////////////////////////////////////////////////////////////////////////
775 #[derive(Clone, Debug)]
780 impl<A
> Iterator
for Item
<A
> {
784 fn next(&mut self) -> Option
<A
> {
789 fn size_hint(&self) -> (usize, Option
<usize>) {
791 Some(_
) => (1, Some(1)),
792 None
=> (0, Some(0)),
797 impl<A
> DoubleEndedIterator
for Item
<A
> {
799 fn next_back(&mut self) -> Option
<A
> {
804 impl<A
> ExactSizeIterator
for Item
<A
> {}
805 impl<A
> FusedIterator
for Item
<A
> {}
807 /// An iterator over a reference of the contained item in an [`Option`].
809 /// [`Option`]: enum.Option.html
810 #[stable(feature = "rust1", since = "1.0.0")]
812 pub struct Iter
<'a
, A
: 'a
> { inner: Item<&'a A> }
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a
, A
> Iterator
for Iter
<'a
, A
> {
819 fn next(&mut self) -> Option
<&'a A
> { self.inner.next() }
821 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl<'a
, A
> DoubleEndedIterator
for Iter
<'a
, A
> {
827 fn next_back(&mut self) -> Option
<&'a A
> { self.inner.next_back() }
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<'a
, A
> ExactSizeIterator
for Iter
<'a
, A
> {}
833 #[unstable(feature = "fused", issue = "35602")]
834 impl<'a
, A
> FusedIterator
for Iter
<'a
, A
> {}
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<'a
, A
> Clone
for Iter
<'a
, A
> {
838 fn clone(&self) -> Iter
<'a
, A
> {
839 Iter { inner: self.inner.clone() }
843 /// An iterator over a mutable reference of the contained item in an [`Option`].
845 /// [`Option`]: enum.Option.html
846 #[stable(feature = "rust1", since = "1.0.0")]
848 pub struct IterMut
<'a
, A
: 'a
> { inner: Item<&'a mut A> }
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a
, A
> Iterator
for IterMut
<'a
, A
> {
852 type Item
= &'a
mut A
;
855 fn next(&mut self) -> Option
<&'a
mut A
> { self.inner.next() }
857 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl<'a
, A
> DoubleEndedIterator
for IterMut
<'a
, A
> {
863 fn next_back(&mut self) -> Option
<&'a
mut A
> { self.inner.next_back() }
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a
, A
> ExactSizeIterator
for IterMut
<'a
, A
> {}
869 #[unstable(feature = "fused", issue = "35602")]
870 impl<'a
, A
> FusedIterator
for IterMut
<'a
, A
> {}
872 /// An iterator over the item contained inside an [`Option`].
874 /// [`Option`]: enum.Option.html
875 #[derive(Clone, Debug)]
876 #[stable(feature = "rust1", since = "1.0.0")]
877 pub struct IntoIter
<A
> { inner: Item<A> }
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<A
> Iterator
for IntoIter
<A
> {
884 fn next(&mut self) -> Option
<A
> { self.inner.next() }
886 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<A
> DoubleEndedIterator
for IntoIter
<A
> {
892 fn next_back(&mut self) -> Option
<A
> { self.inner.next_back() }
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl<A
> ExactSizeIterator
for IntoIter
<A
> {}
898 #[unstable(feature = "fused", issue = "35602")]
899 impl<A
> FusedIterator
for IntoIter
<A
> {}
901 /////////////////////////////////////////////////////////////////////////////
903 /////////////////////////////////////////////////////////////////////////////
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<A
, V
: FromIterator
<A
>> FromIterator
<Option
<A
>> for Option
<V
> {
907 /// Takes each element in the `Iterator`: if it is `None`, no further
908 /// elements are taken, and the `None` is returned. Should no `None` occur, a
909 /// container with the values of each `Option` is returned.
911 /// Here is an example which increments every integer in a vector,
912 /// checking for overflow:
917 /// let v = vec!(1, 2);
918 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
919 /// if x == u16::MAX { None }
920 /// else { Some(x + 1) }
922 /// assert!(res == Some(vec!(2, 3)));
925 fn from_iter
<I
: IntoIterator
<Item
=Option
<A
>>>(iter
: I
) -> Option
<V
> {
926 // FIXME(#11084): This could be replaced with Iterator::scan when this
927 // performance bug is closed.
929 struct Adapter
<Iter
> {
934 impl<T
, Iter
: Iterator
<Item
=Option
<T
>>> Iterator
for Adapter
<Iter
> {
938 fn next(&mut self) -> Option
<T
> {
939 match self.iter
.next() {
940 Some(Some(value
)) => Some(value
),
942 self.found_none
= true;
950 let mut adapter
= Adapter { iter: iter.into_iter(), found_none: false }
;
951 let v
: V
= FromIterator
::from_iter(adapter
.by_ref());
953 if adapter
.found_none
{