1//! impl bool {}
2
3impl bool {
4 /// Returns `Some(t)` if the `bool` is [`true`](../std/keyword.true.html),
5 /// or `None` otherwise.
6 ///
7 /// Arguments passed to `then_some` are eagerly evaluated; if you are
8 /// passing the result of a function call, it is recommended to use
9 /// [`then`], which is lazily evaluated.
10 ///
11 /// [`then`]: bool::then
12 ///
13 /// # Examples
14 ///
15 /// ```
16 /// assert_eq!(false.then_some(0), None);
17 /// assert_eq!(true.then_some(0), Some(0));
18 /// ```
19 ///
20 /// ```
21 /// let mut a = 0;
22 /// let mut function_with_side_effects = || { a += 1; };
23 ///
24 /// true.then_some(function_with_side_effects());
25 /// false.then_some(function_with_side_effects());
26 ///
27 /// // `a` is incremented twice because the value passed to `then_some` is
28 /// // evaluated eagerly.
29 /// assert_eq!(a, 2);
30 /// ```
31 #[stable(feature = "bool_to_option", since = "1.62.0")]
32 #[inline]
33 pub fn then_some<T>(self, t: T) -> Option<T> {
34 if self { Some(t) } else { None }
35 }
36
37 /// Returns `Some(f())` if the `bool` is [`true`](../std/keyword.true.html),
38 /// or `None` otherwise.
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// assert_eq!(false.then(|| 0), None);
44 /// assert_eq!(true.then(|| 0), Some(0));
45 /// ```
46 ///
47 /// ```
48 /// let mut a = 0;
49 ///
50 /// true.then(|| { a += 1; });
51 /// false.then(|| { a += 1; });
52 ///
53 /// // `a` is incremented once because the closure is evaluated lazily by
54 /// // `then`.
55 /// assert_eq!(a, 1);
56 /// ```
57 #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
58 #[inline]
59 pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
60 if self { Some(f()) } else { None }
61 }
62}
63