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"
49 use iterator::Iterator;
54 #[cfg(test)] use iterator::IteratorUtil;
57 #[deriving(Clone, DeepClone, Eq)]
63 impl<T:Ord> Ord for Option<T> {
64 fn lt(&self, other: &Option<T>) -> bool {
66 (&None, &None) => false,
67 (&None, &Some(_)) => true,
68 (&Some(_), &None) => false,
69 (&Some(ref a), &Some(ref b)) => *a < *b
73 fn le(&self, other: &Option<T>) -> bool {
75 (&None, &None) => true,
76 (&None, &Some(_)) => true,
77 (&Some(_), &None) => false,
78 (&Some(ref a), &Some(ref b)) => *a <= *b
82 fn ge(&self, other: &Option<T>) -> bool {
86 fn gt(&self, other: &Option<T>) -> bool {
91 impl<T: Copy+Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
93 fn add(&self, other: &Option<T>) -> Option<T> {
94 match (&*self, &*other) {
95 (&None, &None) => None,
96 (_, &None) => copy *self,
97 (&None, _) => copy *other,
98 (&Some(ref lhs), &Some(ref rhs)) => Some(*lhs + *rhs)
104 /// Return an iterator over the possibly contained value
106 pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
108 Some(ref x) => OptionIterator{opt: Some(x)},
109 None => OptionIterator{opt: None}
113 /// Return a mutable iterator over the possibly contained value
115 pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
117 Some(ref mut x) => OptionMutIterator{opt: Some(x)},
118 None => OptionMutIterator{opt: None}
122 /// Returns true if the option equals `none`
124 pub fn is_none(&const self) -> bool {
125 match *self { None => true, Some(_) => false }
128 /// Returns true if the option contains some value
130 pub fn is_some(&const self) -> bool { !self.is_none() }
132 /// Update an optional value by optionally running its content through a
133 /// function that returns an option.
135 pub fn chain<U>(self, f: &fn(t: T) -> Option<U>) -> Option<U> {
142 /// Returns the leftmost Some() value, or None if both are None.
144 pub fn or(self, optb: Option<T>) -> Option<T> {
146 Some(opta) => Some(opta),
151 /// Update an optional value by optionally running its content by reference
152 /// through a function that returns an option.
154 pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>)
162 /// Filters an optional value using given function.
164 pub fn filtered<'a>(self, f: &fn(t: &'a T) -> bool) -> Option<T> {
166 Some(x) => if(f(&x)) {Some(x)} else {None},
171 /// Maps a `some` value from one type to another by reference
173 pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
174 match *self { Some(ref x) => Some(f(x)), None => None }
177 /// As `map`, but consumes the option and gives `f` ownership to avoid
180 pub fn map_consume<U>(self, f: &fn(v: T) -> U) -> Option<U> {
181 match self { None => None, Some(v) => Some(f(v)) }
184 /// Applies a function to the contained value or returns a default
186 pub fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
187 match *self { None => def, Some(ref t) => f(t) }
190 /// As `map_default`, but consumes the option and gives `f`
191 /// ownership to avoid copying.
193 pub fn map_consume_default<U>(self, def: U, f: &fn(v: T) -> U) -> U {
194 match self { None => def, Some(v) => f(v) }
197 /// Apply a function to the contained value or do nothing
198 pub fn mutate(&mut self, f: &fn(T) -> T) {
200 *self = Some(f(self.swap_unwrap()));
204 /// Apply a function to the contained value or set it to a default
205 pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
207 *self = Some(f(self.swap_unwrap()));
214 Gets an immutable reference to the value inside an option.
218 Fails if the value equals `None`
222 In general, because this function may fail, its use is discouraged
223 (calling `get` on `None` is akin to dereferencing a null pointer).
224 Instead, prefer to use pattern matching and handle the `None`
228 pub fn get_ref<'a>(&'a self) -> &'a T {
231 None => fail!("option::get_ref none")
236 Gets a mutable reference to the value inside an option.
240 Fails if the value equals `None`
244 In general, because this function may fail, its use is discouraged
245 (calling `get` on `None` is akin to dereferencing a null pointer).
246 Instead, prefer to use pattern matching and handle the `None`
250 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
252 Some(ref mut x) => x,
253 None => fail!("option::get_mut_ref none")
258 pub fn unwrap(self) -> T {
260 Moves a value out of an option type and returns it.
262 Useful primarily for getting strings, vectors and unique pointers out
263 of option types without copying them.
267 Fails if the value equals `None`.
271 In general, because this function may fail, its use is discouraged.
272 Instead, prefer to use pattern matching and handle the `None`
277 None => fail!("option::unwrap none")
282 * The option dance. Moves a value out of an option type and returns it,
283 * replacing the original with `None`.
287 * Fails if the value equals `None`.
290 pub fn swap_unwrap(&mut self) -> T {
291 if self.is_none() { fail!("option::swap_unwrap none") }
292 util::replace(self, None).unwrap()
296 * Gets the value out of an option, printing a specified message on
301 * Fails if the value equals `none`
304 pub fn expect(self, reason: &str) -> T {
307 None => fail!(reason.to_owned()),
312 impl<T:Copy> Option<T> {
314 Gets the value out of an option
318 Fails if the value equals `None`
322 In general, because this function may fail, its use is discouraged
323 (calling `get` on `None` is akin to dereferencing a null pointer).
324 Instead, prefer to use pattern matching and handle the `None`
328 pub fn get(self) -> T {
331 None => fail!("option::get none")
335 /// Returns the contained value or a default
337 pub fn get_or_default(self, def: T) -> T {
338 match self { Some(x) => x, None => def }
341 /// Applies a function zero or more times until the result is none.
343 pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
345 while opt.is_some() {
346 opt = blk(opt.unwrap());
351 impl<T:Copy + Zero> Option<T> {
352 /// Returns the contained value or zero (for this type)
354 pub fn get_or_zero(self) -> T {
362 impl<T> Zero for Option<T> {
363 fn zero() -> Option<T> { None }
364 fn is_zero(&self) -> bool { self.is_none() }
367 /// Immutable iterator over an `Option<A>`
368 pub struct OptionIterator<'self, A> {
369 priv opt: Option<&'self A>
372 impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
373 fn next(&mut self) -> Option<&'self A> {
374 util::replace(&mut self.opt, None)
378 /// Mutable iterator over an `Option<A>`
379 pub struct OptionMutIterator<'self, A> {
380 priv opt: Option<&'self mut A>
383 impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
384 fn next(&mut self) -> Option<&'self mut A> {
385 util::replace(&mut self.opt, None)
390 fn test_unwrap_ptr() {
393 let addr_x: *int = ::cast::transmute(&*x);
395 let y = opt.unwrap();
396 let addr_y: *int = ::cast::transmute(&*y);
397 assert_eq!(addr_x, addr_y);
402 fn test_unwrap_str() {
404 let addr_x = str::as_buf(x, |buf, _len| buf);
406 let y = opt.unwrap();
407 let addr_y = str::as_buf(y, |buf, _len| buf);
408 assert_eq!(addr_x, addr_y);
412 fn test_unwrap_resource() {
418 impl ::ops::Drop for R {
419 fn drop(&self) { *(self.i) += 1; }
422 fn R(i: @mut int) -> R {
432 let _y = opt.unwrap();
438 fn test_option_dance() {
442 for x.iter().advance |_x| {
443 y2 = y.swap_unwrap();
446 assert!(y.is_none());
448 #[test] #[should_fail] #[ignore(cfg(windows))]
449 fn test_option_too_much_dance() {
450 let mut y = Some(util::NonCopyable::new());
451 let _y2 = y.swap_unwrap();
452 let _y3 = y.swap_unwrap();
456 fn test_option_while_some() {
458 do Some(10).while_some |j| {
470 fn test_get_or_zero() {
471 let some_stuff = Some(42);
472 assert_eq!(some_stuff.get_or_zero(), 42);
473 let no_stuff: Option<int> = None;
474 assert_eq!(no_stuff.get_or_zero(), 0);
479 let some_stuff = Some(42);
480 let modified_stuff = some_stuff.filtered(|&x| {x < 10});
481 assert_eq!(some_stuff.get(), 42);
482 assert!(modified_stuff.is_none());