Skip to content

Commit dba9cdf

Browse files
committed
Make bool::then_some and bool::then const methods
This change makes both `then_some` and `then` methods on bool const-compatible, allowing them to be used in const contexts for compile-time evaluation. Benefits: - Enables compile-time conditional Option creation - Allows usage in const generics and static initialization - Provides zero-cost abstraction in const contexts - Improves ergonomics for const programming patterns The `then_some` method is straightforward to make const as it only uses basic conditional logic. The `then` method requires a `~const FnOnce` bound to ensure the closure can be called in const contexts. This resolves the FIXME in the test suite and enables the const tests for these methods that were previously disabled.
1 parent 8b6b15b commit dba9cdf

File tree

2 files changed

+5
-4
lines changed

2 files changed

+5
-4
lines changed

library/core/src/bool.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ impl bool {
3030
/// ```
3131
#[stable(feature = "bool_to_option", since = "1.62.0")]
3232
#[inline]
33-
pub fn then_some<T>(self, t: T) -> Option<T> {
33+
pub const fn then_some<T>(self, t: T) -> Option<T> {
3434
if self { Some(t) } else { None }
3535
}
3636

@@ -58,7 +58,10 @@ impl bool {
5858
#[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
5959
#[rustc_diagnostic_item = "bool_then"]
6060
#[inline]
61-
pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> {
61+
pub const fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T>
62+
where
63+
F: [const] FnOnce() -> T,
64+
{
6265
if self { Some(f()) } else { None }
6366
}
6467

library/coretests/tests/bool.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,6 @@ fn test_bool_to_option() {
8989
assert_eq!(false.then(|| 0), None);
9090
assert_eq!(true.then(|| 0), Some(0));
9191

92-
/* FIXME(#110395)
9392
const fn zero() -> i32 {
9493
0
9594
}
@@ -103,7 +102,6 @@ fn test_bool_to_option() {
103102
assert_eq!(B, Some(0));
104103
assert_eq!(C, None);
105104
assert_eq!(D, Some(0));
106-
*/
107105
}
108106

109107
#[test]

0 commit comments

Comments
 (0)