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:Clone+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) => (*self).clone(),
97 (&None, _) => (*other).clone(),
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(&self) -> bool {
125 match *self { None => true, Some(_) => false }
128 /// Returns true if the option contains some value
130 pub fn is_some(&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(self, f: &fn(t: &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>(&'a self, f: &fn(&'a T) -> U) -> Option<U> {
174 match *self { Some(ref x) => Some(f(x)), None => None }
177 /// Maps a `some` value from one type to another by a mutable reference
179 pub fn map_mut<'a, U>(&'a mut self, f: &fn(&'a mut T) -> U) -> Option<U> {
180 match *self { Some(ref mut x) => Some(f(x)), None => None }
183 /// Maps a `some` value from one type to another by a mutable reference,
184 /// or returns a default value.
186 pub fn map_mut_default<'a, U>(&'a mut self, def: U, f: &fn(&'a mut T) -> U) -> U {
187 match *self { Some(ref mut x) => f(x), None => def }
190 /// As `map`, but consumes the option and gives `f` ownership to avoid
193 pub fn map_consume<U>(self, f: &fn(v: T) -> U) -> Option<U> {
194 match self { None => None, Some(v) => Some(f(v)) }
197 /// Applies a function to the contained value or returns a default
199 pub fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
200 match *self { None => def, Some(ref t) => f(t) }
203 /// As `map_default`, but consumes the option and gives `f`
204 /// ownership to avoid copying.
206 pub fn map_consume_default<U>(self, def: U, f: &fn(v: T) -> U) -> U {
207 match self { None => def, Some(v) => f(v) }
210 /// Take the value out of the option, leaving a `None` in its place.
212 pub fn take(&mut self) -> Option<T> {
213 util::replace(self, None)
216 /// As `map_consume`, but swaps a None into the original option rather
217 /// than consuming it by-value.
219 pub fn take_map<U>(&mut self, blk: &fn(T) -> U) -> Option<U> {
220 self.take().map_consume(blk)
223 /// As `map_consume_default`, but swaps a None into the original option
224 /// rather than consuming it by-value.
226 pub fn take_map_default<U> (&mut self, def: U, blk: &fn(T) -> U) -> U {
227 self.take().map_consume_default(def, blk)
230 /// Apply a function to the contained value or do nothing
231 pub fn mutate(&mut self, f: &fn(T) -> T) {
233 *self = Some(f(self.take_unwrap()));
237 /// Apply a function to the contained value or set it to a default
238 pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
240 *self = Some(f(self.take_unwrap()));
247 Gets an immutable reference to the value inside an option.
251 Fails if the value equals `None`
255 In general, because this function may fail, its use is discouraged
256 (calling `get` on `None` is akin to dereferencing a null pointer).
257 Instead, prefer to use pattern matching and handle the `None`
261 pub fn get_ref<'a>(&'a self) -> &'a T {
264 None => fail!("option::get_ref none")
269 Gets a mutable reference to the value inside an option.
273 Fails if the value equals `None`
277 In general, because this function may fail, its use is discouraged
278 (calling `get` on `None` is akin to dereferencing a null pointer).
279 Instead, prefer to use pattern matching and handle the `None`
283 pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
285 Some(ref mut x) => x,
286 None => fail!("option::get_mut_ref none")
291 pub fn unwrap(self) -> T {
293 Moves a value out of an option type and returns it.
295 Useful primarily for getting strings, vectors and unique pointers out
296 of option types without copying them.
300 Fails if the value equals `None`.
304 In general, because this function may fail, its use is discouraged.
305 Instead, prefer to use pattern matching and handle the `None`
310 None => fail!("option::unwrap none")
315 * The option dance. Moves a value out of an option type and returns it,
316 * replacing the original with `None`.
320 * Fails if the value equals `None`.
323 pub fn take_unwrap(&mut self) -> T {
324 if self.is_none() { fail!("option::take_unwrap none") }
329 * Gets the value out of an option, printing a specified message on
334 * Fails if the value equals `none`
337 pub fn expect(self, reason: &str) -> T {
340 None => fail!(reason.to_owned()),
345 Gets the value out of an option
349 Fails if the value equals `None`
353 In general, because this function may fail, its use is discouraged
354 (calling `get` on `None` is akin to dereferencing a null pointer).
355 Instead, prefer to use pattern matching and handle the `None`
359 pub fn get(self) -> T {
362 None => fail!("option::get none")
366 /// Returns the contained value or a default
368 pub fn get_or_default(self, def: T) -> T {
369 match self { Some(x) => x, None => def }
372 /// Applies a function zero or more times until the result is none.
374 pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
376 while opt.is_some() {
377 opt = blk(opt.unwrap());
382 impl<T:Zero> Option<T> {
383 /// Returns the contained value or zero (for this type)
385 pub fn get_or_zero(self) -> T {
393 impl<T> Zero for Option<T> {
394 fn zero() -> Option<T> { None }
395 fn is_zero(&self) -> bool { self.is_none() }
398 /// Immutable iterator over an `Option<A>`
399 pub struct OptionIterator<'self, A> {
400 priv opt: Option<&'self A>
403 impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
404 fn next(&mut self) -> Option<&'self A> {
405 util::replace(&mut self.opt, None)
408 fn size_hint(&self) -> (uint, Option<uint>) {
410 Some(_) => (1, Some(1)),
411 None => (0, Some(0)),
416 /// Mutable iterator over an `Option<A>`
417 pub struct OptionMutIterator<'self, A> {
418 priv opt: Option<&'self mut A>
421 impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
422 fn next(&mut self) -> Option<&'self mut A> {
423 util::replace(&mut self.opt, None)
426 fn size_hint(&self) -> (uint, Option<uint>) {
428 Some(_) => (1, Some(1)),
429 None => (0, Some(0)),
435 fn test_unwrap_ptr() {
438 let addr_x: *int = ::cast::transmute(&*x);
440 let y = opt.unwrap();
441 let addr_y: *int = ::cast::transmute(&*y);
442 assert_eq!(addr_x, addr_y);
447 fn test_unwrap_str() {
449 let addr_x = str::as_buf(x, |buf, _len| buf);
451 let y = opt.unwrap();
452 let addr_y = str::as_buf(y, |buf, _len| buf);
453 assert_eq!(addr_x, addr_y);
457 fn test_unwrap_resource() {
463 impl ::ops::Drop for R {
464 fn drop(&self) { *(self.i) += 1; }
467 fn R(i: @mut int) -> R {
477 let _y = opt.unwrap();
483 fn test_option_dance() {
487 for x.iter().advance |_x| {
488 y2 = y.take_unwrap();
491 assert!(y.is_none());
493 #[test] #[should_fail] #[ignore(cfg(windows))]
494 fn test_option_too_much_dance() {
495 let mut y = Some(util::NonCopyable);
496 let _y2 = y.take_unwrap();
497 let _y3 = y.take_unwrap();
501 fn test_option_while_some() {
503 do Some(10).while_some |j| {
515 fn test_get_or_zero() {
516 let some_stuff = Some(42);
517 assert_eq!(some_stuff.get_or_zero(), 42);
518 let no_stuff: Option<int> = None;
519 assert_eq!(no_stuff.get_or_zero(), 0);
524 let some_stuff = Some(42);
525 let modified_stuff = some_stuff.filtered(|&x| {x < 10});
526 assert_eq!(some_stuff.get(), 42);
527 assert!(modified_stuff.is_none());
535 let mut it = x.iter();
537 assert_eq!(it.size_hint(), (1, Some(1)));
538 assert_eq!(it.next(), Some(&val));
539 assert_eq!(it.size_hint(), (0, Some(0)));
540 assert!(it.next().is_none());
548 let mut x = Some(val);
549 let mut it = x.mut_iter();
551 assert_eq!(it.size_hint(), (1, Some(1)));
555 assert_eq!(*interior, val);
557 assert_eq!(x, Some(new_val));
559 None => assert!(false),
562 assert_eq!(it.size_hint(), (0, Some(0)));
563 assert!(it.next().is_none());