]> git.lizzy.rs Git - rust.git/blob - src/libcore/option.rs
Rollup merge of #57085 - glaubitz:sparc64-abi-fix, r=nagisa
[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     #[stable(feature = "pin", since = "1.33.0")]
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     #[stable(feature = "pin", since = "1.33.0")]
286     pub fn as_pin_mut<'a>(self: Pin<&'a mut Option<T>>) -> Option<Pin<&'a mut T>> {
287         unsafe {
288             Pin::get_unchecked_mut(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     /// let mut x = Some(2);
871     /// let old = x.replace(5);
872     /// assert_eq!(x, Some(5));
873     /// assert_eq!(old, Some(2));
874     ///
875     /// let mut x = None;
876     /// let old = x.replace(3);
877     /// assert_eq!(x, Some(3));
878     /// assert_eq!(old, None);
879     /// ```
880     #[inline]
881     #[stable(feature = "option_replace", since = "1.31.0")]
882     pub fn replace(&mut self, value: T) -> Option<T> {
883         mem::replace(self, Some(value))
884     }
885 }
886
887 impl<'a, T: Clone> Option<&'a T> {
888     /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the
889     /// option.
890     ///
891     /// # Examples
892     ///
893     /// ```
894     /// let x = 12;
895     /// let opt_x = Some(&x);
896     /// assert_eq!(opt_x, Some(&12));
897     /// let cloned = opt_x.cloned();
898     /// assert_eq!(cloned, Some(12));
899     /// ```
900     #[stable(feature = "rust1", since = "1.0.0")]
901     pub fn cloned(self) -> Option<T> {
902         self.map(|t| t.clone())
903     }
904 }
905
906 impl<'a, T: Clone> Option<&'a mut T> {
907     /// Maps an `Option<&mut T>` to an `Option<T>` by cloning the contents of the
908     /// option.
909     ///
910     /// # Examples
911     ///
912     /// ```
913     /// let mut x = 12;
914     /// let opt_x = Some(&mut x);
915     /// assert_eq!(opt_x, Some(&mut 12));
916     /// let cloned = opt_x.cloned();
917     /// assert_eq!(cloned, Some(12));
918     /// ```
919     #[stable(since = "1.26.0", feature = "option_ref_mut_cloned")]
920     pub fn cloned(self) -> Option<T> {
921         self.map(|t| t.clone())
922     }
923 }
924
925 impl<T: Default> Option<T> {
926     /// Returns the contained value or a default
927     ///
928     /// Consumes the `self` argument then, if [`Some`], returns the contained
929     /// value, otherwise if [`None`], returns the [default value] for that
930     /// type.
931     ///
932     /// # Examples
933     ///
934     /// Convert a string to an integer, turning poorly-formed strings
935     /// into 0 (the default value for integers). [`parse`] converts
936     /// a string to any other type that implements [`FromStr`], returning
937     /// [`None`] on error.
938     ///
939     /// ```
940     /// let good_year_from_input = "1909";
941     /// let bad_year_from_input = "190blarg";
942     /// let good_year = good_year_from_input.parse().ok().unwrap_or_default();
943     /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default();
944     ///
945     /// assert_eq!(1909, good_year);
946     /// assert_eq!(0, bad_year);
947     /// ```
948     ///
949     /// [`Some`]: #variant.Some
950     /// [`None`]: #variant.None
951     /// [default value]: ../default/trait.Default.html#tymethod.default
952     /// [`parse`]: ../../std/primitive.str.html#method.parse
953     /// [`FromStr`]: ../../std/str/trait.FromStr.html
954     #[inline]
955     #[stable(feature = "rust1", since = "1.0.0")]
956     pub fn unwrap_or_default(self) -> T {
957         match self {
958             Some(x) => x,
959             None => Default::default(),
960         }
961     }
962 }
963
964 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
965 impl<T: Deref> Option<T> {
966     /// Converts from `&Option<T>` to `Option<&T::Target>`.
967     ///
968     /// Leaves the original Option in-place, creating a new one with a reference
969     /// to the original one, additionally coercing the contents via `Deref`.
970     pub fn deref(&self) -> Option<&T::Target> {
971         self.as_ref().map(|t| t.deref())
972     }
973 }
974
975 impl<T, E> Option<Result<T, E>> {
976     /// Transposes an `Option` of a `Result` into a `Result` of an `Option`.
977     ///
978     /// `None` will be mapped to `Ok(None)`.
979     /// `Some(Ok(_))` and `Some(Err(_))` will be mapped to `Ok(Some(_))` and `Err(_)`.
980     ///
981     /// # Examples
982     ///
983     /// ```
984     /// #![feature(transpose_result)]
985     ///
986     /// #[derive(Debug, Eq, PartialEq)]
987     /// struct SomeErr;
988     ///
989     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
990     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
991     /// assert_eq!(x, y.transpose());
992     /// ```
993     #[inline]
994     #[unstable(feature = "transpose_result", issue = "47338")]
995     pub fn transpose(self) -> Result<Option<T>, E> {
996         match self {
997             Some(Ok(x)) => Ok(Some(x)),
998             Some(Err(e)) => Err(e),
999             None => Ok(None),
1000         }
1001     }
1002 }
1003
1004 // This is a separate function to reduce the code size of .expect() itself.
1005 #[inline(never)]
1006 #[cold]
1007 fn expect_failed(msg: &str) -> ! {
1008     panic!("{}", msg)
1009 }
1010
1011 /////////////////////////////////////////////////////////////////////////////
1012 // Trait implementations
1013 /////////////////////////////////////////////////////////////////////////////
1014
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 impl<T> Default for Option<T> {
1017     /// Returns [`None`][Option::None].
1018     #[inline]
1019     fn default() -> Option<T> { None }
1020 }
1021
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<T> IntoIterator for Option<T> {
1024     type Item = T;
1025     type IntoIter = IntoIter<T>;
1026
1027     /// Returns a consuming iterator over the possibly contained value.
1028     ///
1029     /// # Examples
1030     ///
1031     /// ```
1032     /// let x = Some("string");
1033     /// let v: Vec<&str> = x.into_iter().collect();
1034     /// assert_eq!(v, ["string"]);
1035     ///
1036     /// let x = None;
1037     /// let v: Vec<&str> = x.into_iter().collect();
1038     /// assert!(v.is_empty());
1039     /// ```
1040     #[inline]
1041     fn into_iter(self) -> IntoIter<T> {
1042         IntoIter { inner: Item { opt: self } }
1043     }
1044 }
1045
1046 #[stable(since = "1.4.0", feature = "option_iter")]
1047 impl<'a, T> IntoIterator for &'a Option<T> {
1048     type Item = &'a T;
1049     type IntoIter = Iter<'a, T>;
1050
1051     fn into_iter(self) -> Iter<'a, T> {
1052         self.iter()
1053     }
1054 }
1055
1056 #[stable(since = "1.4.0", feature = "option_iter")]
1057 impl<'a, T> IntoIterator for &'a mut Option<T> {
1058     type Item = &'a mut T;
1059     type IntoIter = IterMut<'a, T>;
1060
1061     fn into_iter(self) -> IterMut<'a, T> {
1062         self.iter_mut()
1063     }
1064 }
1065
1066 #[stable(since = "1.12.0", feature = "option_from")]
1067 impl<T> From<T> for Option<T> {
1068     fn from(val: T) -> Option<T> {
1069         Some(val)
1070     }
1071 }
1072
1073 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1074 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1075     fn from(o: &'a Option<T>) -> Option<&'a T> {
1076         o.as_ref()
1077     }
1078 }
1079
1080 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1081 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1082     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
1083         o.as_mut()
1084     }
1085 }
1086
1087 /////////////////////////////////////////////////////////////////////////////
1088 // The Option Iterators
1089 /////////////////////////////////////////////////////////////////////////////
1090
1091 #[derive(Clone, Debug)]
1092 struct Item<A> {
1093     opt: Option<A>
1094 }
1095
1096 impl<A> Iterator for Item<A> {
1097     type Item = A;
1098
1099     #[inline]
1100     fn next(&mut self) -> Option<A> {
1101         self.opt.take()
1102     }
1103
1104     #[inline]
1105     fn size_hint(&self) -> (usize, Option<usize>) {
1106         match self.opt {
1107             Some(_) => (1, Some(1)),
1108             None => (0, Some(0)),
1109         }
1110     }
1111 }
1112
1113 impl<A> DoubleEndedIterator for Item<A> {
1114     #[inline]
1115     fn next_back(&mut self) -> Option<A> {
1116         self.opt.take()
1117     }
1118 }
1119
1120 impl<A> ExactSizeIterator for Item<A> {}
1121 impl<A> FusedIterator for Item<A> {}
1122 unsafe impl<A> TrustedLen for Item<A> {}
1123
1124 /// An iterator over a reference to the [`Some`] variant of an [`Option`].
1125 ///
1126 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1127 ///
1128 /// This `struct` is created by the [`Option::iter`] function.
1129 ///
1130 /// [`Option`]: enum.Option.html
1131 /// [`Some`]: enum.Option.html#variant.Some
1132 /// [`Option::iter`]: enum.Option.html#method.iter
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 #[derive(Debug)]
1135 pub struct Iter<'a, A: 'a> { inner: Item<&'a A> }
1136
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<'a, A> Iterator for Iter<'a, A> {
1139     type Item = &'a A;
1140
1141     #[inline]
1142     fn next(&mut self) -> Option<&'a A> { self.inner.next() }
1143     #[inline]
1144     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1145 }
1146
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
1149     #[inline]
1150     fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() }
1151 }
1152
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl<A> ExactSizeIterator for Iter<'_, A> {}
1155
1156 #[stable(feature = "fused", since = "1.26.0")]
1157 impl<A> FusedIterator for Iter<'_, A> {}
1158
1159 #[unstable(feature = "trusted_len", issue = "37572")]
1160 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1161
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<A> Clone for Iter<'_, A> {
1164     #[inline]
1165     fn clone(&self) -> Self {
1166         Iter { inner: self.inner.clone() }
1167     }
1168 }
1169
1170 /// An iterator over a mutable reference to the [`Some`] variant of an [`Option`].
1171 ///
1172 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1173 ///
1174 /// This `struct` is created by the [`Option::iter_mut`] function.
1175 ///
1176 /// [`Option`]: enum.Option.html
1177 /// [`Some`]: enum.Option.html#variant.Some
1178 /// [`Option::iter_mut`]: enum.Option.html#method.iter_mut
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 #[derive(Debug)]
1181 pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> }
1182
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<'a, A> Iterator for IterMut<'a, A> {
1185     type Item = &'a mut A;
1186
1187     #[inline]
1188     fn next(&mut self) -> Option<&'a mut A> { self.inner.next() }
1189     #[inline]
1190     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1191 }
1192
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
1195     #[inline]
1196     fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() }
1197 }
1198
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<A> ExactSizeIterator for IterMut<'_, A> {}
1201
1202 #[stable(feature = "fused", since = "1.26.0")]
1203 impl<A> FusedIterator for IterMut<'_, A> {}
1204 #[unstable(feature = "trusted_len", issue = "37572")]
1205 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1206
1207 /// An iterator over the value in [`Some`] variant of an [`Option`].
1208 ///
1209 /// The iterator yields one value if the [`Option`] is a [`Some`], otherwise none.
1210 ///
1211 /// This `struct` is created by the [`Option::into_iter`] function.
1212 ///
1213 /// [`Option`]: enum.Option.html
1214 /// [`Some`]: enum.Option.html#variant.Some
1215 /// [`Option::into_iter`]: enum.Option.html#method.into_iter
1216 #[derive(Clone, Debug)]
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub struct IntoIter<A> { inner: Item<A> }
1219
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl<A> Iterator for IntoIter<A> {
1222     type Item = A;
1223
1224     #[inline]
1225     fn next(&mut self) -> Option<A> { self.inner.next() }
1226     #[inline]
1227     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
1228 }
1229
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 impl<A> DoubleEndedIterator for IntoIter<A> {
1232     #[inline]
1233     fn next_back(&mut self) -> Option<A> { self.inner.next_back() }
1234 }
1235
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<A> ExactSizeIterator for IntoIter<A> {}
1238
1239 #[stable(feature = "fused", since = "1.26.0")]
1240 impl<A> FusedIterator for IntoIter<A> {}
1241
1242 #[unstable(feature = "trusted_len", issue = "37572")]
1243 unsafe impl<A> TrustedLen for IntoIter<A> {}
1244
1245 /////////////////////////////////////////////////////////////////////////////
1246 // FromIterator
1247 /////////////////////////////////////////////////////////////////////////////
1248
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
1251     /// Takes each element in the [`Iterator`]: if it is [`None`][Option::None],
1252     /// no further elements are taken, and the [`None`][Option::None] is
1253     /// returned. Should no [`None`][Option::None] occur, a container with the
1254     /// values of each [`Option`] is returned.
1255     ///
1256     /// # Examples
1257     ///
1258     /// Here is an example which increments every integer in a vector.
1259     /// `We use the checked variant of `add` that returns `None` when the
1260     /// calculation would result in an overflow.
1261     ///
1262     /// ```
1263     /// let items = vec![0_u16, 1, 2];
1264     ///
1265     /// let res: Option<Vec<u16>> = items
1266     ///     .iter()
1267     ///     .map(|x| x.checked_add(1))
1268     ///     .collect();
1269     ///
1270     /// assert_eq!(res, Some(vec![1, 2, 3]));
1271     /// ```
1272     ///
1273     /// As you can see, this will return the expected, valid items.
1274     ///
1275     /// Here is another example that tries to subtract one from another list
1276     /// of integers, this time checking for underflow:
1277     ///
1278     /// ```
1279     /// let items = vec![2_u16, 1, 0];
1280     ///
1281     /// let res: Option<Vec<u16>> = items
1282     ///     .iter()
1283     ///     .map(|x| x.checked_sub(1))
1284     ///     .collect();
1285     ///
1286     /// assert_eq!(res, None);
1287     /// ```
1288     ///
1289     /// Since the last element is zero, it would underflow. Thus, the resulting
1290     /// value is `None`.
1291     ///
1292     /// [`Iterator`]: ../iter/trait.Iterator.html
1293     #[inline]
1294     fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> {
1295         // FIXME(#11084): This could be replaced with Iterator::scan when this
1296         // performance bug is closed.
1297
1298         struct Adapter<Iter> {
1299             iter: Iter,
1300             found_none: bool,
1301         }
1302
1303         impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> {
1304             type Item = T;
1305
1306             #[inline]
1307             fn next(&mut self) -> Option<T> {
1308                 match self.iter.next() {
1309                     Some(Some(value)) => Some(value),
1310                     Some(None) => {
1311                         self.found_none = true;
1312                         None
1313                     }
1314                     None => None,
1315                 }
1316             }
1317
1318             #[inline]
1319             fn size_hint(&self) -> (usize, Option<usize>) {
1320                 if self.found_none {
1321                     (0, Some(0))
1322                 } else {
1323                     let (_, upper) = self.iter.size_hint();
1324                     (0, upper)
1325                 }
1326             }
1327         }
1328
1329         let mut adapter = Adapter { iter: iter.into_iter(), found_none: false };
1330         let v: V = FromIterator::from_iter(adapter.by_ref());
1331
1332         if adapter.found_none {
1333             None
1334         } else {
1335             Some(v)
1336         }
1337     }
1338 }
1339
1340 /// The error type that results from applying the try operator (`?`) to a `None` value. If you wish
1341 /// to allow `x?` (where `x` is an `Option<T>`) to be converted into your error type, you can
1342 /// implement `impl From<NoneError>` for `YourErrorType`. In that case, `x?` within a function that
1343 /// returns `Result<_, YourErrorType>` will translate a `None` value into an `Err` result.
1344 #[unstable(feature = "try_trait", issue = "42327")]
1345 #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
1346 pub struct NoneError;
1347
1348 #[unstable(feature = "try_trait", issue = "42327")]
1349 impl<T> ops::Try for Option<T> {
1350     type Ok = T;
1351     type Error = NoneError;
1352
1353     #[inline]
1354     fn into_result(self) -> Result<T, NoneError> {
1355         self.ok_or(NoneError)
1356     }
1357
1358     #[inline]
1359     fn from_ok(v: T) -> Self {
1360         Some(v)
1361     }
1362
1363     #[inline]
1364     fn from_error(_: NoneError) -> Self {
1365         None
1366     }
1367 }