Skip to content

Fallible map on Option #38282

@golddranks

Description

@golddranks

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>.

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

    Issue actions