Rust Attributes for conditional compilation, crate, lints, mark functions, macros

CK CK 3788 
Created at  
318 0 0

An attribute is metadata applied to some module, crate or item. This metadata can be used to/for:

  • conditional compilation of code
  • set crate name, version and type (binary or library)
  • disable lints (warnings)
  • enable compiler features (macros, glob imports, etc.)
  • link to a foreign library
  • mark functions as unit tests
  • mark functions that will be part of a benchmark
  • attribute like macros

Attributes look like #[outer_attribute] or #![inner_attribute], with the difference between them being where they apply.

  • #[outer_attribute] applies to the item immediately following it. Some examples of items are: a function, a module declaration, a constant, a structure, an enum. Here is an example where attribute #[derive(Debug)] applies to the struct Rectangle:

    #[derive(Debug)]
    struct Rectangle {
        width: u32,
        height: u32,
    }
  • #![inner_attribute] applies to the enclosing item (typically a module or a crate). In other words, this attribute is interpreted as applying to the entire scope in which it's placed. Here is an example where #![allow(unused_variables)] applies to the whole crate (if placed in main.rs):

    #![allow(unused_variables)]
    
    fn main() {
        let x = 3; // This would normally warn about an unused variable.
    }

Attributes can take arguments with different syntaxes:

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

Attributes can have multiple values and can be separated over multiple lines, too:

#[attribute(value, value2)]


#[attribute(value, value2, value3,
            value4, value5)]


dead_code

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

fn used_function() {}

// `#[allow(dead_code)]` is an attribute that disables the `dead_code` lint
#[allow(dead_code)]
fn unused_function() {}

fn noisy_unused_function() {}
// FIXME ^ Add an attribute to suppress the warning

fn main() {
    used_function();
}

Note that in real programs, you should eliminate dead code. In these examples we'll allow dead code in some places because of the interactive nature of the examples.


Crates

The crate_type attribute can be used to tell the compiler whether a crate is a binary or a library (and even which type of library), and the crate_name attribute can be used to set the name of the crate.

However, it is important to note that both the crate_type and crate_name attributes have no effect whatsoever when using Cargo, the Rust package manager. Since Cargo is used for the majority of Rust projects, this means real-world uses of crate_type and crate_name are relatively limited.

// This crate is a library
#![crate_type = "lib"]
// The library is named "rary"
#![crate_name = "rary"]

pub fn public_function() {
    println!("called rary's `public_function()`");
}

fn private_function() {
    println!("called rary's `private_function()`");
}

pub fn indirect_access() {
    print!("called rary's `indirect_access()`, that\n> ");

    private_function();
}

When the crate_type attribute is used, we no longer need to pass the --crate-type flag to rustc.

$ rustc lib.rs
$ ls lib*
library.rlib

 

cfg

Configuration conditional checks are possible through two different operators:

  • the cfg attribute: #[cfg(...)] in attribute position
  • the cfg! macro: cfg!(...) in boolean expressions

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

cfg!, unlike #[cfg], does not remove any code and only evaluates to true or false. For example, all blocks in an if/else expression need to be valid when cfg! is used for the condition, regardless of what cfg! is evaluating.

// This function only gets compiled if the target OS is linux
#[cfg(target_os = "linux")]
fn are_you_on_linux() {
    println!("You are running linux!");
}

// And this function only gets compiled if the target OS is *not* linux
#[cfg(not(target_os = "linux"))]
fn are_you_on_linux() {
    println!("You are *not* running linux!");
}

fn main() {
    are_you_on_linux();

    println!("Are you sure?");
    if cfg!(target_os = "linux") {
        println!("Yes. It's definitely linux!");
    } else {
        println!("Yes. It's definitely *not* linux!");
    }
}

 

Custom

Some conditionals like target_os are implicitly provided by rustc, but custom conditionals must be passed to rustc using the --cfg flag.

#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!");
}

fn main() {
    conditional_function();
}

 

Try to run this to see what happens without the custom cfg flag.

With the custom cfg flag:

$ rustc --cfg some_condition custom.rs && ./custom
condition met!
Tags Mark Functions Rust Attributes Rust Macros Rust Mark Functions crate dead_code Facebook X
Comments 0
Similar posts
  1. Rust compilation unit - Crates
    254
  1. Multi-threaded HLS Server in Rust
    772
  2. Run a specific module in a external file with Rust
    570
  3. Question(?) Operator in Rust
    572
  4. Rust code example to access MySQL
    1,100
  5. Rust Documentation
    315
  6. Rust Compatibility
    724
  7. Rust Unsafe Operations
    368
  8. Rust Testing
    1,245
  9. Rust Std misc
    375
  10. Rust Std library types
    370
  11. Rust Error Handling
    349
  12. Rust Macro Rules
    1,523
  13. Rust mechanism for defining shared behavior across different types - Traits
    1,772
  14. Rust Scoping Rules - only accessible within the block of code
    1,073
  15. Rust Generics - Generalizing types and functionalities
    1,356
  16. Rust Package Management Tool - cargo
    307
  17. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,908
  18. Rust functions - Methods, Closures, Capturing
    1,210
  19. Rust Flow of Control - if/else, loop. while, for and range, match, if let, let-else, while let
    339
  20. Rust Expressions
    933
  21. Rust Conversion - From, Into, TryFrom, TryInto
    1,321
  22. gRPC library for Rust
    345
  23. Rust Data Type Operations - Casting, Literals, Inference, Aliasing
    326
  24. Variable Bindings in Rust
    975
  25. Rust Custom Data Types - struct, enum, use, constants
    299
  26. Arrays and Slices in Rust
    341
  27. Tuples in Rust - a collection of values of different types
    298
  28. Literals and operators in Rust
    300
  29. Rust Data Type - What is mutable?
    256
  30. Rust Code Testing Environment without installing anything on your computer
    327
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    29
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    55
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    49
  4. How do I create animated background for Google Meet?
    22,890
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    271
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    103
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    168
  8. Array of arguments passed to script in PHP
    97
  9. Invalid Auction Storms in Ad Tech
    106
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    207
  11. The Two Clocks of Ad Server Architecture
    77
  12. Frequency Cap Architecture Overview
    526
  13. Collecting Proof-of-Play from 100,000 Screens
    152
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    302
  15. What is RedisVL?
    114
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    246
  17. TPU & GPU Cluster Management Tools
    257
  18. The Concept of Scaffolding in AI Agents
    244
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    596
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    267
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    353
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    206
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    202
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    671
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    200
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    232