Thomas Payne - Rust Notes

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:

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)
    );