Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This post overlooks a very important technique to get type hiding without the cost of boxing. Having an opaque public type that wraps the private one:

    public struct SqlError(sqlx::Error)

    #[derive(Debug, thiserror::Error)]
    pub enum MyError {
        #[error("Database error: {0}")]
        DatabaseError(#[from] SqlError)
    }
It’s a bit more annoying to construct since result has to have a .map_error(SqlError) but that’s not that much honestly.


This also gives the flexibility to easily change your decision later if you determine that it's important to expose the inner type for some reason. With a boxed trait error type, you'd only be able to by adding a new method to one of the traits, and the implementation would be a lot messier with downcasting, (and unwrapping if you wanted to avoid the optional, which could open the door to bugs where you accidentally don't have the error type you expect and then panic).


That's a valid point, it never occurred to me that this pattern remains useful. But I certainly see the charm it has besides being a bit more annoying to handwrite. I will update the post. Thanks




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: