Collecting Option with Result inside

I have a value x of the type Value (from serde_json).

I want to return Result<Option<String>, WrongFieldsError> (WrongFieldsError is my type).

  • It is Ok(None) if x has no subobject with key sub.
  • It is Ok(Some(_)) if x has a string subobject with key sub of string type.
  • It is Err(WrongFieldsError) if x has a string subobject with key sub of non-string type.

How to write it in idiomatic Rust?

Isn't standard library (trait Option) missing the version of map() (or call it collect()) that receives Option<Result<T, E>> and returns Result<Option<T>, E>>, similarly to "an iterator of Result<T, E> items can be collected into Result<Collection<T>, E>." for vectors?

Should we add something like this to the standard library, in order to ease solving problems like the problem above with serde_json.

Are you looking for transpose?

Yes, thanks. This compiles:

value.get("sub").map(
  |v| Ok::<_, WrongFieldsError>(v.as_str().ok_or(WrongFieldsError::new())?)
).transpose()?

Isn't this just v.as_str().ok_or(WrongFieldsError::new()) ?

Yes, thanks for simplification.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.