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