Attributes

An attribute is an annotation on an item in Rust code. Items are top-level language constructs in a crate such as functions, modules, structs, enums, and constant declarations, and other things that are meant to be defined only at the crate root. Attributes are usually compiler built-ins, but can also be created by users through compiler plugins. They instruct the compiler to inject extra code or meaning for the item that appears below them, or for the module if they apply to a module. We'll cover more on these in Chapter 7, Advanced Concepts. For the sake of keeping things in scope, we will talk about two forms of attributes here:

  • #[<name>]: This applies per item and usually appears above them in their definition. For example, test functions in Rust are annotated with the #[test] attribute. It signifies that the function is to be treated as part of the test harness.
  • #![<name>]: This applies to the whole crate. Notice that it has an extra ! there. It usually goes at the very top of your crate root.
If we are creating a library crate, the crate root is basically lib.rs, whereas when creating a binary crate, the crate root would be the main.rs file.

There are also other forms of attributes such as #[cfg(test)] that are used when writing tests within a module. This attribute is added on top of test modules to hint to the compiler to conditionally compile the module, but only when code is compiled in test mode. Attributes are not just limited to being used in testing code; they are widely used in Rust. We'll get to see more of them in upcoming chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset