Skip to content

Commit 758ca9d

Browse files
authored
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`.
1 parent db4b4d3 commit 758ca9d

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

library/core/src/bool.rs

Lines changed: 22 additions & 0 deletions
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,16 @@ 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+
/// ```
4062
#[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
4163
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
4264
#[inline]

0 commit comments

Comments
 (0)