Option counter method to ok_or

Would there be any desire to have a complementing err_or and err_or_else methods on Option<T>. There already are ok_or and ok_or_else so it seems only natural to have the opposite.

Signatures:

impl<E> Option<E> {
    fn err_or<O>(self, ok: O) -> Result<O, E>;

    fn err_or_else<O, F>(self, ok: F) -> Result<O, E> where F : FnOnce() -> O;
}

The alternative (or in addition) would be a method on Result<U, V> called flip which has the following signature:

impl<U, V> Result<U, V> {
    fn flip(self) -> Result<V, U>;
}

These methods would be useful for when you want to return an optional error in conjunction with some other information.

That would be useful only if you had to work with existing Option<Error>, but that situation is more idiomatically expressed by Result<(), Error>.

So I think lack of these methods is a valuable reminder that you should be using Result for errors.

Result has very clear Ok/Err sides that you should never need to flip around. For cases where the two types are interchangeble, there is the Either type.

3 Likes

I agree that result shouldn't have something like flip. I just suggested it as an option.

Yes, it would be useful in situations of Option<Error>

One way to write this today is: opt.map_or(Ok(foo), Err)

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.