Skip to content

Mapping booleans to Option #50523

Closed
Closed
@jonhoo

Description

@jonhoo

In a decent number of situations, I end up finding myself writing code like:

if foo {
    Some(bar)
} else {
    None
}

This happens especially in closures passed to Iterator::filter_map, but I also frequently find that I want this in .and_then (e.g., on futures). For cases like these, it'd be very handy to have a concise way of turning booleans into Options. For example:

impl bool {
    fn map_true<T>(&self, on_true: T) -> Option<T> { if *self { Some(on_true) } else { None }}
    fn map_false<T>(&self, on_true: T) -> Option<T> { if *self { None } else { Some(on_true) }}
}

There could also be closure variants of this for cases where the T is expensive to construct, but in my experience those cases are rarer. That would let the code above become:

foo.map_true(bar)

The name could of course be bikeshed (if_true?), but I think this is a pretty versatile and useful shorthand!

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions