Understanding attributes
Rust allows us to conditionally compile certain parts of the code depending on what we call attributes. These attributes can be applied to either complete crates/modules or to specific functions, scopes, or even structure fields or enumeration variants. We saw some examples when we talked about Clippy, but these attributes allow for so much more that we will now look at them in depth.
Let's first see how an attribute works. An attribute that you want to apply to the whole current module/crate will be written like this: #![{attribute}]
. Ones that apply to the scope/function/field/variant next to it will be written like this: #[{attribute}]
. Note that the first has the !
symbol between the hash tag and the attribute.
You have probably seen attributes such as #[macro_use]
or #[derive(Debug)]
somewhere in some code. The first one will allow using macros from an external crate, while the second one will derive the Debug
trait in the given structure or enumeration. Let's...