Should Option<T> impl Termination?

Should Option impl Termination?

I'm thinking of something like this:

impl<T: Into<ExitCode>> Termination for Option<T> {
    fn report(self) -> ExitCode {
        if let Some(val) = self {
            val.into()
        } else {
            ExitCode::FAILURE
        }
    }
}

// maybe specialization can work here?
impl<T: !Into<ExitCode>> Termination for Option<T> {
    fn report(self) -> ExitCode {
        if self.is_some() {
            ExitCode::SUCCESS
        } else {
            ExitCode::FAILURE
        }
    }
}

No, because a person might assume either

  • that None was success rather than failure (analogous to 0), or
  • that Some would always count as a success ("it's like returning Option from a function, the Some variant always indicates success even if it is "successfully returning a result that means failure")

so it's best to require the programmer to be explicit.

10 Likes

Would this be that much of a stretch compared to, say, Result::Ok counting as a success? What if Option::<T>::Some only means success?

And how about an impl<T: Termination> Termination for Option<T> analogous to the one for Result<T: Termination, E: Debug>?

Result signals success-or-failure. Thus, it makes sense to have it as an exit code.

Option indicates a missing value. What does a missing exit code even mean? Thus, Option is not suitable for use as Termination.

If you want Option to impl Termination, you likely have other code that misuses Option to mean Result.

5 Likes

The difference is that no one could assume Ok is a failure. On the other hand, people could assume that Some is a failure, given the common convention of "0 is success, other values are failures".

Hmm. I didn't know about this impl, and if it was suggested to me, I would think it was bad for the same reasons of "implicitly conflating things like Err and Ok(Err)". So it seems Rust has taken different priorities than me. Nevertheless, it still seems worse to extend it to Option, for the additional reason I mention above.

You can always call option.ok_or(... to be explicit that the None case means Err.

2 Likes

Another problem is that None would not print an error message, which is not great.

2 Likes

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