Skip to content

Commit 6b001f3

Browse files
authored
Rollup merge of #102115 - Alfriadox:master, r=thomcc
Add examples to `bool::then` and `bool::then_some` Added examples to `bool::then` and `bool::then_some` to show the distinction between the eager evaluation of `bool::then_some` and the lazy evaluation of `bool::then`.
2 parents 986fc4b + ca26dec commit 6b001f3

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

library/core/src/bool.rs

+23
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,18 @@ impl bool {
1818
/// assert_eq!(false.then_some(0), None);
1919
/// assert_eq!(true.then_some(0), Some(0));
2020
/// ```
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+
/// ```
2133
#[stable(feature = "bool_to_option", since = "1.62.0")]
2234
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
2335
#[inline]
@@ -37,6 +49,17 @@ impl bool {
3749
/// assert_eq!(false.then(|| 0), None);
3850
/// assert_eq!(true.then(|| 0), Some(0));
3951
/// ```
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+
/// ```
4063
#[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
4164
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
4265
#[inline]

0 commit comments

Comments
 (0)