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.

An inner attribute is a metadata directive that applies to the enclosing lexical scope or Abstract Syntax Tree (AST) node in which it is declared, rather than the item immediately following it. It is syntactically distinguished by an exclamation mark (!) placed between the hash symbol (#) and the opening bracket ([).

Syntax

Inner attributes follow the same structural forms as outer attributes—simple, key-value, or list—but utilize the #![...] token sequence.
// Simple inner attribute
#![no_std]

// Key-value inner attribute
#![crate_type = "lib"]

// List inner attribute
#![allow(dead_code, unused_variables)]

Placement and Parsing Rules

Because an inner attribute modifies the scope that contains it, the Rust compiler enforces strict parsing rules regarding its placement:
  1. Valid Scopes: Inner attributes are permitted at the crate root (e.g., main.rs or lib.rs), and inside modules, function or expression blocks, impl blocks, and extern blocks (foreign modules).
  2. Top of Scope: They must appear at the very beginning of their enclosing scope. They can only be preceded by comments, whitespace, or other inner attributes.
  3. Invalidation: If an inner attribute is placed after any standard item declaration (such as a fn, struct, or use item) or after any statement (such as a let binding or an expression statement) within the same scope, the compiler will emit a syntax error (an inner attribute is not permitted in this context).

AST Mechanics: Inner vs. Outer

The distinction between inner and outer attributes is purely mechanical in how the compiler constructs the AST. In the Rust AST, attributes are not standalone sibling nodes; they are parsed as properties (specifically, the attrs field) of an AST node.
  • Inner Attribute (#![...]): Appended to the attrs field of the AST node representing the enclosing scope (the parent node).
  • Outer Attribute (#[...]): Appended to the attrs field of the AST node representing the item immediately following the attribute.
// Example 1: Inner Attribute
// The attribute is parsed into the `attrs` field of the `parent_scope` module node.
mod parent_scope {
    #![allow(dead_code)] 
    
    fn child_item() {}
}

// Example 2: Outer Attribute
// The attribute is parsed into the `attrs` field of the `child_item` function node.
mod parent_scope {
    #[allow(dead_code)]
    fn child_item() {}
}

Block-Level Application

Inner attributes can be applied to arbitrary expression blocks and function bodies. The attribute modifies the AST node of the block expression itself.
fn example() {
    let x = {
        #![allow(clippy::let_and_return)]
        let y = 42;
        y
    };
}
Master Rust with Deep Grasping Methodology!Learn More