]>
Commit | Line | Data |
---|---|---|
1a4d82fc JJ |
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 | ||
54a0048b | 11 | //! Optional values. |
1a4d82fc JJ |
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 | //! Options 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 | |
c1a9b12d | 49 | //! None => println!("Cannot divide by 0"), |
1a4d82fc JJ |
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 | |
85aaf69f | 63 | //! `i32`. Notice that in order to use the inner `i32` value first the |
1a4d82fc JJ |
64 | //! `check_optional` function needs to use pattern matching to |
65 | //! determine whether the box has a value (i.e. it is `Some(...)`) or | |
66 | //! not (`None`). | |
67 | //! | |
68 | //! ``` | |
85aaf69f | 69 | //! let optional: Option<Box<i32>> = None; |
1a4d82fc JJ |
70 | //! check_optional(&optional); |
71 | //! | |
85aaf69f | 72 | //! let optional: Option<Box<i32>> = Some(Box::new(9000)); |
1a4d82fc JJ |
73 | //! check_optional(&optional); |
74 | //! | |
85aaf69f | 75 | //! fn check_optional(optional: &Option<Box<i32>>) { |
1a4d82fc JJ |
76 | //! match *optional { |
77 | //! Some(ref p) => println!("have value {}", p), | |
c1a9b12d | 78 | //! None => println!("have no value"), |
1a4d82fc JJ |
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 | |
54a0048b SL |
96 | //! if let Some(ref m) = msg { |
97 | //! println!("{}", *m); | |
1a4d82fc JJ |
98 | //! } |
99 | //! | |
100 | //! // Remove the contained string, destroying the Option | |
54a0048b | 101 | //! let unwrapped_msg = msg.unwrap_or("default message"); |
1a4d82fc JJ |
102 | //! ``` |
103 | //! | |
104 | //! Initialize a result to `None` before a loop: | |
105 | //! | |
106 | //! ``` | |
85aaf69f | 107 | //! enum Kingdom { Plant(u32, &'static str), Animal(u32, &'static str) } |
1a4d82fc JJ |
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; | |
62682a34 | 123 | //! for big_thing in &all_the_big_things { |
1a4d82fc JJ |
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), | |
c1a9b12d | 136 | //! None => println!("there are no animals :("), |
1a4d82fc JJ |
137 | //! } |
138 | //! ``` | |
139 | ||
85aaf69f | 140 | #![stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
141 | |
142 | use self::Option::*; | |
143 | ||
144 | use clone::Clone; | |
5bcae85e | 145 | use convert::From; |
1a4d82fc | 146 | use default::Default; |
c34b1796 AL |
147 | use iter::ExactSizeIterator; |
148 | use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator}; | |
1a4d82fc | 149 | use mem; |
c34b1796 | 150 | use ops::FnOnce; |
1a4d82fc JJ |
151 | use result::Result::{Ok, Err}; |
152 | use result::Result; | |
1a4d82fc JJ |
153 | |
154 | // Note that this is not a lang item per se, but it has a hidden dependency on | |
155 | // `Iterator`, which is one. The compiler assumes that the `next` method of | |
156 | // `Iterator` is an enumeration with one type parameter and two variants, | |
157 | // which basically means it must be `Option`. | |
158 | ||
d9579d0f | 159 | /// The `Option` type. See [the module level documentation](index.html) for more. |
85aaf69f SL |
160 | #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] |
161 | #[stable(feature = "rust1", since = "1.0.0")] | |
1a4d82fc JJ |
162 | pub enum Option<T> { |
163 | /// No value | |
85aaf69f | 164 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
165 | None, |
166 | /// Some value `T` | |
85aaf69f | 167 | #[stable(feature = "rust1", since = "1.0.0")] |
7453a54e | 168 | Some(#[stable(feature = "rust1", since = "1.0.0")] T) |
1a4d82fc JJ |
169 | } |
170 | ||
171 | ///////////////////////////////////////////////////////////////////////////// | |
172 | // Type implementation | |
173 | ///////////////////////////////////////////////////////////////////////////// | |
174 | ||
175 | impl<T> Option<T> { | |
176 | ///////////////////////////////////////////////////////////////////////// | |
177 | // Querying the contained values | |
178 | ///////////////////////////////////////////////////////////////////////// | |
179 | ||
180 | /// Returns `true` if the option is a `Some` value | |
181 | /// | |
c34b1796 | 182 | /// # Examples |
1a4d82fc JJ |
183 | /// |
184 | /// ``` | |
85aaf69f | 185 | /// let x: Option<u32> = Some(2); |
1a4d82fc JJ |
186 | /// assert_eq!(x.is_some(), true); |
187 | /// | |
85aaf69f | 188 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
189 | /// assert_eq!(x.is_some(), false); |
190 | /// ``` | |
191 | #[inline] | |
85aaf69f | 192 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
193 | pub fn is_some(&self) -> bool { |
194 | match *self { | |
195 | Some(_) => true, | |
c1a9b12d | 196 | None => false, |
1a4d82fc JJ |
197 | } |
198 | } | |
199 | ||
200 | /// Returns `true` if the option is a `None` value | |
201 | /// | |
c34b1796 | 202 | /// # Examples |
1a4d82fc JJ |
203 | /// |
204 | /// ``` | |
85aaf69f | 205 | /// let x: Option<u32> = Some(2); |
1a4d82fc JJ |
206 | /// assert_eq!(x.is_none(), false); |
207 | /// | |
85aaf69f | 208 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
209 | /// assert_eq!(x.is_none(), true); |
210 | /// ``` | |
211 | #[inline] | |
85aaf69f | 212 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
213 | pub fn is_none(&self) -> bool { |
214 | !self.is_some() | |
215 | } | |
216 | ||
217 | ///////////////////////////////////////////////////////////////////////// | |
218 | // Adapter for working with references | |
219 | ///////////////////////////////////////////////////////////////////////// | |
220 | ||
9346a6ac | 221 | /// Converts from `Option<T>` to `Option<&T>` |
1a4d82fc | 222 | /// |
c34b1796 | 223 | /// # Examples |
1a4d82fc | 224 | /// |
85aaf69f | 225 | /// Convert an `Option<String>` into an `Option<usize>`, preserving the original. |
1a4d82fc JJ |
226 | /// The `map` method takes the `self` argument by value, consuming the original, |
227 | /// so this technique uses `as_ref` to first take an `Option` to a reference | |
228 | /// to the value inside the original. | |
229 | /// | |
230 | /// ``` | |
231 | /// let num_as_str: Option<String> = Some("10".to_string()); | |
232 | /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`, | |
233 | /// // then consume *that* with `map`, leaving `num_as_str` on the stack. | |
85aaf69f | 234 | /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len()); |
1a4d82fc JJ |
235 | /// println!("still can print num_as_str: {:?}", num_as_str); |
236 | /// ``` | |
237 | #[inline] | |
85aaf69f | 238 | #[stable(feature = "rust1", since = "1.0.0")] |
e9174d1e | 239 | pub fn as_ref(&self) -> Option<&T> { |
1a4d82fc JJ |
240 | match *self { |
241 | Some(ref x) => Some(x), | |
c1a9b12d | 242 | None => None, |
1a4d82fc JJ |
243 | } |
244 | } | |
245 | ||
9346a6ac | 246 | /// Converts from `Option<T>` to `Option<&mut T>` |
1a4d82fc | 247 | /// |
c34b1796 | 248 | /// # Examples |
1a4d82fc JJ |
249 | /// |
250 | /// ``` | |
85aaf69f | 251 | /// let mut x = Some(2); |
1a4d82fc JJ |
252 | /// match x.as_mut() { |
253 | /// Some(v) => *v = 42, | |
254 | /// None => {}, | |
255 | /// } | |
85aaf69f | 256 | /// assert_eq!(x, Some(42)); |
1a4d82fc JJ |
257 | /// ``` |
258 | #[inline] | |
85aaf69f | 259 | #[stable(feature = "rust1", since = "1.0.0")] |
e9174d1e | 260 | pub fn as_mut(&mut self) -> Option<&mut T> { |
1a4d82fc JJ |
261 | match *self { |
262 | Some(ref mut x) => Some(x), | |
c1a9b12d | 263 | None => None, |
1a4d82fc JJ |
264 | } |
265 | } | |
266 | ||
1a4d82fc JJ |
267 | ///////////////////////////////////////////////////////////////////////// |
268 | // Getting to contained values | |
269 | ///////////////////////////////////////////////////////////////////////// | |
270 | ||
9cc50fc6 | 271 | /// Unwraps an option, yielding the content of a `Some`. |
1a4d82fc JJ |
272 | /// |
273 | /// # Panics | |
274 | /// | |
275 | /// Panics if the value is a `None` with a custom panic message provided by | |
276 | /// `msg`. | |
277 | /// | |
c34b1796 | 278 | /// # Examples |
1a4d82fc JJ |
279 | /// |
280 | /// ``` | |
281 | /// let x = Some("value"); | |
282 | /// assert_eq!(x.expect("the world is ending"), "value"); | |
283 | /// ``` | |
284 | /// | |
c34b1796 | 285 | /// ```{.should_panic} |
1a4d82fc | 286 | /// let x: Option<&str> = None; |
62682a34 | 287 | /// x.expect("the world is ending"); // panics with `the world is ending` |
1a4d82fc JJ |
288 | /// ``` |
289 | #[inline] | |
85aaf69f | 290 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
291 | pub fn expect(self, msg: &str) -> T { |
292 | match self { | |
293 | Some(val) => val, | |
7453a54e | 294 | None => expect_failed(msg), |
1a4d82fc JJ |
295 | } |
296 | } | |
297 | ||
c34b1796 | 298 | /// Moves the value `v` out of the `Option<T>` if it is `Some(v)`. |
1a4d82fc JJ |
299 | /// |
300 | /// # Panics | |
301 | /// | |
302 | /// Panics if the self value equals `None`. | |
303 | /// | |
304 | /// # Safety note | |
305 | /// | |
306 | /// In general, because this function may panic, its use is discouraged. | |
307 | /// Instead, prefer to use pattern matching and handle the `None` | |
308 | /// case explicitly. | |
309 | /// | |
c34b1796 | 310 | /// # Examples |
1a4d82fc JJ |
311 | /// |
312 | /// ``` | |
313 | /// let x = Some("air"); | |
314 | /// assert_eq!(x.unwrap(), "air"); | |
315 | /// ``` | |
316 | /// | |
c34b1796 | 317 | /// ```{.should_panic} |
1a4d82fc JJ |
318 | /// let x: Option<&str> = None; |
319 | /// assert_eq!(x.unwrap(), "air"); // fails | |
320 | /// ``` | |
321 | #[inline] | |
85aaf69f | 322 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
323 | pub fn unwrap(self) -> T { |
324 | match self { | |
325 | Some(val) => val, | |
326 | None => panic!("called `Option::unwrap()` on a `None` value"), | |
327 | } | |
328 | } | |
329 | ||
330 | /// Returns the contained value or a default. | |
331 | /// | |
c34b1796 | 332 | /// # Examples |
1a4d82fc JJ |
333 | /// |
334 | /// ``` | |
335 | /// assert_eq!(Some("car").unwrap_or("bike"), "car"); | |
336 | /// assert_eq!(None.unwrap_or("bike"), "bike"); | |
337 | /// ``` | |
338 | #[inline] | |
85aaf69f | 339 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
340 | pub fn unwrap_or(self, def: T) -> T { |
341 | match self { | |
342 | Some(x) => x, | |
c1a9b12d | 343 | None => def, |
1a4d82fc JJ |
344 | } |
345 | } | |
346 | ||
347 | /// Returns the contained value or computes it from a closure. | |
348 | /// | |
c34b1796 | 349 | /// # Examples |
1a4d82fc JJ |
350 | /// |
351 | /// ``` | |
c34b1796 | 352 | /// let k = 10; |
85aaf69f SL |
353 | /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); |
354 | /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); | |
1a4d82fc JJ |
355 | /// ``` |
356 | #[inline] | |
85aaf69f | 357 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
358 | pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T { |
359 | match self { | |
360 | Some(x) => x, | |
c1a9b12d | 361 | None => f(), |
1a4d82fc JJ |
362 | } |
363 | } | |
364 | ||
365 | ///////////////////////////////////////////////////////////////////////// | |
366 | // Transforming contained values | |
367 | ///////////////////////////////////////////////////////////////////////// | |
368 | ||
369 | /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value | |
370 | /// | |
c34b1796 | 371 | /// # Examples |
1a4d82fc | 372 | /// |
85aaf69f | 373 | /// Convert an `Option<String>` into an `Option<usize>`, consuming the original: |
1a4d82fc JJ |
374 | /// |
375 | /// ``` | |
62682a34 SL |
376 | /// let maybe_some_string = Some(String::from("Hello, World!")); |
377 | /// // `Option::map` takes self *by value*, consuming `maybe_some_string` | |
378 | /// let maybe_some_len = maybe_some_string.map(|s| s.len()); | |
379 | /// | |
380 | /// assert_eq!(maybe_some_len, Some(13)); | |
1a4d82fc JJ |
381 | /// ``` |
382 | #[inline] | |
85aaf69f | 383 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
384 | pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> { |
385 | match self { | |
386 | Some(x) => Some(f(x)), | |
c1a9b12d | 387 | None => None, |
1a4d82fc JJ |
388 | } |
389 | } | |
390 | ||
62682a34 SL |
391 | /// Applies a function to the contained value (if any), |
392 | /// or returns a `default` (if not). | |
1a4d82fc | 393 | /// |
c34b1796 | 394 | /// # Examples |
1a4d82fc JJ |
395 | /// |
396 | /// ``` | |
397 | /// let x = Some("foo"); | |
85aaf69f | 398 | /// assert_eq!(x.map_or(42, |v| v.len()), 3); |
1a4d82fc JJ |
399 | /// |
400 | /// let x: Option<&str> = None; | |
85aaf69f | 401 | /// assert_eq!(x.map_or(42, |v| v.len()), 42); |
1a4d82fc JJ |
402 | /// ``` |
403 | #[inline] | |
85aaf69f | 404 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 405 | pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U { |
1a4d82fc JJ |
406 | match self { |
407 | Some(t) => f(t), | |
62682a34 | 408 | None => default, |
1a4d82fc JJ |
409 | } |
410 | } | |
411 | ||
62682a34 SL |
412 | /// Applies a function to the contained value (if any), |
413 | /// or computes a `default` (if not). | |
1a4d82fc | 414 | /// |
c34b1796 | 415 | /// # Examples |
1a4d82fc JJ |
416 | /// |
417 | /// ``` | |
85aaf69f | 418 | /// let k = 21; |
1a4d82fc JJ |
419 | /// |
420 | /// let x = Some("foo"); | |
85aaf69f | 421 | /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); |
1a4d82fc JJ |
422 | /// |
423 | /// let x: Option<&str> = None; | |
85aaf69f | 424 | /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); |
1a4d82fc JJ |
425 | /// ``` |
426 | #[inline] | |
85aaf69f | 427 | #[stable(feature = "rust1", since = "1.0.0")] |
62682a34 | 428 | pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { |
1a4d82fc JJ |
429 | match self { |
430 | Some(t) => f(t), | |
c1a9b12d | 431 | None => default(), |
1a4d82fc JJ |
432 | } |
433 | } | |
434 | ||
435 | /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to | |
436 | /// `Ok(v)` and `None` to `Err(err)`. | |
437 | /// | |
c34b1796 | 438 | /// # Examples |
1a4d82fc JJ |
439 | /// |
440 | /// ``` | |
441 | /// let x = Some("foo"); | |
85aaf69f | 442 | /// assert_eq!(x.ok_or(0), Ok("foo")); |
1a4d82fc JJ |
443 | /// |
444 | /// let x: Option<&str> = None; | |
85aaf69f | 445 | /// assert_eq!(x.ok_or(0), Err(0)); |
1a4d82fc JJ |
446 | /// ``` |
447 | #[inline] | |
c34b1796 | 448 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
449 | pub fn ok_or<E>(self, err: E) -> Result<T, E> { |
450 | match self { | |
451 | Some(v) => Ok(v), | |
452 | None => Err(err), | |
453 | } | |
454 | } | |
455 | ||
456 | /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to | |
457 | /// `Ok(v)` and `None` to `Err(err())`. | |
458 | /// | |
c34b1796 | 459 | /// # Examples |
1a4d82fc JJ |
460 | /// |
461 | /// ``` | |
462 | /// let x = Some("foo"); | |
85aaf69f | 463 | /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); |
1a4d82fc JJ |
464 | /// |
465 | /// let x: Option<&str> = None; | |
85aaf69f | 466 | /// assert_eq!(x.ok_or_else(|| 0), Err(0)); |
1a4d82fc JJ |
467 | /// ``` |
468 | #[inline] | |
c34b1796 | 469 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
470 | pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> { |
471 | match self { | |
472 | Some(v) => Ok(v), | |
473 | None => Err(err()), | |
474 | } | |
475 | } | |
476 | ||
477 | ///////////////////////////////////////////////////////////////////////// | |
478 | // Iterator constructors | |
479 | ///////////////////////////////////////////////////////////////////////// | |
480 | ||
481 | /// Returns an iterator over the possibly contained value. | |
482 | /// | |
c34b1796 | 483 | /// # Examples |
1a4d82fc JJ |
484 | /// |
485 | /// ``` | |
85aaf69f | 486 | /// let x = Some(4); |
1a4d82fc JJ |
487 | /// assert_eq!(x.iter().next(), Some(&4)); |
488 | /// | |
85aaf69f | 489 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
490 | /// assert_eq!(x.iter().next(), None); |
491 | /// ``` | |
492 | #[inline] | |
85aaf69f | 493 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
494 | pub fn iter(&self) -> Iter<T> { |
495 | Iter { inner: Item { opt: self.as_ref() } } | |
496 | } | |
497 | ||
498 | /// Returns a mutable iterator over the possibly contained value. | |
499 | /// | |
c34b1796 | 500 | /// # Examples |
1a4d82fc JJ |
501 | /// |
502 | /// ``` | |
85aaf69f | 503 | /// let mut x = Some(4); |
1a4d82fc | 504 | /// match x.iter_mut().next() { |
b039eaaf | 505 | /// Some(v) => *v = 42, |
1a4d82fc JJ |
506 | /// None => {}, |
507 | /// } | |
508 | /// assert_eq!(x, Some(42)); | |
509 | /// | |
85aaf69f | 510 | /// let mut x: Option<u32> = None; |
1a4d82fc JJ |
511 | /// assert_eq!(x.iter_mut().next(), None); |
512 | /// ``` | |
513 | #[inline] | |
c34b1796 | 514 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
515 | pub fn iter_mut(&mut self) -> IterMut<T> { |
516 | IterMut { inner: Item { opt: self.as_mut() } } | |
517 | } | |
518 | ||
1a4d82fc JJ |
519 | ///////////////////////////////////////////////////////////////////////// |
520 | // Boolean operations on the values, eager and lazy | |
521 | ///////////////////////////////////////////////////////////////////////// | |
522 | ||
523 | /// Returns `None` if the option is `None`, otherwise returns `optb`. | |
524 | /// | |
c34b1796 | 525 | /// # Examples |
1a4d82fc JJ |
526 | /// |
527 | /// ``` | |
85aaf69f | 528 | /// let x = Some(2); |
1a4d82fc JJ |
529 | /// let y: Option<&str> = None; |
530 | /// assert_eq!(x.and(y), None); | |
531 | /// | |
85aaf69f | 532 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
533 | /// let y = Some("foo"); |
534 | /// assert_eq!(x.and(y), None); | |
535 | /// | |
85aaf69f | 536 | /// let x = Some(2); |
1a4d82fc JJ |
537 | /// let y = Some("foo"); |
538 | /// assert_eq!(x.and(y), Some("foo")); | |
539 | /// | |
85aaf69f | 540 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
541 | /// let y: Option<&str> = None; |
542 | /// assert_eq!(x.and(y), None); | |
543 | /// ``` | |
544 | #[inline] | |
85aaf69f | 545 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
546 | pub fn and<U>(self, optb: Option<U>) -> Option<U> { |
547 | match self { | |
548 | Some(_) => optb, | |
549 | None => None, | |
550 | } | |
551 | } | |
552 | ||
553 | /// Returns `None` if the option is `None`, otherwise calls `f` with the | |
554 | /// wrapped value and returns the result. | |
555 | /// | |
85aaf69f SL |
556 | /// Some languages call this operation flatmap. |
557 | /// | |
c34b1796 | 558 | /// # Examples |
1a4d82fc JJ |
559 | /// |
560 | /// ``` | |
85aaf69f SL |
561 | /// fn sq(x: u32) -> Option<u32> { Some(x * x) } |
562 | /// fn nope(_: u32) -> Option<u32> { None } | |
1a4d82fc JJ |
563 | /// |
564 | /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); | |
565 | /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); | |
566 | /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); | |
567 | /// assert_eq!(None.and_then(sq).and_then(sq), None); | |
568 | /// ``` | |
569 | #[inline] | |
85aaf69f | 570 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
571 | pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> { |
572 | match self { | |
573 | Some(x) => f(x), | |
574 | None => None, | |
575 | } | |
576 | } | |
577 | ||
578 | /// Returns the option if it contains a value, otherwise returns `optb`. | |
579 | /// | |
c34b1796 | 580 | /// # Examples |
1a4d82fc JJ |
581 | /// |
582 | /// ``` | |
85aaf69f | 583 | /// let x = Some(2); |
1a4d82fc | 584 | /// let y = None; |
85aaf69f | 585 | /// assert_eq!(x.or(y), Some(2)); |
1a4d82fc JJ |
586 | /// |
587 | /// let x = None; | |
85aaf69f SL |
588 | /// let y = Some(100); |
589 | /// assert_eq!(x.or(y), Some(100)); | |
1a4d82fc | 590 | /// |
85aaf69f SL |
591 | /// let x = Some(2); |
592 | /// let y = Some(100); | |
593 | /// assert_eq!(x.or(y), Some(2)); | |
1a4d82fc | 594 | /// |
85aaf69f | 595 | /// let x: Option<u32> = None; |
1a4d82fc JJ |
596 | /// let y = None; |
597 | /// assert_eq!(x.or(y), None); | |
598 | /// ``` | |
599 | #[inline] | |
85aaf69f | 600 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
601 | pub fn or(self, optb: Option<T>) -> Option<T> { |
602 | match self { | |
603 | Some(_) => self, | |
c1a9b12d | 604 | None => optb, |
1a4d82fc JJ |
605 | } |
606 | } | |
607 | ||
608 | /// Returns the option if it contains a value, otherwise calls `f` and | |
609 | /// returns the result. | |
610 | /// | |
c34b1796 | 611 | /// # Examples |
1a4d82fc JJ |
612 | /// |
613 | /// ``` | |
614 | /// fn nobody() -> Option<&'static str> { None } | |
615 | /// fn vikings() -> Option<&'static str> { Some("vikings") } | |
616 | /// | |
617 | /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); | |
618 | /// assert_eq!(None.or_else(vikings), Some("vikings")); | |
619 | /// assert_eq!(None.or_else(nobody), None); | |
620 | /// ``` | |
621 | #[inline] | |
85aaf69f | 622 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
623 | pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> { |
624 | match self { | |
625 | Some(_) => self, | |
c1a9b12d | 626 | None => f(), |
1a4d82fc JJ |
627 | } |
628 | } | |
629 | ||
630 | ///////////////////////////////////////////////////////////////////////// | |
631 | // Misc | |
632 | ///////////////////////////////////////////////////////////////////////// | |
633 | ||
634 | /// Takes the value out of the option, leaving a `None` in its place. | |
635 | /// | |
c34b1796 | 636 | /// # Examples |
1a4d82fc JJ |
637 | /// |
638 | /// ``` | |
85aaf69f | 639 | /// let mut x = Some(2); |
1a4d82fc JJ |
640 | /// x.take(); |
641 | /// assert_eq!(x, None); | |
642 | /// | |
85aaf69f | 643 | /// let mut x: Option<u32> = None; |
1a4d82fc JJ |
644 | /// x.take(); |
645 | /// assert_eq!(x, None); | |
646 | /// ``` | |
647 | #[inline] | |
85aaf69f | 648 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
649 | pub fn take(&mut self) -> Option<T> { |
650 | mem::replace(self, None) | |
651 | } | |
652 | } | |
653 | ||
c34b1796 | 654 | impl<'a, T: Clone> Option<&'a T> { |
b039eaaf SL |
655 | /// Maps an `Option<&T>` to an `Option<T>` by cloning the contents of the |
656 | /// option. | |
c34b1796 | 657 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc | 658 | pub fn cloned(self) -> Option<T> { |
c34b1796 | 659 | self.map(|t| t.clone()) |
1a4d82fc JJ |
660 | } |
661 | } | |
662 | ||
663 | impl<T: Default> Option<T> { | |
664 | /// Returns the contained value or a default | |
665 | /// | |
666 | /// Consumes the `self` argument then, if `Some`, returns the contained | |
667 | /// value, otherwise if `None`, returns the default value for that | |
668 | /// type. | |
669 | /// | |
c34b1796 | 670 | /// # Examples |
1a4d82fc JJ |
671 | /// |
672 | /// Convert a string to an integer, turning poorly-formed strings | |
673 | /// into 0 (the default value for integers). `parse` converts | |
674 | /// a string to any other type that implements `FromStr`, returning | |
675 | /// `None` on error. | |
676 | /// | |
677 | /// ``` | |
678 | /// let good_year_from_input = "1909"; | |
679 | /// let bad_year_from_input = "190blarg"; | |
85aaf69f SL |
680 | /// let good_year = good_year_from_input.parse().ok().unwrap_or_default(); |
681 | /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default(); | |
1a4d82fc | 682 | /// |
85aaf69f SL |
683 | /// assert_eq!(1909, good_year); |
684 | /// assert_eq!(0, bad_year); | |
1a4d82fc JJ |
685 | /// ``` |
686 | #[inline] | |
85aaf69f | 687 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
688 | pub fn unwrap_or_default(self) -> T { |
689 | match self { | |
690 | Some(x) => x, | |
c1a9b12d | 691 | None => Default::default(), |
1a4d82fc JJ |
692 | } |
693 | } | |
694 | } | |
695 | ||
7453a54e SL |
696 | // This is a separate function to reduce the code size of .expect() itself. |
697 | #[inline(never)] | |
698 | #[cold] | |
699 | fn expect_failed(msg: &str) -> ! { | |
700 | panic!("{}", msg) | |
701 | } | |
702 | ||
703 | ||
1a4d82fc JJ |
704 | ///////////////////////////////////////////////////////////////////////////// |
705 | // Trait implementations | |
706 | ///////////////////////////////////////////////////////////////////////////// | |
707 | ||
85aaf69f | 708 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
709 | impl<T> Default for Option<T> { |
710 | #[inline] | |
1a4d82fc JJ |
711 | fn default() -> Option<T> { None } |
712 | } | |
713 | ||
9346a6ac AL |
714 | #[stable(feature = "rust1", since = "1.0.0")] |
715 | impl<T> IntoIterator for Option<T> { | |
716 | type Item = T; | |
717 | type IntoIter = IntoIter<T>; | |
718 | ||
719 | /// Returns a consuming iterator over the possibly contained value. | |
720 | /// | |
721 | /// # Examples | |
722 | /// | |
723 | /// ``` | |
724 | /// let x = Some("string"); | |
725 | /// let v: Vec<&str> = x.into_iter().collect(); | |
726 | /// assert_eq!(v, ["string"]); | |
727 | /// | |
728 | /// let x = None; | |
729 | /// let v: Vec<&str> = x.into_iter().collect(); | |
730 | /// assert!(v.is_empty()); | |
731 | /// ``` | |
732 | #[inline] | |
733 | fn into_iter(self) -> IntoIter<T> { | |
734 | IntoIter { inner: Item { opt: self } } | |
735 | } | |
736 | } | |
737 | ||
e9174d1e SL |
738 | #[stable(since = "1.4.0", feature = "option_iter")] |
739 | impl<'a, T> IntoIterator for &'a Option<T> { | |
740 | type Item = &'a T; | |
741 | type IntoIter = Iter<'a, T>; | |
742 | ||
743 | fn into_iter(self) -> Iter<'a, T> { | |
744 | self.iter() | |
745 | } | |
746 | } | |
747 | ||
748 | #[stable(since = "1.4.0", feature = "option_iter")] | |
749 | impl<'a, T> IntoIterator for &'a mut Option<T> { | |
750 | type Item = &'a mut T; | |
751 | type IntoIter = IterMut<'a, T>; | |
752 | ||
753 | fn into_iter(mut self) -> IterMut<'a, T> { | |
754 | self.iter_mut() | |
755 | } | |
756 | } | |
757 | ||
5bcae85e SL |
758 | #[stable(since = "1.12.0", feature = "option_from")] |
759 | impl<T> From<T> for Option<T> { | |
760 | fn from(val: T) -> Option<T> { | |
761 | Some(val) | |
762 | } | |
763 | } | |
764 | ||
1a4d82fc JJ |
765 | ///////////////////////////////////////////////////////////////////////////// |
766 | // The Option Iterators | |
767 | ///////////////////////////////////////////////////////////////////////////// | |
768 | ||
54a0048b | 769 | #[derive(Clone, Debug)] |
1a4d82fc JJ |
770 | struct Item<A> { |
771 | opt: Option<A> | |
772 | } | |
773 | ||
774 | impl<A> Iterator for Item<A> { | |
775 | type Item = A; | |
776 | ||
777 | #[inline] | |
778 | fn next(&mut self) -> Option<A> { | |
779 | self.opt.take() | |
780 | } | |
781 | ||
782 | #[inline] | |
85aaf69f | 783 | fn size_hint(&self) -> (usize, Option<usize>) { |
1a4d82fc JJ |
784 | match self.opt { |
785 | Some(_) => (1, Some(1)), | |
786 | None => (0, Some(0)), | |
787 | } | |
788 | } | |
789 | } | |
790 | ||
791 | impl<A> DoubleEndedIterator for Item<A> { | |
792 | #[inline] | |
793 | fn next_back(&mut self) -> Option<A> { | |
794 | self.opt.take() | |
795 | } | |
796 | } | |
797 | ||
798 | impl<A> ExactSizeIterator for Item<A> {} | |
799 | ||
800 | /// An iterator over a reference of the contained item in an Option. | |
85aaf69f | 801 | #[stable(feature = "rust1", since = "1.0.0")] |
54a0048b | 802 | #[derive(Debug)] |
1a4d82fc JJ |
803 | pub struct Iter<'a, A: 'a> { inner: Item<&'a A> } |
804 | ||
85aaf69f | 805 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
806 | impl<'a, A> Iterator for Iter<'a, A> { |
807 | type Item = &'a A; | |
808 | ||
809 | #[inline] | |
810 | fn next(&mut self) -> Option<&'a A> { self.inner.next() } | |
811 | #[inline] | |
85aaf69f | 812 | fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } |
1a4d82fc JJ |
813 | } |
814 | ||
85aaf69f | 815 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
816 | impl<'a, A> DoubleEndedIterator for Iter<'a, A> { |
817 | #[inline] | |
818 | fn next_back(&mut self) -> Option<&'a A> { self.inner.next_back() } | |
819 | } | |
820 | ||
85aaf69f | 821 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
822 | impl<'a, A> ExactSizeIterator for Iter<'a, A> {} |
823 | ||
85aaf69f | 824 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
825 | impl<'a, A> Clone for Iter<'a, A> { |
826 | fn clone(&self) -> Iter<'a, A> { | |
827 | Iter { inner: self.inner.clone() } | |
828 | } | |
829 | } | |
830 | ||
831 | /// An iterator over a mutable reference of the contained item in an Option. | |
85aaf69f | 832 | #[stable(feature = "rust1", since = "1.0.0")] |
54a0048b | 833 | #[derive(Debug)] |
1a4d82fc JJ |
834 | pub struct IterMut<'a, A: 'a> { inner: Item<&'a mut A> } |
835 | ||
85aaf69f | 836 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
837 | impl<'a, A> Iterator for IterMut<'a, A> { |
838 | type Item = &'a mut A; | |
839 | ||
840 | #[inline] | |
841 | fn next(&mut self) -> Option<&'a mut A> { self.inner.next() } | |
842 | #[inline] | |
85aaf69f | 843 | fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } |
1a4d82fc JJ |
844 | } |
845 | ||
85aaf69f | 846 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
847 | impl<'a, A> DoubleEndedIterator for IterMut<'a, A> { |
848 | #[inline] | |
849 | fn next_back(&mut self) -> Option<&'a mut A> { self.inner.next_back() } | |
850 | } | |
851 | ||
85aaf69f | 852 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
853 | impl<'a, A> ExactSizeIterator for IterMut<'a, A> {} |
854 | ||
855 | /// An iterator over the item contained inside an Option. | |
54a0048b | 856 | #[derive(Clone, Debug)] |
85aaf69f | 857 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
858 | pub struct IntoIter<A> { inner: Item<A> } |
859 | ||
85aaf69f | 860 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
861 | impl<A> Iterator for IntoIter<A> { |
862 | type Item = A; | |
863 | ||
864 | #[inline] | |
865 | fn next(&mut self) -> Option<A> { self.inner.next() } | |
866 | #[inline] | |
85aaf69f | 867 | fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() } |
1a4d82fc JJ |
868 | } |
869 | ||
85aaf69f | 870 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
871 | impl<A> DoubleEndedIterator for IntoIter<A> { |
872 | #[inline] | |
873 | fn next_back(&mut self) -> Option<A> { self.inner.next_back() } | |
874 | } | |
875 | ||
85aaf69f | 876 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
877 | impl<A> ExactSizeIterator for IntoIter<A> {} |
878 | ||
879 | ///////////////////////////////////////////////////////////////////////////// | |
880 | // FromIterator | |
881 | ///////////////////////////////////////////////////////////////////////////// | |
882 | ||
85aaf69f | 883 | #[stable(feature = "rust1", since = "1.0.0")] |
1a4d82fc JJ |
884 | impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> { |
885 | /// Takes each element in the `Iterator`: if it is `None`, no further | |
886 | /// elements are taken, and the `None` is returned. Should no `None` occur, a | |
887 | /// container with the values of each `Option` is returned. | |
888 | /// | |
889 | /// Here is an example which increments every integer in a vector, | |
890 | /// checking for overflow: | |
891 | /// | |
c34b1796 | 892 | /// ``` |
85aaf69f | 893 | /// use std::u16; |
1a4d82fc | 894 | /// |
85aaf69f SL |
895 | /// let v = vec!(1, 2); |
896 | /// let res: Option<Vec<u16>> = v.iter().map(|&x: &u16| | |
897 | /// if x == u16::MAX { None } | |
1a4d82fc JJ |
898 | /// else { Some(x + 1) } |
899 | /// ).collect(); | |
85aaf69f | 900 | /// assert!(res == Some(vec!(2, 3))); |
1a4d82fc JJ |
901 | /// ``` |
902 | #[inline] | |
85aaf69f | 903 | fn from_iter<I: IntoIterator<Item=Option<A>>>(iter: I) -> Option<V> { |
1a4d82fc JJ |
904 | // FIXME(#11084): This could be replaced with Iterator::scan when this |
905 | // performance bug is closed. | |
906 | ||
907 | struct Adapter<Iter> { | |
908 | iter: Iter, | |
909 | found_none: bool, | |
910 | } | |
911 | ||
912 | impl<T, Iter: Iterator<Item=Option<T>>> Iterator for Adapter<Iter> { | |
913 | type Item = T; | |
914 | ||
915 | #[inline] | |
916 | fn next(&mut self) -> Option<T> { | |
917 | match self.iter.next() { | |
918 | Some(Some(value)) => Some(value), | |
919 | Some(None) => { | |
920 | self.found_none = true; | |
921 | None | |
922 | } | |
923 | None => None, | |
924 | } | |
925 | } | |
926 | } | |
927 | ||
85aaf69f | 928 | let mut adapter = Adapter { iter: iter.into_iter(), found_none: false }; |
1a4d82fc JJ |
929 | let v: V = FromIterator::from_iter(adapter.by_ref()); |
930 | ||
931 | if adapter.found_none { | |
932 | None | |
933 | } else { | |
934 | Some(v) | |
935 | } | |
936 | } | |
937 | } |