Are there any plans to add Option methods that convert Some to Result::Err?

Sometimes, when one searches through a haystack, one is not so much looking for a needle, as looking to prove the haystack contains no needles. In such cases, the user will generally want a descriptive certificate of the needle’s existence and nature, so that they may strive to provide a needle-free haystack next time.

In this case, when dealing with Options in a function that returns a Result, the meaning of Option::ok() et al is dual to what is desirable.

The duals of ok() and ok_or() might be written as follows:

impl<E> Option<E> {
    fn err(self) -> Result<(), E> {
        match self {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }
    fn err_or<F, T>(self, f: F) -> Result<T, E> where F: FnOnce() -> T {
        match self {
            Some(e) => Err(e),
            None => Ok(f()),
        }
    }
}

Is there already a similar RFC or stdlib PR?



Read more here: https://stackoverflow.com/questions/65708630/are-there-any-plans-to-add-option-methods-that-convert-some-to-resulterr

Content Attribution

This content was originally published by mmirate at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: