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 old_iter::{BaseIter, MutableIter, ExtendedIter};
55 #[deriving(Clone, Eq)]
61 impl<T:Ord> Ord for Option<T> {
62 fn lt(&self, other: &Option<T>) -> bool {
64 (&None, &None) => false,
65 (&None, &Some(_)) => true,
66 (&Some(_), &None) => false,
67 (&Some(ref a), &Some(ref b)) => *a < *b
71 fn le(&self, other: &Option<T>) -> bool {
73 (&None, &None) => true,
74 (&None, &Some(_)) => true,
75 (&Some(_), &None) => false,
76 (&Some(ref a), &Some(ref b)) => *a <= *b
80 fn ge(&self, other: &Option<T>) -> bool {
84 fn gt(&self, other: &Option<T>) -> bool {
89 impl<T: Copy + Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
91 fn add(&self, other: &Option<T>) -> Option<T> {
92 match (*self, *other) {
96 (Some(ref lhs), Some(ref rhs)) => Some(*lhs + *rhs)
101 impl<T> BaseIter<T> for Option<T> {
102 /// Performs an operation on the contained value by reference
105 fn each(&self, f: &fn(x: &'self T) -> bool) {
106 match *self { None => (), Some(ref t) => { f(t); } }
109 /// Performs an operation on the contained value by reference
114 fn each<'a>(&'a self, f: &fn(x: &'a T) -> bool) {
115 match *self { None => (), Some(ref t) => { f(t); } }
119 fn size_hint(&self) -> Option<uint> {
120 if self.is_some() { Some(1) } else { Some(0) }
124 impl<T> MutableIter<T> for Option<T> {
127 fn each_mut(&mut self, f: &fn(&'self mut T) -> bool) {
128 match *self { None => (), Some(ref mut t) => { f(t); } }
135 fn each_mut<'a>(&'a mut self, f: &fn(&'a mut T) -> bool) {
136 match *self { None => (), Some(ref mut t) => { f(t); } }
140 impl<A> ExtendedIter<A> for Option<A> {
141 pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) {
142 old_iter::eachi(self, blk)
144 pub fn all(&self, blk: &fn(&A) -> bool) -> bool {
145 old_iter::all(self, blk)
147 pub fn any(&self, blk: &fn(&A) -> bool) -> bool {
148 old_iter::any(self, blk)
150 pub fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
151 old_iter::foldl(self, b0, blk)
153 pub fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
154 old_iter::position(self, f)
156 fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
157 old_iter::map_to_vec(self, op)
159 fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
161 old_iter::flat_map_to_vec(self, op)
165 pub impl<T> Option<T> {
166 /// Returns true if the option equals `none`
167 fn is_none(&const self) -> bool {
168 match *self { None => true, Some(_) => false }
171 /// Returns true if the option contains some value
173 fn is_some(&const self) -> bool { !self.is_none() }
176 fn chain<U>(self, f: &fn(t: T) -> Option<U>) -> Option<U> {
178 * Update an optional value by optionally running its content through a
179 * function that returns an option.
189 fn or(self, optb: Option<T>) -> Option<T> {
191 * Returns the leftmost Some() value, or None if both are None.
194 Some(opta) => Some(opta),
200 * Update an optional value by optionally running its content by reference
201 * through a function that returns an option.
205 fn chain_ref<U>(&self, f: &fn(x: &'self T) -> Option<U>) -> Option<U> {
206 match *self { Some(ref x) => f(x), None => None }
210 * Update an optional value by optionally running its content by reference
211 * through a function that returns an option.
217 fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>) -> Option<U> {
218 match *self { Some(ref x) => f(x), None => None }
221 /// Maps a `some` value from one type to another by reference
224 fn map<U>(&self, f: &fn(&'self T) -> U) -> Option<U> {
225 match *self { Some(ref x) => Some(f(x)), None => None }
228 /// Maps a `some` value from one type to another by reference
233 fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
234 match *self { Some(ref x) => Some(f(x)), None => None }
237 /// As `map`, but consumes the option and gives `f` ownership to avoid
240 fn map_consume<U>(self, f: &fn(v: T) -> U) -> Option<U> {
241 match self { None => None, Some(v) => Some(f(v)) }
244 /// Applies a function to the contained value or returns a default
247 fn map_default<U>(&self, def: U, f: &fn(&'self T) -> U) -> U {
248 match *self { None => def, Some(ref t) => f(t) }
251 /// Applies a function to the contained value or returns a default
256 fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
257 match *self { None => def, Some(ref t) => f(t) }
260 /// As `map_default`, but consumes the option and gives `f`
261 /// ownership to avoid copying.
263 fn map_consume_default<U>(self, def: U, f: &fn(v: T) -> U) -> U {
264 match self { None => def, Some(v) => f(v) }
267 /// Apply a function to the contained value or do nothing
268 fn mutate(&mut self, f: &fn(T) -> T) {
270 *self = Some(f(self.swap_unwrap()));
274 /// Apply a function to the contained value or set it to a default
275 fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
277 *self = Some(f(self.swap_unwrap()));
284 Gets an immutable reference to the value inside an option.
288 Fails if the value equals `None`
292 In general, because this function may fail, its use is discouraged
293 (calling `get` on `None` is akin to dereferencing a null pointer).
294 Instead, prefer to use pattern matching and handle the `None`
299 fn get_ref(&self) -> &'self T {
302 None => fail!(~"option::get_ref none")
307 Gets an immutable reference to the value inside an option.
311 Fails if the value equals `None`
315 In general, because this function may fail, its use is discouraged
316 (calling `get` on `None` is akin to dereferencing a null pointer).
317 Instead, prefer to use pattern matching and handle the `None`
324 fn get_ref<'a>(&'a self) -> &'a T {
327 None => fail!(~"option::get_ref none")
332 Gets a mutable reference to the value inside an option.
336 Fails if the value equals `None`
340 In general, because this function may fail, its use is discouraged
341 (calling `get` on `None` is akin to dereferencing a null pointer).
342 Instead, prefer to use pattern matching and handle the `None`
347 fn get_mut_ref(&mut self) -> &'self mut T {
349 Some(ref mut x) => x,
350 None => fail!(~"option::get_mut_ref none")
355 Gets a mutable reference to the value inside an option.
359 Fails if the value equals `None`
363 In general, because this function may fail, its use is discouraged
364 (calling `get` on `None` is akin to dereferencing a null pointer).
365 Instead, prefer to use pattern matching and handle the `None`
372 fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
374 Some(ref mut x) => x,
375 None => fail!(~"option::get_mut_ref none")
380 fn unwrap(self) -> T {
382 Moves a value out of an option type and returns it.
384 Useful primarily for getting strings, vectors and unique pointers out
385 of option types without copying them.
389 Fails if the value equals `None`.
393 In general, because this function may fail, its use is discouraged.
394 Instead, prefer to use pattern matching and handle the `None`
399 None => fail!(~"option::unwrap none")
404 * The option dance. Moves a value out of an option type and returns it,
405 * replacing the original with `None`.
409 * Fails if the value equals `None`.
412 fn swap_unwrap(&mut self) -> T {
413 if self.is_none() { fail!(~"option::swap_unwrap none") }
414 util::replace(self, None).unwrap()
418 * Gets the value out of an option, printing a specified message on
423 * Fails if the value equals `none`
426 fn expect(self, reason: &str) -> T {
429 None => fail!(reason.to_owned()),
434 pub impl<T:Copy> Option<T> {
436 Gets the value out of an option
440 Fails if the value equals `None`
444 In general, because this function may fail, its use is discouraged
445 (calling `get` on `None` is akin to dereferencing a null pointer).
446 Instead, prefer to use pattern matching and handle the `None`
452 Some(copy x) => return x,
453 None => fail!(~"option::get none")
457 /// Returns the contained value or a default
459 fn get_or_default(self, def: T) -> T {
460 match self { Some(copy x) => x, None => def }
463 /// Applies a function zero or more times until the result is none.
465 fn while_some(self, blk: &fn(v: T) -> Option<T>) {
467 while opt.is_some() {
468 opt = blk(opt.unwrap());
473 pub impl<T:Copy + Zero> Option<T> {
474 /// Returns the contained value or zero (for this type)
476 fn get_or_zero(self) -> T {
477 match self { Some(copy x) => x, None => Zero::zero() }
482 fn test_unwrap_ptr() {
485 let addr_x: *int = ::cast::transmute(&*x);
487 let y = opt.unwrap();
488 let addr_y: *int = ::cast::transmute(&*y);
489 assert!(addr_x == addr_y);
494 fn test_unwrap_str() {
496 let addr_x = str::as_buf(x, |buf, _len| buf);
498 let y = opt.unwrap();
499 let addr_y = str::as_buf(y, |buf, _len| buf);
500 assert!(addr_x == addr_y);
504 fn test_unwrap_resource() {
510 impl ::ops::Drop for R {
511 fn finalize(&self) { *(self.i) += 1; }
514 fn R(i: @mut int) -> R {
524 let _y = opt.unwrap();
530 fn test_option_dance() {
535 y2 = y.swap_unwrap();
538 assert!(y.is_none());
540 #[test] #[should_fail] #[ignore(cfg(windows))]
541 fn test_option_too_much_dance() {
542 let mut y = Some(util::NonCopyable());
543 let _y2 = y.swap_unwrap();
544 let _y3 = y.swap_unwrap();
548 fn test_option_while_some() {
550 do Some(10).while_some |j| {
562 fn test_get_or_zero() {
563 let some_stuff = Some(42);
564 assert!(some_stuff.get_or_zero() == 42);
565 let no_stuff: Option<int> = None;
566 assert!(no_stuff.get_or_zero() == 0);
572 // indent-tabs-mode: nil
574 // buffer-file-coding-system: utf-8-unix