Description
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 Result
s 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 Option
s:
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 commentedon Dec 10, 2016
Shouldn't this issue go in the RFCs repo?
killercup commentedon Dec 11, 2016
I would call fallible_map
try_map
instead. A simple implementation could look like this and live in a third-party crate.sfackler commentedon Dec 11, 2016
Yep, this should live in the RFCs repo.