Attributes

Any item in a Rust program can be decorated with attributes, which are Rust's catch-all syntax for writing miscellaneous instructions and advice to the compiler.

Tip: To attach an attribute to a whole crate, add it at the top of the main.rs or lib.rs file, before any items and write #! instead of #:


#![allow(unused)]
fn main() {
// src/lib.rs
#![allow(non_camel_case_types)]
pub struct weird_type_name {  }
}

Tip: To include a module only when testing, use #[cfg(test)].

#! can also be used inside functions, structs, etc, but it's only typically used at the beginning of a file to attach an attribute to the whole module or crate.

Some attributes must use #! because they can only be applied to an entire module or crate. For example, #![feature] is used to turn on unstable features of the Rust language and libraries.

Conditional Compilation

Conditional compilation is configured using the #[cfg] attribute:


#![allow(unused)]
fn main() {
#[cfg(target_os = "macos")]
mod mac_stuff; // will only be be included if the target is macOS
}

Links