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 //! `int`. Notice that in order to use the inner `int` 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<int>> = None;
70 //! check_optional(&optional);
72 //! let optional: Option<Box<int>> = Some(box 9000);
73 //! check_optional(&optional);
75 //! fn check_optional(optional: &Option<Box<int>>) {
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(uint, &'static str), Animal(uint, &'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.iter() {
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 :(")
146 pub use self::Option::*;
149 use default::Default;
150 use iter::{Iterator, IteratorExt, DoubleEndedIterator, FromIterator, ExactSizeIterator};
152 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.
164 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
173 /////////////////////////////////////////////////////////////////////////////
174 // Type implementation
175 /////////////////////////////////////////////////////////////////////////////
178 /////////////////////////////////////////////////////////////////////////
179 // Querying the contained values
180 /////////////////////////////////////////////////////////////////////////
182 /// Returns `true` if the option is a `Some` value
187 /// let x: Option<uint> = Some(2);
188 /// assert_eq!(x.is_some(), true);
190 /// let x: Option<uint> = None;
191 /// assert_eq!(x.is_some(), false);
195 pub fn is_some(&self) -> bool {
202 /// Returns `true` if the option is a `None` value
207 /// let x: Option<uint> = Some(2);
208 /// assert_eq!(x.is_none(), false);
210 /// let x: Option<uint> = None;
211 /// assert_eq!(x.is_none(), true);
215 pub fn is_none(&self) -> bool {
219 /////////////////////////////////////////////////////////////////////////
220 // Adapter for working with references
221 /////////////////////////////////////////////////////////////////////////
223 /// Convert from `Option<T>` to `Option<&T>`
227 /// Convert an `Option<String>` into an `Option<int>`, 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.
233 /// let num_as_str: Option<String> = Some("10".to_string());
234 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
235 /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
236 /// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
237 /// println!("still can print num_as_str: {}", num_as_str);
241 pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
243 Some(ref x) => Some(x),
248 /// Convert from `Option<T>` to `Option<&mut T>`
253 /// let mut x = Some(2u);
254 /// match x.as_mut() {
255 /// Some(v) => *v = 42,
258 /// assert_eq!(x, Some(42u));
261 #[unstable = "waiting for mut conventions"]
262 pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
264 Some(ref mut x) => Some(x),
269 /// Convert from `Option<T>` to `&mut [T]` (without copying)
274 /// let mut x = Some("Diamonds");
276 /// let v = x.as_mut_slice();
277 /// assert!(v == ["Diamonds"]);
279 /// assert!(v == ["Dirt"]);
281 /// assert_eq!(x, Some("Dirt"));
284 #[unstable = "waiting for mut conventions"]
285 pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
288 let result: &mut [T] = slice::mut_ref_slice(x);
292 let result: &mut [T] = &mut [];
298 /////////////////////////////////////////////////////////////////////////
299 // Getting to contained values
300 /////////////////////////////////////////////////////////////////////////
302 /// Unwraps an option, yielding the content of a `Some`
306 /// Panics if the value is a `None` with a custom panic message provided by
312 /// let x = Some("value");
313 /// assert_eq!(x.expect("the world is ending"), "value");
316 /// ```{.should_fail}
317 /// let x: Option<&str> = None;
318 /// x.expect("the world is ending"); // panics with `world is ending`
321 #[unstable = "waiting for conventions"]
322 pub fn expect(self, msg: &str) -> T {
325 None => panic!("{}", msg),
329 /// Returns the inner `T` of a `Some(T)`.
333 /// Panics if the self value equals `None`.
337 /// In general, because this function may panic, its use is discouraged.
338 /// Instead, prefer to use pattern matching and handle the `None`
344 /// let x = Some("air");
345 /// assert_eq!(x.unwrap(), "air");
348 /// ```{.should_fail}
349 /// let x: Option<&str> = None;
350 /// assert_eq!(x.unwrap(), "air"); // fails
353 #[unstable = "waiting for conventions"]
354 pub fn unwrap(self) -> T {
357 None => panic!("called `Option::unwrap()` on a `None` value"),
361 /// Returns the contained value or a default.
366 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
367 /// assert_eq!(None.unwrap_or("bike"), "bike");
370 #[unstable = "waiting for conventions"]
371 pub fn unwrap_or(self, def: T) -> T {
378 /// Returns the contained value or computes it from a closure.
384 /// assert_eq!(Some(4u).unwrap_or_else(|| 2 * k), 4u);
385 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20u);
388 #[unstable = "waiting for conventions"]
389 pub fn unwrap_or_else(self, f: || -> T) -> T {
396 /////////////////////////////////////////////////////////////////////////
397 // Transforming contained values
398 /////////////////////////////////////////////////////////////////////////
400 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
404 /// Convert an `Option<String>` into an `Option<uint>`, consuming the original:
407 /// let num_as_str: Option<String> = Some("10".to_string());
408 /// // `Option::map` takes self *by value*, consuming `num_as_str`
409 /// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
412 #[unstable = "waiting for unboxed closures"]
413 pub fn map<U>(self, f: |T| -> U) -> Option<U> {
415 Some(x) => Some(f(x)),
420 /// Applies a function to the contained value or returns a default.
425 /// let x = Some("foo");
426 /// assert_eq!(x.map_or(42u, |v| v.len()), 3u);
428 /// let x: Option<&str> = None;
429 /// assert_eq!(x.map_or(42u, |v| v.len()), 42u);
432 #[unstable = "waiting for unboxed closures"]
433 pub fn map_or<U>(self, def: U, f: |T| -> U) -> U {
440 /// Applies a function to the contained value or computes a default.
447 /// let x = Some("foo");
448 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3u);
450 /// let x: Option<&str> = None;
451 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42u);
454 #[unstable = "waiting for unboxed closures"]
455 pub fn map_or_else<U>(self, def: || -> U, f: |T| -> U) -> U {
462 /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
463 /// `Ok(v)` and `None` to `Err(err)`.
468 /// let x = Some("foo");
469 /// assert_eq!(x.ok_or(0i), Ok("foo"));
471 /// let x: Option<&str> = None;
472 /// assert_eq!(x.ok_or(0i), Err(0i));
476 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
483 /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to
484 /// `Ok(v)` and `None` to `Err(err())`.
489 /// let x = Some("foo");
490 /// assert_eq!(x.ok_or_else(|| 0i), Ok("foo"));
492 /// let x: Option<&str> = None;
493 /// assert_eq!(x.ok_or_else(|| 0i), Err(0i));
497 pub fn ok_or_else<E>(self, err: || -> E) -> Result<T, E> {
504 /////////////////////////////////////////////////////////////////////////
505 // Iterator constructors
506 /////////////////////////////////////////////////////////////////////////
508 /// Returns an iterator over the possibly contained value.
513 /// let x = Some(4u);
514 /// assert_eq!(x.iter().next(), Some(&4));
516 /// let x: Option<uint> = None;
517 /// assert_eq!(x.iter().next(), None);
520 #[unstable = "waiting for iterator conventions"]
521 pub fn iter<'r>(&'r self) -> Item<&'r T> {
522 Item{opt: self.as_ref()}
525 /// Returns a mutable iterator over the possibly contained value.
530 /// let mut x = Some(4u);
531 /// match x.iter_mut().next() {
532 /// Some(&ref mut v) => *v = 42u,
535 /// assert_eq!(x, Some(42));
537 /// let mut x: Option<uint> = None;
538 /// assert_eq!(x.iter_mut().next(), None);
541 #[unstable = "waiting for iterator conventions"]
542 pub fn iter_mut<'r>(&'r mut self) -> Item<&'r mut T> {
543 Item{opt: self.as_mut()}
546 /// Returns a consuming iterator over the possibly contained value.
551 /// let x = Some("string");
552 /// let v: Vec<&str> = x.into_iter().collect();
553 /// assert_eq!(v, vec!["string"]);
556 /// let v: Vec<&str> = x.into_iter().collect();
557 /// assert!(v.is_empty());
560 #[unstable = "waiting for iterator conventions"]
561 pub fn into_iter(self) -> Item<T> {
565 /////////////////////////////////////////////////////////////////////////
566 // Boolean operations on the values, eager and lazy
567 /////////////////////////////////////////////////////////////////////////
569 /// Returns `None` if the option is `None`, otherwise returns `optb`.
574 /// let x = Some(2u);
575 /// let y: Option<&str> = None;
576 /// assert_eq!(x.and(y), None);
578 /// let x: Option<uint> = None;
579 /// let y = Some("foo");
580 /// assert_eq!(x.and(y), None);
582 /// let x = Some(2u);
583 /// let y = Some("foo");
584 /// assert_eq!(x.and(y), Some("foo"));
586 /// let x: Option<uint> = None;
587 /// let y: Option<&str> = None;
588 /// assert_eq!(x.and(y), None);
592 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
599 /// Returns `None` if the option is `None`, otherwise calls `f` with the
600 /// wrapped value and returns the result.
605 /// fn sq(x: uint) -> Option<uint> { Some(x * x) }
606 /// fn nope(_: uint) -> Option<uint> { None }
608 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
609 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
610 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
611 /// assert_eq!(None.and_then(sq).and_then(sq), None);
614 #[unstable = "waiting for unboxed closures"]
615 pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
622 /// Returns the option if it contains a value, otherwise returns `optb`.
627 /// let x = Some(2u);
629 /// assert_eq!(x.or(y), Some(2u));
632 /// let y = Some(100u);
633 /// assert_eq!(x.or(y), Some(100u));
635 /// let x = Some(2u);
636 /// let y = Some(100u);
637 /// assert_eq!(x.or(y), Some(2u));
639 /// let x: Option<uint> = None;
641 /// assert_eq!(x.or(y), None);
645 pub fn or(self, optb: Option<T>) -> Option<T> {
652 /// Returns the option if it contains a value, otherwise calls `f` and
653 /// returns the result.
658 /// fn nobody() -> Option<&'static str> { None }
659 /// fn vikings() -> Option<&'static str> { Some("vikings") }
661 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
662 /// assert_eq!(None.or_else(vikings), Some("vikings"));
663 /// assert_eq!(None.or_else(nobody), None);
666 #[unstable = "waiting for unboxed closures"]
667 pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
674 /////////////////////////////////////////////////////////////////////////
676 /////////////////////////////////////////////////////////////////////////
678 /// Takes the value out of the option, leaving a `None` in its place.
683 /// let mut x = Some(2u);
685 /// assert_eq!(x, None);
687 /// let mut x: Option<uint> = None;
689 /// assert_eq!(x, None);
693 pub fn take(&mut self) -> Option<T> {
694 mem::replace(self, None)
698 impl<'a, T: Clone, D: Deref<T>> Option<D> {
699 /// Maps an Option<D> to an Option<T> by dereffing and cloning the contents of the Option.
700 /// Useful for converting an Option<&T> to an Option<T>.
701 #[unstable = "recently added as part of collections reform"]
702 pub fn cloned(self) -> Option<T> {
703 self.map(|t| t.deref().clone())
707 impl<T: Default> Option<T> {
708 /// Returns the contained value or a default
710 /// Consumes the `self` argument then, if `Some`, returns the contained
711 /// value, otherwise if `None`, returns the default value for that
716 /// Convert a string to an integer, turning poorly-formed strings
717 /// into 0 (the default value for integers). `from_str` converts
718 /// a string to any other type that implements `FromStr`, returning
722 /// let good_year_from_input = "1909";
723 /// let bad_year_from_input = "190blarg";
724 /// let good_year = from_str(good_year_from_input).unwrap_or_default();
725 /// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
727 /// assert_eq!(1909i, good_year);
728 /// assert_eq!(0i, bad_year);
731 #[unstable = "waiting for conventions"]
732 pub fn unwrap_or_default(self) -> T {
735 None => Default::default()
740 /////////////////////////////////////////////////////////////////////////////
741 // Trait implementations
742 /////////////////////////////////////////////////////////////////////////////
744 impl<T> AsSlice<T> for Option<T> {
745 /// Convert from `Option<T>` to `&[T]` (without copying)
747 fn as_slice<'a>(&'a self) -> &'a [T] {
749 Some(ref x) => slice::ref_slice(x),
751 let result: &[_] = &[];
759 impl<T> Default for Option<T> {
761 fn default() -> Option<T> { None }
764 /////////////////////////////////////////////////////////////////////////////
765 // The Option Iterator
766 /////////////////////////////////////////////////////////////////////////////
768 /// An `Option` iterator that yields either one or zero elements
770 /// The `Item` iterator is returned by the `iter`, `iter_mut` and `into_iter`
771 /// methods on `Option`.
773 #[unstable = "waiting for iterator conventions"]
778 impl<A> Iterator<A> for Item<A> {
780 fn next(&mut self) -> Option<A> {
785 fn size_hint(&self) -> (uint, Option<uint>) {
787 Some(_) => (1, Some(1)),
788 None => (0, Some(0)),
793 impl<A> DoubleEndedIterator<A> for Item<A> {
795 fn next_back(&mut self) -> Option<A> {
800 impl<A> ExactSizeIterator<A> for Item<A> {}
802 /////////////////////////////////////////////////////////////////////////////
804 /////////////////////////////////////////////////////////////////////////////
807 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
808 /// Takes each element in the `Iterator`: if it is `None`, no further
809 /// elements are taken, and the `None` is returned. Should no `None` occur, a
810 /// container with the values of each `Option` is returned.
812 /// Here is an example which increments every integer in a vector,
813 /// checking for overflow:
818 /// let v = vec!(1u, 2u);
819 /// let res: Option<Vec<uint>> = v.iter().map(|&x: &uint|
820 /// if x == uint::MAX { None }
821 /// else { Some(x + 1) }
823 /// assert!(res == Some(vec!(2u, 3u)));
826 fn from_iter<I: Iterator<Option<A>>>(iter: I) -> Option<V> {
827 // FIXME(#11084): This could be replaced with Iterator::scan when this
828 // performance bug is closed.
830 struct Adapter<Iter> {
835 impl<T, Iter: Iterator<Option<T>>> Iterator<T> for Adapter<Iter> {
837 fn next(&mut self) -> Option<T> {
838 match self.iter.next() {
839 Some(Some(value)) => Some(value),
841 self.found_none = true;
849 let mut adapter = Adapter { iter: iter, found_none: false };
850 let v: V = FromIterator::from_iter(adapter.by_ref());
852 if adapter.found_none {