Skip to content

Fallible map on Option #38282

Closed
Closed
@golddranks

Description

@golddranks
Contributor

Using Option::map together with the ? operator is a pain. If you are mapping over an optional type, you can't use ? inside the closure to signal error. This means that it's often impractical to map functions that return Results over optional types. Here's a way to alleviate that:

item.explanation = item.explanation
    .and_then(|s| sanitize_links(&s).ok() ); // FIXME silently ignores errors

...but as noted in the comment, in the cases where the error matters, this is bad, and needs to be refactored into a match statement.

It would help the ergonomics, if Option<T> had a method – let's call it fallible_map for the sake of the argument (feel free to suggest more succinct names) – like this:

fallible_map(self, FnOnce(T) → Result<U, E>) → Result<Option<U>, E>

What it would do, it would map the function over T, but wrap an Ok result into Option and return that Option wrapped into a Result. This would allow mapping fallible functions over Options:

item.explanation = item.explanation
    .fallible_map(|s| sanitize_links(&s))?;

Which, combined with ?, allows neat, fluid APIs while handling errors properly.

Comments? Does adding this kind of an API to Option need an RFC?

Note that alternative to this would be a method over Option<Result<T, E>> that would "flip" the types to Result<Option<T>, E>.

Activity

leoyvens

leoyvens commented on Dec 10, 2016

@leoyvens
Contributor

Shouldn't this issue go in the RFCs repo?

killercup

killercup commented on Dec 11, 2016

@killercup
Member

I would call fallible_map try_map instead. A simple implementation could look like this and live in a third-party crate.

sfackler

sfackler commented on Dec 11, 2016

@sfackler
Member

Yep, this should live in the RFCs repo.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @killercup@sfackler@golddranks@leoyvens

        Issue actions

          Fallible map on Option · Issue #38282 · rust-lang/rust