Laziness, Rust errors and the secret to being a 10x engineer

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
a few moons ago I made a video on Rust erors where I focused on using boxed objects implementing the air trait some of you in the comments were quick to point out that it's more utilitarian to build custom air types especially when we're building a library to be used by Downstream projects but what if you don't want to go through the hassle of implementing the airor trade on your types luckily we can use the air macro from the this error crate to easily derive the standard error trait on our objects today we'll be talking about the different attributes that we can use with this macro and for each of those I'll also gently touch on how they worked under the hood before we begin let's understand how these attributes work attributes in Rust can be active or inner during attribute processing active attributes remove themselves from the abstract syntax tree and transform or expand what they're annotating into some other code inert attributes on the other hand stay on the thing that they're annotating take the example of the active attribute CFG when we annotate a block of code with CFG for it to only compile for Windows if we now compile our program for Linux the CFG attribute gets removed and it transforms the code at annotates into nothing take another example of the test attribute which is inert when we're compiling for tests but active otherwise that is it has to stay on the test functions when we're compiling them for test but it gets removed and transforms the function it annotates into nothing when we're compiling our project for a release build in our case the only active attribute we'll talk about is the derive macro apart from that all the other attributes you'll discuss are inner more specific typically they're known as derived macro helper attributes they don't get removed and don't transform any code by themselves instead they only serve as inputs to the derived macro this error comprises a single procedural macro known as error glorified into a crate to add it to our project will run cargo add this eror let's start with the most common use case where we create an enum with each variant representing a variant of our custom error we import the error macro from this error and derive it on our enum like so we also need to derive the debug trait so that our error can be formatted using this debuck formatting notation now the airor trade in the standard Library requires us to implement the format method as required by the display trade this ensures that the error can be displayed in a console window or a log to ease the implementation of the display trade this error supports the error attribute to display an error message we can also interpolate the message with the inner fields of our air for example here's the parse error for a config parser which only accepts asky characters the air variant that describes unexpected characters can then be a tubal struck containing one character to report this unexpected character to the user we can access it using a zero in this curly brace format string this translates to writing the zeroth member to the formatter with the use of the debug notation we can also display the debug repres representation of the field all of this formatting equally applies to named fields for example if we Name the character from the previous eror we can access it using its name in The Format strings the error attribute also allows any additional format arguments just like a regular call to the format macro arguably the thing that annoys most Russ beginners is standard IO result you're creating a file or perhaps reading from one and you just want to convert that ioer in the result S type into your custom error well this error makes such conversions trivial with the from attribute just create a variant in your enum with an IO eror member and then annotate it with the from attribute during compilation the macro creates a from implementation for an ioer for conversion into your type for a better understanding let's take a look at how the macro gets expanded using the cargo expand tool to install it run cargo install cargo expand expand note The Hyphen between cargo and expand now run cargo expand D- lip to expand your crates library or cargo expand D- bin followed by a Target binary name if you're working with the binary here we can observe that the macro creates a from implementation using core convert from which takes in the standard ioer and creates an error variant that wraps around it now there are cases where might want to have one catchall variant for all underlying errors you don't really care about it would be desirable to delegate the display methods of those variants directly to their underlying errors and this can be achieved using the error transparent annotation this way when the errors are logged we don't see mentions of the outer error all we can see are the error messages directly from the inner error another use case as demonstrated by the crates documentation is when want to have an opaque public air with accessors that we deliberately make public the underlying air type can remain private and it gives us the flexibility to change its Fields And implementations while keeping the public API stable consequently the inner air and the public error might be displayed differently in the logs across different minor versions of our crate however Downstream crates will still be able to use the publicly exposed accessors for additional checks now let's get to some of the more nuanced attributes starting with the source attribute but first let's revisit the standard error trait itself every error implements this set of methods additionally every type that implements error is required to implement debug and display as well looking at the source method we can see that it returns to reference to some underlying error if it exists or the default none with the source attribute we can make this method return a reference to an inner member as some underlying air the first thing you should be careful about is that using the from attribute on a field in your error type implicitly applies The Source attribute to it during compilation the error macro prevents the use of the source attribute on multiple fields and consequently also prevents us from using both the from and the source attributes on different [Music] fields the second Nuance is that given your struct direct the error trait using this error's error macro naming a struct field as Source automatically annotates it with the source attribute consider this example when we inspect the output of this code with the main function we can clearly see that the source method call returns a reference to an IO error that we simply used as a value for the source field remember we never explicitly annotated it with the source attribute the last set of quirks that I want to address relate to the provide method of the error crit as of rating this method is only available in Rust nightly it provides no pun intended a way to extract references to members of a dynamic air trade object generally these include contextual information for error reports like back traces to see back traces you'd typically set the rust back Trace environment variable to one coming back to our custom error if a field is either annotated with the back Trace attribute or has its type named back trace the provide method for our type yields that member as a reference there's a subtle difference between this and using the back Trace annotation in conjunction with either of source or from in such a case the provide method for our custom error is forwarded to that of the source so that both layers of the air share the same back Trace so yeah that's more or less how you use the air macro from this air a big thank you to David to the author of this air for backchecking the script of this video and helping me clear some of the misconceptions I had regarding this a all the sources for this video as well as the code used to render these animations will be available in the video description but until the next video I'll see you around
Info
Channel: Lavafroth
Views: 362
Rating: undefined out of 5
Keywords: programming, rust, thiserror, coding, learn, analysis, intermediate, how to learn rust
Id: Dps-4V3LmRc
Channel Id: undefined
Length: 8min 51sec (531 seconds)
Published: Tue Jun 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.