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.
341 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
342 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
343 /// which is lazily evaluated.
345 /// [`unwrap_or_else`]: #method.unwrap_or_else
350 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
351 /// assert_eq!(None.unwrap_or("bike"), "bike");
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn unwrap_or(self, def: T) -> T {
362 /// Returns the contained value or computes it from a closure.
368 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
369 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
380 /////////////////////////////////////////////////////////////////////////
381 // Transforming contained values
382 /////////////////////////////////////////////////////////////////////////
384 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
388 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
390 /// [`String`]: ../../std/string/struct.String.html
391 /// [`usize`]: ../../std/primitive.usize.html
394 /// let maybe_some_string = Some(String::from("Hello, World!"));
395 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
396 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
398 /// assert_eq!(maybe_some_len, Some(13));
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
404 Some(x) => Some(f(x)),
409 /// Applies a function to the contained value (if any),
410 /// or returns the provided default (if not).
415 /// let x = Some("foo");
416 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
418 /// let x: Option<&str> = None;
419 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
430 /// Applies a function to the contained value (if any),
431 /// or computes a default (if not).
438 /// let x = Some("foo");
439 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
441 /// let x: Option<&str> = None;
442 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
453 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
454 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
456 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
457 /// result of a function call, it is recommended to use [`ok_or_else`], which is
458 /// lazily evaluated.
460 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
461 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
462 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
463 /// [`None`]: #variant.None
464 /// [`Some(v)`]: #variant.Some
465 /// [`ok_or_else`]: #method.ok_or_else
470 /// let x = Some("foo");
471 /// assert_eq!(x.ok_or(0), Ok("foo"));
473 /// let x: Option<&str> = None;
474 /// assert_eq!(x.ok_or(0), Err(0));
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
485 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
486 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
488 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
489 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
490 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
491 /// [`None`]: #variant.None
492 /// [`Some(v)`]: #variant.Some
497 /// let x = Some("foo");
498 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
500 /// let x: Option<&str> = None;
501 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
512 /////////////////////////////////////////////////////////////////////////
513 // Iterator constructors
514 /////////////////////////////////////////////////////////////////////////
516 /// Returns an iterator over the possibly contained value.
522 /// assert_eq!(x.iter().next(), Some(&4));
524 /// let x: Option<u32> = None;
525 /// assert_eq!(x.iter().next(), None);
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn iter(&self) -> Iter<T> {
530 Iter { inner: Item { opt: self.as_ref() } }
533 /// Returns a mutable iterator over the possibly contained value.
538 /// let mut x = Some(4);
539 /// match x.iter_mut().next() {
540 /// Some(v) => *v = 42,
543 /// assert_eq!(x, Some(42));
545 /// let mut x: Option<u32> = None;
546 /// assert_eq!(x.iter_mut().next(), None);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn iter_mut(&mut self) -> IterMut<T> {
551 IterMut { inner: Item { opt: self.as_mut() } }
554 /////////////////////////////////////////////////////////////////////////
555 // Boolean operations on the values, eager and lazy
556 /////////////////////////////////////////////////////////////////////////
558 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
560 /// [`None`]: #variant.None
566 /// let y: Option<&str> = None;
567 /// assert_eq!(x.and(y), None);
569 /// let x: Option<u32> = None;
570 /// let y = Some("foo");
571 /// assert_eq!(x.and(y), None);
574 /// let y = Some("foo");
575 /// assert_eq!(x.and(y), Some("foo"));
577 /// let x: Option<u32> = None;
578 /// let y: Option<&str> = None;
579 /// assert_eq!(x.and(y), None);
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
590 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
591 /// wrapped value and returns the result.
593 /// Some languages call this operation flatmap.
595 /// [`None`]: #variant.None
600 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
601 /// fn nope(_: u32) -> Option<u32> { None }
603 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
604 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
605 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
606 /// assert_eq!(None.and_then(sq).and_then(sq), None);
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
617 /// Returns `None` if the option is `None`, otherwise calls `predicate`
618 /// with the wrapped value and returns:
620 /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
622 /// - `None` if `predicate` returns `false`.
624 /// This function works similar to `Iterator::filter()`. You can imagine
625 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
626 /// lets you decide which elements to keep.
631 /// #![feature(option_filter)]
633 /// fn is_even(n: &i32) -> bool {
637 /// assert_eq!(None.filter(is_even), None);
638 /// assert_eq!(Some(3).filter(is_even), None);
639 /// assert_eq!(Some(4).filter(is_even), Some(4));
642 #[unstable(feature = "option_filter", issue = "45860")]
643 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
644 if let Some(x) = self {
652 /// Returns the option if it contains a value, otherwise returns `optb`.
654 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
655 /// result of a function call, it is recommended to use [`or_else`], which is
656 /// lazily evaluated.
658 /// [`or_else`]: #method.or_else
665 /// assert_eq!(x.or(y), Some(2));
668 /// let y = Some(100);
669 /// assert_eq!(x.or(y), Some(100));
672 /// let y = Some(100);
673 /// assert_eq!(x.or(y), Some(2));
675 /// let x: Option<u32> = None;
677 /// assert_eq!(x.or(y), None);
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn or(self, optb: Option<T>) -> Option<T> {
688 /// Returns the option if it contains a value, otherwise calls `f` and
689 /// returns the result.
694 /// fn nobody() -> Option<&'static str> { None }
695 /// fn vikings() -> Option<&'static str> { Some("vikings") }
697 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
698 /// assert_eq!(None.or_else(vikings), Some("vikings"));
699 /// assert_eq!(None.or_else(nobody), None);
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
710 /////////////////////////////////////////////////////////////////////////
711 // Entry-like operations to insert if None and return a reference
712 /////////////////////////////////////////////////////////////////////////
714 /// Inserts `v` into the option if it is [`None`], then
715 /// returns a mutable reference to the contained value.
717 /// [`None`]: #variant.None
722 /// let mut x = None;
725 /// let y: &mut u32 = x.get_or_insert(5);
726 /// assert_eq!(y, &5);
731 /// assert_eq!(x, Some(7));
734 #[stable(feature = "option_entry", since = "1.20.0")]
735 pub fn get_or_insert(&mut self, v: T) -> &mut T {
737 None => *self = Some(v),
742 Some(ref mut v) => v,
747 /// Inserts a value computed from `f` into the option if it is [`None`], then
748 /// returns a mutable reference to the contained value.
750 /// [`None`]: #variant.None
755 /// let mut x = None;
758 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
759 /// assert_eq!(y, &5);
764 /// assert_eq!(x, Some(7));
767 #[stable(feature = "option_entry", since = "1.20.0")]
768 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
770 None => *self = Some(f()),
775 Some(ref mut v) => v,
780 /////////////////////////////////////////////////////////////////////////
782 /////////////////////////////////////////////////////////////////////////
784 /// Takes the value out of the option, leaving a [`None`] in its place.
786 /// [`None`]: #variant.None
791 /// let mut x = Some(2);
793 /// assert_eq!(x, None);
795 /// let mut x: Option<u32> = None;
797 /// assert_eq!(x, None);
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub fn take(&mut self) -> Option<T> {
802 mem::replace(self, None)
806 impl<'a, T: Clone> Option<&'a T> {
807 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
814 /// let opt_x = Some(&x);
815 /// assert_eq!(opt_x, Some(&12));
816 /// let cloned = opt_x.cloned();
817 /// assert_eq!(cloned, Some(12));
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn cloned(self) -> Option<T> {
821 self.map(|t| t.clone())
825 impl<'a, T: Clone> Option<&'a mut T> {
826 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
832 /// #![feature(option_ref_mut_cloned)]
834 /// let opt_x = Some(&mut x);
835 /// assert_eq!(opt_x, Some(&mut 12));
836 /// let cloned = opt_x.cloned();
837 /// assert_eq!(cloned, Some(12));
839 #[unstable(feature = "option_ref_mut_cloned", issue = "43738")]
840 pub fn cloned(self) -> Option<T> {
841 self.map(|t| t.clone())
845 impl<T: Default> Option<T> {
846 /// Returns the contained value or a default
848 /// Consumes the `self` argument then, if [`Some`], returns the contained
849 /// value, otherwise if [`None`], returns the [default value] for that
854 /// Convert a string to an integer, turning poorly-formed strings
855 /// into 0 (the default value for integers). [`parse`] converts
856 /// a string to any other type that implements [`FromStr`], returning
857 /// [`None`] on error.
860 /// let good_year_from_input = "1909";
861 /// let bad_year_from_input = "190blarg";
862 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
863 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
865 /// assert_eq!(1909, good_year);
866 /// assert_eq!(0, bad_year);
869 /// [`Some`]: #variant.Some
870 /// [`None`]: #variant.None
871 /// [default value]: ../default/trait.Default.html#tymethod.default
872 /// [`parse`]: ../../std/primitive.str.html#method.parse
873 /// [`FromStr`]: ../../std/str/trait.FromStr.html
875 #[stable(feature = "rust1", since = "1.0.0")]
876 pub fn unwrap_or_default(self) -> T {
879 None => Default::default(),
884 impl<T, E> Option<Result<T, E>> {
885 /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
887 /// `None` will be mapped to `Ok(None)`.
888 /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
893 /// #![feature(transpose_result)]
895 /// #[derive(Debug, Eq, PartialEq)]
898 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
899 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
900 /// assert_eq!(x, y.transpose());
903 #[unstable(feature = "transpose_result", issue = "47338")]
904 pub fn transpose(self) -> Result<Option<T>, E> {
906 Some(Ok(x)) => Ok(Some(x)),
907 Some(Err(e)) => Err(e),
913 // This is a separate function to reduce the code size of .expect() itself.
916 fn expect_failed(msg: &str) -> ! {
921 /////////////////////////////////////////////////////////////////////////////
922 // Trait implementations
923 /////////////////////////////////////////////////////////////////////////////
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<T> Default for Option<T> {
927 /// Returns [`None`].
929 /// [`None`]: #variant.None
931 fn default() -> Option<T> { None }
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<T> IntoIterator for Option<T> {
937 type IntoIter = IntoIter<T>;
939 /// Returns a consuming iterator over the possibly contained value.
944 /// let x = Some("string");
945 /// let v: Vec<&str> = x.into_iter().collect();
946 /// assert_eq!(v, ["string"]);
949 /// let v: Vec<&str> = x.into_iter().collect();
950 /// assert!(v.is_empty());
953 fn into_iter(self) -> IntoIter<T> {
954 IntoIter { inner: Item { opt: self } }
958 #[stable(since = "1.4.0", feature = "option_iter")]
959 impl<'a, T> IntoIterator for &'a Option<T> {
961 type IntoIter = Iter<'a, T>;
963 fn into_iter(self) -> Iter<'a, T> {
968 #[stable(since = "1.4.0", feature = "option_iter")]
969 impl<'a, T> IntoIterator for &'a mut Option<T> {
970 type Item = &'a mut T;
971 type IntoIter = IterMut<'a, T>;
973 fn into_iter(self) -> IterMut<'a, T> {
978 #[stable(since = "1.12.0", feature = "option_from")]
979 impl<T> From<T> for Option<T> {
980 fn from(val: T) -> Option<T> {
985 /////////////////////////////////////////////////////////////////////////////
986 // The Option Iterators
987 /////////////////////////////////////////////////////////////////////////////
989 #[derive(Clone, Debug)]
994 impl<A> Iterator for Item<A> {
998 fn next(&mut self) -> Option<A> {
1003 fn size_hint(&self) -> (usize, Option<usize>) {
1005 Some(_) => (1, Some(1)),
1006 None => (0, Some(0)),
1011 impl<A> DoubleEndedIterator for Item<A> {
1013 fn next_back(&mut self) -> Option<A> {
1018 impl<A> ExactSizeIterator for Item<A> {}
1019 impl<A> FusedIterator for Item<A> {}
1020 unsafe impl<A> TrustedLen for Item<A> {}
1022 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1024 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1026 /// This `struct` is created by the [`Option::iter`] function.
1028 /// [`Option`]: enum.Option.html
1029 /// [`Some`]: enum.Option.html#variant.Some
1030 /// [`Option::iter`]: enum.Option.html#method.iter
1031 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 impl<'a, A> Iterator for Iter<'a, A> {
1040 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1042 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1048 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
1054 #[unstable(feature = "fused", issue = "35602")]
1055 impl<'a, A> FusedIterator for Iter<'a, A> {}
1057 #[unstable(feature = "trusted_len", issue = "37572")]
1058 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<'a, A> Clone for Iter<'a, A> {
1062 fn clone(&self) -> Iter<'a, A> {
1063 Iter { inner: self.inner.clone() }
1067 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1069 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1071 /// This `struct` is created by the [`Option::iter_mut`] function.
1073 /// [`Option`]: enum.Option.html
1074 /// [`Some`]: enum.Option.html#variant.Some
1075 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1076 #[stable(feature = "rust1", since = "1.0.0")]
1078 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<'a, A> Iterator for IterMut<'a, A> {
1082 type Item = &'a mut A;
1085 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1087 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1093 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
1099 #[unstable(feature = "fused", issue = "35602")]
1100 impl<'a, A> FusedIterator for IterMut<'a, A> {}
1101 #[unstable(feature = "trusted_len", issue = "37572")]
1102 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1104 /// An iterator over the value in [`Some`] variant of an [`Option`].
1106 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1108 /// This `struct` is created by the [`Option::into_iter`] function.
1110 /// [`Option`]: enum.Option.html
1111 /// [`Some`]: enum.Option.html#variant.Some
1112 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1113 #[derive(Clone, Debug)]
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub struct IntoIter<A> { inner: Item<A> }
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 impl<A> Iterator for IntoIter<A> {
1122 fn next(&mut self) -> Option<A> { self.inner.next() }
1124 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl<A> DoubleEndedIterator for IntoIter<A> {
1130 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<A> ExactSizeIterator for IntoIter<A> {}
1136 #[unstable(feature = "fused", issue = "35602")]
1137 impl<A> FusedIterator for IntoIter<A> {}
1139 #[unstable(feature = "trusted_len", issue = "37572")]
1140 unsafe impl<A> TrustedLen for IntoIter<A> {}
1142 /////////////////////////////////////////////////////////////////////////////
1144 /////////////////////////////////////////////////////////////////////////////
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1148 /// Takes each element in the [`Iterator`]: if it is [`None`], no further
1149 /// elements are taken, and the [`None`] is returned. Should no [`None`] occur, a
1150 /// container with the values of each `Option` is returned.
1152 /// Here is an example which increments every integer in a vector,
1153 /// checking for overflow:
1158 /// let v = vec![1, 2];
1159 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1160 /// if x == u16::MAX { None }
1161 /// else { Some(x + 1) }
1163 /// assert!(res == Some(vec![2, 3]));
1166 /// [`Iterator`]: ../iter/trait.Iterator.html
1167 /// [`None`]: enum.Option.html#variant.None
1169 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1170 // FIXME(#11084): This could be replaced with Iterator::scan when this
1171 // performance bug is closed.
1173 struct Adapter<Iter> {
1178 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1182 fn next(&mut self) -> Option<T> {
1183 match self.iter.next() {
1184 Some(Some(value)) => Some(value),
1186 self.found_none = true;
1194 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1195 let v: V = FromIterator::from_iter(adapter.by_ref());
1197 if adapter.found_none {
1205 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1206 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1207 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1208 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1209 #[unstable(feature = "try_trait", issue = "42327")]
1210 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1211 pub struct NoneError;
1213 #[unstable(feature = "try_trait", issue = "42327")]
1214 impl<T> ops::Try for Option<T> {
1216 type Error = NoneError;
1218 fn into_result(self) -> Result<T, NoneError> {
1219 self.ok_or(NoneError)
1222 fn from_ok(v: T) -> Self {
1226 fn from_error(_: NoneError) -> Self {