liveBook · Manning

Macro

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

A macro is a code-generation construct that expands source syntax into program code rather than directly returning a runtime value.

A macro is a code-generation construct marked with !. Unlike a function, which returns data at runtime, a macro expands into program code and helps remove repetitive boilerplate. section 1.3.2 section 1.5

Rust's printing macros demonstrate several useful ideas:

  • println! writes formatted output to standard output, while eprintln! writes to standard error. section 1.5
  • Their first string literal can contain a formatting mini-language: {} uses a programmer-defined representation, while {:?} requests a default representation. section 1.5
  • The macro handles type detection for arbitrary values, hiding repetitive implementation work behind a compact call. section 1.3.2

Printing several greetings

A greeting function can call println!("Hello, world!") and then iterate over stored German and Japanese greetings, passing each value to println!("{}", &region). Running the program prints all three messages, including their Unicode characters. section 1.3.2

Listing 1.1 “Hello World!” in three languages
 fn greet_world() {
     println!("Hello, world!");                   #1
     let southern_germany = "Grüß Gott!";         #2
     let japan = "ハロー・ワールド";                    #3
     let regions = [southern_germany, japan];     #4
     for region in regions.iter() {               #5
             println!("{}", &region);             #6
     }
 }
 
 fn main() {
     greet_world();                               #7
 }

Inspect the complete greeting program to see macro calls embedded in an ordinary function and loop. section 1.3.2

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

How deep it goes
Defines macros by contrasting them with functions and sketches type detection, but defers detailed expansion mechanics.
Examples
Uses println!, eprintln!, formatted placeholders, and a multilingual greeting program as concrete examples.
What you can do after
Apply it via println! and eprintln! to generate formatted console-output code without writing type-specific boilerplate.
How it connects
Connects macros with functions, formatted strings, type detection, standard output, and standard error.

Also explained in

Compare how 9 books explain macro →

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.