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