1 // Copyright 2012-2013 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 Operations on the ubiquitous `Option` type.
15 Type `Option` represents an optional value.
17 Every `Option<T>` value can either be `Some(T)` or `None`. Where in other
18 languages you might use a nullable type, in Rust you would use an option
21 Options are most commonly used with pattern matching to query the presence
22 of a value and take action, always accounting for the `None` case.
27 let msg = Some(~"howdy");
29 // Take a reference to the contained string
31 Some(ref m) => io::println(m),
35 // Remove the contained string, destroying the Option
36 let unwrapped_msg = match msg {
38 None => ~"default message"
51 use iter::{Iterator, DoubleEndedIterator, ExactSize};
53 use str::{StrSlice, OwnedStr};
58 #[deriving(Clone, DeepClone, Eq)]
64 impl<T: Eq + Ord> Ord for Option<T> {
65 fn lt(&self, other: &Option<T>) -> bool {
66 iter::order::lt(self.iter(), other.iter())
69 fn le(&self, other: &Option<T>) -> bool {
70 iter::order::le(self.iter(), other.iter())
73 fn ge(&self, other: &Option<T>) -> bool {
74 iter::order::ge(self.iter(), other.iter())
77 fn gt(&self, other: &Option<T>) -> bool {
78 iter::order::gt(self.iter(), other.iter())
82 // FIXME: #8242 implementing manually because deriving doesn't work for some reason
83 impl<T: ToStr> ToStr for Option<T> {
84 fn to_str(&self) -> ~str {
88 s.push_str(x.to_str());
98 /// Return an iterator over the possibly contained value
100 pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
102 Some(ref x) => OptionIterator{opt: Some(x)},
103 None => OptionIterator{opt: None}
107 /// Return a mutable iterator over the possibly contained value
109 pub fn mut_iter<'r>(&'r mut self) -> OptionIterator<&'r mut T> {
111 Some(ref mut x) => OptionIterator{opt: Some(x)},
112 None => OptionIterator{opt: None}
116 /// Return a consuming iterator over the possibly contained value
118 pub fn move_iter(self) -> OptionIterator<T> {
119 OptionIterator{opt: self}
122 /// Returns true if the option equals `None`
124 pub fn is_none(&self) -> bool {
125 match *self { None => true, Some(_) => false }
128 /// Returns true if the option contains a `Some` value
130 pub fn is_some(&self) -> bool { !self.is_none() }
132 /// Returns `None` if the option is `None`, otherwise returns `optb`.
134 pub fn and(self, optb: Option<T>) -> Option<T> {
141 /// Returns `None` if the option is `None`, otherwise calls `f` with the
142 /// wrapped value and returns the result.
144 pub fn and_then<U>(self, f: &fn(T) -> Option<U>) -> Option<U> {
151 /// Returns `None` if the option is `None`, otherwise calls `f` with a
152 /// reference to the wrapped value and returns the result.
154 pub fn and_then_ref<'a, U>(&'a self, f: &fn(&'a T) -> Option<U>) -> Option<U> {
161 /// Returns `None` if the option is `None`, otherwise calls `f` with a
162 /// mutable reference to the wrapped value and returns the result.
164 pub fn and_then_mut_ref<'a, U>(&'a mut self, f: &fn(&'a mut T) -> Option<U>) -> Option<U> {
166 Some(ref mut x) => f(x),
171 /// Returns the option if it contains a value, otherwise returns `optb`.
173 pub fn or(self, optb: Option<T>) -> Option<T> {
180 /// Returns the option if it contains a value, otherwise calls `f` and
181 /// returns the result.
183 pub fn or_else(self, f: &fn() -> Option<T>) -> Option<T> {
190 /// Filters an optional value using given function.
192 pub fn filtered(self, f: &fn(t: &T) -> bool) -> Option<T> {
194 Some(x) => if(f(&x)) {Some(x)} else {None},
199 /// Maps a `Some` value from one type to another by reference
201 pub fn map<'a, U>(&'a self, f: &fn(&'a T) -> U) -> Option<U> {
202 match *self { Some(ref x) => Some(f(x)), None => None }
205 /// Maps a `Some` value from one type to another by a mutable reference
207 pub fn map_mut<'a, U>(&'a mut self, f: &fn(&'a mut T) -> U) -> Option<U> {
208 match *self { Some(ref mut x) => Some(f(x)), None => None }
211 /// Applies a function to the contained value or returns a default
213 pub fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
214 match *self { None => def, Some(ref t) => f(t) }
217 /// Maps a `Some` value from one type to another by a mutable reference,
218 /// or returns a default value.
220 pub fn map_mut_default<'a, U>(&'a mut self, def: U, f: &fn(&'a mut T) -> U) -> U {
221 match *self { Some(ref mut x) => f(x), None => def }
224 /// As `map`, but consumes the option and gives `f` ownership to avoid
227 pub fn map_move<U>(self, f: &fn(T) -> U) -> Option<U> {
228 match self { Some(x) => Some(f(x)), None => None }
231 /// As `map_default`, but consumes the option and gives `f`
232 /// ownership to avoid copying.
234 pub fn map_move_default<U>(self, def: U, f: &fn(T) -> U) -> U {
235 match self { None => def, Some(t) => f(t) }
238 /// Take the value out of the option, leaving a `None` in its place.
240 pub fn take(&mut self) -> Option<T> {
241 util::replace(self, None)
244 /// Apply a function to the contained value or do nothing.
245 /// Returns true if the contained value was mutated.
246 pub fn mutate(&mut self, f: &fn(T) -> T) -> bool {
248 *self = Some(f(self.take_unwrap()));
253 /// Apply a function to the contained value or set it to a default.
254 /// Returns true if the contained value was mutated, or false if set to the default.
255 pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) -> bool {
257 *self = Some(f(self.take_unwrap()));
265 /// Gets an immutable reference to the value inside an option.
269 /// Fails if the value equals `None`
273 /// In general, because this function may fail, its use is discouraged
274 /// (calling `get` on `None` is akin to dereferencing a null pointer).
275 /// Instead, prefer to use pattern matching and handle the `None`
278 pub fn get_ref<'a>(&'a self) -> &'a T {
281 None => fail!("called `Option::get_ref()` on a `None` value"),
285 /// Gets a mutable reference to the value inside an option.
289 /// Fails if the value equals `None`
293 /// In general, because this function may fail, its use is discouraged
294 /// (calling `get` on `None` is akin to dereferencing a null pointer).
295 /// Instead, prefer to use pattern matching and handle the `None`
298 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
300 Some(ref mut x) => x,
301 None => fail!("called `Option::get_mut_ref()` on a `None` value"),
305 /// Moves a value out of an option type and returns it.
307 /// Useful primarily for getting strings, vectors and unique pointers out
308 /// of option types without copying them.
312 /// Fails if the value equals `None`.
316 /// In general, because this function may fail, its use is discouraged.
317 /// Instead, prefer to use pattern matching and handle the `None`
320 pub fn unwrap(self) -> T {
323 None => fail!("called `Option::unwrap()` on a `None` value"),
327 /// The option dance. Moves a value out of an option type and returns it,
328 /// replacing the original with `None`.
332 /// Fails if the value equals `None`.
334 pub fn take_unwrap(&mut self) -> T {
336 fail!("called `Option::take_unwrap()` on a `None` value")
341 /// Gets the value out of an option, printing a specified message on
346 /// Fails if the value equals `None`
348 pub fn expect(self, reason: &str) -> T {
351 None => fail!(reason.to_owned()),
355 /// Returns the contained value or a default
357 pub fn unwrap_or(self, def: T) -> T {
364 /// Returns the contained value or computes it from a closure
366 pub fn unwrap_or_else(self, f: &fn() -> T) -> T {
373 /// Applies a function zero or more times until the result is `None`.
375 pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
377 while opt.is_some() {
378 opt = blk(opt.unwrap());
383 /// A generic trait for converting a value to a `Option`
384 pub trait ToOption<T> {
385 /// Convert to the `option` type
386 fn to_option(&self) -> Option<T>;
389 /// A generic trait for converting a value to a `Option`
390 pub trait IntoOption<T> {
391 /// Convert to the `option` type
392 fn into_option(self) -> Option<T>;
395 /// A generic trait for converting a value to a `Option`
396 pub trait AsOption<T> {
397 /// Convert to the `option` type
398 fn as_option<'a>(&'a self) -> Option<&'a T>;
401 impl<T: Clone> ToOption<T> for Option<T> {
403 fn to_option(&self) -> Option<T> { self.clone() }
406 impl<T> IntoOption<T> for Option<T> {
408 fn into_option(self) -> Option<T> { self }
411 impl<T> AsOption<T> for Option<T> {
413 fn as_option<'a>(&'a self) -> Option<&'a T> {
415 Some(ref x) => Some(x),
421 impl<T: Clone> result::ToResult<T, ()> for Option<T> {
423 fn to_result(&self) -> result::Result<T, ()> {
425 Some(ref x) => result::Ok(x.clone()),
426 None => result::Err(()),
431 impl<T> result::IntoResult<T, ()> for Option<T> {
433 fn into_result(self) -> result::Result<T, ()> {
435 Some(x) => result::Ok(x),
436 None => result::Err(()),
441 impl<T: Clone> either::ToEither<(), T> for Option<T> {
443 fn to_either(&self) -> either::Either<(), T> {
445 Some(ref x) => either::Right(x.clone()),
446 None => either::Left(()),
451 impl<T> either::IntoEither<(), T> for Option<T> {
453 fn into_either(self) -> either::Either<(), T> {
455 Some(x) => either::Right(x),
456 None => either::Left(()),
461 impl<T: Default> Option<T> {
462 /// Returns the contained value or default (for this type)
464 pub fn unwrap_or_default(self) -> T {
467 None => Default::default()
471 /// Returns self or `Some`-wrapped default value
473 pub fn or_default(self) -> Option<T> {
475 None => Some(Default::default()),
481 impl<T> Default for Option<T> {
483 fn default() -> Option<T> { None }
486 impl<T:Zero> Option<T> {
487 /// Returns the contained value or zero (for this type)
489 pub fn unwrap_or_zero(self) -> T {
496 /// Returns self or `Some`-wrapped zero value
498 pub fn or_zero(self) -> Option<T> {
500 None => Some(Zero::zero()),
506 /// An iterator that yields either one or zero elements
507 #[deriving(Clone, DeepClone)]
508 pub struct OptionIterator<A> {
512 impl<A> Iterator<A> for OptionIterator<A> {
514 fn next(&mut self) -> Option<A> {
519 fn size_hint(&self) -> (uint, Option<uint>) {
521 Some(_) => (1, Some(1)),
522 None => (0, Some(0)),
527 impl<A> DoubleEndedIterator<A> for OptionIterator<A> {
529 fn next_back(&mut self) -> Option<A> {
534 impl<A> ExactSize<A> for OptionIterator<A> {}
540 use either::{IntoEither, ToEither};
542 use result::{IntoResult, ToResult};
550 let addr_x: *int = ::cast::transmute(&*x);
552 let y = opt.unwrap();
553 let addr_y: *int = ::cast::transmute(&*y);
554 assert_eq!(addr_x, addr_y);
561 let addr_x = x.as_imm_buf(|buf, _len| buf);
563 let y = opt.unwrap();
564 let addr_y = y.as_imm_buf(|buf, _len| buf);
565 assert_eq!(addr_x, addr_y);
569 fn test_get_resource() {
575 impl ::ops::Drop for R {
576 fn drop(&mut self) { *(self.i) += 1; }
579 fn R(i: @mut int) -> R {
589 let _y = opt.unwrap();
595 fn test_option_dance() {
600 y2 = y.take_unwrap();
603 assert!(y.is_none());
605 #[test] #[should_fail]
606 fn test_option_too_much_dance() {
607 let mut y = Some(util::NonCopyable);
608 let _y2 = y.take_unwrap();
609 let _y3 = y.take_unwrap();
614 let x: Option<int> = Some(1);
615 assert_eq!(x.and(Some(2)), Some(2));
616 assert_eq!(x.and(None), None);
618 let x: Option<int> = None;
619 assert_eq!(x.and(Some(2)), None);
620 assert_eq!(x.and(None), None);
625 let x: Option<int> = Some(1);
626 assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
627 assert_eq!(x.and_then(|_| None::<int>), None);
629 let x: Option<int> = None;
630 assert_eq!(x.and_then(|x| Some(x + 1)), None);
631 assert_eq!(x.and_then(|_| None::<int>), None);
636 let x: Option<int> = Some(1);
637 assert_eq!(x.or(Some(2)), Some(1));
638 assert_eq!(x.or(None), Some(1));
640 let x: Option<int> = None;
641 assert_eq!(x.or(Some(2)), Some(2));
642 assert_eq!(x.or(None), None);
647 let x: Option<int> = Some(1);
648 assert_eq!(x.or_else(|| Some(2)), Some(1));
649 assert_eq!(x.or_else(|| None), Some(1));
651 let x: Option<int> = None;
652 assert_eq!(x.or_else(|| Some(2)), Some(2));
653 assert_eq!(x.or_else(|| None), None);
657 fn test_option_while_some() {
659 do Some(10).while_some |j| {
672 assert_eq!(Some(1).unwrap(), 1);
673 assert_eq!(Some(~"hello").unwrap(), ~"hello");
678 fn test_unwrap_fail1() {
679 let x: Option<int> = None;
685 fn test_unwrap_fail2() {
686 let x: Option<~str> = None;
691 fn test_unwrap_or() {
692 let x: Option<int> = Some(1);
693 assert_eq!(x.unwrap_or(2), 1);
695 let x: Option<int> = None;
696 assert_eq!(x.unwrap_or(2), 2);
700 fn test_unwrap_or_else() {
701 let x: Option<int> = Some(1);
702 assert_eq!(x.unwrap_or_else(|| 2), 1);
704 let x: Option<int> = None;
705 assert_eq!(x.unwrap_or_else(|| 2), 2);
709 fn test_unwrap_or_zero() {
710 let some_stuff = Some(42);
711 assert_eq!(some_stuff.unwrap_or_zero(), 42);
712 let no_stuff: Option<int> = None;
713 assert_eq!(no_stuff.unwrap_or_zero(), 0);
718 let some_stuff = Some(42);
719 let modified_stuff = some_stuff.filtered(|&x| {x < 10});
720 assert_eq!(some_stuff.unwrap(), 42);
721 assert!(modified_stuff.is_none());
729 let mut it = x.iter();
731 assert_eq!(it.size_hint(), (1, Some(1)));
732 assert_eq!(it.next(), Some(&val));
733 assert_eq!(it.size_hint(), (0, Some(0)));
734 assert!(it.next().is_none());
742 let mut x = Some(val);
743 let mut it = x.mut_iter();
745 assert_eq!(it.size_hint(), (1, Some(1)));
749 assert_eq!(*interior, val);
751 assert_eq!(x, Some(new_val));
753 None => assert!(false),
756 assert_eq!(it.size_hint(), (0, Some(0)));
757 assert!(it.next().is_none());
762 let small = Some(1.0);
764 let nan = Some(0.0/0.0);
765 assert!(!(nan < big));
766 assert!(!(nan > big));
767 assert!(small < big);
774 let mut x = Some(3i);
775 assert!(x.mutate(|i| i+1));
776 assert_eq!(x, Some(4i));
777 assert!(x.mutate_default(0, |i| i+1));
778 assert_eq!(x, Some(5i));
780 assert!(!x.mutate(|i| i+1));
782 assert!(!x.mutate_default(0i, |i| i+1));
783 assert_eq!(x, Some(0i));
787 pub fn test_to_option() {
788 let some: Option<int> = Some(100);
789 let none: Option<int> = None;
791 assert_eq!(some.to_option(), Some(100));
792 assert_eq!(none.to_option(), None);
796 pub fn test_into_option() {
797 let some: Option<int> = Some(100);
798 let none: Option<int> = None;
800 assert_eq!(some.into_option(), Some(100));
801 assert_eq!(none.into_option(), None);
805 pub fn test_as_option() {
806 let some: Option<int> = Some(100);
807 let none: Option<int> = None;
809 assert_eq!(some.as_option().unwrap(), &100);
810 assert_eq!(none.as_option(), None);
814 pub fn test_to_result() {
815 let some: Option<int> = Some(100);
816 let none: Option<int> = None;
818 assert_eq!(some.to_result(), result::Ok(100));
819 assert_eq!(none.to_result(), result::Err(()));
823 pub fn test_into_result() {
824 let some: Option<int> = Some(100);
825 let none: Option<int> = None;
827 assert_eq!(some.into_result(), result::Ok(100));
828 assert_eq!(none.into_result(), result::Err(()));
832 pub fn test_to_either() {
833 let some: Option<int> = Some(100);
834 let none: Option<int> = None;
836 assert_eq!(some.to_either(), either::Right(100));
837 assert_eq!(none.to_either(), either::Left(()));
841 pub fn test_into_either() {
842 let some: Option<int> = Some(100);
843 let none: Option<int> = None;
845 assert_eq!(some.into_either(), either::Right(100));
846 assert_eq!(none.into_either(), either::Left(()));