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 //! Options 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(...)`) or
69 //! let optional: Option<Box<i32>> = None;
70 //! check_optional(&optional);
72 //! let optional: Option<Box<i32>> = Some(Box::new(9000));
73 //! check_optional(&optional);
75 //! fn check_optional(optional: &Option<Box<i32>>) {
77 //! Some(ref p) => println!("have value {}", p),
78 //! None => println!("have no value"),
83 //! This usage of `Option` to create safe nullable pointers is so
84 //! common that Rust does special optimizations to make the
85 //! representation of `Option<Box<T>>` a single pointer. Optional pointers
86 //! in Rust are stored as efficiently as any other pointer type.
90 //! Basic pattern matching on `Option`:
93 //! let msg = Some("howdy");
95 //! // Take a reference to the contained string
97 //! Some(ref m) => println!("{}", *m),
101 //! // Remove the contained string, destroying the Option
102 //! let unwrapped_msg = match msg {
104 //! None => "default message",
108 //! Initialize a result to `None` before a loop:
111 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
113 //! // A list of data to search through.
114 //! let all_the_big_things = [
115 //! Kingdom::Plant(250, "redwood"),
116 //! Kingdom::Plant(230, "noble fir"),
117 //! Kingdom::Plant(229, "sugar pine"),
118 //! Kingdom::Animal(25, "blue whale"),
119 //! Kingdom::Animal(19, "fin whale"),
120 //! Kingdom::Animal(15, "north pacific right whale"),
123 //! // We're going to search for the name of the biggest animal,
124 //! // but to start with we've just got `None`.
125 //! let mut name_of_biggest_animal = None;
126 //! let mut size_of_biggest_animal = 0;
127 //! for big_thing in &all_the_big_things {
128 //! match *big_thing {
129 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
130 //! // Now we've found the name of some big animal
131 //! size_of_biggest_animal = size;
132 //! name_of_biggest_animal = Some(name);
134 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
138 //! match name_of_biggest_animal {
139 //! Some(name) => println!("the biggest animal is {}", name),
140 //! None => println!("there are no animals :("),
144 #![stable(feature = "rust1", since = "1.0.0")]
150 use default::Default;
151 use iter::ExactSizeIterator;
152 use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
155 use result::Result::{Ok, Err};
158 // Note that this is not a lang item per se, but it has a hidden dependency on
159 // `Iterator`, which is one. The compiler assumes that the `next` method of
160 // `Iterator` is an enumeration with one type parameter and two variants,
161 // which basically means it must be `Option`.
163 /// The `Option` type. See [the module level documentation](index.html) for more.
164 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
165 #[stable(feature = "rust1", since = "1.0.0")]
168 #[stable(feature = "rust1", since = "1.0.0")]
171 #[stable(feature = "rust1", since = "1.0.0")]
172 Some(#[stable(feature = "rust1", since = "1.0.0")] T)
175 /////////////////////////////////////////////////////////////////////////////
176 // Type implementation
177 /////////////////////////////////////////////////////////////////////////////
180 /////////////////////////////////////////////////////////////////////////
181 // Querying the contained values
182 /////////////////////////////////////////////////////////////////////////
184 /// Returns `true` if the option is a `Some` value
189 /// let x: Option<u32> = Some(2);
190 /// assert_eq!(x.is_some(), true);
192 /// let x: Option<u32> = None;
193 /// assert_eq!(x.is_some(), false);
196 #[stable(feature = "rust1", since = "1.0.0")]
197 pub fn is_some(&self) -> bool {
204 /// Returns `true` if the option is a `None` value
209 /// let x: Option<u32> = Some(2);
210 /// assert_eq!(x.is_none(), false);
212 /// let x: Option<u32> = None;
213 /// assert_eq!(x.is_none(), true);
216 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn is_none(&self) -> bool {
221 /////////////////////////////////////////////////////////////////////////
222 // Adapter for working with references
223 /////////////////////////////////////////////////////////////////////////
225 /// Converts from `Option<T>` to `Option<&T>`
229 /// Convert an `Option<String>` into an `Option<usize>`, preserving the original.
230 /// The `map` method takes the `self` argument by value, consuming the original,
231 /// so this technique uses `as_ref` to first take an `Option` to a reference
232 /// to the value inside the original.
235 /// let num_as_str: Option<String> = Some("10".to_string());
236 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
237 /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
238 /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len());
239 /// println!("still can print num_as_str: {:?}", num_as_str);
242 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn as_ref(&self) -> Option<&T> {
245 Some(ref x) => Some(x),
250 /// Converts from `Option<T>` to `Option<&mut T>`
255 /// let mut x = Some(2);
256 /// match x.as_mut() {
257 /// Some(v) => *v = 42,
260 /// assert_eq!(x, Some(42));
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub fn as_mut(&mut self) -> Option<&mut T> {
266 Some(ref mut x) => Some(x),
271 /////////////////////////////////////////////////////////////////////////
272 // Getting to contained values
273 /////////////////////////////////////////////////////////////////////////
275 /// Unwraps an option, yielding the content of a `Some`.
279 /// Panics if the value is a `None` with a custom panic message provided by
285 /// let x = Some("value");
286 /// assert_eq!(x.expect("the world is ending"), "value");
289 /// ```{.should_panic}
290 /// let x: Option<&str> = None;
291 /// x.expect("the world is ending"); // panics with `the world is ending`
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn expect(self, msg: &str) -> T {
298 None => expect_failed(msg),
302 /// Moves the value `v` out of the `Option<T>` if it is `Some(v)`.
306 /// Panics if the self value equals `None`.
310 /// In general, because this function may panic, its use is discouraged.
311 /// Instead, prefer to use pattern matching and handle the `None`
317 /// let x = Some("air");
318 /// assert_eq!(x.unwrap(), "air");
321 /// ```{.should_panic}
322 /// let x: Option<&str> = None;
323 /// assert_eq!(x.unwrap(), "air"); // fails
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn unwrap(self) -> T {
330 None => panic!("called `Option::unwrap()` on a `None` value"),
334 /// Returns the contained value or a default.
339 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
340 /// assert_eq!(None.unwrap_or("bike"), "bike");
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn unwrap_or(self, def: T) -> T {
351 /// Returns the contained value or computes it from a closure.
357 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
358 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
369 /////////////////////////////////////////////////////////////////////////
370 // Transforming contained values
371 /////////////////////////////////////////////////////////////////////////
373 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
377 /// Convert an `Option<String>` into an `Option<usize>`, consuming the original:
380 /// let maybe_some_string = Some(String::from("Hello, World!"));
381 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
382 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
384 /// assert_eq!(maybe_some_len, Some(13));
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
390 Some(x) => Some(f(x)),
395 /// Applies a function to the contained value (if any),
396 /// or returns a `default` (if not).
401 /// let x = Some("foo");
402 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
404 /// let x: Option<&str> = None;
405 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
416 /// Applies a function to the contained value (if any),
417 /// or computes a `default` (if not).
424 /// let x = Some("foo");
425 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
427 /// let x: Option<&str> = None;
428 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
439 /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
440 /// `Ok(v)` and `None` to `Err(err)`.
445 /// let x = Some("foo");
446 /// assert_eq!(x.ok_or(0), Ok("foo"));
448 /// let x: Option<&str> = None;
449 /// assert_eq!(x.ok_or(0), Err(0));
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
460 /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
461 /// `Ok(v)` and `None` to `Err(err())`.
466 /// let x = Some("foo");
467 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
469 /// let x: Option<&str> = None;
470 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
481 /////////////////////////////////////////////////////////////////////////
482 // Iterator constructors
483 /////////////////////////////////////////////////////////////////////////
485 /// Returns an iterator over the possibly contained value.
491 /// assert_eq!(x.iter().next(), Some(&4));
493 /// let x: Option<u32> = None;
494 /// assert_eq!(x.iter().next(), None);
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn iter(&self) -> Iter<T> {
499 Iter { inner: Item { opt: self.as_ref() } }
502 /// Returns a mutable iterator over the possibly contained value.
507 /// let mut x = Some(4);
508 /// match x.iter_mut().next() {
509 /// Some(v) => *v = 42,
512 /// assert_eq!(x, Some(42));
514 /// let mut x: Option<u32> = None;
515 /// assert_eq!(x.iter_mut().next(), None);
518 #[stable(feature = "rust1", since = "1.0.0")]
519 pub fn iter_mut(&mut self) -> IterMut<T> {
520 IterMut { inner: Item { opt: self.as_mut() } }
523 /////////////////////////////////////////////////////////////////////////
524 // Boolean operations on the values, eager and lazy
525 /////////////////////////////////////////////////////////////////////////
527 /// Returns `None` if the option is `None`, otherwise returns `optb`.
533 /// let y: Option<&str> = None;
534 /// assert_eq!(x.and(y), None);
536 /// let x: Option<u32> = None;
537 /// let y = Some("foo");
538 /// assert_eq!(x.and(y), None);
541 /// let y = Some("foo");
542 /// assert_eq!(x.and(y), Some("foo"));
544 /// let x: Option<u32> = None;
545 /// let y: Option<&str> = None;
546 /// assert_eq!(x.and(y), None);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
557 /// Returns `None` if the option is `None`, otherwise calls `f` with the
558 /// wrapped value and returns the result.
560 /// Some languages call this operation flatmap.
565 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
566 /// fn nope(_: u32) -> Option<u32> { None }
568 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
569 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
570 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
571 /// assert_eq!(None.and_then(sq).and_then(sq), None);
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
582 /// Returns the option if it contains a value, otherwise returns `optb`.
589 /// assert_eq!(x.or(y), Some(2));
592 /// let y = Some(100);
593 /// assert_eq!(x.or(y), Some(100));
596 /// let y = Some(100);
597 /// assert_eq!(x.or(y), Some(2));
599 /// let x: Option<u32> = None;
601 /// assert_eq!(x.or(y), None);
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn or(self, optb: Option<T>) -> Option<T> {
612 /// Returns the option if it contains a value, otherwise calls `f` and
613 /// returns the result.
618 /// fn nobody() -> Option<&'static str> { None }
619 /// fn vikings() -> Option<&'static str> { Some("vikings") }
621 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
622 /// assert_eq!(None.or_else(vikings), Some("vikings"));
623 /// assert_eq!(None.or_else(nobody), None);
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
634 /////////////////////////////////////////////////////////////////////////
636 /////////////////////////////////////////////////////////////////////////
638 /// Takes the value out of the option, leaving a `None` in its place.
643 /// let mut x = Some(2);
645 /// assert_eq!(x, None);
647 /// let mut x: Option<u32> = None;
649 /// assert_eq!(x, None);
652 #[stable(feature = "rust1", since = "1.0.0")]
653 pub fn take(&mut self) -> Option<T> {
654 mem::replace(self, None)
658 impl<'a, T: Clone> Option<&'a T> {
659 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn cloned(self) -> Option<T> {
663 self.map(|t| t.clone())
667 impl<T: Default> Option<T> {
668 /// Returns the contained value or a default
670 /// Consumes the `self` argument then, if `Some`, returns the contained
671 /// value, otherwise if `None`, returns the default value for that
676 /// Convert a string to an integer, turning poorly-formed strings
677 /// into 0 (the default value for integers). `parse` converts
678 /// a string to any other type that implements `FromStr`, returning
682 /// let good_year_from_input = "1909";
683 /// let bad_year_from_input = "190blarg";
684 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
685 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
687 /// assert_eq!(1909, good_year);
688 /// assert_eq!(0, bad_year);
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn unwrap_or_default(self) -> T {
695 None => Default::default(),
700 // This is a separate function to reduce the code size of .expect() itself.
703 fn expect_failed(msg: &str) -> ! {
708 /////////////////////////////////////////////////////////////////////////////
709 // Trait implementations
710 /////////////////////////////////////////////////////////////////////////////
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl<T> Default for Option<T> {
715 fn default() -> Option<T> { None }
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<T> IntoIterator for Option<T> {
721 type IntoIter = IntoIter<T>;
723 /// Returns a consuming iterator over the possibly contained value.
728 /// let x = Some("string");
729 /// let v: Vec<&str> = x.into_iter().collect();
730 /// assert_eq!(v, ["string"]);
733 /// let v: Vec<&str> = x.into_iter().collect();
734 /// assert!(v.is_empty());
737 fn into_iter(self) -> IntoIter<T> {
738 IntoIter { inner: Item { opt: self } }
742 #[stable(since = "1.4.0", feature = "option_iter")]
743 impl<'a, T> IntoIterator for &'a Option<T> {
745 type IntoIter = Iter<'a, T>;
747 fn into_iter(self) -> Iter<'a, T> {
752 #[stable(since = "1.4.0", feature = "option_iter")]
753 impl<'a, T> IntoIterator for &'a mut Option<T> {
754 type Item = &'a mut T;
755 type IntoIter = IterMut<'a, T>;
757 fn into_iter(mut self) -> IterMut<'a, T> {
762 /////////////////////////////////////////////////////////////////////////////
763 // The Option Iterators
764 /////////////////////////////////////////////////////////////////////////////
766 #[derive(Clone, Debug)]
771 impl<A> Iterator for Item<A> {
775 fn next(&mut self) -> Option<A> {
780 fn size_hint(&self) -> (usize, Option<usize>) {
782 Some(_) => (1, Some(1)),
783 None => (0, Some(0)),
788 impl<A> DoubleEndedIterator for Item<A> {
790 fn next_back(&mut self) -> Option<A> {
795 impl<A> ExactSizeIterator for Item<A> {}
797 /// An iterator over a reference of the contained item in an Option.
798 #[stable(feature = "rust1", since = "1.0.0")]
800 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl<'a, A> Iterator for Iter<'a, A> {
807 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
809 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
815 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
821 #[stable(feature = "rust1", since = "1.0.0")]
822 impl<'a, A> Clone for Iter<'a, A> {
823 fn clone(&self) -> Iter<'a, A> {
824 Iter { inner: self.inner.clone() }
828 /// An iterator over a mutable reference of the contained item in an Option.
829 #[stable(feature = "rust1", since = "1.0.0")]
831 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a, A> Iterator for IterMut<'a, A> {
835 type Item = &'a mut A;
838 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
840 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
843 #[stable(feature = "rust1", since = "1.0.0")]
844 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
846 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
849 #[stable(feature = "rust1", since = "1.0.0")]
850 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
852 /// An iterator over the item contained inside an Option.
853 #[derive(Clone, Debug)]
854 #[stable(feature = "rust1", since = "1.0.0")]
855 pub struct IntoIter<A> { inner: Item<A> }
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<A> Iterator for IntoIter<A> {
862 fn next(&mut self) -> Option<A> { self.inner.next() }
864 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl<A> DoubleEndedIterator for IntoIter<A> {
870 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<A> ExactSizeIterator for IntoIter<A> {}
876 /////////////////////////////////////////////////////////////////////////////
878 /////////////////////////////////////////////////////////////////////////////
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
882 /// Takes each element in the `Iterator`: if it is `None`, no further
883 /// elements are taken, and the `None` is returned. Should no `None` occur, a
884 /// container with the values of each `Option` is returned.
886 /// Here is an example which increments every integer in a vector,
887 /// checking for overflow:
892 /// let v = vec!(1, 2);
893 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
894 /// if x == u16::MAX { None }
895 /// else { Some(x + 1) }
897 /// assert!(res == Some(vec!(2, 3)));
900 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
901 // FIXME(#11084): This could be replaced with Iterator::scan when this
902 // performance bug is closed.
904 struct Adapter<Iter> {
909 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
913 fn next(&mut self) -> Option<T> {
914 match self.iter.next() {
915 Some(Some(value)) => Some(value),
917 self.found_none = true;
925 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
926 let v: V = FromIterator::from_iter(adapter.by_ref());
928 if adapter.found_none {