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 //! Plant(250, "redwood"),
116 //! Plant(230, "noble fir"),
117 //! Plant(229, "sugar pine"),
118 //! Animal(25, "blue whale"),
119 //! Animal(19, "fin whale"),
120 //! 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 //! 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 //! Animal(..) | Plant(..) => ()
138 //! match name_of_biggest_animal {
139 //! Some(name) => println!("the biggest animal is {}", name),
140 //! None => println!("there are no animals :(")
144 use cmp::{PartialEq, Eq, Ord};
145 use default::Default;
147 use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
151 // Note that this is not a lang item per se, but it has a hidden dependency on
152 // `Iterator`, which is one. The compiler assumes that the `next` method of
153 // `Iterator` is an enumeration with one type parameter and two variants,
154 // which basically means it must be `Option`.
156 /// The `Option` type.
157 #[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
165 /////////////////////////////////////////////////////////////////////////////
166 // Type implementation
167 /////////////////////////////////////////////////////////////////////////////
170 /////////////////////////////////////////////////////////////////////////
171 // Querying the contained values
172 /////////////////////////////////////////////////////////////////////////
174 /// Returns `true` if the option is a `Some` value
176 pub fn is_some(&self) -> bool {
183 /// Returns `true` if the option is a `None` value
185 pub fn is_none(&self) -> bool {
189 /////////////////////////////////////////////////////////////////////////
190 // Adapter for working with references
191 /////////////////////////////////////////////////////////////////////////
193 /// Convert from `Option<T>` to `Option<&T>`
197 /// Convert an `Option<String>` into an `Option<int>`, preserving the original.
198 /// The `map` method takes the `self` argument by value, consuming the original,
199 /// so this technique uses `as_ref` to first take an `Option` to a reference
200 /// to the value inside the original.
203 /// let num_as_str: Option<String> = Some("10".to_string());
204 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
205 /// // then consume *that* with `map`, leaving `num_as_str` on the stack.
206 /// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
207 /// println!("still can print num_as_str: {}", num_as_str);
210 pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
211 match *self { Some(ref x) => Some(x), None => None }
214 /// Convert from `Option<T>` to `Option<&mut T>`
216 pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
217 match *self { Some(ref mut x) => Some(x), None => None }
220 /// Convert from `Option<T>` to `&mut [T]` (without copying)
222 pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
224 Some(ref mut x) => slice::mut_ref_slice(x),
229 /////////////////////////////////////////////////////////////////////////
230 // Getting to contained values
231 /////////////////////////////////////////////////////////////////////////
233 /// Unwraps an option, yielding the content of a `Some`
237 /// Fails if the value is a `None` with a custom failure message provided by
240 pub fn expect(self, msg: &str) -> T {
247 /// Moves a value out of an option type and returns it, consuming the `Option`.
251 /// Fails if the self value equals `None`.
255 /// In general, because this function may fail, its use is discouraged.
256 /// Instead, prefer to use pattern matching and handle the `None`
259 pub fn unwrap(self) -> T {
262 None => fail!("called `Option::unwrap()` on a `None` value"),
266 /// Returns the contained value or a default.
268 pub fn unwrap_or(self, def: T) -> T {
275 /// Returns the contained value or computes it from a closure.
277 pub fn unwrap_or_else(self, f: || -> T) -> T {
284 /////////////////////////////////////////////////////////////////////////
285 // Transforming contained values
286 /////////////////////////////////////////////////////////////////////////
288 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value
292 /// Convert an `Option<String>` into an `Option<uint>`, consuming the original:
295 /// let num_as_str: Option<String> = Some("10".to_string());
296 /// // `Option::map` takes self *by value*, consuming `num_as_str`
297 /// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
300 pub fn map<U>(self, f: |T| -> U) -> Option<U> {
301 match self { Some(x) => Some(f(x)), None => None }
304 /// Applies a function to the contained value or returns a default.
306 pub fn map_or<U>(self, def: U, f: |T| -> U) -> U {
307 match self { None => def, Some(t) => f(t) }
310 /// Applies a function to the contained value or does nothing.
311 /// Returns true if the contained value was mutated.
312 pub fn mutate(&mut self, f: |T| -> T) -> bool {
314 *self = Some(f(self.take_unwrap()));
319 /// Applies a function to the contained value or sets it to a default.
320 /// Returns true if the contained value was mutated, or false if set to the default.
321 pub fn mutate_or_set(&mut self, def: T, f: |T| -> T) -> bool {
323 *self = Some(f(self.take_unwrap()));
331 /////////////////////////////////////////////////////////////////////////
332 // Iterator constructors
333 /////////////////////////////////////////////////////////////////////////
335 /// Returns an iterator over the possibly contained value.
337 pub fn iter<'r>(&'r self) -> Item<&'r T> {
338 Item{opt: self.as_ref()}
341 /// Returns a mutable iterator over the possibly contained value.
343 pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
344 Item{opt: self.as_mut()}
347 /// Returns a consuming iterator over the possibly contained value.
349 pub fn move_iter(self) -> Item<T> {
353 /////////////////////////////////////////////////////////////////////////
354 // Boolean operations on the values, eager and lazy
355 /////////////////////////////////////////////////////////////////////////
357 /// Returns `None` if the option is `None`, otherwise returns `optb`.
359 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
366 /// Returns `None` if the option is `None`, otherwise calls `f` with the
367 /// wrapped value and returns the result.
369 pub fn and_then<U>(self, f: |T| -> Option<U>) -> Option<U> {
376 /// Returns the option if it contains a value, otherwise returns `optb`.
378 pub fn or(self, optb: Option<T>) -> Option<T> {
385 /// Returns the option if it contains a value, otherwise calls `f` and
386 /// returns the result.
388 pub fn or_else(self, f: || -> Option<T>) -> Option<T> {
395 /////////////////////////////////////////////////////////////////////////
397 /////////////////////////////////////////////////////////////////////////
399 /// Takes the value out of the option, leaving a `None` in its place.
401 pub fn take(&mut self) -> Option<T> {
402 mem::replace(self, None)
405 /// Filters an optional value using a given function.
407 pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
409 Some(x) => if f(&x) { Some(x) } else { None },
414 /// Applies a function zero or more times until the result is `None`.
416 pub fn while_some(self, f: |v: T| -> Option<T>) {
420 Some(x) => opt = f(x),
426 /////////////////////////////////////////////////////////////////////////
427 // Common special cases
428 /////////////////////////////////////////////////////////////////////////
430 /// The option dance. Moves a value out of an option type and returns it,
431 /// replacing the original with `None`.
435 /// Fails if the value equals `None`.
437 pub fn take_unwrap(&mut self) -> T {
440 None => fail!("called `Option::take_unwrap()` on a `None` value")
444 /// Gets an immutable reference to the value inside an option.
448 /// Fails if the value equals `None`
452 /// In general, because this function may fail, its use is discouraged
453 /// (calling `get` on `None` is akin to dereferencing a null pointer).
454 /// Instead, prefer to use pattern matching and handle the `None`
457 pub fn get_ref<'a>(&'a self) -> &'a T {
460 None => fail!("called `Option::get_ref()` on a `None` value"),
464 /// Gets a mutable reference to the value inside an option.
468 /// Fails if the value equals `None`
472 /// In general, because this function may fail, its use is discouraged
473 /// (calling `get` on `None` is akin to dereferencing a null pointer).
474 /// Instead, prefer to use pattern matching and handle the `None`
477 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
479 Some(ref mut x) => x,
480 None => fail!("called `Option::get_mut_ref()` on a `None` value"),
485 impl<T: Default> Option<T> {
486 /// Returns the contained value or a default
488 /// Consumes the `self` argument then, if `Some`, returns the contained
489 /// value, otherwise if `None`, returns the default value for that
494 /// Convert a string to an integer, turning poorly-formed strings
495 /// into 0 (the default value for integers). `from_str` converts
496 /// a string to any other type that implements `FromStr`, returning
500 /// let good_year_from_input = "1909";
501 /// let bad_year_from_input = "190blarg";
502 /// let good_year = from_str(good_year_from_input).unwrap_or_default();
503 /// let bad_year = from_str(bad_year_from_input).unwrap_or_default();
505 /// assert_eq!(1909i, good_year);
506 /// assert_eq!(0i, bad_year);
509 pub fn unwrap_or_default(self) -> T {
512 None => Default::default()
517 /////////////////////////////////////////////////////////////////////////////
518 // Trait implementations
519 /////////////////////////////////////////////////////////////////////////////
521 impl<T> Slice<T> for Option<T> {
522 /// Convert from `Option<T>` to `&[T]` (without copying)
524 fn as_slice<'a>(&'a self) -> &'a [T] {
526 Some(ref x) => slice::ref_slice(x),
532 impl<T> Default for Option<T> {
534 fn default() -> Option<T> { None }
537 /////////////////////////////////////////////////////////////////////////////
538 // The Option Iterator
539 /////////////////////////////////////////////////////////////////////////////
541 /// An `Option` iterator that yields either one or zero elements
543 /// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
544 /// methods on `Option`.
550 impl<A> Iterator<A> for Item<A> {
552 fn next(&mut self) -> Option<A> {
557 fn size_hint(&self) -> (uint, Option<uint>) {
559 Some(_) => (1, Some(1)),
560 None => (0, Some(0)),
565 impl<A> DoubleEndedIterator<A> for Item<A> {
567 fn next_back(&mut self) -> Option<A> {
572 impl<A> ExactSize<A> for Item<A> {}
574 /////////////////////////////////////////////////////////////////////////////
576 /////////////////////////////////////////////////////////////////////////////
578 /// Takes each element in the `Iterator`: if it is `None`, no further
579 /// elements are taken, and the `None` is returned. Should no `None` occur, a
580 /// vector containing the values of each `Option` is returned.
582 /// Here is an example which increments every integer in a vector,
583 /// checking for overflow:
589 /// let v = vec!(1u, 2u);
590 /// let res: Option<Vec<uint>> = option::collect(v.iter().map(|x: &uint|
591 /// if *x == uint::MAX { None }
592 /// else { Some(x + 1) }
594 /// assert!(res == Some(vec!(2u, 3u)));
597 pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(iter: Iter) -> Option<V> {
598 // FIXME(#11084): This could be replaced with Iterator::scan when this
599 // performance bug is closed.
601 struct Adapter<Iter> {
606 impl<T, Iter: Iterator<Option<T>>> Iterator<T> for Adapter<Iter> {
608 fn next(&mut self) -> Option<T> {
609 match self.iter.next() {
610 Some(Some(value)) => Some(value),
612 self.found_none = true;
620 let mut adapter = Adapter { iter: iter, found_none: false };
621 let v: V = FromIterator::from_iter(adapter.by_ref());
623 if adapter.found_none {