liveBook · Manning

Outer attribute

As explained in Learn Rust in a Month of Lunches

An outer attribute is a Rust attribute written with # that applies to the item immediately following it.

An outer attribute is written with # and applies to the Rust item immediately following it. Attributes let the compiler, derive system, or tools interpret extra instructions. section 13.1.5

Reading the hash marks

Write #[...] before an item to affect that item. For example, #[derive(Debug)] can request a derived trait implementation, while #[deprecated] marks a function for warning-producing use. By contrast, #![...] is an inner attribute: it affects the enclosing file or module and normally belongs at the very top. section 13.1.5

Common outer-attribute patterns include:

  • Use #[derive(...)] to request derived traits such as Debug, Clone, or PartialEq. section 13.1.5
  • Use #[deprecated] to make later calls produce a deprecation warning; add note = "..." to explain the replacement. section 13.1.5
error: an inner attribute is not permitted in this context
 --> src/lib.rs:3:1
  |
3 | #![allow(dead_code)]
  | ^^^^^^^^^^^^^^^^^^^^
  |
  = note: inner attributes, like `#![no_std]`, annotate the item enclosing
  them, and are usually found at the beginning of source files
  = note: outer attributes, like `#[test]`, annotate the item following them

Compiler feedback contrasts outer attributes, which annotate the following item, with misplaced inner attributes. section 13.1.5

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines placement and demonstrates derivation, lint suppression, deprecation, and diagnostics without explaining attribute creation.
Examples
Uses derive, deprecated functions, unused-code allowances, and diagnostics contrasting outer and inner placement.
What you can do after
Apply outer attributes to derive traits, control warnings, and mark functions as deprecated.
How it connects
Connects attributes with compiler warnings, derive macros, traits, tools, and inner attributes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.