]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
Ignore new test on Windows
[rust.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 {hint, mem, ops::{self, Deref}};
150 use pin::PinMut;
151
152 // Note that this is not a lang item per se, but it has a hidden dependency on
153 // `Iterator`, which is one. The compiler assumes that the `next` method of
154 // `Iterator` is an enumeration with one type parameter and two variants,
155 // which basically means it must be `Option`.
156
157 /// The `Option` type. See [the module level documentation](index.html) for more.
158 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 pub enum Option<T> {
161     /// No value
162     #[stable(feature = "rust1", since = "1.0.0")]
163     None,
164     /// Some value `T`
165     #[stable(feature = "rust1", since = "1.0.0")]
166     Some(#[stable(feature = "rust1", since = "1.0.0")] T),
167 }
168
169 /////////////////////////////////////////////////////////////////////////////
170 // Type implementation
171 /////////////////////////////////////////////////////////////////////////////
172
173 impl<T> Option<T> {
174     /////////////////////////////////////////////////////////////////////////
175     // Querying the contained values
176     /////////////////////////////////////////////////////////////////////////
177
178     /// Returns `true` if the option is a [`Some`] value.
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// let x: Option<u32> = Some(2);
184     /// assert_eq!(x.is_some(), true);
185     ///
186     /// let x: Option<u32> = None;
187     /// assert_eq!(x.is_some(), false);
188     /// ```
189     ///
190     /// [`Some`]: #variant.Some
191     #[inline]
192     #[stable(feature = "rust1", since = "1.0.0")]
193     pub fn is_some(&self) -> bool {
194         match *self {
195             Some(_) => true,
196             None => false,
197         }
198     }
199
200     /// Returns `true` if the option is a [`None`] value.
201     ///
202     /// # Examples
203     ///
204     /// ```
205     /// let x: Option<u32> = Some(2);
206     /// assert_eq!(x.is_none(), false);
207     ///
208     /// let x: Option<u32> = None;
209     /// assert_eq!(x.is_none(), true);
210     /// ```
211     ///
212     /// [`None`]: #variant.None
213     #[inline]
214     #[stable(feature = "rust1", since = "1.0.0")]
215     pub fn is_none(&self) -> bool {
216         !self.is_some()
217     }
218
219     /////////////////////////////////////////////////////////////////////////
220     // Adapter for working with references
221     /////////////////////////////////////////////////////////////////////////
222
223     /// Converts from `Option<T>` to `Option<&T>`.
224     ///
225     /// # Examples
226     ///
227     /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
228     /// The [`map`] method takes the `self` argument by value, consuming the original,
229     /// so this technique uses `as_ref` to first take an `Option` to a reference
230     /// to the value inside the original.
231     ///
232     /// [`map`]: enum.Option.html#method.map
233     /// [`String`]: ../../std/string/struct.String.html
234     /// [`usize`]: ../../std/primitive.usize.html
235     ///
236     /// ```
237     /// let text: Option<String> = Some("Hello, world!".to_string());
238     /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
239     /// // then consume *that* with `map`, leaving `text` on the stack.
240     /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
241     /// println!("still can print text: {:?}", text);
242     /// ```
243     #[inline]
244     #[stable(feature = "rust1", since = "1.0.0")]
245     pub fn as_ref(&self) -> Option<&T> {
246         match *self {
247             Some(ref x) => Some(x),
248             None => None,
249         }
250     }
251
252     /// Converts from `Option<T>` to `Option<&mut T>`.
253     ///
254     /// # Examples
255     ///
256     /// ```
257     /// let mut x = Some(2);
258     /// match x.as_mut() {
259     ///     Some(v) => *v = 42,
260     ///     None => {},
261     /// }
262     /// assert_eq!(x, Some(42));
263     /// ```
264     #[inline]
265     #[stable(feature = "rust1", since = "1.0.0")]
266     pub fn as_mut(&mut self) -> Option<&mut T> {
267         match *self {
268             Some(ref mut x) => Some(x),
269             None => None,
270         }
271     }
272
273     /// Converts from `Option<T>` to `Option<PinMut<'_, T>>`
274     #[inline]
275     #[unstable(feature = "pin", issue = "49150")]
276     pub fn as_pin_mut<'a>(self: PinMut<'a, Self>) -> Option<PinMut<'a, T>> {
277         unsafe {
278             PinMut::get_mut_unchecked(self).as_mut().map(|x| PinMut::new_unchecked(x))
279         }
280     }
281
282     /////////////////////////////////////////////////////////////////////////
283     // Getting to contained values
284     /////////////////////////////////////////////////////////////////////////
285
286     /// Unwraps an option, yielding the content of a [`Some`].
287     ///
288     /// # Panics
289     ///
290     /// Panics if the value is a [`None`] with a custom panic message provided by
291     /// `msg`.
292     ///
293     /// [`Some`]: #variant.Some
294     /// [`None`]: #variant.None
295     ///
296     /// # Examples
297     ///
298     /// ```
299     /// let x = Some("value");
300     /// assert_eq!(x.expect("the world is ending"), "value");
301     /// ```
302     ///
303     /// ```{.should_panic}
304     /// let x: Option<&str> = None;
305     /// x.expect("the world is ending"); // panics with `the world is ending`
306     /// ```
307     #[inline]
308     #[stable(feature = "rust1", since = "1.0.0")]
309     pub fn expect(self, msg: &str) -> T {
310         match self {
311             Some(val) => val,
312             None => expect_failed(msg),
313         }
314     }
315
316     /// Moves the value `v` out of the `Option<T>` if it is [`Some(v)`].
317     ///
318     /// In general, because this function may panic, its use is discouraged.
319     /// Instead, prefer to use pattern matching and handle the [`None`]
320     /// case explicitly.
321     ///
322     /// # Panics
323     ///
324     /// Panics if the self value equals [`None`].
325     ///
326     /// [`Some(v)`]: #variant.Some
327     /// [`None`]: #variant.None
328     ///
329     /// # Examples
330     ///
331     /// ```
332     /// let x = Some("air");
333     /// assert_eq!(x.unwrap(), "air");
334     /// ```
335     ///
336     /// ```{.should_panic}
337     /// let x: Option<&str> = None;
338     /// assert_eq!(x.unwrap(), "air"); // fails
339     /// ```
340     #[inline]
341     #[stable(feature = "rust1", since = "1.0.0")]
342     pub fn unwrap(self) -> T {
343         match self {
344             Some(val) => val,
345             None => panic!("called `Option::unwrap()` on a `None` value"),
346         }
347     }
348
349     /// Returns the contained value or a default.
350     ///
351     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
352     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
353     /// which is lazily evaluated.
354     ///
355     /// [`unwrap_or_else`]: #method.unwrap_or_else
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// assert_eq!(Some("car").unwrap_or("bike"), "car");
361     /// assert_eq!(None.unwrap_or("bike"), "bike");
362     /// ```
363     #[inline]
364     #[stable(feature = "rust1", since = "1.0.0")]
365     pub fn unwrap_or(self, def: T) -> T {
366         match self {
367             Some(x) => x,
368             None => def,
369         }
370     }
371
372     /// Returns the contained value or computes it from a closure.
373     ///
374     /// # Examples
375     ///
376     /// ```
377     /// let k = 10;
378     /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4);
379     /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20);
380     /// ```
381     #[inline]
382     #[stable(feature = "rust1", since = "1.0.0")]
383     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
384         match self {
385             Some(x) => x,
386             None => f(),
387         }
388     }
389
390     /////////////////////////////////////////////////////////////////////////
391     // Transforming contained values
392     /////////////////////////////////////////////////////////////////////////
393
394     /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value.
395     ///
396     /// # Examples
397     ///
398     /// Convert an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, consuming the original:
399     ///
400     /// [`String`]: ../../std/string/struct.String.html
401     /// [`usize`]: ../../std/primitive.usize.html
402     ///
403     /// ```
404     /// let maybe_some_string = Some(String::from("Hello, World!"));
405     /// // `Option::map` takes self *by value*, consuming `maybe_some_string`
406     /// let maybe_some_len = maybe_some_string.map(|s| s.len());
407     ///
408     /// assert_eq!(maybe_some_len, Some(13));
409     /// ```
410     #[inline]
411     #[stable(feature = "rust1", since = "1.0.0")]
412     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
413         match self {
414             Some(x) => Some(f(x)),
415             None => None,
416         }
417     }
418
419     /// Applies a function to the contained value (if any),
420     /// or returns the provided default (if not).
421     ///
422     /// # Examples
423     ///
424     /// ```
425     /// let x = Some("foo");
426     /// assert_eq!(x.map_or(42, |v| v.len()), 3);
427     ///
428     /// let x: Option<&str> = None;
429     /// assert_eq!(x.map_or(42, |v| v.len()), 42);
430     /// ```
431     #[inline]
432     #[stable(feature = "rust1", since = "1.0.0")]
433     pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
434         match self {
435             Some(t) => f(t),
436             None => default,
437         }
438     }
439
440     /// Applies a function to the contained value (if any),
441     /// or computes a default (if not).
442     ///
443     /// # Examples
444     ///
445     /// ```
446     /// let k = 21;
447     ///
448     /// let x = Some("foo");
449     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3);
450     ///
451     /// let x: Option<&str> = None;
452     /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42);
453     /// ```
454     #[inline]
455     #[stable(feature = "rust1", since = "1.0.0")]
456     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
457         match self {
458             Some(t) => f(t),
459             None => default(),
460         }
461     }
462
463     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
464     /// [`Ok(v)`] and [`None`] to [`Err(err)`].
465     ///
466     /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the
467     /// result of a function call, it is recommended to use [`ok_or_else`], which is
468     /// lazily evaluated.
469     ///
470     /// [`Result<T, E>`]: ../../std/result/enum.Result.html
471     /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
472     /// [`Err(err)`]: ../../std/result/enum.Result.html#variant.Err
473     /// [`None`]: #variant.None
474     /// [`Some(v)`]: #variant.Some
475     /// [`ok_or_else`]: #method.ok_or_else
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// let x = Some("foo");
481     /// assert_eq!(x.ok_or(0), Ok("foo"));
482     ///
483     /// let x: Option<&str> = None;
484     /// assert_eq!(x.ok_or(0), Err(0));
485     /// ```
486     #[inline]
487     #[stable(feature = "rust1", since = "1.0.0")]
488     pub fn ok_or<E>(self, err: E) -> Result<T, E> {
489         match self {
490             Some(v) => Ok(v),
491             None => Err(err),
492         }
493     }
494
495     /// Transforms the `Option<T>` into a [`Result<T, E>`], mapping [`Some(v)`] to
496     /// [`Ok(v)`] and [`None`] to [`Err(err())`].
497     ///
498     /// [`Result<T, E>`]: ../../std/result/enum.Result.html
499     /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok
500     /// [`Err(err())`]: ../../std/result/enum.Result.html#variant.Err
501     /// [`None`]: #variant.None
502     /// [`Some(v)`]: #variant.Some
503     ///
504     /// # Examples
505     ///
506     /// ```
507     /// let x = Some("foo");
508     /// assert_eq!(x.ok_or_else(|| 0), Ok("foo"));
509     ///
510     /// let x: Option<&str> = None;
511     /// assert_eq!(x.ok_or_else(|| 0), Err(0));
512     /// ```
513     #[inline]
514     #[stable(feature = "rust1", since = "1.0.0")]
515     pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> {
516         match self {
517             Some(v) => Ok(v),
518             None => Err(err()),
519         }
520     }
521
522     /////////////////////////////////////////////////////////////////////////
523     // Iterator constructors
524     /////////////////////////////////////////////////////////////////////////
525
526     /// Returns an iterator over the possibly contained value.
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// let x = Some(4);
532     /// assert_eq!(x.iter().next(), Some(&4));
533     ///
534     /// let x: Option<u32> = None;
535     /// assert_eq!(x.iter().next(), None);
536     /// ```
537     #[inline]
538     #[stable(feature = "rust1", since = "1.0.0")]
539     pub fn iter(&self) -> Iter<T> {
540         Iter { inner: Item { opt: self.as_ref() } }
541     }
542
543     /// Returns a mutable iterator over the possibly contained value.
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// let mut x = Some(4);
549     /// match x.iter_mut().next() {
550     ///     Some(v) => *v = 42,
551     ///     None => {},
552     /// }
553     /// assert_eq!(x, Some(42));
554     ///
555     /// let mut x: Option<u32> = None;
556     /// assert_eq!(x.iter_mut().next(), None);
557     /// ```
558     #[inline]
559     #[stable(feature = "rust1", since = "1.0.0")]
560     pub fn iter_mut(&mut self) -> IterMut<T> {
561         IterMut { inner: Item { opt: self.as_mut() } }
562     }
563
564     /////////////////////////////////////////////////////////////////////////
565     // Boolean operations on the values, eager and lazy
566     /////////////////////////////////////////////////////////////////////////
567
568     /// Returns [`None`] if the option is [`None`], otherwise returns `optb`.
569     ///
570     /// [`None`]: #variant.None
571     ///
572     /// # Examples
573     ///
574     /// ```
575     /// let x = Some(2);
576     /// let y: Option<&str> = None;
577     /// assert_eq!(x.and(y), None);
578     ///
579     /// let x: Option<u32> = None;
580     /// let y = Some("foo");
581     /// assert_eq!(x.and(y), None);
582     ///
583     /// let x = Some(2);
584     /// let y = Some("foo");
585     /// assert_eq!(x.and(y), Some("foo"));
586     ///
587     /// let x: Option<u32> = None;
588     /// let y: Option<&str> = None;
589     /// assert_eq!(x.and(y), None);
590     /// ```
591     #[inline]
592     #[stable(feature = "rust1", since = "1.0.0")]
593     pub fn and<U>(self, optb: Option<U>) -> Option<U> {
594         match self {
595             Some(_) => optb,
596             None => None,
597         }
598     }
599
600     /// Returns [`None`] if the option is [`None`], otherwise calls `f` with the
601     /// wrapped value and returns the result.
602     ///
603     /// Some languages call this operation flatmap.
604     ///
605     /// [`None`]: #variant.None
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// fn sq(x: u32) -> Option<u32> { Some(x * x) }
611     /// fn nope(_: u32) -> Option<u32> { None }
612     ///
613     /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16));
614     /// assert_eq!(Some(2).and_then(sq).and_then(nope), None);
615     /// assert_eq!(Some(2).and_then(nope).and_then(sq), None);
616     /// assert_eq!(None.and_then(sq).and_then(sq), None);
617     /// ```
618     #[inline]
619     #[stable(feature = "rust1", since = "1.0.0")]
620     pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
621         match self {
622             Some(x) => f(x),
623             None => None,
624         }
625     }
626
627     /// Returns `None` if the option is `None`, otherwise calls `predicate`
628     /// with the wrapped value and returns:
629     ///
630     /// - `Some(t)` if `predicate` returns `true` (where `t` is the wrapped
631     ///   value), and
632     /// - `None` if `predicate` returns `false`.
633     ///
634     /// This function works similar to `Iterator::filter()`. You can imagine
635     /// the `Option<T>` being an iterator over one or zero elements. `filter()`
636     /// lets you decide which elements to keep.
637     ///
638     /// # Examples
639     ///
640     /// ```rust
641     /// fn is_even(n: &i32) -> bool {
642     ///     n % 2 == 0
643     /// }
644     ///
645     /// assert_eq!(None.filter(is_even), None);
646     /// assert_eq!(Some(3).filter(is_even), None);
647     /// assert_eq!(Some(4).filter(is_even), Some(4));
648     /// ```
649     #[inline]
650     #[stable(feature = "option_filter", since = "1.27.0")]
651     pub fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self {
652         if let Some(x) = self {
653             if predicate(&x) {
654                 return Some(x)
655             }
656         }
657         None
658     }
659
660     /// Returns the option if it contains a value, otherwise returns `optb`.
661     ///
662     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
663     /// result of a function call, it is recommended to use [`or_else`], which is
664     /// lazily evaluated.
665     ///
666     /// [`or_else`]: #method.or_else
667     ///
668     /// # Examples
669     ///
670     /// ```
671     /// let x = Some(2);
672     /// let y = None;
673     /// assert_eq!(x.or(y), Some(2));
674     ///
675     /// let x = None;
676     /// let y = Some(100);
677     /// assert_eq!(x.or(y), Some(100));
678     ///
679     /// let x = Some(2);
680     /// let y = Some(100);
681     /// assert_eq!(x.or(y), Some(2));
682     ///
683     /// let x: Option<u32> = None;
684     /// let y = None;
685     /// assert_eq!(x.or(y), None);
686     /// ```
687     #[inline]
688     #[stable(feature = "rust1", since = "1.0.0")]
689     pub fn or(self, optb: Option<T>) -> Option<T> {
690         match self {
691             Some(_) => self,
692             None => optb,
693         }
694     }
695
696     /// Returns the option if it contains a value, otherwise calls `f` and
697     /// returns the result.
698     ///
699     /// # Examples
700     ///
701     /// ```
702     /// fn nobody() -> Option<&'static str> { None }
703     /// fn vikings() -> Option<&'static str> { Some("vikings") }
704     ///
705     /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians"));
706     /// assert_eq!(None.or_else(vikings), Some("vikings"));
707     /// assert_eq!(None.or_else(nobody), None);
708     /// ```
709     #[inline]
710     #[stable(feature = "rust1", since = "1.0.0")]
711     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
712         match self {
713             Some(_) => self,
714             None => f(),
715         }
716     }
717
718     /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns `None`.
719     ///
720     /// [`Some`]: #variant.Some
721     /// [`None`]: #variant.None
722     ///
723     /// # Examples
724     ///
725     /// ```
726     /// #![feature(option_xor)]
727     ///
728     /// let x = Some(2);
729     /// let y: Option<u32> = None;
730     /// assert_eq!(x.xor(y), Some(2));
731     ///
732     /// let x: Option<u32> = None;
733     /// let y = Some(2);
734     /// assert_eq!(x.xor(y), Some(2));
735     ///
736     /// let x = Some(2);
737     /// let y = Some(2);
738     /// assert_eq!(x.xor(y), None);
739     ///
740     /// let x: Option<u32> = None;
741     /// let y: Option<u32> = None;
742     /// assert_eq!(x.xor(y), None);
743     /// ```
744     #[inline]
745     #[unstable(feature = "option_xor", issue = "50512")]
746     pub fn xor(self, optb: Option<T>) -> Option<T> {
747         match (self, optb) {
748             (Some(a), None) => Some(a),
749             (None, Some(b)) => Some(b),
750             _ => None,
751         }
752     }
753
754     /////////////////////////////////////////////////////////////////////////
755     // Entry-like operations to insert if None and return a reference
756     /////////////////////////////////////////////////////////////////////////
757
758     /// Inserts `v` into the option if it is [`None`], then
759     /// returns a mutable reference to the contained value.
760     ///
761     /// [`None`]: #variant.None
762     ///
763     /// # Examples
764     ///
765     /// ```
766     /// let mut x = None;
767     ///
768     /// {
769     ///     let y: &mut u32 = x.get_or_insert(5);
770     ///     assert_eq!(y, &5);
771     ///
772     ///     *y = 7;
773     /// }
774     ///
775     /// assert_eq!(x, Some(7));
776     /// ```
777     #[inline]
778     #[stable(feature = "option_entry", since = "1.20.0")]
779     pub fn get_or_insert(&mut self, v: T) -> &mut T {
780         match *self {
781             None => *self = Some(v),
782             _ => (),
783         }
784
785         match *self {
786             Some(ref mut v) => v,
787             None => unsafe { hint::unreachable_unchecked() },
788         }
789     }
790
791     /// Inserts a value computed from `f` into the option if it is [`None`], then
792     /// returns a mutable reference to the contained value.
793     ///
794     /// [`None`]: #variant.None
795     ///
796     /// # Examples
797     ///
798     /// ```
799     /// let mut x = None;
800     ///
801     /// {
802     ///     let y: &mut u32 = x.get_or_insert_with(|| 5);
803     ///     assert_eq!(y, &5);
804     ///
805     ///     *y = 7;
806     /// }
807     ///
808     /// assert_eq!(x, Some(7));
809     /// ```
810     #[inline]
811     #[stable(feature = "option_entry", since = "1.20.0")]
812     pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T {
813         match *self {
814             None => *self = Some(f()),
815             _ => (),
816         }
817
818         match *self {
819             Some(ref mut v) => v,
820             None => unsafe { hint::unreachable_unchecked() },
821         }
822     }
823
824     /////////////////////////////////////////////////////////////////////////
825     // Misc
826     /////////////////////////////////////////////////////////////////////////
827
828     /// Takes the value out of the option, leaving a [`None`] in its place.
829     ///
830     /// [`None`]: #variant.None
831     ///
832     /// # Examples
833     ///
834     /// ```
835     /// let mut x = Some(2);
836     /// let y = x.take();
837     /// assert_eq!(x, None);
838     /// assert_eq!(y, Some(2));
839     ///
840     /// let mut x: Option<u32> = None;
841     /// let y = x.take();
842     /// assert_eq!(x, None);
843     /// assert_eq!(y, None);
844     /// ```
845     #[inline]
846     #[stable(feature = "rust1", since = "1.0.0")]
847     pub fn take(&mut self) -> Option<T> {
848         mem::replace(self, None)
849     }
850
851     /// Replaces the actual value in the option by the value given in parameter,
852     /// returning the old value if present,
853     /// leaving a [`Some`] in its place without deinitializing either one.
854     ///
855     /// [`Some`]: #variant.Some
856     ///
857     /// # Examples
858     ///
859     /// ```
860     /// #![feature(option_replace)]
861     ///
862     /// let mut x = Some(2);
863     /// let old = x.replace(5);
864     /// assert_eq!(x, Some(5));
865     /// assert_eq!(old, Some(2));
866     ///
867     /// let mut x = None;
868     /// let old = x.replace(3);
869     /// assert_eq!(x, Some(3));
870     /// assert_eq!(old, None);
871     /// ```
872     #[inline]
873     #[unstable(feature = "option_replace", issue = "51998")]
874     pub fn replace(&mut self, value: T) -> Option<T> {
875         mem::replace(self, Some(value))
876     }
877 }
878
879 impl<'a, T: Clone> Option<&'a T> {
880     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
881     /// option.
882     ///
883     /// # Examples
884     ///
885     /// ```
886     /// let x = 12;
887     /// let opt_x = Some(&x);
888     /// assert_eq!(opt_x, Some(&12));
889     /// let cloned = opt_x.cloned();
890     /// assert_eq!(cloned, Some(12));
891     /// ```
892     #[stable(feature = "rust1", since = "1.0.0")]
893     pub fn cloned(self) -> Option<T> {
894         self.map(|t| t.clone())
895     }
896 }
897
898 impl<'a, T: Clone> Option<&'a mut T> {
899     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
900     /// option.
901     ///
902     /// # Examples
903     ///
904     /// ```
905     /// let mut x = 12;
906     /// let opt_x = Some(&mut x);
907     /// assert_eq!(opt_x, Some(&mut 12));
908     /// let cloned = opt_x.cloned();
909     /// assert_eq!(cloned, Some(12));
910     /// ```
911     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
912     pub fn cloned(self) -> Option<T> {
913         self.map(|t| t.clone())
914     }
915 }
916
917 impl<T: Default> Option<T> {
918     /// Returns the contained value or a default
919     ///
920     /// Consumes the `self` argument then, if [`Some`], returns the contained
921     /// value, otherwise if [`None`], returns the [default value] for that
922     /// type.
923     ///
924     /// # Examples
925     ///
926     /// Convert a string to an integer, turning poorly-formed strings
927     /// into 0 (the default value for integers). [`parse`] converts
928     /// a string to any other type that implements [`FromStr`], returning
929     /// [`None`] on error.
930     ///
931     /// ```
932     /// let good_year_from_input = "1909";
933     /// let bad_year_from_input = "190blarg";
934     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
935     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
936     ///
937     /// assert_eq!(1909, good_year);
938     /// assert_eq!(0, bad_year);
939     /// ```
940     ///
941     /// [`Some`]: #variant.Some
942     /// [`None`]: #variant.None
943     /// [default value]: ../default/trait.Default.html#tymethod.default
944     /// [`parse`]: ../../std/primitive.str.html#method.parse
945     /// [`FromStr`]: ../../std/str/trait.FromStr.html
946     #[inline]
947     #[stable(feature = "rust1", since = "1.0.0")]
948     pub fn unwrap_or_default(self) -> T {
949         match self {
950             Some(x) => x,
951             None => Default::default(),
952         }
953     }
954 }
955
956 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
957 impl<T: Deref> Option<T> {
958     /// Converts from `&Option<T>` to `Option<&T::Target>`.
959     ///
960     /// Leaves the original Option in-place, creating a new one with a reference
961     /// to the original one, additionally coercing the contents via `Deref`.
962     pub fn deref(&self) -> Option<&T::Target> {
963         self.as_ref().map(|t| t.deref())
964     }
965 }
966
967 impl<T, E> Option<Result<T, E>> {
968     /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
969     ///
970     /// `None` will be mapped to `Ok(None)`.
971     /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
972     ///
973     /// # Examples
974     ///
975     /// ```
976     /// #![feature(transpose_result)]
977     ///
978     /// #[derive(Debug, Eq, PartialEq)]
979     /// struct SomeErr;
980     ///
981     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
982     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
983     /// assert_eq!(x, y.transpose());
984     /// ```
985     #[inline]
986     #[unstable(feature = "transpose_result", issue = "47338")]
987     pub fn transpose(self) -> Result<Option<T>, E> {
988         match self {
989             Some(Ok(x)) => Ok(Some(x)),
990             Some(Err(e)) => Err(e),
991             None => Ok(None),
992         }
993     }
994 }
995
996 // This is a separate function to reduce the code size of .expect() itself.
997 #[inline(never)]
998 #[cold]
999 fn expect_failed(msg: &str) -> ! {
1000     panic!("{}", msg)
1001 }
1002
1003 /////////////////////////////////////////////////////////////////////////////
1004 // Trait implementations
1005 /////////////////////////////////////////////////////////////////////////////
1006
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<T> Default for Option<T> {
1009     /// Returns [`None`][Option::None].
1010     #[inline]
1011     fn default() -> Option<T> { None }
1012 }
1013
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 impl<T> IntoIterator for Option<T> {
1016     type Item = T;
1017     type IntoIter = IntoIter<T>;
1018
1019     /// Returns a consuming iterator over the possibly contained value.
1020     ///
1021     /// # Examples
1022     ///
1023     /// ```
1024     /// let x = Some("string");
1025     /// let v: Vec<&str> = x.into_iter().collect();
1026     /// assert_eq!(v, ["string"]);
1027     ///
1028     /// let x = None;
1029     /// let v: Vec<&str> = x.into_iter().collect();
1030     /// assert!(v.is_empty());
1031     /// ```
1032     #[inline]
1033     fn into_iter(self) -> IntoIter<T> {
1034         IntoIter { inner: Item { opt: self } }
1035     }
1036 }
1037
1038 #[stable(since = "1.4.0", feature = "option_iter")]
1039 impl<'a, T> IntoIterator for &'a Option<T> {
1040     type Item = &'a T;
1041     type IntoIter = Iter<'a, T>;
1042
1043     fn into_iter(self) -> Iter<'a, T> {
1044         self.iter()
1045     }
1046 }
1047
1048 #[stable(since = "1.4.0", feature = "option_iter")]
1049 impl<'a, T> IntoIterator for &'a mut Option<T> {
1050     type Item = &'a mut T;
1051     type IntoIter = IterMut<'a, T>;
1052
1053     fn into_iter(self) -> IterMut<'a, T> {
1054         self.iter_mut()
1055     }
1056 }
1057
1058 #[stable(since = "1.12.0", feature = "option_from")]
1059 impl<T> From<T> for Option<T> {
1060     fn from(val: T) -> Option<T> {
1061         Some(val)
1062     }
1063 }
1064
1065 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1066 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1067     fn from(o: &'a Option<T>) -> Option<&'a T> {
1068         o.as_ref()
1069     }
1070 }
1071
1072 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1073 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1074     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1075         o.as_mut()
1076     }
1077 }
1078
1079 /////////////////////////////////////////////////////////////////////////////
1080 // The Option Iterators
1081 /////////////////////////////////////////////////////////////////////////////
1082
1083 #[derive(Clone, Debug)]
1084 struct Item<A> {
1085     opt: Option<A>
1086 }
1087
1088 impl<A> Iterator for Item<A> {
1089     type Item = A;
1090
1091     #[inline]
1092     fn next(&mut self) -> Option<A> {
1093         self.opt.take()
1094     }
1095
1096     #[inline]
1097     fn size_hint(&self) -> (usize, Option<usize>) {
1098         match self.opt {
1099             Some(_) => (1, Some(1)),
1100             None => (0, Some(0)),
1101         }
1102     }
1103 }
1104
1105 impl<A> DoubleEndedIterator for Item<A> {
1106     #[inline]
1107     fn next_back(&mut self) -> Option<A> {
1108         self.opt.take()
1109     }
1110 }
1111
1112 impl<A> ExactSizeIterator for Item<A> {}
1113 impl<A> FusedIterator for Item<A> {}
1114 unsafe impl<A> TrustedLen for Item<A> {}
1115
1116 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1117 ///
1118 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1119 ///
1120 /// This `struct` is created by the [`Option::iter`] function.
1121 ///
1122 /// [`Option`]: enum.Option.html
1123 /// [`Some`]: enum.Option.html#variant.Some
1124 /// [`Option::iter`]: enum.Option.html#method.iter
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 #[derive(Debug)]
1127 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1128
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<'a, A> Iterator for Iter<'a, A> {
1131     type Item = &'a A;
1132
1133     #[inline]
1134     fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1135     #[inline]
1136     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1137 }
1138
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1141     #[inline]
1142     fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1143 }
1144
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
1147
1148 #[stable(feature = "fused", since = "1.26.0")]
1149 impl<'a, A> FusedIterator for Iter<'a, A> {}
1150
1151 #[unstable(feature = "trusted_len", issue = "37572")]
1152 unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
1153
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<'a, A> Clone for Iter<'a, A> {
1156     #[inline]
1157     fn clone(&self) -> Iter<'a, A> {
1158         Iter { inner: self.inner.clone() }
1159     }
1160 }
1161
1162 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1163 ///
1164 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1165 ///
1166 /// This `struct` is created by the [`Option::iter_mut`] function.
1167 ///
1168 /// [`Option`]: enum.Option.html
1169 /// [`Some`]: enum.Option.html#variant.Some
1170 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 #[derive(Debug)]
1173 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1174
1175 #[stable(feature = "rust1", since = "1.0.0")]
1176 impl<'a, A> Iterator for IterMut<'a, A> {
1177     type Item = &'a mut A;
1178
1179     #[inline]
1180     fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1181     #[inline]
1182     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1183 }
1184
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1187     #[inline]
1188     fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1189 }
1190
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
1193
1194 #[stable(feature = "fused", since = "1.26.0")]
1195 impl<'a, A> FusedIterator for IterMut<'a, A> {}
1196 #[unstable(feature = "trusted_len", issue = "37572")]
1197 unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
1198
1199 /// An iterator over the value in [`Some`] variant of an [`Option`].
1200 ///
1201 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1202 ///
1203 /// This `struct` is created by the [`Option::into_iter`] function.
1204 ///
1205 /// [`Option`]: enum.Option.html
1206 /// [`Some`]: enum.Option.html#variant.Some
1207 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1208 #[derive(Clone, Debug)]
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 pub struct IntoIter<A> { inner: Item<A> }
1211
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl<A> Iterator for IntoIter<A> {
1214     type Item = A;
1215
1216     #[inline]
1217     fn next(&mut self) -> Option<A> { self.inner.next() }
1218     #[inline]
1219     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1220 }
1221
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl<A> DoubleEndedIterator for IntoIter<A> {
1224     #[inline]
1225     fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1226 }
1227
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<A> ExactSizeIterator for IntoIter<A> {}
1230
1231 #[stable(feature = "fused", since = "1.26.0")]
1232 impl<A> FusedIterator for IntoIter<A> {}
1233
1234 #[unstable(feature = "trusted_len", issue = "37572")]
1235 unsafe impl<A> TrustedLen for IntoIter<A> {}
1236
1237 /////////////////////////////////////////////////////////////////////////////
1238 // FromIterator
1239 /////////////////////////////////////////////////////////////////////////////
1240
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1243     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1244     /// no further elements are taken, and the [`None`][Option::None] is
1245     /// returned. Should no [`None`][Option::None] occur, a container with the
1246     /// values of each [`Option`] is returned.
1247     ///
1248     /// Here is an example which increments every integer in a vector,
1249     /// checking for overflow:
1250     ///
1251     /// ```
1252     /// use std::u16;
1253     ///
1254     /// let v = vec![1, 2];
1255     /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16|
1256     ///     if x == u16::MAX { None }
1257     ///     else { Some(x + 1) }
1258     /// ).collect();
1259     /// assert!(res == Some(vec![2, 3]));
1260     /// ```
1261     ///
1262     /// [`Iterator`]: ../iter/trait.Iterator.html
1263     #[inline]
1264     fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1265         // FIXME(#11084): This could be replaced with Iterator::scan when this
1266         // performance bug is closed.
1267
1268         struct Adapter<Iter> {
1269             iter: Iter,
1270             found_none: bool,
1271         }
1272
1273         impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1274             type Item = T;
1275
1276             #[inline]
1277             fn next(&mut self) -> Option<T> {
1278                 match self.iter.next() {
1279                     Some(Some(value)) => Some(value),
1280                     Some(None) => {
1281                         self.found_none = true;
1282                         None
1283                     }
1284                     None => None,
1285                 }
1286             }
1287
1288             #[inline]
1289             fn size_hint(&self) -> (usize, Option<usize>) {
1290                 if self.found_none {
1291                     (0, Some(0))
1292                 } else {
1293                     let (_, upper) = self.iter.size_hint();
1294                     (0, upper)
1295                 }
1296             }
1297         }
1298
1299         let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1300         let v: V = FromIterator::from_iter(adapter.by_ref());
1301
1302         if adapter.found_none {
1303             None
1304         } else {
1305             Some(v)
1306         }
1307     }
1308 }
1309
1310 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1311 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1312 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1313 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1314 #[unstable(feature = "try_trait", issue = "42327")]
1315 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1316 pub struct NoneError;
1317
1318 #[unstable(feature = "try_trait", issue = "42327")]
1319 impl<T> ops::Try for Option<T> {
1320     type Ok = T;
1321     type Error = NoneError;
1322
1323     #[inline]
1324     fn into_result(self) -> Result<T, NoneError> {
1325         self.ok_or(NoneError)
1326     }
1327
1328     #[inline]
1329     fn from_ok(v: T) -> Self {
1330         Some(v)
1331     }
1332
1333     #[inline]
1334     fn from_error(_: NoneError) -> Self {
1335         None
1336     }
1337 }