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 = None;
70 //! check_optional(optional);
72 //! let optional = Some(Box::new(9000));
73 //! check_optional(optional);
75 //! fn check_optional(optional: Option<Box<i32>>) {
77 //! Some(ref p) => println!("has value {}", p),
78 //! None => println!("has 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, TrustedLen};
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 /// [`Some`]: #variant.Some
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn is_some(&self) -> bool {
199 /// Returns `true` if the option is a [`None`] value.
204 /// let x: Option<u32> = Some(2);
205 /// assert_eq!(x.is_none(), false);
207 /// let x: Option<u32> = None;
208 /// assert_eq!(x.is_none(), true);
211 /// [`None`]: #variant.None
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn is_none(&self) -> bool {
218 /////////////////////////////////////////////////////////////////////////
219 // Adapter for working with references
220 /////////////////////////////////////////////////////////////////////////
222 /// Converts from `Option<T>` to `Option<&T>`.
226 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
227 /// The [`map`] method takes the `self` argument by value, consuming the original,
228 /// so this technique uses `as_ref` to first take an `Option` to a reference
229 /// to the value inside the original.
231 /// [`map`]: enum.Option.html#method.map
232 /// [`String`]: ../../std/string/struct.String.html
233 /// [`usize`]: ../../std/primitive.usize.html
236 /// let num_as_str: Option<String> = Some("10".to_string());
237 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
238 /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
239 /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len());
240 /// println!("still can print num_as_str: {:?}", num_as_str);
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn as_ref(&self) -> Option<&T> {
246 Some(ref x) => Some(x),
251 /// Converts from `Option<T>` to `Option<&mut T>`.
256 /// let mut x = Some(2);
257 /// match x.as_mut() {
258 /// Some(v) => *v = 42,
261 /// assert_eq!(x, Some(42));
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub fn as_mut(&mut self) -> Option<&mut T> {
267 Some(ref mut x) => Some(x),
272 /////////////////////////////////////////////////////////////////////////
273 // Getting to contained values
274 /////////////////////////////////////////////////////////////////////////
276 /// Unwraps an option, yielding the content of a [`Some`].
280 /// Panics if the value is a [`None`] with a custom panic message provided by
283 /// [`Some`]: #variant.Some
284 /// [`None`]: #variant.None
289 /// let x = Some("value");
290 /// assert_eq!(x.expect("the world is ending"), "value");
293 /// ```{.should_panic}
294 /// let x: Option<&str> = None;
295 /// x.expect("the world is ending"); // panics with `the world is ending`
298 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn expect(self, msg: &str) -> T {
302 None => expect_failed(msg),
306 /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
308 /// In general, because this function may panic, its use is discouraged.
309 /// Instead, prefer to use pattern matching and handle the [`None`]
314 /// Panics if the self value equals [`None`].
316 /// [`Some(v)`]: #variant.Some
317 /// [`None`]: #variant.None
322 /// let x = Some("air");
323 /// assert_eq!(x.unwrap(), "air");
326 /// ```{.should_panic}
327 /// let x: Option<&str> = None;
328 /// assert_eq!(x.unwrap(), "air"); // fails
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn unwrap(self) -> T {
335 None => panic!("called `Option::unwrap()` on a `None` value"),
339 /// Returns the contained value or a default.
344 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
345 /// assert_eq!(None.unwrap_or("bike"), "bike");
348 #[stable(feature = "rust1", since = "1.0.0")]
349 pub fn unwrap_or(self, def: T) -> T {
356 /// Returns the contained value or computes it from a closure.
362 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
363 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
366 #[stable(feature = "rust1", since = "1.0.0")]
367 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
374 /////////////////////////////////////////////////////////////////////////
375 // Transforming contained values
376 /////////////////////////////////////////////////////////////////////////
378 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
382 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
384 /// [`String`]: ../../std/string/struct.String.html
385 /// [`usize`]: ../../std/primitive.usize.html
388 /// let maybe_some_string = Some(String::from("Hello, World!"));
389 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
390 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
392 /// assert_eq!(maybe_some_len, Some(13));
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
398 Some(x) => Some(f(x)),
403 /// Applies a function to the contained value (if any),
404 /// or returns a [`default`][] (if not).
406 /// [`default`]: ../default/trait.Default.html#tymethod.default
411 /// let x = Some("foo");
412 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
414 /// let x: Option<&str> = None;
415 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
426 /// Applies a function to the contained value (if any),
427 /// or computes a [`default`][] (if not).
429 /// [`default`]: ../default/trait.Default.html#tymethod.default
436 /// let x = Some("foo");
437 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
439 /// let x: Option<&str> = None;
440 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
451 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
452 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
454 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
455 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
456 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
457 /// [`None`]: #variant.None
458 /// [`Some(v)`]: #variant.Some
463 /// let x = Some("foo");
464 /// assert_eq!(x.ok_or(0), Ok("foo"));
466 /// let x: Option<&str> = None;
467 /// assert_eq!(x.ok_or(0), Err(0));
470 #[stable(feature = "rust1", since = "1.0.0")]
471 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
478 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
479 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
481 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
482 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
483 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
484 /// [`None`]: #variant.None
485 /// [`Some(v)`]: #variant.Some
490 /// let x = Some("foo");
491 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
493 /// let x: Option<&str> = None;
494 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
505 /////////////////////////////////////////////////////////////////////////
506 // Iterator constructors
507 /////////////////////////////////////////////////////////////////////////
509 /// Returns an iterator over the possibly contained value.
515 /// assert_eq!(x.iter().next(), Some(&4));
517 /// let x: Option<u32> = None;
518 /// assert_eq!(x.iter().next(), None);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn iter(&self) -> Iter<T> {
523 Iter { inner: Item { opt: self.as_ref() } }
526 /// Returns a mutable iterator over the possibly contained value.
531 /// let mut x = Some(4);
532 /// match x.iter_mut().next() {
533 /// Some(v) => *v = 42,
536 /// assert_eq!(x, Some(42));
538 /// let mut x: Option<u32> = None;
539 /// assert_eq!(x.iter_mut().next(), None);
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn iter_mut(&mut self) -> IterMut<T> {
544 IterMut { inner: Item { opt: self.as_mut() } }
547 /////////////////////////////////////////////////////////////////////////
548 // Boolean operations on the values, eager and lazy
549 /////////////////////////////////////////////////////////////////////////
551 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
553 /// [`None`]: #variant.None
559 /// let y: Option<&str> = None;
560 /// assert_eq!(x.and(y), None);
562 /// let x: Option<u32> = None;
563 /// let y = Some("foo");
564 /// assert_eq!(x.and(y), None);
567 /// let y = Some("foo");
568 /// assert_eq!(x.and(y), Some("foo"));
570 /// let x: Option<u32> = None;
571 /// let y: Option<&str> = None;
572 /// assert_eq!(x.and(y), None);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
583 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
584 /// wrapped value and returns the result.
586 /// Some languages call this operation flatmap.
588 /// [`None`]: #variant.None
593 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
594 /// fn nope(_: u32) -> Option<u32> { None }
596 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
597 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
598 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
599 /// assert_eq!(None.and_then(sq).and_then(sq), None);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
610 /// Returns the option if it contains a value, otherwise returns `optb`.
617 /// assert_eq!(x.or(y), Some(2));
620 /// let y = Some(100);
621 /// assert_eq!(x.or(y), Some(100));
624 /// let y = Some(100);
625 /// assert_eq!(x.or(y), Some(2));
627 /// let x: Option<u32> = None;
629 /// assert_eq!(x.or(y), None);
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn or(self, optb: Option<T>) -> Option<T> {
640 /// Returns the option if it contains a value, otherwise calls `f` and
641 /// returns the result.
646 /// fn nobody() -> Option<&'static str> { None }
647 /// fn vikings() -> Option<&'static str> { Some("vikings") }
649 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
650 /// assert_eq!(None.or_else(vikings), Some("vikings"));
651 /// assert_eq!(None.or_else(nobody), None);
654 #[stable(feature = "rust1", since = "1.0.0")]
655 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
662 /////////////////////////////////////////////////////////////////////////
663 // Entry-like operations to insert if None and return a reference
664 /////////////////////////////////////////////////////////////////////////
666 /// Inserts `v` into the option if it is [`None`], then
667 /// returns a mutable reference to the contained value.
669 /// [`None`]: #variant.None
674 /// let mut x = None;
677 /// let y: &mut u32 = x.get_or_insert(5);
678 /// assert_eq!(y, &5);
683 /// assert_eq!(x, Some(7));
686 #[stable(feature = "option_entry", since = "1.20.0")]
687 pub fn get_or_insert(&mut self, v: T) -> &mut T {
689 None => *self = Some(v),
694 Some(ref mut v) => v,
699 /// Inserts a value computed from `f` into the option if it is [`None`], then
700 /// returns a mutable reference to the contained value.
702 /// [`None`]: #variant.None
707 /// let mut x = None;
710 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
711 /// assert_eq!(y, &5);
716 /// assert_eq!(x, Some(7));
719 #[stable(feature = "option_entry", since = "1.20.0")]
720 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
722 None => *self = Some(f()),
727 Some(ref mut v) => v,
732 /////////////////////////////////////////////////////////////////////////
734 /////////////////////////////////////////////////////////////////////////
736 /// Takes the value out of the option, leaving a [`None`] in its place.
738 /// [`None`]: #variant.None
743 /// let mut x = Some(2);
745 /// assert_eq!(x, None);
747 /// let mut x: Option<u32> = None;
749 /// assert_eq!(x, None);
752 #[stable(feature = "rust1", since = "1.0.0")]
753 pub fn take(&mut self) -> Option<T> {
754 mem::replace(self, None)
758 impl<'a, T: Clone> Option<&'a T> {
759 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
766 /// let opt_x = Some(&x);
767 /// assert_eq!(opt_x, Some(&12));
768 /// let cloned = opt_x.cloned();
769 /// assert_eq!(cloned, Some(12));
771 #[stable(feature = "rust1", since = "1.0.0")]
772 pub fn cloned(self) -> Option<T> {
773 self.map(|t| t.clone())
777 impl<T: Default> Option<T> {
778 /// Returns the contained value or a default
780 /// Consumes the `self` argument then, if [`Some`], returns the contained
781 /// value, otherwise if [`None`], returns the default value for that
786 /// Convert a string to an integer, turning poorly-formed strings
787 /// into 0 (the default value for integers). [`parse`] converts
788 /// a string to any other type that implements [`FromStr`], returning
789 /// [`None`] on error.
792 /// let good_year_from_input = "1909";
793 /// let bad_year_from_input = "190blarg";
794 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
795 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
797 /// assert_eq!(1909, good_year);
798 /// assert_eq!(0, bad_year);
801 /// [`Some`]: #variant.Some
802 /// [`None`]: #variant.None
803 /// [`parse`]: ../../std/primitive.str.html#method.parse
804 /// [`FromStr`]: ../../std/str/trait.FromStr.html
806 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn unwrap_or_default(self) -> T {
810 None => Default::default(),
815 // This is a separate function to reduce the code size of .expect() itself.
818 fn expect_failed(msg: &str) -> ! {
823 /////////////////////////////////////////////////////////////////////////////
824 // Trait implementations
825 /////////////////////////////////////////////////////////////////////////////
827 #[stable(feature = "rust1", since = "1.0.0")]
828 impl<T> Default for Option<T> {
829 /// Returns [`None`].
831 /// [`None`]: #variant.None
833 fn default() -> Option<T> { None }
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<T> IntoIterator for Option<T> {
839 type IntoIter = IntoIter<T>;
841 /// Returns a consuming iterator over the possibly contained value.
846 /// let x = Some("string");
847 /// let v: Vec<&str> = x.into_iter().collect();
848 /// assert_eq!(v, ["string"]);
851 /// let v: Vec<&str> = x.into_iter().collect();
852 /// assert!(v.is_empty());
855 fn into_iter(self) -> IntoIter<T> {
856 IntoIter { inner: Item { opt: self } }
860 #[stable(since = "1.4.0", feature = "option_iter")]
861 impl<'a, T> IntoIterator for &'a Option<T> {
863 type IntoIter = Iter<'a, T>;
865 fn into_iter(self) -> Iter<'a, T> {
870 #[stable(since = "1.4.0", feature = "option_iter")]
871 impl<'a, T> IntoIterator for &'a mut Option<T> {
872 type Item = &'a mut T;
873 type IntoIter = IterMut<'a, T>;
875 fn into_iter(self) -> IterMut<'a, T> {
880 #[stable(since = "1.12.0", feature = "option_from")]
881 impl<T> From<T> for Option<T> {
882 fn from(val: T) -> Option<T> {
887 /////////////////////////////////////////////////////////////////////////////
888 // The Option Iterators
889 /////////////////////////////////////////////////////////////////////////////
891 #[derive(Clone, Debug)]
896 impl<A> Iterator for Item<A> {
900 fn next(&mut self) -> Option<A> {
905 fn size_hint(&self) -> (usize, Option<usize>) {
907 Some(_) => (1, Some(1)),
908 None => (0, Some(0)),
913 impl<A> DoubleEndedIterator for Item<A> {
915 fn next_back(&mut self) -> Option<A> {
920 impl<A> ExactSizeIterator for Item<A> {}
921 impl<A> FusedIterator for Item<A> {}
922 unsafe impl<A> TrustedLen for Item<A> {}
924 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
926 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
928 /// This `struct` is created by the [`Option::iter`] function.
930 /// [`Option`]: enum.Option.html
931 /// [`Some`]: enum.Option.html#variant.Some
932 /// [`Option::iter`]: enum.Option.html#method.iter
933 #[stable(feature = "rust1", since = "1.0.0")]
935 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, A> Iterator for Iter<'a, A> {
942 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
944 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
950 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
956 #[unstable(feature = "fused", issue = "35602")]
957 impl<'a, A> FusedIterator for Iter<'a, A> {}
959 #[unstable(feature = "trusted_len", issue = "37572")]
960 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
962 #[stable(feature = "rust1", since = "1.0.0")]
963 impl<'a, A> Clone for Iter<'a, A> {
964 fn clone(&self) -> Iter<'a, A> {
965 Iter { inner: self.inner.clone() }
969 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
971 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
973 /// This `struct` is created by the [`Option::iter_mut`] function.
975 /// [`Option`]: enum.Option.html
976 /// [`Some`]: enum.Option.html#variant.Some
977 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
978 #[stable(feature = "rust1", since = "1.0.0")]
980 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<'a, A> Iterator for IterMut<'a, A> {
984 type Item = &'a mut A;
987 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
989 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
995 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
998 #[stable(feature = "rust1", since = "1.0.0")]
999 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
1001 #[unstable(feature = "fused", issue = "35602")]
1002 impl<'a, A> FusedIterator for IterMut<'a, A> {}
1003 #[unstable(feature = "trusted_len", issue = "37572")]
1004 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1006 /// An iterator over the value in [`Some`] variant of an [`Option`].
1008 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1010 /// This `struct` is created by the [`Option::into_iter`] function.
1012 /// [`Option`]: enum.Option.html
1013 /// [`Some`]: enum.Option.html#variant.Some
1014 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1015 #[derive(Clone, Debug)]
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub struct IntoIter<A> { inner: Item<A> }
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl<A> Iterator for IntoIter<A> {
1024 fn next(&mut self) -> Option<A> { self.inner.next() }
1026 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 impl<A> DoubleEndedIterator for IntoIter<A> {
1032 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 impl<A> ExactSizeIterator for IntoIter<A> {}
1038 #[unstable(feature = "fused", issue = "35602")]
1039 impl<A> FusedIterator for IntoIter<A> {}
1041 #[unstable(feature = "trusted_len", issue = "37572")]
1042 unsafe impl<A> TrustedLen for IntoIter<A> {}
1044 /////////////////////////////////////////////////////////////////////////////
1046 /////////////////////////////////////////////////////////////////////////////
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1050 /// Takes each element in the [`Iterator`]: if it is [`None`], no further
1051 /// elements are taken, and the [`None`] is returned. Should no [`None`] occur, a
1052 /// container with the values of each `Option` is returned.
1054 /// Here is an example which increments every integer in a vector,
1055 /// checking for overflow:
1060 /// let v = vec![1, 2];
1061 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1062 /// if x == u16::MAX { None }
1063 /// else { Some(x + 1) }
1065 /// assert!(res == Some(vec![2, 3]));
1068 /// [`Iterator`]: ../iter/trait.Iterator.html
1069 /// [`None`]: enum.Option.html#variant.None
1071 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1072 // FIXME(#11084): This could be replaced with Iterator::scan when this
1073 // performance bug is closed.
1075 struct Adapter<Iter> {
1080 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1084 fn next(&mut self) -> Option<T> {
1085 match self.iter.next() {
1086 Some(Some(value)) => Some(value),
1088 self.found_none = true;
1096 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1097 let v: V = FromIterator::from_iter(adapter.by_ref());
1099 if adapter.found_none {