Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The warn attribute is a built-in compiler directive that modifies the diagnostic lint level for specific Abstract Syntax Tree (AST) nodes. It instructs the Rust compiler (rustc) to emit a non-fatal diagnostic warning when a specified lint or lint group rule is violated, allowing the compilation process to complete successfully while flagging the violation in the standard error output.

Syntax

The attribute accepts a comma-separated list of lint identifiers or lint groups. It can be applied as an outer attribute (applying to the item it precedes) or an inner attribute (applying to the enclosing scope).
// Inner attribute: Applies to the enclosing scope (e.g., the entire crate or module)
#![warn(lint_identifier)]
#![warn(lint_group_a, lint_group_b)]
#![warn(tool_name::lint_identifier)]

// Outer attribute: Applies to the specific item it precedes (e.g., a struct, function, or trait)
#[warn(lint_identifier)]

Mechanics and Resolution

Lexical Scoping The warn attribute applies lexically. When attached to an item, it affects that item and all of its descendant AST nodes, unless explicitly overridden by another lint level attribute deeper in the hierarchy. Lint Level Hierarchy Rust utilizes four primary lint levels: allow, warn, deny, and forbid. The compiler resolves the active lint level based on the most specific (closest) attribute to the code triggering the lint.
  • warn will override a broader allow attribute.
  • warn will override a broader deny attribute, downgrading the compiler error to a warning for that specific scope.
  • warn cannot override a forbid attribute. If a lint is marked as forbid higher in the AST, applying #[warn] to a descendant node will trigger a compilation error.
Tool-Specific Lints The warn attribute can target lints from external tools (like Clippy or Rustdoc) by using path syntax. The compiler will ignore tool-specific lints if the corresponding tool is not currently executing, preventing compilation failures in standard cargo build environments.

Syntax Visualization

The following example demonstrates how warn interacts with lexical scoping and overrides:
// Sets the baseline lint level for the entire module to 'allow'
#![allow(unused_variables)]

// Overrides the module-level 'allow' with 'warn' for this specific function
#[warn(unused_variables)]
fn compute_value() {
    let unused_local = 42; // rustc emits a warning: unused variable
    
    // Overrides the function-level 'warn' back to 'allow' for this specific block
    #[allow(unused_variables)]
    {
        let another_unused = 10; // rustc emits no diagnostic
    }
}
Master Rust with Deep Grasping Methodology!Learn More