Rust Notes
Flipping an Option<Result<T, E>>
to a Result<Option<T>, E>
I was writing a command line application which took a regex from a flag, the details aren't important. I knew that the valid states for this parameter were:
- Flag was not used, the output should be
Ok(None)
- Flag was used but the regex was invalid, the output should be
Err(E)
- Flag was used and the regex was valid, the output should be
Ok(T)
let pattern: Option<String> = Some("[a-z]".into());
let pattern: Result<Option<Regex>, regex::Error> = pattern
.as_ref()
.map_or(
Ok(None),
// The following line turns Result<T, E> into a Result<Option<T>, E>
|pattern| Regex::new(&pattern).map(Some)
);