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 /// #![feature(option_replace)]
872 /// let mut x = Some(2);
873 /// let old = x.replace(5);
874 /// assert_eq!(x, Some(5));
875 /// assert_eq!(old, Some(2));
877 /// let mut x = None;
878 /// let old = x.replace(3);
879 /// assert_eq!(x, Some(3));
880 /// assert_eq!(old, None);
883 #[unstable(feature = "option_replace", issue = "51998")]
884 pub fn replace(&mut self, value: T) -> Option<T> {
885 mem::replace(self, Some(value))
889 impl<'a, T: Clone> Option<&'a T> {
890 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
897 /// let opt_x = Some(&x);
898 /// assert_eq!(opt_x, Some(&12));
899 /// let cloned = opt_x.cloned();
900 /// assert_eq!(cloned, Some(12));
902 #[stable(feature = "rust1", since = "1.0.0")]
903 pub fn cloned(self) -> Option<T> {
904 self.map(|t| t.clone())
908 impl<'a, T: Clone> Option<&'a mut T> {
909 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
916 /// let opt_x = Some(&mut x);
917 /// assert_eq!(opt_x, Some(&mut 12));
918 /// let cloned = opt_x.cloned();
919 /// assert_eq!(cloned, Some(12));
921 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
922 pub fn cloned(self) -> Option<T> {
923 self.map(|t| t.clone())
927 impl<T: Default> Option<T> {
928 /// Returns the contained value or a default
930 /// Consumes the `self` argument then, if [`Some`], returns the contained
931 /// value, otherwise if [`None`], returns the [default value] for that
936 /// Convert a string to an integer, turning poorly-formed strings
937 /// into 0 (the default value for integers). [`parse`] converts
938 /// a string to any other type that implements [`FromStr`], returning
939 /// [`None`] on error.
942 /// let good_year_from_input = "1909";
943 /// let bad_year_from_input = "190blarg";
944 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
945 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
947 /// assert_eq!(1909, good_year);
948 /// assert_eq!(0, bad_year);
951 /// [`Some`]: #variant.Some
952 /// [`None`]: #variant.None
953 /// [default value]: ../default/trait.Default.html#tymethod.default
954 /// [`parse`]: ../../std/primitive.str.html#method.parse
955 /// [`FromStr`]: ../../std/str/trait.FromStr.html
957 #[stable(feature = "rust1", since = "1.0.0")]
958 pub fn unwrap_or_default(self) -> T {
961 None => Default::default(),
966 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
967 impl<T: Deref> Option<T> {
968 /// Converts from `&Option<T>` to `Option<&T::Target>`.
970 /// Leaves the original Option in-place, creating a new one with a reference
971 /// to the original one, additionally coercing the contents via `Deref`.
972 pub fn deref(&self) -> Option<&T::Target> {
973 self.as_ref().map(|t| t.deref())
977 impl<T, E> Option<Result<T, E>> {
978 /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
980 /// `None` will be mapped to `Ok(None)`.
981 /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
986 /// #![feature(transpose_result)]
988 /// #[derive(Debug, Eq, PartialEq)]
991 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
992 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
993 /// assert_eq!(x, y.transpose());
996 #[unstable(feature = "transpose_result", issue = "47338")]
997 pub fn transpose(self) -> Result<Option<T>, E> {
999 Some(Ok(x)) => Ok(Some(x)),
1000 Some(Err(e)) => Err(e),
1006 // This is a separate function to reduce the code size of .expect() itself.
1009 fn expect_failed(msg: &str) -> ! {
1013 /////////////////////////////////////////////////////////////////////////////
1014 // Trait implementations
1015 /////////////////////////////////////////////////////////////////////////////
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<T> Default for Option<T> {
1019 /// Returns [`None`][Option::None].
1021 fn default() -> Option<T> { None }
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<T> IntoIterator for Option<T> {
1027 type IntoIter = IntoIter<T>;
1029 /// Returns a consuming iterator over the possibly contained value.
1034 /// let x = Some("string");
1035 /// let v: Vec<&str> = x.into_iter().collect();
1036 /// assert_eq!(v, ["string"]);
1039 /// let v: Vec<&str> = x.into_iter().collect();
1040 /// assert!(v.is_empty());
1043 fn into_iter(self) -> IntoIter<T> {
1044 IntoIter { inner: Item { opt: self } }
1048 #[stable(since = "1.4.0", feature = "option_iter")]
1049 impl<'a, T> IntoIterator for &'a Option<T> {
1051 type IntoIter = Iter<'a, T>;
1053 fn into_iter(self) -> Iter<'a, T> {
1058 #[stable(since = "1.4.0", feature = "option_iter")]
1059 impl<'a, T> IntoIterator for &'a mut Option<T> {
1060 type Item = &'a mut T;
1061 type IntoIter = IterMut<'a, T>;
1063 fn into_iter(self) -> IterMut<'a, T> {
1068 #[stable(since = "1.12.0", feature = "option_from")]
1069 impl<T> From<T> for Option<T> {
1070 fn from(val: T) -> Option<T> {
1075 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1076 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1077 fn from(o: &'a Option<T>) -> Option<&'a T> {
1082 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1083 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1084 fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1089 /////////////////////////////////////////////////////////////////////////////
1090 // The Option Iterators
1091 /////////////////////////////////////////////////////////////////////////////
1093 #[derive(Clone, Debug)]
1098 impl<A> Iterator for Item<A> {
1102 fn next(&mut self) -> Option<A> {
1107 fn size_hint(&self) -> (usize, Option<usize>) {
1109 Some(_) => (1, Some(1)),
1110 None => (0, Some(0)),
1115 impl<A> DoubleEndedIterator for Item<A> {
1117 fn next_back(&mut self) -> Option<A> {
1122 impl<A> ExactSizeIterator for Item<A> {}
1123 impl<A> FusedIterator for Item<A> {}
1124 unsafe impl<A> TrustedLen for Item<A> {}
1126 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1128 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1130 /// This `struct` is created by the [`Option::iter`] function.
1132 /// [`Option`]: enum.Option.html
1133 /// [`Some`]: enum.Option.html#variant.Some
1134 /// [`Option::iter`]: enum.Option.html#method.iter
1135 #[stable(feature = "rust1", since = "1.0.0")]
1137 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<'a, A> Iterator for Iter<'a, A> {
1144 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1146 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1152 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
1158 #[stable(feature = "fused", since = "1.26.0")]
1159 impl<'a, A> FusedIterator for Iter<'a, A> {}
1161 #[unstable(feature = "trusted_len", issue = "37572")]
1162 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<'a, A> Clone for Iter<'a, A> {
1167 fn clone(&self) -> Iter<'a, A> {
1168 Iter { inner: self.inner.clone() }
1172 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1174 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1176 /// This `struct` is created by the [`Option::iter_mut`] function.
1178 /// [`Option`]: enum.Option.html
1179 /// [`Some`]: enum.Option.html#variant.Some
1180 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1181 #[stable(feature = "rust1", since = "1.0.0")]
1183 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<'a, A> Iterator for IterMut<'a, A> {
1187 type Item = &'a mut A;
1190 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1192 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1198 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
1204 #[stable(feature = "fused", since = "1.26.0")]
1205 impl<'a, A> FusedIterator for IterMut<'a, A> {}
1206 #[unstable(feature = "trusted_len", issue = "37572")]
1207 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1209 /// An iterator over the value in [`Some`] variant of an [`Option`].
1211 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1213 /// This `struct` is created by the [`Option::into_iter`] function.
1215 /// [`Option`]: enum.Option.html
1216 /// [`Some`]: enum.Option.html#variant.Some
1217 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1218 #[derive(Clone, Debug)]
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 pub struct IntoIter<A> { inner: Item<A> }
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl<A> Iterator for IntoIter<A> {
1227 fn next(&mut self) -> Option<A> { self.inner.next() }
1229 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl<A> DoubleEndedIterator for IntoIter<A> {
1235 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<A> ExactSizeIterator for IntoIter<A> {}
1241 #[stable(feature = "fused", since = "1.26.0")]
1242 impl<A> FusedIterator for IntoIter<A> {}
1244 #[unstable(feature = "trusted_len", issue = "37572")]
1245 unsafe impl<A> TrustedLen for IntoIter<A> {}
1247 /////////////////////////////////////////////////////////////////////////////
1249 /////////////////////////////////////////////////////////////////////////////
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1253 /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1254 /// no further elements are taken, and the [`None`][Option::None] is
1255 /// returned. Should no [`None`][Option::None] occur, a container with the
1256 /// values of each [`Option`] is returned.
1258 /// Here is an example which increments every integer in a vector,
1259 /// checking for overflow:
1264 /// let v = vec![1, 2];
1265 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1266 /// if x == u16::MAX { None }
1267 /// else { Some(x + 1) }
1269 /// assert!(res == Some(vec![2, 3]));
1272 /// [`Iterator`]: ../iter/trait.Iterator.html
1274 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1275 // FIXME(#11084): This could be replaced with Iterator::scan when this
1276 // performance bug is closed.
1278 struct Adapter<Iter> {
1283 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1287 fn next(&mut self) -> Option<T> {
1288 match self.iter.next() {
1289 Some(Some(value)) => Some(value),
1291 self.found_none = true;
1299 fn size_hint(&self) -> (usize, Option<usize>) {
1300 if self.found_none {
1303 let (_, upper) = self.iter.size_hint();
1309 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1310 let v: V = FromIterator::from_iter(adapter.by_ref());
1312 if adapter.found_none {
1320 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1321 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1322 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1323 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1324 #[unstable(feature = "try_trait", issue = "42327")]
1325 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1326 pub struct NoneError;
1328 #[unstable(feature = "try_trait", issue = "42327")]
1329 impl<T> ops::Try for Option<T> {
1331 type Error = NoneError;
1334 fn into_result(self) -> Result<T, NoneError> {
1335 self.ok_or(NoneError)
1339 fn from_ok(v: T) -> Self {
1344 fn from_error(_: NoneError) -> Self {