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;
53 #[cfg(test)] use iterator::IteratorUtil;
56 #[deriving(Clone, DeepClone, Eq)]
62 impl<T:Ord> Ord for Option<T> {
63 fn lt(&self, other: &Option<T>) -> bool {
65 (&None, &None) => false,
66 (&None, &Some(_)) => true,
67 (&Some(_), &None) => false,
68 (&Some(ref a), &Some(ref b)) => *a < *b
72 fn le(&self, other: &Option<T>) -> bool {
74 (&None, &None) => true,
75 (&None, &Some(_)) => true,
76 (&Some(_), &None) => false,
77 (&Some(ref a), &Some(ref b)) => *a <= *b
81 fn ge(&self, other: &Option<T>) -> bool {
85 fn gt(&self, other: &Option<T>) -> bool {
90 impl<T:Clone+Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
92 fn add(&self, other: &Option<T>) -> Option<T> {
93 match (&*self, &*other) {
94 (&None, &None) => None,
95 (_, &None) => (*self).clone(),
96 (&None, _) => (*other).clone(),
97 (&Some(ref lhs), &Some(ref rhs)) => Some(*lhs + *rhs)
103 /// Return an iterator over the possibly contained value
105 pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
107 Some(ref x) => OptionIterator{opt: Some(x)},
108 None => OptionIterator{opt: None}
112 /// Return a mutable iterator over the possibly contained value
114 pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
116 Some(ref mut x) => OptionMutIterator{opt: Some(x)},
117 None => OptionMutIterator{opt: None}
121 /// Returns true if the option equals `none`
123 pub fn is_none(&self) -> bool {
124 match *self { None => true, Some(_) => false }
127 /// Returns true if the option contains some value
129 pub fn is_some(&self) -> bool { !self.is_none() }
131 /// Update an optional value by optionally running its content through a
132 /// function that returns an option.
134 pub fn chain<U>(self, f: &fn(t: T) -> Option<U>) -> Option<U> {
141 /// Returns the leftmost Some() value, or None if both are None.
143 pub fn or(self, optb: Option<T>) -> Option<T> {
145 Some(opta) => Some(opta),
150 /// Update an optional value by optionally running its content by reference
151 /// through a function that returns an option.
153 pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>)
161 /// Filters an optional value using given function.
163 pub fn filtered(self, f: &fn(t: &T) -> bool) -> Option<T> {
165 Some(x) => if(f(&x)) {Some(x)} else {None},
170 /// Maps a `some` value from one type to another by reference
172 pub fn map<'a, U>(&'a self, f: &fn(&'a T) -> U) -> Option<U> {
173 match *self { Some(ref x) => Some(f(x)), None => None }
176 /// Maps a `some` value from one type to another by a mutable reference
178 pub fn map_mut<'a, U>(&'a mut self, f: &fn(&'a mut T) -> U) -> Option<U> {
179 match *self { Some(ref mut x) => Some(f(x)), None => None }
182 /// Maps a `some` value from one type to another by a mutable reference,
183 /// or returns a default value.
185 pub fn map_mut_default<'a, U>(&'a mut self, def: U, f: &fn(&'a mut T) -> U) -> U {
186 match *self { Some(ref mut x) => f(x), None => def }
189 /// As `map`, but consumes the option and gives `f` ownership to avoid
192 pub fn map_consume<U>(self, f: &fn(v: T) -> U) -> Option<U> {
193 match self { None => None, Some(v) => Some(f(v)) }
196 /// Applies a function to the contained value or returns a default
198 pub fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
199 match *self { None => def, Some(ref t) => f(t) }
202 /// As `map_default`, but consumes the option and gives `f`
203 /// ownership to avoid copying.
205 pub fn map_consume_default<U>(self, def: U, f: &fn(v: T) -> U) -> U {
206 match self { None => def, Some(v) => f(v) }
209 /// Take the value out of the option, leaving a `None` in its place.
211 pub fn take(&mut self) -> Option<T> {
212 util::replace(self, None)
215 /// As `map_consume`, but swaps a None into the original option rather
216 /// than consuming it by-value.
218 pub fn take_map<U>(&mut self, blk: &fn(T) -> U) -> Option<U> {
219 self.take().map_consume(blk)
222 /// As `map_consume_default`, but swaps a None into the original option
223 /// rather than consuming it by-value.
225 pub fn take_map_default<U> (&mut self, def: U, blk: &fn(T) -> U) -> U {
226 self.take().map_consume_default(def, blk)
229 /// Apply a function to the contained value or do nothing
230 pub fn mutate(&mut self, f: &fn(T) -> T) {
232 *self = Some(f(self.take_unwrap()));
236 /// Apply a function to the contained value or set it to a default
237 pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
239 *self = Some(f(self.take_unwrap()));
246 Gets an immutable reference to the value inside an option.
250 Fails if the value equals `None`
254 In general, because this function may fail, its use is discouraged
255 (calling `get` on `None` is akin to dereferencing a null pointer).
256 Instead, prefer to use pattern matching and handle the `None`
260 pub fn get_ref<'a>(&'a self) -> &'a T {
263 None => fail!("option::get_ref none")
268 Gets a mutable reference to the value inside an option.
272 Fails if the value equals `None`
276 In general, because this function may fail, its use is discouraged
277 (calling `get` on `None` is akin to dereferencing a null pointer).
278 Instead, prefer to use pattern matching and handle the `None`
282 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
284 Some(ref mut x) => x,
285 None => fail!("option::get_mut_ref none")
290 pub fn unwrap(self) -> T {
292 Moves a value out of an option type and returns it.
294 Useful primarily for getting strings, vectors and unique pointers out
295 of option types without copying them.
299 Fails if the value equals `None`.
303 In general, because this function may fail, its use is discouraged.
304 Instead, prefer to use pattern matching and handle the `None`
309 None => fail!("option::unwrap none")
314 * The option dance. Moves a value out of an option type and returns it,
315 * replacing the original with `None`.
319 * Fails if the value equals `None`.
322 pub fn take_unwrap(&mut self) -> T {
323 if self.is_none() { fail!("option::take_unwrap none") }
328 * Gets the value out of an option, printing a specified message on
333 * Fails if the value equals `none`
336 pub fn expect(self, reason: &str) -> T {
339 None => fail!(reason.to_owned()),
344 Gets the value out of an option
348 Fails if the value equals `None`
352 In general, because this function may fail, its use is discouraged
353 (calling `get` on `None` is akin to dereferencing a null pointer).
354 Instead, prefer to use pattern matching and handle the `None`
358 pub fn get(self) -> T {
361 None => fail!("option::get none")
365 /// Returns the contained value or a default
367 pub fn get_or_default(self, def: T) -> T {
368 match self { Some(x) => x, None => def }
371 /// Applies a function zero or more times until the result is none.
373 pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
375 while opt.is_some() {
376 opt = blk(opt.unwrap());
381 impl<T:Zero> Option<T> {
382 /// Returns the contained value or zero (for this type)
384 pub fn get_or_zero(self) -> T {
392 impl<T> Zero for Option<T> {
393 fn zero() -> Option<T> { None }
394 fn is_zero(&self) -> bool { self.is_none() }
397 /// Immutable iterator over an `Option<A>`
398 pub struct OptionIterator<'self, A> {
399 priv opt: Option<&'self A>
402 impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
403 fn next(&mut self) -> Option<&'self A> {
404 util::replace(&mut self.opt, None)
407 fn size_hint(&self) -> (uint, Option<uint>) {
409 Some(_) => (1, Some(1)),
410 None => (0, Some(0)),
415 /// Mutable iterator over an `Option<A>`
416 pub struct OptionMutIterator<'self, A> {
417 priv opt: Option<&'self mut A>
420 impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
421 fn next(&mut self) -> Option<&'self mut A> {
422 util::replace(&mut self.opt, None)
425 fn size_hint(&self) -> (uint, Option<uint>) {
427 Some(_) => (1, Some(1)),
428 None => (0, Some(0)),
434 fn test_unwrap_ptr() {
437 let addr_x: *int = ::cast::transmute(&*x);
439 let y = opt.unwrap();
440 let addr_y: *int = ::cast::transmute(&*y);
441 assert_eq!(addr_x, addr_y);
446 fn test_unwrap_str() {
448 let addr_x = x.as_buf(|buf, _len| buf);
450 let y = opt.unwrap();
451 let addr_y = y.as_buf(|buf, _len| buf);
452 assert_eq!(addr_x, addr_y);
456 fn test_unwrap_resource() {
462 impl ::ops::Drop for R {
463 fn drop(&self) { *(self.i) += 1; }
466 fn R(i: @mut int) -> R {
476 let _y = opt.unwrap();
482 fn test_option_dance() {
486 for x.iter().advance |_x| {
487 y2 = y.take_unwrap();
490 assert!(y.is_none());
492 #[test] #[should_fail] #[ignore(cfg(windows))]
493 fn test_option_too_much_dance() {
494 let mut y = Some(util::NonCopyable);
495 let _y2 = y.take_unwrap();
496 let _y3 = y.take_unwrap();
500 fn test_option_while_some() {
502 do Some(10).while_some |j| {
514 fn test_get_or_zero() {
515 let some_stuff = Some(42);
516 assert_eq!(some_stuff.get_or_zero(), 42);
517 let no_stuff: Option<int> = None;
518 assert_eq!(no_stuff.get_or_zero(), 0);
523 let some_stuff = Some(42);
524 let modified_stuff = some_stuff.filtered(|&x| {x < 10});
525 assert_eq!(some_stuff.get(), 42);
526 assert!(modified_stuff.is_none());
534 let mut it = x.iter();
536 assert_eq!(it.size_hint(), (1, Some(1)));
537 assert_eq!(it.next(), Some(&val));
538 assert_eq!(it.size_hint(), (0, Some(0)));
539 assert!(it.next().is_none());
547 let mut x = Some(val);
548 let mut it = x.mut_iter();
550 assert_eq!(it.size_hint(), (1, Some(1)));
554 assert_eq!(*interior, val);
556 assert_eq!(x, Some(new_val));
558 None => assert!(false),
561 assert_eq!(it.size_hint(), (0, Some(0)));
562 assert!(it.next().is_none());