Result alias within a crate (style check)

After reading this post, I decided it was time I thought about error handling a bit more in my current project.

Then I came across this post which overall seemed like a pretty simple setup for integrating to a single point for error handling.

However, immediately upon going to implement it I realized that an aliased Result<T> seemed problematic for shadowing the standard Result<T, E>. And apparently others have had this question as well, because I then found this discussion suggesting using Fallible<T> instead.

I'm now wondering, is there a community standard? Or if something else like Expect<T> might be suitable. Thought I suppose that's the reverse logic from .expect(), so perhaps Success<T> or Correct<T> might play nicely with use of ? for unwrapping...

Does anyone have any good ideas on the matter?

Creating a Result alias is very normal, although some people prefer to define it like this:

pub type Result<T, E = MyError> = std::result::Result<T, E>;

Then you can do both Result<T> and Result<T, SomeOtherError>.

6 Likes

Ah, that is pretty nice. Allowing for Result<T> keeps things concise, while also allowing for more specified exception handling, if so desired, seems to be a best of both worlds kind of solution!

A question on a possible further step. Would using From/Into work to allow returning just the unit error structs that go into the top-level error enum?

pub type Result<T, E = Into<MyError>> = std::result::Result<T, E>;

impl From<ErrorType> for MyError {
    fn from(err: ErrorType) -> MyError {
        MyError::ErrorType(err)
    }
}

so that a function could return

pub fn example() -> Result<f64> {
    if true {
        Ok(0.0)
    } else {
        Err(ErrorType)
    }
}

I suppose a similarly simple alternative would be to just make new functions for each enum variant:

pub fn example() -> Result<f64> {
    if true {
        Ok(0.0)
    } else {
        Err(MyError::error_type())
    }
}

No, the default in a type alias must be a type. It cannot be a trait.

Ahh, well, the alternative is still pretty clean and easy. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.