liveBook · Manning

Attribute

As explained in Rust in Action: Systems programming concepts and techniques

An attribute is Rust syntax that attaches metadata to a program item and can control compiler behavior such as conditional inclusion.

An attribute attaches metadata to a Rust item and can influence compiler behavior. Attributes can relax warnings, prescribe an enum’s representation, or enable platform-specific compilation. section 3.1 section 7.8 section 11.5.2

Attributes shown here control different parts of compilation:

  • `#![allow(unused_variables)]` relaxes an unused-variable warning; `#[allow(dead_code)]` applies warning suppression to a function. section 3.1
  • The `cfg` attribute compiles platform-specific code. The `repr` attribute can prescribe an enum’s integer representation, trading flexibility and space optimizations for control. section 7.8 section 11.5.2
Listing 3.1 Using type aliases to stub out a type
 #![allow(unused_variables)]              #1
 
 type File = String;                      #2
 
 fn open(f: &mut File) -> bool {
     true                                 #3
 
 fn close(f: &mut File) -> bool {
     true                                 #3
 }
 
 #[allow(dead_code)]                      #4
 fn read(f: &mut File,
         save_to: &mut Vec<u8>) -> ! {    #5
     unimplemented!()                     #6
 }
 
 fn main() {
     let mut f1 = File::from("f1.txt");   #7
     open(&mut f1);
     //read(f1, vec![]);                  #8
     close(&mut f1);
 }

See warning-suppression attributes used in a small file-handling stub. section 3.1

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Demonstrates warning suppression, conditional compilation, and fixed enum representations, including flexibility and optimization tradeoffs.
Examples
Uses unused-variable and dead-code warning allowances, platform-specific compilation, and a VGA palette enum represented by `u8`.
What you can do after
Configure warning handling, platform-specific code, and enum representation with Rust attributes.
How it connects
Connects attributes to compiler warnings, conditional compilation, and enum representation.

Also explained in

Compare how 26 books explain attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.