18 / 35

Rust for the Web· 9 min read· Lesson 18 of 35

Macros and Attributes

Part 1 · Rust. Understand what println!, vec! and #[derive] really are, learn the three kinds of macros, and read #[...] lines with confidence.

You have typed println! since your very first program and #[derive(Debug)] since structs. They look odd: why the !, why the #? This lesson lifts the curtain. Once you understand macros, the code in Laravel Rust (which uses them heavily) will read like plain English.

What is a macro?

A macro is code that writes code. Think of a stamp: you press it once and it prints a whole pre-made pattern. You write a short line, and Rust expands it into the longer code before compiling.

You can tell a function from a macro by the !:

fn main() {
let drinks = vec!["Latte", "Mocha"]; // macro
println!("We sell {} drinks", drinks.len()); // macro
let n = drinks.len(); // plain method call
}

vec! builds a vector, println! prints formatted text. Why are they macros and not functions? A normal function takes a fixed number of inputs. println!("{} {}", a, b) takes any number, and vec![...] takes any number of items. Macros can do that.

Writing a tiny macro

You rarely need to write your own, but seeing one helps:

src/main.rs
macro_rules! cents {
($dollars:expr, $cents:expr) => {
$dollars * 100 + $cents
};
}
fn main() {
let price: u32 = cents!(3, 50);
println!("{}", price);
}
Output
350
  1. macro_rules! cents defines a macro called cents.
  2. The part in parentheses is the pattern it matches: two expressions.
  3. The part after => is what it expands to. cents!(3, 50) becomes 3 * 100 + 50.

Note

You do not need to master macro_rules! yet. The goal is to see that macros are pattern-based code generators, not magic.

The three kinds of macros

1. Function-like macros

These look like function calls with a !: println!(...), vec![...], format!(...), panic!(...), assert_eq!(...). You can use (), [] or {} after the !; vec![] just reads best with square brackets.

Laravel Rust uses these for things that are checked when your program compiles:

  • route!(posts::show, &post) builds a URL for a handler, so a renamed route becomes a compile error, not a broken link.
  • db::query! writes raw SQL and lets you capture Rust variables inside braces; the macro turns each one into a safe bound query parameter at compile time.
  • task::try_join! runs several async jobs together (we meet its cousin tokio::join! in the next lesson).

2. Derive macros

These attach to a struct or enum and generate trait code for it. You write them as #[derive(...)]:

#[derive(Debug, Clone, PartialEq)]
struct MenuItem {
name: String,
price_cents: u32,
}

Each name in the list produces a ready-made impl block for that trait. You met this in the traits lesson. In Laravel Rust, a job struct derives Queueable and a mail struct derives Mailable. The shape is identical, only the name differs.

3. Attribute macros

These sit above an item and transform it. They are written #[name] or #[name(options)]:

#[tokio::main]
async fn main() {
// ...
}

#[tokio::main] rewrites your async fn main into a normal main that starts an async runtime. You will use it in the next lesson.

Laravel Rust’s headline features are attribute macros. From the launch announcement you will see names like:

  • #[model] on a struct, which turns it into a database model (relations use field attributes like #[belongs_to] and #[has_many]).
  • #[job] on an impl block containing an async fn handle, which makes a queued job (the struct itself also has #[derive(Queueable)]).
  • #[laravel::input] on a struct, marking it as a typed request input for a form or JSON payload.
  • #[validate(...)] on a field, adding rules such as required or max_length(255).

You will build with these later. For now, the point is that you can read them: “this attribute changes how the item beneath it behaves.”

Reading #[…] with confidence

Here is a decoder. Whenever you see #[...], ask three questions:

  1. Is it derive? Then it lists traits to generate for the item below.
  2. Does it have a path with ::, like tokio::main? It is an attribute macro from a crate (tokio, laravel, serde…). The part before :: tells you which crate to look up on docs.rs.
  3. Is it a plain word, like test or allow? It is a built-in attribute that tells the compiler something.
