4 ms·
I think having Result alone does not make error handling complicated, but having different error types for each operation (and concrete result) instead of using
by Matthias247 9y ago
I think having Result alone does not make error handling complicated, but having different error types for each operation (and concrete result) instead of using one generic error type for all of them does by pushing the job of unifying erros towards the user.
Go works around the problem by Error being an interface, which means any function can return any kind of error without needing to transform it to another form. However Go benefits from the Garbage Collector here - I totally understand why Rust libraries don't want to return heap allocated errors.
Maybe C++ std::error_code/error_condition provides some kind of middle ground: It should not require a dynamic allocation. And yet the framework can be expanded: Different libraries can create their own error codes (categories), and error_codes from different libraries can all be handled in the same way: No need for a function that handles multiple error sources to convert the error_codes into another type.
The downside is that the size of the error structure is really fixed and there's no space to add custom error fields to it for error conditions that might require it. A custom error type in Result<ResultType,ErrorType> can be as big or small as one needs.
- deleted 9y ago[deleted]
- whyever 9y ago> instead of using one generic error type for all of them But you can do that in Rust, just use Box<Error>. No library does that though, because it is not a zero-cost abstraction.
- leshow 9y agoNote that Rust's Error is also a trait (similar to an interface) and Box<Error> does return heap allocated errors, and you're free to use that if you like. Being a trait object, it will erase the type of the error, but you don't have to write any of the accompanying From or Error implementations you normally would with your own ErrorType.
- pcwalton 9y ago> However Go benefits from the Garbage Collector here - I totally understand why Rust libraries don't want to return heap allocated errors. This doesn't have to do with the GC or lack thereof. Instead it's part of the philosophy of zero-cost abstractions: idiomatic C libraries don't require heap allocations to return errors, so neither does Rust.