]> git.lizzy.rs Git - rust.git/blob - library/core/src/bool.rs
Rollup merge of #104936 - cjgillot:self-rpit-orig-too, r=oli-obk
[rust.git] / library / core / src / bool.rs
1 //! impl bool {}
2
3 use crate::marker::Destruct;
4
5 impl bool {
6     /// Returns `Some(t)` if the `bool` is [`true`](../std/keyword.true.html),
7     /// or `None` otherwise.
8     ///
9     /// Arguments passed to `then_some` are eagerly evaluated; if you are
10     /// passing the result of a function call, it is recommended to use
11     /// [`then`], which is lazily evaluated.
12     ///
13     /// [`then`]: bool::then
14     ///
15     /// # Examples
16     ///
17     /// ```
18     /// assert_eq!(false.then_some(0), None);
19     /// assert_eq!(true.then_some(0), Some(0));
20     /// ```
21     ///
22     /// ```
23     /// let mut a = 0;
24     /// let mut function_with_side_effects = || { a += 1; };
25     ///
26     /// true.then_some(function_with_side_effects());
27     /// false.then_some(function_with_side_effects());
28     ///
29     /// // `a` is incremented twice because the value passed to `then_some` is
30     /// // evaluated eagerly.
31     /// assert_eq!(a, 2);
32     /// ```
33     #[stable(feature = "bool_to_option", since = "1.62.0")]
34     #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
35     #[inline]
36     pub const fn then_some<T>(self, t: T) -> Option<T>
37     where
38         T: ~const Destruct,
39     {
40         if self { Some(t) } else { None }
41     }
42
43     /// Returns `Some(f())` if the `bool` is [`true`](../std/keyword.true.html),
44     /// or `None` otherwise.
45     ///
46     /// # Examples
47     ///
48     /// ```
49     /// assert_eq!(false.then(|| 0), None);
50     /// assert_eq!(true.then(|| 0), Some(0));
51     /// ```
52     ///
53     /// ```
54     /// let mut a = 0;
55     ///
56     /// true.then(|| { a += 1; });
57     /// false.then(|| { a += 1; });
58     ///
59     /// // `a` is incremented once because the closure is evaluated lazily by
60     /// // `then`.
61     /// assert_eq!(a, 1);
62     /// ```
63     #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
64     #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
65     #[inline]
66     pub const fn then<T, F>(self, f: F) -> Option<T>
67     where
68         F: ~const FnOnce() -> T,
69         F: ~const Destruct,
70     {
71         if self { Some(f()) } else { None }
72     }
73 }