
And with Rust, you can be pretty sure somebody already did that.
DOWNCAST RUST CODE
Trait objects are just so convenient, aren’t they? But with everything that looks like repetition and boilerplate, also looks like we could have macros helping us with code generation. The only thing we sacrifice in comparison to Boxis the amount of boilerplate we need to create. It’s a language that allows you to go from a very low-level to a very high-level programming style without sacrificing elegance! Repetition # This is also one of the beautiful things about Rust. NumFromFileErr :: ParseError (_ ) => println! ( "Error from Parsing!" ) , NumFromFileErr :: IoError (_ ) => println! ( "Error from IO!" ) , use std ::error įn number_from_file (filename : & str ) -> Result > ", v ) , Let’s quickly recap what we ended up with in the last example.

It requires setting up a lot more boilerplate (which surely can be macro’d somehow), but in the end, I find it much better to use, and it arguably has some benefits at runtime as well. This is what I want to share with you today.

There is a really nice pattern to handle multiple errors that involve enums. I’d rather have this information erased at compile time! Memory layout of Box and Box Which you might consider not convenient at all, because there’s some downcasting involved to get the original error back, and we rely on trait objects and dynamic dispatch to carry something like an error along our codebase. The moment we want to use error propagation for different error types, we have to rely on trait objects with Box, which means we defer a lot of information from compile-time to runtime, for the sake of convenient error handling. This is a follow-up to Error handling in Rust from a couple of days ago.
