Inspection for booleans

bool::then is, to say the least, amazing. However, in a case where preserving the boolean value is required it inflicts a bit of boilerplate upon us:

value
    .then(|| {<action>; true})
    .unwrap_or(false)

// or

value
    .then_some(true)
    .inspect(|_| <action>)
    .unwrap_or(false)

This is a minor complaint for sure, but wouldn’t it be a little nicer if we had a couple of methods akin to inspect (let’s call them do for now)?

value.do_true(|| <action>)

Wouldn’t make even less of a difference in case two branches are needed, but it might still indicate intention clearer:

value
    .do_true(|| <action1>)
    .do_false(|| <action2>)

// vs

value
    .then(|| {<action1>; true})
    .unwrap_or_else(|| {<action2>; false})
if value {
    <action1>
} else {
    <action2>
}
25 Likes

You could also do

_ = value && { <action1>; true } || { <action2>; false };
value.then(action1).is_some()
value.then(action1).is_none().then(action2);
value.then(action1).ok_or_else(action2).is_ok()

Playground

2 Likes

For value-independent inspection in method chains you'll want tap, which isn't specific to bools.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.