» Quick Introduction to Rust » 1. Basics » 1.11 Attributes

Attributes

An attribute is metadata applied to some module, crate or item.

When attributes apply to a whole crate, their syntax is #![crate_attribute], and when they apply to a module or item, the syntax is #[item_attribute] (notice the missing bang !).

Attributes can take arguments with different syntaxes:

  • #[attribute = "value"]
  • #[attribute(key = "value")]
  • #[attribute(value)]

dead_code

The compiler will warn about unused functions. An dead_code attribute can be used to disable the lint.

fn used_function() {}

#[allow(dead_code)]
fn unused_function() {}

fn main() {
    used_function();
}

cfg

Configuration conditional checks are possible through two different operators:

  • the cfg attribute: #[cfg(...)]
  • the cfg! macro: cfg!(...)

While the former enables conditional compilation, the latter conditionally evaluates to true or false literals allowing for checks at run-time.

// This only gets compiled in Linux
#[cfg(target_os = "linux")]
fn on_linux() {
    println!("Running Linux!");
}

fn main() {
    on_linux();

    // Check if it's Linux at runtime
    if cfg!(target_os = "linux") {
        println!("Yes, on linux!");
    } else {
        println!("No, not on linux!");
    }
}

Code Challenge

Try to modify the code provided in the editor to play with cfg attribute.

Loading...
> code result goes here
Prev
Next