#[derive(Debug)] // derive: generate Debug
#[allow(dead_code)] // built-in: silence "unused" warnings
struct Draft {
#[allow(unused)] // an attribute can sit on a field too
note: String,
}
#[test] // built-in: this function is a test
fn menu_is_not_empty() {
assert!(!vec!["Latte"].is_empty());
}

Attributes can also carry options in parentheses, like #[validate(required, max_length(255))] or serde’s #[serde(rename = "price")]. The options are specific to each macro, so the docs of that crate explain them.

Note

#![...] with an exclamation mark after the # applies to the whole file or crate rather than to the next item. For example, #![allow(unused)] at the top of a file.

Seeing what a macro does

A macro’s output is ordinary Rust. When something confuses you, you can ask Cargo to show it using the community tool cargo-expand:

Terminal window
cargo install cargo-expand
cargo expand

It prints your code after every macro has been replaced. It is a fantastic way to learn, though you do not need it to start.

Your first test

Rust has testing built in, and it is driven by attributes. Put tests in a module marked #[cfg(test)] (compile this only when testing), and mark each test function with #[test]:

src/main.rs
fn total_cents(prices: &[u32]) -> u32 {
prices.iter().sum()
}
fn main() {
println!("Total: {} cents", total_cents(&[450, 325]));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_up_an_order() {
assert_eq!(total_cents(&[450, 325]), 775);
}
#[test]
fn empty_order_is_free() {
assert_eq!(total_cents(&[]), 0);
}
}

Run the tests with:

Terminal window
cargo test
Output
running 2 tests
test tests::adds_up_an_order ... ok
test tests::empty_order_is_free ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  1. #[cfg(test)] keeps the tests module out of your normal build.
  2. use super::*; brings the parent module’s names (like total_cents) into the test module.
  3. #[test] marks a function as a test; cargo test runs each one.
  4. assert_eq!(left, right) checks the two values are equal and fails the test, showing both values, if they are not.

(Cargo also prints a few lines about compiling and which binary it runs; they are trimmed here.)

Common mistakes

Warning

Forgetting the ! is the classic slip: println("hi") fails with cannot find function `println` in this scope, and the compiler helpfully adds “a macro named println exists in another namespace” and “use ! to invoke the macro”. Likewise vec alone is not a thing; you need vec!.

Tip

Errors inside macros can look strange because they point at the macro call. Read the message itself first. It usually names the real problem, such as a missing trait or a wrong argument count.

A peek ahead: why Laravel Rust loves macros

Because macros run at compile time, they can check things before your café ever opens: that a column name exists, that a route is real, that a validated input has the right rules. Laravel’s announcement highlights these compile-time checks. Macros are the tool that makes that possible, while the code you write stays short.

Try it yourself

  1. Write a macro_rules! named dollars that takes one expression and expands to $x * 100. Print dollars!(4).
  2. Look at this line and explain, in your own words, what each part does: #[derive(Debug, Clone)] above struct Order.
Show solution
macro_rules! dollars {
($x:expr) => {
$x * 100
};
}
fn main() {
println!("{}", dollars!(4));
}
Output
400

For the second: # and the square brackets mark an attribute; derive is the built-in macro that generates code; Debug makes Order printable with {:?}, and Clone gives it a .clone() method.

Recap

  • A macro is code that writes code; the ! tells you a call is a macro.
  • Function-like macros (println!, vec!) look like calls.
  • Derive macros generate trait implementations.
  • Attribute macros (#[tokio::main]) transform the item below them.
  • Reading #[...]: derive, crate-path attribute, or built-in.
  • Laravel Rust leans on all three kinds, so reading them now pays off later.

What’s next

The last piece of the bridge is async Rust, the way web servers handle many customers at once. Continue to Async, Await and Tokio.

0 of 35 lessons complete

Search lessons

Type to search all lessons.