]> git.proxmox.com Git - rustc.git/blob - src/libcore/option.rs
New upstream version 1.26.0+dfsg1
[rustc.git] / src / libcore / option.rs
1 // Copyright 2012-2014 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.
4 //
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.
10
11 //! Optional values.
12 //!
13 //! Type [`Option`] represents an optional value: every [`Option`]
14 //! is either [`Some`] and contains a value, or [`None`], and
15 //! does not. [`Option`] types are very common in Rust code, as
16 //! they have a number of uses:
17 //!
18 //! * Initial values
19 //! * Return values for functions that are not defined
20 //! over their entire input range (partial functions)
21 //! * Return value for otherwise reporting simple errors, where `None` is
22 //! returned on error
23 //! * Optional struct fields
24 //! * Struct fields that can be loaned or "taken"
25 //! * Optional function arguments
26 //! * Nullable pointers
27 //! * Swapping things out of difficult situations
28 //!
29 //! [`Option`]s are commonly paired with pattern matching to query the presence
30 //! of a value and take action, always accounting for the [`None`] case.
31 //!
32 //! ```
33 //! fn divide(numerator: f64, denominator: f64) -> Option<f64> {
34 //! if denominator == 0.0 {
35 //! None
36 //! } else {
37 //! Some(numerator / denominator)
38 //! }
39 //! }
40 //!
41 //! // The return value of the function is an option
42 //! let result = divide(2.0, 3.0);
43 //!
44 //! // Pattern match to retrieve the value
45 //! match result {
46 //! // The division was valid
47 //! Some(x) => println!("Result: {}", x),
48 //! // The division was invalid
49 //! None => println!("Cannot divide by 0"),
50 //! }
51 //! ```
52 //!
53 //
54 // FIXME: Show how `Option` is used in practice, with lots of methods
55 //
56 //! # Options and pointers ("nullable" pointers)
57 //!
58 //! Rust's pointer types must always point to a valid location; there are
59 //! no "null" pointers. Instead, Rust has *optional* pointers, like
60 //! the optional owned box, [`Option`]`<`[`Box<T>`]`>`.
61 //!
62 //! The following example uses [`Option`] to create an optional box of
63 //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the
64 //! `check_optional` function needs to use pattern matching to
65 //! determine whether the box has a value (i.e. it is [`Some(...)`][`Some`]) or
66 //! not ([`None`]).
67 //!
68 //! ```
69 //! let optional = None;
70 //! check_optional(optional);
71 //!
72 //! let optional = Some(Box::new(9000));
73 //! check_optional(optional);
74 //!
75 //! fn check_optional(optional: Option<Box<i32>>) {
76 //! match optional {
77 //! Some(ref p) => println!("has value {}", p),
78 //! None => println!("has no value"),
79 //! }
80 //! }
81 //! ```
82 //!
83 //! This usage of [`Option`] to create safe nullable pointers is so
84 //! common that Rust does special optimizations to make the
85 //! representation of [`Option`]`<`[`Box<T>`]`>` a single pointer. Optional pointers
86 //! in Rust are stored as efficiently as any other pointer type.
87 //!
88 //! # Examples
89 //!
90 //! Basic pattern matching on [`Option`]:
91 //!
92 //! ```
93 //! let msg = Some("howdy");
94 //!
95 //! // Take a reference to the contained string
96 //! if let Some(ref m) = msg {
97 //! println!("{}", *m);
98 //! }
99 //!
100 //! // Remove the contained string, destroying the Option
101 //! let unwrapped_msg = msg.unwrap_or("default message");
102 //! ```
103 //!
104 //! Initialize a result to [`None`] before a loop:
105 //!
106 //! ```
107 //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) }
108 //!
109 //! // A list of data to search through.
110 //! let all_the_big_things = [
111 //! Kingdom::Plant(250, "redwood"),
112 //! Kingdom::Plant(230, "noble fir"),
113 //! Kingdom::Plant(229, "sugar pine"),
114 //! Kingdom::Animal(25, "blue whale"),
115 //! Kingdom::Animal(19, "fin whale"),
116 //! Kingdom::Animal(15, "north pacific right whale"),
117 //! ];
118 //!
119 //! // We're going to search for the name of the biggest animal,
120 //! // but to start with we've just got `None`.
121 //! let mut name_of_biggest_animal = None;
122 //! let mut size_of_biggest_animal = 0;
123 //! for big_thing in &all_the_big_things {
124 //! match *big_thing {
125 //! Kingdom::Animal(size, name) if size > size_of_biggest_animal => {
126 //! // Now we've found the name of some big animal
127 //! size_of_biggest_animal = size;
128 //! name_of_biggest_animal = Some(name);
129 //! }
130 //! Kingdom::Animal(..) | Kingdom::Plant(..) => ()
131 //! }
132 //! }
133 //!
134 //! match name_of_biggest_animal {
135 //! Some(name) => println!("the biggest animal is {}", name),
136 //! None => println!("there are no animals :("),
137 //! }
138 //! ```
139 //!
140 //! [`Option`]: enum.Option.html
141 //! [`Some`]: enum.Option.html#variant.Some
142 //! [`None`]: enum.Option.html#variant.None
143 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
144 //! [`i32`]: ../../std/primitive.i32.html
145
146 #![stable(feature = "rust1", since = "1.0.0")]
147
148 use iter::{FromIterator, FusedIterator, TrustedLen};
149 use {mem, ops};
150
151 // Note that this is not a lang item per se, but it has a hidden dependency on
152 // `Iterator`, which is one. The compiler assumes that the `next` method of
153 // `Iterator` is an enumeration with one type parameter and two variants,
154 // which basically means it must be `Option`.
155
156 /// The `Option` type. See [the module level documentation](index.html) for more.
157 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub enum Option<T> {
160 /// No value
161 #[stable(feature = "rust1", since = "1.0.0")]
162 None,
163 /// Some value `T`
164 #[stable(feature = "rust1", since = "1.0.0")]
165 Some(#[stable(feature = "rust1", since = "1.0.0")] T),
166 }
167
168 /////////////////////////////////////////////////////////////////////////////
169 // Type implementation
170 /////////////////////////////////////////////////////////////////////////////
171
172 impl<T> Option<T> {
173 /////////////////////////////////////////////////////////////////////////
174 // Querying the contained values
175 /////////////////////////////////////////////////////////////////////////
176
177 /// Returns `true` if the option is a [`Some`] value.
178 ///
179 /// # Examples
180 ///
181 /// ```
182 /// let x: Option<u32> = Some(2);
183 /// assert_eq!(x.is_some(), true);
184 ///
185 /// let x: Option<u32> = None;
186 /// assert_eq!(x.is_some(), false);
187 /// ```
188 ///
189 /// [`Some`]: #variant.Some
190 #[inline]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 pub fn is_some(&self) -> bool {
193 match *self {
194 Some(_) => true,
195 None => false,
196 }
197 }
198
199 /// Returns `true` if the option is a [`None`] value.
200 ///
201 /// # Examples
202 ///
203 /// ```
204 /// let x: Option<u32> = Some(2);
205 /// assert_eq!(x.is_none(), false);
206 ///
207 /// let x: Option<u32> = None;
208 /// assert_eq!(x.is_none(), true);
209 /// ```
210 ///
211 /// [`None`]: #variant.None
212 #[inline]
213 #[stable(feature = "rust1", since = "1.0.0")]
214 pub fn is_none(&self) -> bool {
215 !self.is_some()
216 }
217
218 /////////////////////////////////////////////////////////////////////////
219 // Adapter for working with references
220 /////////////////////////////////////////////////////////////////////////
221
222 /// Converts from `Option<T>` to `Option<&T>`.
223 ///
224 /// # Examples
225 ///
226 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
227 /// The [`map`] method takes the `self` argument by value, consuming the original,
228 /// so this technique uses `as_ref` to first take an `Option` to a reference
229 /// to the value inside the original.
230 ///
231 /// [`map`]: enum.Option.html#method.map
232 /// [`String`]: ../../std/string/struct.String.html
233 /// [`usize`]: ../../std/primitive.usize.html
234 ///
235 /// ```
236 /// let text: Option<String> = Some("Hello, world!".to_string());
237 /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
238 /// // then consume *that* with `map`, leaving `text` on the stack.
239 /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
240 /// println!("still can print text: {:?}", text);
241 /// ```
242 #[inline]
243 #[stable(feature = "rust1", since = "1.0.0")]
244 pub fn as_ref(&self) -> Option<&T> {
245 match *self {
246 Some(ref x) => Some(x),
247 None => None,
248 }
249 }
250
251 /// Converts from `Option<T>` to `Option<&mut T>`.
252 ///
253 /// # Examples
254 ///
255 /// ```
256 /// let mut x = Some(2);
257 /// match x.as_mut() {
258 /// Some(v) => *v = 42,
259 /// None => {},
260 /// }
261 /// assert_eq!(x, Some(42));
262 /// ```
263 #[inline]
264 #[stable(feature = "rust1", since = "1.0.0")]
265 pub fn as_mut(&mut self) -> Option<&mut T> {
266 match *self {
267 Some(ref mut x) => Some(x),
268 None => None,
269 }
270 }
271
272 /////////////////////////////////////////////////////////////////////////
273 // Getting to contained values
274 /////////////////////////////////////////////////////////////////////////
275
276 /// Unwraps an option, yielding the content of a [`Some`].
277 ///
278 /// # Panics
279 ///
280 /// Panics if the value is a [`None`] with a custom panic message provided by
281 /// `msg`.
282 ///
283 /// [`Some`]: #variant.Some
284 /// [`None`]: #variant.None
285 ///
286 /// # Examples
287 ///
288 /// ```
289 /// let x = Some("value");
290 /// assert_eq!(x.expect("the world is ending"), "value");
291 /// ```
292 ///
293 /// ```{.should_panic}
294 /// let x: Option<&str> = None;
295 /// x.expect("the world is ending"); // panics with `the world is ending`
296 /// ```
297 #[inline]
298 #[stable(feature = "rust1", since = "1.0.0")]
299 pub fn expect(self, msg: &str) -> T {
300 match self {
301 Some(val) => val,
302 None => expect_failed(msg),
303 }
304 }
305
306 /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
307 ///
308 /// In general, because this function may panic, its use is discouraged.
309 /// Instead, prefer to use pattern matching and handle the [`None`]
310 /// case explicitly.
311 ///
312 /// # Panics
313 ///
314 /// Panics if the self value equals [`None`].
315 ///
316 /// [`Some(v)`]: #variant.Some
317 /// [`None`]: #variant.None
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// let x = Some("air");
323 /// assert_eq!(x.unwrap(), "air");
324 /// ```
325 ///
326 /// ```{.should_panic}
327 /// let x: Option<&str> = None;
328 /// assert_eq!(x.unwrap(), "air"); // fails
329 /// ```
330 #[inline]
331 #[stable(feature = "rust1", since = "1.0.0")]
332 pub fn unwrap(self) -> T {
333 match self {
334 Some(val) => val,
335 None => panic!("called `Option::unwrap()` on a `None` value"),
336 }
337 }
338
339 /// Returns the contained value or a default.
340 ///
341 /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
342 /// the result of a function call, it is recommended to use [`unwrap_or_else`],
343 /// which is lazily evaluated.
344 ///
345 /// [`unwrap_or_else`]: #method.unwrap_or_else
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// assert_eq!(Some("car").unwrap_or("bike"), "car");
351 /// assert_eq!(None.unwrap_or("bike"), "bike");
352 /// ```
353 #[inline]
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn unwrap_or(self, def: T) -> T {
356 match self {
357 Some(x) => x,
358 None => def,
359 }
360 }
361
362 /// Returns the contained value or computes it from a closure.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// let k = 10;
368 /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
369 /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
370 /// ```
371 #[inline]
372 #[stable(feature = "rust1", since = "1.0.0")]
373 pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
374 match self {
375 Some(x) => x,
376 None => f(),
377 }
378 }
379
380 /////////////////////////////////////////////////////////////////////////
381 // Transforming contained values
382 /////////////////////////////////////////////////////////////////////////
383
384 /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
385 ///
386 /// # Examples
387 ///
388 /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
389 ///
390 /// [`String`]: ../../std/string/struct.String.html
391 /// [`usize`]: ../../std/primitive.usize.html
392 ///
393 /// ```
394 /// let maybe_some_string = Some(String::from("Hello, World!"));
395 /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
396 /// let maybe_some_len = maybe_some_string.map(|s| s.len());
397 ///
398 /// assert_eq!(maybe_some_len, Some(13));
399 /// ```
400 #[inline]
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
403 match self {
404 Some(x) => Some(f(x)),
405 None => None,
406 }
407 }
408
409 /// Applies a function to the contained value (if any),
410 /// or returns the provided default (if not).
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// let x = Some("foo");
416 /// assert_eq!(x.map_or(42, |v| v.len()), 3);
417 ///
418 /// let x: Option<&str> = None;
419 /// assert_eq!(x.map_or(42, |v| v.len()), 42);
420 /// ```
421 #[inline]
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
424 match self {
425 Some(t) => f(t),
426 None => default,
427 }
428 }
429
430 /// Applies a function to the contained value (if any),
431 /// or computes a default (if not).
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// let k = 21;
437 ///
438 /// let x = Some("foo");
439 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
440 ///
441 /// let x: Option<&str> = None;
442 /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
443 /// ```
444 #[inline]
445 #[stable(feature = "rust1", since = "1.0.0")]
446 pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
447 match self {
448 Some(t) => f(t),
449 None => default(),
450 }
451 }
452
453 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
454 /// [`Ok(v)`] and [`None`] to [`Err(err)`].
455 ///
456 /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
457 /// result of a function call, it is recommended to use [`ok_or_else`], which is
458 /// lazily evaluated.
459 ///
460 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
461 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
462 /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
463 /// [`None`]: #variant.None
464 /// [`Some(v)`]: #variant.Some
465 /// [`ok_or_else`]: #method.ok_or_else
466 ///
467 /// # Examples
468 ///
469 /// ```
470 /// let x = Some("foo");
471 /// assert_eq!(x.ok_or(0), Ok("foo"));
472 ///
473 /// let x: Option<&str> = None;
474 /// assert_eq!(x.ok_or(0), Err(0));
475 /// ```
476 #[inline]
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn ok_or<E>(self, err: E) -> Result<T, E> {
479 match self {
480 Some(v) => Ok(v),
481 None => Err(err),
482 }
483 }
484
485 /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
486 /// [`Ok(v)`] and [`None`] to [`Err(err())`].
487 ///
488 /// [`Result<T, E>`]: ../../std/result/enum.Result.html
489 /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
490 /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
491 /// [`None`]: #variant.None
492 /// [`Some(v)`]: #variant.Some
493 ///
494 /// # Examples
495 ///
496 /// ```
497 /// let x = Some("foo");
498 /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
499 ///
500 /// let x: Option<&str> = None;
501 /// assert_eq!(x.ok_or_else(|| 0), Err(0));
502 /// ```
503 #[inline]
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
506 match self {
507 Some(v) => Ok(v),
508 None => Err(err()),
509 }
510 }
511
512 /////////////////////////////////////////////////////////////////////////
513 // Iterator constructors
514 /////////////////////////////////////////////////////////////////////////
515
516 /// Returns an iterator over the possibly contained value.
517 ///
518 /// # Examples
519 ///
520 /// ```
521 /// let x = Some(4);
522 /// assert_eq!(x.iter().next(), Some(&4));
523 ///
524 /// let x: Option<u32> = None;
525 /// assert_eq!(x.iter().next(), None);
526 /// ```
527 #[inline]
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn iter(&self) -> Iter<T> {
530 Iter { inner: Item { opt: self.as_ref() } }
531 }
532
533 /// Returns a mutable iterator over the possibly contained value.
534 ///
535 /// # Examples
536 ///
537 /// ```
538 /// let mut x = Some(4);
539 /// match x.iter_mut().next() {
540 /// Some(v) => *v = 42,
541 /// None => {},
542 /// }
543 /// assert_eq!(x, Some(42));
544 ///
545 /// let mut x: Option<u32> = None;
546 /// assert_eq!(x.iter_mut().next(), None);
547 /// ```
548 #[inline]
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn iter_mut(&mut self) -> IterMut<T> {
551 IterMut { inner: Item { opt: self.as_mut() } }
552 }
553
554 /////////////////////////////////////////////////////////////////////////
555 // Boolean operations on the values, eager and lazy
556 /////////////////////////////////////////////////////////////////////////
557
558 /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
559 ///
560 /// [`None`]: #variant.None
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// let x = Some(2);
566 /// let y: Option<&str> = None;
567 /// assert_eq!(x.and(y), None);
568 ///
569 /// let x: Option<u32> = None;
570 /// let y = Some("foo");
571 /// assert_eq!(x.and(y), None);
572 ///
573 /// let x = Some(2);
574 /// let y = Some("foo");
575 /// assert_eq!(x.and(y), Some("foo"));
576 ///
577 /// let x: Option<u32> = None;
578 /// let y: Option<&str> = None;
579 /// assert_eq!(x.and(y), None);
580 /// ```
581 #[inline]
582 #[stable(feature = "rust1", since = "1.0.0")]
583 pub fn and<U>(self, optb: Option<U>) -> Option<U> {
584 match self {
585 Some(_) => optb,
586 None => None,
587 }
588 }
589
590 /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
591 /// wrapped value and returns the result.
592 ///
593 /// Some languages call this operation flatmap.
594 ///
595 /// [`None`]: #variant.None
596 ///
597 /// # Examples
598 ///
599 /// ```
600 /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
601 /// fn nope(_: u32) -> Option<u32> { None }
602 ///
603 /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
604 /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
605 /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
606 /// assert_eq!(None.and_then(sq).and_then(sq), None);
607 /// ```
608 #[inline]
609 #[stable(feature = "rust1", since = "1.0.0")]
610 pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
611 match self {
612 Some(x) => f(x),
613 None => None,
614 }
615 }
616
617 /// Returns `None` if the option is `None`, otherwise calls `predicate`
618 /// with the wrapped value and returns:
619 ///
620 /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
621 /// value), and
622 /// - `None` if `predicate` returns `false`.
623 ///
624 /// This function works similar to `Iterator::filter()`. You can imagine
625 /// the `Option<T>` being an iterator over one or zero elements. `filter()`
626 /// lets you decide which elements to keep.
627 ///
628 /// # Examples
629 ///
630 /// ```rust
631 /// #![feature(option_filter)]
632 ///
633 /// fn is_even(n: &i32) -> bool {
634 /// n % 2 == 0
635 /// }
636 ///
637 /// assert_eq!(None.filter(is_even), None);
638 /// assert_eq!(Some(3).filter(is_even), None);
639 /// assert_eq!(Some(4).filter(is_even), Some(4));
640 /// ```
641 #[inline]
642 #[unstable(feature = "option_filter", issue = "45860")]
643 pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
644 if let Some(x) = self {
645 if predicate(&x) {
646 return Some(x)
647 }
648 }
649 None
650 }
651
652 /// Returns the option if it contains a value, otherwise returns `optb`.
653 ///
654 /// Arguments passed to `or` are eagerly evaluated; if you are passing the
655 /// result of a function call, it is recommended to use [`or_else`], which is
656 /// lazily evaluated.
657 ///
658 /// [`or_else`]: #method.or_else
659 ///
660 /// # Examples
661 ///
662 /// ```
663 /// let x = Some(2);
664 /// let y = None;
665 /// assert_eq!(x.or(y), Some(2));
666 ///
667 /// let x = None;
668 /// let y = Some(100);
669 /// assert_eq!(x.or(y), Some(100));
670 ///
671 /// let x = Some(2);
672 /// let y = Some(100);
673 /// assert_eq!(x.or(y), Some(2));
674 ///
675 /// let x: Option<u32> = None;
676 /// let y = None;
677 /// assert_eq!(x.or(y), None);
678 /// ```
679 #[inline]
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn or(self, optb: Option<T>) -> Option<T> {
682 match self {
683 Some(_) => self,
684 None => optb,
685 }
686 }
687
688 /// Returns the option if it contains a value, otherwise calls `f` and
689 /// returns the result.
690 ///
691 /// # Examples
692 ///
693 /// ```
694 /// fn nobody() -> Option<&'static str> { None }
695 /// fn vikings() -> Option<&'static str> { Some("vikings") }
696 ///
697 /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
698 /// assert_eq!(None.or_else(vikings), Some("vikings"));
699 /// assert_eq!(None.or_else(nobody), None);
700 /// ```
701 #[inline]
702 #[stable(feature = "rust1", since = "1.0.0")]
703 pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
704 match self {
705 Some(_) => self,
706 None => f(),
707 }
708 }
709
710 /////////////////////////////////////////////////////////////////////////
711 // Entry-like operations to insert if None and return a reference
712 /////////////////////////////////////////////////////////////////////////
713
714 /// Inserts `v` into the option if it is [`None`], then
715 /// returns a mutable reference to the contained value.
716 ///
717 /// [`None`]: #variant.None
718 ///
719 /// # Examples
720 ///
721 /// ```
722 /// let mut x = None;
723 ///
724 /// {
725 /// let y: &mut u32 = x.get_or_insert(5);
726 /// assert_eq!(y, &5);
727 ///
728 /// *y = 7;
729 /// }
730 ///
731 /// assert_eq!(x, Some(7));
732 /// ```
733 #[inline]
734 #[stable(feature = "option_entry", since = "1.20.0")]
735 pub fn get_or_insert(&mut self, v: T) -> &mut T {
736 match *self {
737 None => *self = Some(v),
738 _ => (),
739 }
740
741 match *self {
742 Some(ref mut v) => v,
743 _ => unreachable!(),
744 }
745 }
746
747 /// Inserts a value computed from `f` into the option if it is [`None`], then
748 /// returns a mutable reference to the contained value.
749 ///
750 /// [`None`]: #variant.None
751 ///
752 /// # Examples
753 ///
754 /// ```
755 /// let mut x = None;
756 ///
757 /// {
758 /// let y: &mut u32 = x.get_or_insert_with(|| 5);
759 /// assert_eq!(y, &5);
760 ///
761 /// *y = 7;
762 /// }
763 ///
764 /// assert_eq!(x, Some(7));
765 /// ```
766 #[inline]
767 #[stable(feature = "option_entry", since = "1.20.0")]
768 pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
769 match *self {
770 None => *self = Some(f()),
771 _ => (),
772 }
773
774 match *self {
775 Some(ref mut v) => v,
776 _ => unreachable!(),
777 }
778 }
779
780 /////////////////////////////////////////////////////////////////////////
781 // Misc
782 /////////////////////////////////////////////////////////////////////////
783
784 /// Takes the value out of the option, leaving a [`None`] in its place.
785 ///
786 /// [`None`]: #variant.None
787 ///
788 /// # Examples
789 ///
790 /// ```
791 /// let mut x = Some(2);
792 /// x.take();
793 /// assert_eq!(x, None);
794 ///
795 /// let mut x: Option<u32> = None;
796 /// x.take();
797 /// assert_eq!(x, None);
798 /// ```
799 #[inline]
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub fn take(&mut self) -> Option<T> {
802 mem::replace(self, None)
803 }
804 }
805
806 impl<'a, T: Clone> Option<&'a T> {
807 /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
808 /// option.
809 ///
810 /// # Examples
811 ///
812 /// ```
813 /// let x = 12;
814 /// let opt_x = Some(&x);
815 /// assert_eq!(opt_x, Some(&12));
816 /// let cloned = opt_x.cloned();
817 /// assert_eq!(cloned, Some(12));
818 /// ```
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn cloned(self) -> Option<T> {
821 self.map(|t| t.clone())
822 }
823 }
824
825 impl<'a, T: Clone> Option<&'a mut T> {
826 /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
827 /// option.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// let mut x = 12;
833 /// let opt_x = Some(&mut x);
834 /// assert_eq!(opt_x, Some(&mut 12));
835 /// let cloned = opt_x.cloned();
836 /// assert_eq!(cloned, Some(12));
837 /// ```
838 #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
839 pub fn cloned(self) -> Option<T> {
840 self.map(|t| t.clone())
841 }
842 }
843
844 impl<T: Default> Option<T> {
845 /// Returns the contained value or a default
846 ///
847 /// Consumes the `self` argument then, if [`Some`], returns the contained
848 /// value, otherwise if [`None`], returns the [default value] for that
849 /// type.
850 ///
851 /// # Examples
852 ///
853 /// Convert a string to an integer, turning poorly-formed strings
854 /// into 0 (the default value for integers). [`parse`] converts
855 /// a string to any other type that implements [`FromStr`], returning
856 /// [`None`] on error.
857 ///
858 /// ```
859 /// let good_year_from_input = "1909";
860 /// let bad_year_from_input = "190blarg";
861 /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
862 /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
863 ///
864 /// assert_eq!(1909, good_year);
865 /// assert_eq!(0, bad_year);
866 /// ```
867 ///
868 /// [`Some`]: #variant.Some
869 /// [`None`]: #variant.None
870 /// [default value]: ../default/trait.Default.html#tymethod.default
871 /// [`parse`]: ../../std/primitive.str.html#method.parse
872 /// [`FromStr`]: ../../std/str/trait.FromStr.html
873 #[inline]
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn unwrap_or_default(self) -> T {
876 match self {
877 Some(x) => x,
878 None => Default::default(),
879 }
880 }
881 }
882
883 impl<T, E> Option<Result<T, E>> {
884 /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
885 ///
886 /// `None` will be mapped to `Ok(None)`.
887 /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
888 ///
889 /// # Examples
890 ///
891 /// ```
892 /// #![feature(transpose_result)]
893 ///
894 /// #[derive(Debug, Eq, PartialEq)]
895 /// struct SomeErr;
896 ///
897 /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
898 /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
899 /// assert_eq!(x, y.transpose());
900 /// ```
901 #[inline]
902 #[unstable(feature = "transpose_result", issue = "47338")]
903 pub fn transpose(self) -> Result<Option<T>, E> {
904 match self {
905 Some(Ok(x)) => Ok(Some(x)),
906 Some(Err(e)) => Err(e),
907 None => Ok(None),
908 }
909 }
910 }
911
912 // This is a separate function to reduce the code size of .expect() itself.
913 #[inline(never)]
914 #[cold]
915 fn expect_failed(msg: &str) -> ! {
916 panic!("{}", msg)
917 }
918
919
920 /////////////////////////////////////////////////////////////////////////////
921 // Trait implementations
922 /////////////////////////////////////////////////////////////////////////////
923
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<T> Default for Option<T> {
926 /// Returns [`None`].
927 ///
928 /// [`None`]: #variant.None
929 #[inline]
930 fn default() -> Option<T> { None }
931 }
932
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<T> IntoIterator for Option<T> {
935 type Item = T;
936 type IntoIter = IntoIter<T>;
937
938 /// Returns a consuming iterator over the possibly contained value.
939 ///
940 /// # Examples
941 ///
942 /// ```
943 /// let x = Some("string");
944 /// let v: Vec<&str> = x.into_iter().collect();
945 /// assert_eq!(v, ["string"]);
946 ///
947 /// let x = None;
948 /// let v: Vec<&str> = x.into_iter().collect();
949 /// assert!(v.is_empty());
950 /// ```
951 #[inline]
952 fn into_iter(self) -> IntoIter<T> {
953 IntoIter { inner: Item { opt: self } }
954 }
955 }
956
957 #[stable(since = "1.4.0", feature = "option_iter")]
958 impl<'a, T> IntoIterator for &'a Option<T> {
959 type Item = &'a T;
960 type IntoIter = Iter<'a, T>;
961
962 fn into_iter(self) -> Iter<'a, T> {
963 self.iter()
964 }
965 }
966
967 #[stable(since = "1.4.0", feature = "option_iter")]
968 impl<'a, T> IntoIterator for &'a mut Option<T> {
969 type Item = &'a mut T;
970 type IntoIter = IterMut<'a, T>;
971
972 fn into_iter(self) -> IterMut<'a, T> {
973 self.iter_mut()
974 }
975 }
976
977 #[stable(since = "1.12.0", feature = "option_from")]
978 impl<T> From<T> for Option<T> {
979 fn from(val: T) -> Option<T> {
980 Some(val)
981 }
982 }
983
984 /////////////////////////////////////////////////////////////////////////////
985 // The Option Iterators
986 /////////////////////////////////////////////////////////////////////////////
987
988 #[derive(Clone, Debug)]
989 struct Item<A> {
990 opt: Option<A>
991 }
992
993 impl<A> Iterator for Item<A> {
994 type Item = A;
995
996 #[inline]
997 fn next(&mut self) -> Option<A> {
998 self.opt.take()
999 }
1000
1001 #[inline]
1002 fn size_hint(&self) -> (usize, Option<usize>) {
1003 match self.opt {
1004 Some(_) => (1, Some(1)),
1005 None => (0, Some(0)),
1006 }
1007 }
1008 }
1009
1010 impl<A> DoubleEndedIterator for Item<A> {
1011 #[inline]
1012 fn next_back(&mut self) -> Option<A> {
1013 self.opt.take()
1014 }
1015 }
1016
1017 impl<A> ExactSizeIterator for Item<A> {}
1018 impl<A> FusedIterator for Item<A> {}
1019 unsafe impl<A> TrustedLen for Item<A> {}
1020
1021 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1022 ///
1023 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1024 ///
1025 /// This `struct` is created by the [`Option::iter`] function.
1026 ///
1027 /// [`Option`]: enum.Option.html
1028 /// [`Some`]: enum.Option.html#variant.Some
1029 /// [`Option::iter`]: enum.Option.html#method.iter
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 #[derive(Debug)]
1032 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1033
1034 #[stable(feature = "rust1", since = "1.0.0")]
1035 impl<'a, A> Iterator for Iter<'a, A> {
1036 type Item = &'a A;
1037
1038 #[inline]
1039 fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1040 #[inline]
1041 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1042 }
1043
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1046 #[inline]
1047 fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1048 }
1049
1050 #[stable(feature = "rust1", since = "1.0.0")]
1051 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
1052
1053 #[stable(feature = "fused", since = "1.26.0")]
1054 impl<'a, A> FusedIterator for Iter<'a, A> {}
1055
1056 #[unstable(feature = "trusted_len", issue = "37572")]
1057 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
1058
1059 #[stable(feature = "rust1", since = "1.0.0")]
1060 impl<'a, A> Clone for Iter<'a, A> {
1061 fn clone(&self) -> Iter<'a, A> {
1062 Iter { inner: self.inner.clone() }
1063 }
1064 }
1065
1066 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1067 ///
1068 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1069 ///
1070 /// This `struct` is created by the [`Option::iter_mut`] function.
1071 ///
1072 /// [`Option`]: enum.Option.html
1073 /// [`Some`]: enum.Option.html#variant.Some
1074 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 #[derive(Debug)]
1077 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1078
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<'a, A> Iterator for IterMut<'a, A> {
1081 type Item = &'a mut A;
1082
1083 #[inline]
1084 fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1085 #[inline]
1086 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1087 }
1088
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1091 #[inline]
1092 fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1093 }
1094
1095 #[stable(feature = "rust1", since = "1.0.0")]
1096 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
1097
1098 #[stable(feature = "fused", since = "1.26.0")]
1099 impl<'a, A> FusedIterator for IterMut<'a, A> {}
1100 #[unstable(feature = "trusted_len", issue = "37572")]
1101 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1102
1103 /// An iterator over the value in [`Some`] variant of an [`Option`].
1104 ///
1105 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1106 ///
1107 /// This `struct` is created by the [`Option::into_iter`] function.
1108 ///
1109 /// [`Option`]: enum.Option.html
1110 /// [`Some`]: enum.Option.html#variant.Some
1111 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1112 #[derive(Clone, Debug)]
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub struct IntoIter<A> { inner: Item<A> }
1115
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 impl<A> Iterator for IntoIter<A> {
1118 type Item = A;
1119
1120 #[inline]
1121 fn next(&mut self) -> Option<A> { self.inner.next() }
1122 #[inline]
1123 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1124 }
1125
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<A> DoubleEndedIterator for IntoIter<A> {
1128 #[inline]
1129 fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1130 }
1131
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 impl<A> ExactSizeIterator for IntoIter<A> {}
1134
1135 #[stable(feature = "fused", since = "1.26.0")]
1136 impl<A> FusedIterator for IntoIter<A> {}
1137
1138 #[unstable(feature = "trusted_len", issue = "37572")]
1139 unsafe impl<A> TrustedLen for IntoIter<A> {}
1140
1141 /////////////////////////////////////////////////////////////////////////////
1142 // FromIterator
1143 /////////////////////////////////////////////////////////////////////////////
1144
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1147 /// Takes each element in the [`Iterator`]: if it is [`None`], no further
1148 /// elements are taken, and the [`None`] is returned. Should no [`None`] occur, a
1149 /// container with the values of each `Option` is returned.
1150 ///
1151 /// Here is an example which increments every integer in a vector,
1152 /// checking for overflow:
1153 ///
1154 /// ```
1155 /// use std::u16;
1156 ///
1157 /// let v = vec![1, 2];
1158 /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1159 /// if x == u16::MAX { None }
1160 /// else { Some(x + 1) }
1161 /// ).collect();
1162 /// assert!(res == Some(vec![2, 3]));
1163 /// ```
1164 ///
1165 /// [`Iterator`]: ../iter/trait.Iterator.html
1166 /// [`None`]: enum.Option.html#variant.None
1167 #[inline]
1168 fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1169 // FIXME(#11084): This could be replaced with Iterator::scan when this
1170 // performance bug is closed.
1171
1172 struct Adapter<Iter> {
1173 iter: Iter,
1174 found_none: bool,
1175 }
1176
1177 impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1178 type Item = T;
1179
1180 #[inline]
1181 fn next(&mut self) -> Option<T> {
1182 match self.iter.next() {
1183 Some(Some(value)) => Some(value),
1184 Some(None) => {
1185 self.found_none = true;
1186 None
1187 }
1188 None => None,
1189 }
1190 }
1191
1192 #[inline]
1193 fn size_hint(&self) -> (usize, Option<usize>) {
1194 if self.found_none {
1195 (0, Some(0))
1196 } else {
1197 let (_, upper) = self.iter.size_hint();
1198 (0, upper)
1199 }
1200 }
1201 }
1202
1203 let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1204 let v: V = FromIterator::from_iter(adapter.by_ref());
1205
1206 if adapter.found_none {
1207 None
1208 } else {
1209 Some(v)
1210 }
1211 }
1212 }
1213
1214 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1215 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1216 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1217 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1218 #[unstable(feature = "try_trait", issue = "42327")]
1219 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1220 pub struct NoneError;
1221
1222 #[unstable(feature = "try_trait", issue = "42327")]
1223 impl<T> ops::Try for Option<T> {
1224 type Ok = T;
1225 type Error = NoneError;
1226
1227 fn into_result(self) -> Result<T, NoneError> {
1228 self.ok_or(NoneError)
1229 }
1230
1231 fn from_ok(v: T) -> Self {
1232 Some(v)
1233 }
1234
1235 fn from_error(_: NoneError) -> Self {
1236 None
1237 }
1238 }