]> git.lizzy.rs Git - rust.git/blob - library/core/src/bool.rs
merge rustc history
[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     #[stable(feature = "bool_to_option", since = "1.62.0")]
22     #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
23     #[inline]
24     pub const fn then_some<T>(self, t: T) -> Option<T>
25     where
26         T: ~const Destruct,
27     {
28         if self { Some(t) } else { None }
29     }
30
31     /// Returns `Some(f())` if the `bool` is [`true`](../std/keyword.true.html),
32     /// or `None` otherwise.
33     ///
34     /// # Examples
35     ///
36     /// ```
37     /// assert_eq!(false.then(|| 0), None);
38     /// assert_eq!(true.then(|| 0), Some(0));
39     /// ```
40     #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
41     #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
42     #[inline]
43     pub const fn then<T, F>(self, f: F) -> Option<T>
44     where
45         F: ~const FnOnce() -> T,
46         F: ~const Destruct,
47     {
48         if self { Some(f()) } else { None }
49     }
50 }