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};
149 use {hint, mem, ops::{self, Deref}};
152 // Note that this is not a lang item per se, but it has a hidden dependency on
153 // `Iterator`, which is one. The compiler assumes that the `next` method of
154 // `Iterator` is an enumeration with one type parameter and two variants,
155 // which basically means it must be `Option`.
157 /// The `Option` type. See [the module level documentation](index.html) for more.
158 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
159 #[stable(feature = "rust1", since = "1.0.0")]
162 #[stable(feature = "rust1", since = "1.0.0")]
165 #[stable(feature = "rust1", since = "1.0.0")]
166 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
169 /////////////////////////////////////////////////////////////////////////////
170 // Type implementation
171 /////////////////////////////////////////////////////////////////////////////
174 /////////////////////////////////////////////////////////////////////////
175 // Querying the contained values
176 /////////////////////////////////////////////////////////////////////////
178 /// Returns `true` if the option is a [`Some`] value.
183 /// let x: Option<u32> = Some(2);
184 /// assert_eq!(x.is_some(), true);
186 /// let x: Option<u32> = None;
187 /// assert_eq!(x.is_some(), false);
190 /// [`Some`]: #variant.Some
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub fn is_some(&self) -> bool {
200 /// Returns `true` if the option is a [`None`] value.
205 /// let x: Option<u32> = Some(2);
206 /// assert_eq!(x.is_none(), false);
208 /// let x: Option<u32> = None;
209 /// assert_eq!(x.is_none(), true);
212 /// [`None`]: #variant.None
214 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn is_none(&self) -> bool {
219 /////////////////////////////////////////////////////////////////////////
220 // Adapter for working with references
221 /////////////////////////////////////////////////////////////////////////
223 /// Converts from `Option<T>` to `Option<&T>`.
227 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
228 /// The [`map`] method takes the `self` argument by value, consuming the original,
229 /// so this technique uses `as_ref` to first take an `Option` to a reference
230 /// to the value inside the original.
232 /// [`map`]: enum.Option.html#method.map
233 /// [`String`]: ../../std/string/struct.String.html
234 /// [`usize`]: ../../std/primitive.usize.html
237 /// let text: Option<String> = Some("Hello, world!".to_string());
238 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
239 /// // then consume *that* with `map`, leaving `text` on the stack.
240 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
241 /// println!("still can print text: {:?}", text);
244 #[stable(feature = "rust1", since = "1.0.0")]
245 pub fn as_ref(&self) -> Option<&T> {
247 Some(ref x) => Some(x),
252 /// Converts from `Option<T>` to `Option<&mut T>`.
257 /// let mut x = Some(2);
258 /// match x.as_mut() {
259 /// Some(v) => *v = 42,
262 /// assert_eq!(x, Some(42));
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub fn as_mut(&mut self) -> Option<&mut T> {
268 Some(ref mut x) => Some(x),
274 /// Converts from `Pin<&Option<T>>` to `Option<Pin<&T>>`
276 #[unstable(feature = "pin", issue = "49150")]
277 pub fn as_pin_ref<'a>(self: Pin<&'a Option<T>>) -> Option<Pin<&'a T>> {
279 Pin::get_ref(self).as_ref().map(|x| Pin::new_unchecked(x))
283 /// Converts from `Pin<&mut Option<T>>` to `Option<Pin<&mut T>>`
285 #[unstable(feature = "pin", issue = "49150")]
286 pub fn as_pin_mut<'a>(self: Pin<&'a mut Option<T>>) -> Option<Pin<&'a mut T>> {
288 Pin::get_mut_unchecked(self).as_mut().map(|x| Pin::new_unchecked(x))
292 /////////////////////////////////////////////////////////////////////////
293 // Getting to contained values
294 /////////////////////////////////////////////////////////////////////////
296 /// Unwraps an option, yielding the content of a [`Some`].
300 /// Panics if the value is a [`None`] with a custom panic message provided by
303 /// [`Some`]: #variant.Some
304 /// [`None`]: #variant.None
309 /// let x = Some("value");
310 /// assert_eq!(x.expect("the world is ending"), "value");
313 /// ```{.should_panic}
314 /// let x: Option<&str> = None;
315 /// x.expect("the world is ending"); // panics with `the world is ending`
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub fn expect(self, msg: &str) -> T {
322 None => expect_failed(msg),
326 /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
328 /// In general, because this function may panic, its use is discouraged.
329 /// Instead, prefer to use pattern matching and handle the [`None`]
334 /// Panics if the self value equals [`None`].
336 /// [`Some(v)`]: #variant.Some
337 /// [`None`]: #variant.None
342 /// let x = Some("air");
343 /// assert_eq!(x.unwrap(), "air");
346 /// ```{.should_panic}
347 /// let x: Option<&str> = None;
348 /// assert_eq!(x.unwrap(), "air"); // fails
351 #[stable(feature = "rust1", since = "1.0.0")]
352 pub fn unwrap(self) -> T {
355 None => panic!("called `Option::unwrap()` on a `None` value"),
359 /// Returns the contained value or a default.
361 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
362 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
363 /// which is lazily evaluated.
365 /// [`unwrap_or_else`]: #method.unwrap_or_else
370 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
371 /// assert_eq!(None.unwrap_or("bike"), "bike");
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn unwrap_or(self, def: T) -> T {
382 /// Returns the contained value or computes it from a closure.
388 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
389 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
400 /////////////////////////////////////////////////////////////////////////
401 // Transforming contained values
402 /////////////////////////////////////////////////////////////////////////
404 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
408 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
410 /// [`String`]: ../../std/string/struct.String.html
411 /// [`usize`]: ../../std/primitive.usize.html
414 /// let maybe_some_string = Some(String::from("Hello, World!"));
415 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
416 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
418 /// assert_eq!(maybe_some_len, Some(13));
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
424 Some(x) => Some(f(x)),
429 /// Applies a function to the contained value (if any),
430 /// or returns the provided default (if not).
435 /// let x = Some("foo");
436 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
438 /// let x: Option<&str> = None;
439 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
442 #[stable(feature = "rust1", since = "1.0.0")]
443 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
450 /// Applies a function to the contained value (if any),
451 /// or computes a default (if not).
458 /// let x = Some("foo");
459 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
461 /// let x: Option<&str> = None;
462 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
473 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
474 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
476 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
477 /// result of a function call, it is recommended to use [`ok_or_else`], which is
478 /// lazily evaluated.
480 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
481 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
482 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
483 /// [`None`]: #variant.None
484 /// [`Some(v)`]: #variant.Some
485 /// [`ok_or_else`]: #method.ok_or_else
490 /// let x = Some("foo");
491 /// assert_eq!(x.ok_or(0), Ok("foo"));
493 /// let x: Option<&str> = None;
494 /// assert_eq!(x.ok_or(0), Err(0));
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
505 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
506 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
508 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
509 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
510 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
511 /// [`None`]: #variant.None
512 /// [`Some(v)`]: #variant.Some
517 /// let x = Some("foo");
518 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
520 /// let x: Option<&str> = None;
521 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
532 /////////////////////////////////////////////////////////////////////////
533 // Iterator constructors
534 /////////////////////////////////////////////////////////////////////////
536 /// Returns an iterator over the possibly contained value.
542 /// assert_eq!(x.iter().next(), Some(&4));
544 /// let x: Option<u32> = None;
545 /// assert_eq!(x.iter().next(), None);
548 #[stable(feature = "rust1", since = "1.0.0")]
549 pub fn iter(&self) -> Iter<T> {
550 Iter { inner: Item { opt: self.as_ref() } }
553 /// Returns a mutable iterator over the possibly contained value.
558 /// let mut x = Some(4);
559 /// match x.iter_mut().next() {
560 /// Some(v) => *v = 42,
563 /// assert_eq!(x, Some(42));
565 /// let mut x: Option<u32> = None;
566 /// assert_eq!(x.iter_mut().next(), None);
569 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn iter_mut(&mut self) -> IterMut<T> {
571 IterMut { inner: Item { opt: self.as_mut() } }
574 /////////////////////////////////////////////////////////////////////////
575 // Boolean operations on the values, eager and lazy
576 /////////////////////////////////////////////////////////////////////////
578 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
580 /// [`None`]: #variant.None
586 /// let y: Option<&str> = None;
587 /// assert_eq!(x.and(y), None);
589 /// let x: Option<u32> = None;
590 /// let y = Some("foo");
591 /// assert_eq!(x.and(y), None);
594 /// let y = Some("foo");
595 /// assert_eq!(x.and(y), Some("foo"));
597 /// let x: Option<u32> = None;
598 /// let y: Option<&str> = None;
599 /// assert_eq!(x.and(y), None);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
610 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
611 /// wrapped value and returns the result.
613 /// Some languages call this operation flatmap.
615 /// [`None`]: #variant.None
620 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
621 /// fn nope(_: u32) -> Option<u32> { None }
623 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
624 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
625 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
626 /// assert_eq!(None.and_then(sq).and_then(sq), None);
629 #[stable(feature = "rust1", since = "1.0.0")]
630 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
637 /// Returns `None` if the option is `None`, otherwise calls `predicate`
638 /// with the wrapped value and returns:
640 /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
642 /// - `None` if `predicate` returns `false`.
644 /// This function works similar to `Iterator::filter()`. You can imagine
645 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
646 /// lets you decide which elements to keep.
651 /// fn is_even(n: &i32) -> bool {
655 /// assert_eq!(None.filter(is_even), None);
656 /// assert_eq!(Some(3).filter(is_even), None);
657 /// assert_eq!(Some(4).filter(is_even), Some(4));
660 #[stable(feature = "option_filter", since = "1.27.0")]
661 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
662 if let Some(x) = self {
670 /// Returns the option if it contains a value, otherwise returns `optb`.
672 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
673 /// result of a function call, it is recommended to use [`or_else`], which is
674 /// lazily evaluated.
676 /// [`or_else`]: #method.or_else
683 /// assert_eq!(x.or(y), Some(2));
686 /// let y = Some(100);
687 /// assert_eq!(x.or(y), Some(100));
690 /// let y = Some(100);
691 /// assert_eq!(x.or(y), Some(2));
693 /// let x: Option<u32> = None;
695 /// assert_eq!(x.or(y), None);
698 #[stable(feature = "rust1", since = "1.0.0")]
699 pub fn or(self, optb: Option<T>) -> Option<T> {
706 /// Returns the option if it contains a value, otherwise calls `f` and
707 /// returns the result.
712 /// fn nobody() -> Option<&'static str> { None }
713 /// fn vikings() -> Option<&'static str> { Some("vikings") }
715 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
716 /// assert_eq!(None.or_else(vikings), Some("vikings"));
717 /// assert_eq!(None.or_else(nobody), None);
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
728 /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns `None`.
730 /// [`Some`]: #variant.Some
731 /// [`None`]: #variant.None
736 /// #![feature(option_xor)]
739 /// let y: Option<u32> = None;
740 /// assert_eq!(x.xor(y), Some(2));
742 /// let x: Option<u32> = None;
744 /// assert_eq!(x.xor(y), Some(2));
748 /// assert_eq!(x.xor(y), None);
750 /// let x: Option<u32> = None;
751 /// let y: Option<u32> = None;
752 /// assert_eq!(x.xor(y), None);
755 #[unstable(feature = "option_xor", issue = "50512")]
756 pub fn xor(self, optb: Option<T>) -> Option<T> {
758 (Some(a), None) => Some(a),
759 (None, Some(b)) => Some(b),
764 /////////////////////////////////////////////////////////////////////////
765 // Entry-like operations to insert if None and return a reference
766 /////////////////////////////////////////////////////////////////////////
768 /// Inserts `v` into the option if it is [`None`], then
769 /// returns a mutable reference to the contained value.
771 /// [`None`]: #variant.None
776 /// let mut x = None;
779 /// let y: &mut u32 = x.get_or_insert(5);
780 /// assert_eq!(y, &5);
785 /// assert_eq!(x, Some(7));
788 #[stable(feature = "option_entry", since = "1.20.0")]
789 pub fn get_or_insert(&mut self, v: T) -> &mut T {
791 None => *self = Some(v),
796 Some(ref mut v) => v,
797 None => unsafe { hint::unreachable_unchecked() },
801 /// Inserts a value computed from `f` into the option if it is [`None`], then
802 /// returns a mutable reference to the contained value.
804 /// [`None`]: #variant.None
809 /// let mut x = None;
812 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
813 /// assert_eq!(y, &5);
818 /// assert_eq!(x, Some(7));
821 #[stable(feature = "option_entry", since = "1.20.0")]
822 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
824 None => *self = Some(f()),
829 Some(ref mut v) => v,
830 None => unsafe { hint::unreachable_unchecked() },
834 /////////////////////////////////////////////////////////////////////////
836 /////////////////////////////////////////////////////////////////////////
838 /// Takes the value out of the option, leaving a [`None`] in its place.
840 /// [`None`]: #variant.None
845 /// let mut x = Some(2);
846 /// let y = x.take();
847 /// assert_eq!(x, None);
848 /// assert_eq!(y, Some(2));
850 /// let mut x: Option<u32> = None;
851 /// let y = x.take();
852 /// assert_eq!(x, None);
853 /// assert_eq!(y, None);
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn take(&mut self) -> Option<T> {
858 mem::replace(self, None)
861 /// Replaces the actual value in the option by the value given in parameter,
862 /// returning the old value if present,
863 /// leaving a [`Some`] in its place without deinitializing either one.
865 /// [`Some`]: #variant.Some
870 /// let mut x = Some(2);
871 /// let old = x.replace(5);
872 /// assert_eq!(x, Some(5));
873 /// assert_eq!(old, Some(2));
875 /// let mut x = None;
876 /// let old = x.replace(3);
877 /// assert_eq!(x, Some(3));
878 /// assert_eq!(old, None);
881 #[stable(feature = "option_replace", since = "1.31.0")]
882 pub fn replace(&mut self, value: T) -> Option<T> {
883 mem::replace(self, Some(value))
887 impl<'a, T: Clone> Option<&'a T> {
888 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
895 /// let opt_x = Some(&x);
896 /// assert_eq!(opt_x, Some(&12));
897 /// let cloned = opt_x.cloned();
898 /// assert_eq!(cloned, Some(12));
900 #[stable(feature = "rust1", since = "1.0.0")]
901 pub fn cloned(self) -> Option<T> {
902 self.map(|t| t.clone())
906 impl<'a, T: Clone> Option<&'a mut T> {
907 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
914 /// let opt_x = Some(&mut x);
915 /// assert_eq!(opt_x, Some(&mut 12));
916 /// let cloned = opt_x.cloned();
917 /// assert_eq!(cloned, Some(12));
919 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
920 pub fn cloned(self) -> Option<T> {
921 self.map(|t| t.clone())
925 impl<T: Default> Option<T> {
926 /// Returns the contained value or a default
928 /// Consumes the `self` argument then, if [`Some`], returns the contained
929 /// value, otherwise if [`None`], returns the [default value] for that
934 /// Convert a string to an integer, turning poorly-formed strings
935 /// into 0 (the default value for integers). [`parse`] converts
936 /// a string to any other type that implements [`FromStr`], returning
937 /// [`None`] on error.
940 /// let good_year_from_input = "1909";
941 /// let bad_year_from_input = "190blarg";
942 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
943 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
945 /// assert_eq!(1909, good_year);
946 /// assert_eq!(0, bad_year);
949 /// [`Some`]: #variant.Some
950 /// [`None`]: #variant.None
951 /// [default value]: ../default/trait.Default.html#tymethod.default
952 /// [`parse`]: ../../std/primitive.str.html#method.parse
953 /// [`FromStr`]: ../../std/str/trait.FromStr.html
955 #[stable(feature = "rust1", since = "1.0.0")]
956 pub fn unwrap_or_default(self) -> T {
959 None => Default::default(),
964 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
965 impl<T: Deref> Option<T> {
966 /// Converts from `&Option<T>` to `Option<&T::Target>`.
968 /// Leaves the original Option in-place, creating a new one with a reference
969 /// to the original one, additionally coercing the contents via `Deref`.
970 pub fn deref(&self) -> Option<&T::Target> {
971 self.as_ref().map(|t| t.deref())
975 impl<T, E> Option<Result<T, E>> {
976 /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
978 /// `None` will be mapped to `Ok(None)`.
979 /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
984 /// #![feature(transpose_result)]
986 /// #[derive(Debug, Eq, PartialEq)]
989 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
990 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
991 /// assert_eq!(x, y.transpose());
994 #[unstable(feature = "transpose_result", issue = "47338")]
995 pub fn transpose(self) -> Result<Option<T>, E> {
997 Some(Ok(x)) => Ok(Some(x)),
998 Some(Err(e)) => Err(e),
1004 // This is a separate function to reduce the code size of .expect() itself.
1007 fn expect_failed(msg: &str) -> ! {
1011 /////////////////////////////////////////////////////////////////////////////
1012 // Trait implementations
1013 /////////////////////////////////////////////////////////////////////////////
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<T> Default for Option<T> {
1017 /// Returns [`None`][Option::None].
1019 fn default() -> Option<T> { None }
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<T> IntoIterator for Option<T> {
1025 type IntoIter = IntoIter<T>;
1027 /// Returns a consuming iterator over the possibly contained value.
1032 /// let x = Some("string");
1033 /// let v: Vec<&str> = x.into_iter().collect();
1034 /// assert_eq!(v, ["string"]);
1037 /// let v: Vec<&str> = x.into_iter().collect();
1038 /// assert!(v.is_empty());
1041 fn into_iter(self) -> IntoIter<T> {
1042 IntoIter { inner: Item { opt: self } }
1046 #[stable(since = "1.4.0", feature = "option_iter")]
1047 impl<'a, T> IntoIterator for &'a Option<T> {
1049 type IntoIter = Iter<'a, T>;
1051 fn into_iter(self) -> Iter<'a, T> {
1056 #[stable(since = "1.4.0", feature = "option_iter")]
1057 impl<'a, T> IntoIterator for &'a mut Option<T> {
1058 type Item = &'a mut T;
1059 type IntoIter = IterMut<'a, T>;
1061 fn into_iter(self) -> IterMut<'a, T> {
1066 #[stable(since = "1.12.0", feature = "option_from")]
1067 impl<T> From<T> for Option<T> {
1068 fn from(val: T) -> Option<T> {
1073 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1074 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1075 fn from(o: &'a Option<T>) -> Option<&'a T> {
1080 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1081 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1082 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1087 /////////////////////////////////////////////////////////////////////////////
1088 // The Option Iterators
1089 /////////////////////////////////////////////////////////////////////////////
1091 #[derive(Clone, Debug)]
1096 impl<A> Iterator for Item<A> {
1100 fn next(&mut self) -> Option<A> {
1105 fn size_hint(&self) -> (usize, Option<usize>) {
1107 Some(_) => (1, Some(1)),
1108 None => (0, Some(0)),
1113 impl<A> DoubleEndedIterator for Item<A> {
1115 fn next_back(&mut self) -> Option<A> {
1120 impl<A> ExactSizeIterator for Item<A> {}
1121 impl<A> FusedIterator for Item<A> {}
1122 unsafe impl<A> TrustedLen for Item<A> {}
1124 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1126 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1128 /// This `struct` is created by the [`Option::iter`] function.
1130 /// [`Option`]: enum.Option.html
1131 /// [`Some`]: enum.Option.html#variant.Some
1132 /// [`Option::iter`]: enum.Option.html#method.iter
1133 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<'a, A> Iterator for Iter<'a, A> {
1142 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1144 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1150 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl<A> ExactSizeIterator for Iter<'_, A> {}
1156 #[stable(feature = "fused", since = "1.26.0")]
1157 impl<A> FusedIterator for Iter<'_, A> {}
1159 #[unstable(feature = "trusted_len", issue = "37572")]
1160 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<A> Clone for Iter<'_, A> {
1165 fn clone(&self) -> Self {
1166 Iter { inner: self.inner.clone() }
1170 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1172 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1174 /// This `struct` is created by the [`Option::iter_mut`] function.
1176 /// [`Option`]: enum.Option.html
1177 /// [`Some`]: enum.Option.html#variant.Some
1178 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1179 #[stable(feature = "rust1", since = "1.0.0")]
1181 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<'a, A> Iterator for IterMut<'a, A> {
1185 type Item = &'a mut A;
1188 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1190 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1196 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1202 #[stable(feature = "fused", since = "1.26.0")]
1203 impl<A> FusedIterator for IterMut<'_, A> {}
1204 #[unstable(feature = "trusted_len", issue = "37572")]
1205 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1207 /// An iterator over the value in [`Some`] variant of an [`Option`].
1209 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1211 /// This `struct` is created by the [`Option::into_iter`] function.
1213 /// [`Option`]: enum.Option.html
1214 /// [`Some`]: enum.Option.html#variant.Some
1215 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1216 #[derive(Clone, Debug)]
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub struct IntoIter<A> { inner: Item<A> }
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl<A> Iterator for IntoIter<A> {
1225 fn next(&mut self) -> Option<A> { self.inner.next() }
1227 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 impl<A> DoubleEndedIterator for IntoIter<A> {
1233 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<A> ExactSizeIterator for IntoIter<A> {}
1239 #[stable(feature = "fused", since = "1.26.0")]
1240 impl<A> FusedIterator for IntoIter<A> {}
1242 #[unstable(feature = "trusted_len", issue = "37572")]
1243 unsafe impl<A> TrustedLen for IntoIter<A> {}
1245 /////////////////////////////////////////////////////////////////////////////
1247 /////////////////////////////////////////////////////////////////////////////
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1251 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1252 /// no further elements are taken, and the [`None`][Option::None] is
1253 /// returned. Should no [`None`][Option::None] occur, a container with the
1254 /// values of each [`Option`] is returned.
1256 /// Here is an example which increments every integer in a vector,
1257 /// checking for overflow:
1262 /// let v = vec![1, 2];
1263 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1264 /// if x == u16::MAX { None }
1265 /// else { Some(x + 1) }
1267 /// assert!(res == Some(vec![2, 3]));
1270 /// [`Iterator`]: ../iter/trait.Iterator.html
1272 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1273 // FIXME(#11084): This could be replaced with Iterator::scan when this
1274 // performance bug is closed.
1276 struct Adapter<Iter> {
1281 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1285 fn next(&mut self) -> Option<T> {
1286 match self.iter.next() {
1287 Some(Some(value)) => Some(value),
1289 self.found_none = true;
1297 fn size_hint(&self) -> (usize, Option<usize>) {
1298 if self.found_none {
1301 let (_, upper) = self.iter.size_hint();
1307 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1308 let v: V = FromIterator::from_iter(adapter.by_ref());
1310 if adapter.found_none {
1318 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1319 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1320 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1321 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1322 #[unstable(feature = "try_trait", issue = "42327")]
1323 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1324 pub struct NoneError;
1326 #[unstable(feature = "try_trait", issue = "42327")]
1327 impl<T> ops::Try for Option<T> {
1329 type Error = NoneError;
1332 fn into_result(self) -> Result<T, NoneError> {
1333 self.ok_or(NoneError)
1337 fn from_ok(v: T) -> Self {
1342 fn from_error(_: NoneError) -> Self {