Skip to content

Mapping booleans to Option #50523

Closed
Closed

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!

Activity

  1. Reconcyl commented on May 8, 2018

    @Reconcyl

    Are you looking for Option::filter()? It's currently unstable so you can only use it with #[feature(option_filter)] on nightly, but it seems like it's what you want.

  2. killercup commented on May 8, 2018

    @killercup
    Contributor

    You could probably use boolinator to write foo.as_some(bar)

  3. varkor commented on May 8, 2018

    @varkor
    Contributor

    For what it's worth, I've seen this question come up multiple times in the past (and I know I've made use of the pattern before). Perhaps it is worth considering adding it to bool's implementation.

    Edit: Ah, I knew I had seen it recently. I forgot it was in the RFCs repository rather than this one.

  4. kennytm commented on May 8, 2018

    @kennytm
    Member

    Please check rust-lang/rfcs#2180.

  5. added
    T-libs-api[DEPRECATED; DO NOT USE]
    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.
    on May 8, 2018
  6. jonhoo commented on May 8, 2018

    @jonhoo
    ContributorAuthor

    @ScratchMan544 Option::filter isn't quite the same, as it is Option<T> -> bool -> Option<T>, whereas what I want is bool -> T -> Option<T>. The RFC @kennytm links is exactly this (though I think it should also have a variant for false)! I guess I'll close in favor of that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-api[DEPRECATED; DO NOT USE]

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions