CourseLesson 16 · Macros and Advanced TraitsSolve

Lesson 16

Macros and Advanced Traits

This lesson covers two more ways to write code once and reuse it in many places. A macro writes Rust code for you, from a pattern, before the program is compiled. Two trait features, an associated type and operator overloading, let a trait describe a piece of your own code closely enough that ordinary operators such as + and the for loop work on your own types.

Declarative Macros with macro_rules!

A macro looks like a function call with a ! after its name, but it runs while the program is being compiled, not while it runs. Calling a macro pastes in the Rust code it produces, which is then compiled as if you had written it yourself. You have already called macros throughout this course: println!, vec!, and format! are all macros, not functions.

macro_rules! greet {
    () => {
        println!("hello from a macro");
    };
}

fn main() {
    greet!();
}
hello from a macro

macro_rules! defines a new macro. () is the pattern this rule matches, here nothing at all, and everything inside the => { ... } is the code greet!() is replaced with. A macro can also take arguments, matched by a pattern with a name and a fragment kind telling the compiler what sort of Rust it is.

macro_rules! square {
    ($x:expr) => {
        $x * $x
    };
}

fn main() {
    println!("{}", square!(5));
}
25

$x:expr matches one Rust expression and binds it to $x. Every place $x appears on the right of => is replaced with whatever expression was passed in, so square!(5) becomes 5 * 5. expr is the most common fragment kind; others match a type, a pattern, or a whole block, among other pieces of Rust syntax.

Matching More Than One Pattern

A macro can have more than one rule, tried in order, the same way a match expression tries each arm in order.

macro_rules! biggest {
    ($x:expr) => {
        $x
    };
    ($x:expr, $y:expr) => {
        if $x > $y { $x } else { $y }
    };
}

fn main() {
    println!("{}", biggest!(5));
    println!("{}", biggest!(3, 9));
}
5
9

biggest!(5) matches the first rule, one argument, and is replaced with just 5. biggest!(3, 9) does not match the first rule, since it has two arguments separated by a comma, so the second rule is tried instead.

Repetition in a Macro

$( ... )* repeats a piece of the pattern, and the matching piece of the replacement, once for every value it matches.

macro_rules! sum {
    ($($x:expr),*) => {{
        let mut total = 0;
        $(total += $x;)*
        total
    }};
}

fn main() {
    println!("{}", sum!(1, 2, 3, 4));
}
10
  • $($x:expr),* matches any number of expressions separated by commas, the same shape as the arguments to vec!.

  • $(total += $x;)* repeats total += $x; once for every expression that was matched, in order, so sum!(1, 2, 3, 4) expands to four total += ...; lines in a row.

  • The replacement is wrapped in an extra pair of braces, {{ ... }}, so that total is a variable local to this one expansion and the whole thing is a single block expression producing a value, not four loose statements.

A Brief Look at Procedural Macros

#[derive(Debug)], written above a struct or enum, is a macro too, of a different kind. A procedural macro is not written as a pattern with macro_rules!. It is an ordinary Rust function, compiled and run separately, that reads the syntax of the item it is attached to and writes out new Rust code for it, such as an implementation of Debug built to match your struct’s exact fields.

Key idea

Writing your own procedural macro needs its own crate, marked proc-macro = true in Cargo.toml, and is well beyond this course. What matters here is recognising one: any macro written as an attribute above an item, such as #[derive(...)], is a procedural macro doing the same kind of work as macro_rules!, only with the full power of a Rust program instead of a pattern.

Associated Types

A trait can declare an associated type, a placeholder type that every implementation fills in with one specific type of its own choosing.

trait Container {
    type Item;
    fn get(&self, index: usize) -> Option<&Self::Item>;
}

struct Playlist {
    songs: Vec<String>,
}

impl Container for Playlist {
    type Item = String;

    fn get(&self, index: usize) -> Option<&String> {
        self.songs.get(index)
    }
}
  • type Item; inside the trait declares that every Container has an associated type called Item, without saying what it is yet.

  • type Item = String; inside the impl fills it in. Self::Item anywhere else in the trait, such as in get’s return type, now means String for this particular implementation.

The most common associated type you will meet is Item on the Iterator trait, which is what a for loop actually calls.

struct Countdown {
    current: i32,
}

impl Iterator for Countdown {
    type Item = i32;

    fn next(&mut self) -> Option<i32> {
        if self.current == 0 {
            None
        } else {
            self.current -= 1;
            Some(self.current + 1)
        }
    }
}

fn main() {
    let countdown = Countdown { current: 3 };
    for n in countdown {
        println!("{n}");
    }
}
3
2
1

Implementing Iterator for Countdown is what makes for n in countdown valid at all. The loop calls next() repeatedly, prints the value inside each Some it gets back, and stops the moment next() returns None.

Associated Types Compared with Generic Parameters

A trait can also take a type as an ordinary generic parameter instead of an associated type. The difference only shows up once a type implements the trait more than once.

trait Converts<T> {
    fn convert(&self) -> T;
}

struct Wrapper(i32);

impl Converts<i32> for Wrapper {
    fn convert(&self) -> i32 {
        self.0
    }
}

impl Converts<String> for Wrapper {
    fn convert(&self) -> String {
        self.0.to_string()
    }
}

fn main() {
    let w = Wrapper(5);
    let a: i32 = w.convert();
    let b: String = w.convert();
    println!("{a} {b}");
}
5 5

Converts<i32> and Converts<String> are different traits as far as the compiler is concerned, since T is part of the trait itself, so Wrapper is allowed to implement both. Write the same idea with an associated type instead, and the second impl is refused.

trait Converts {
    type Output;
    fn convert(&self) -> Self::Output;
}

struct Wrapper(i32);

impl Converts for Wrapper {
    type Output = i32;
    fn convert(&self) -> i32 {
        self.0
    }
}

impl Converts for Wrapper {
    type Output = String;
    fn convert(&self) -> String {
        self.0.to_string()
    }
}
error[E0119]: conflicting implementations of trait
              `Converts` for type `Wrapper`
  --> src/main.rs:15:1
   |
 8 | impl Converts for Wrapper {
   | ------------------------- first implementation
   |                            here
...
15 | impl Converts for Wrapper {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting
   |                           implementation for `Wrapper`

Key idea

Reach for a generic parameter, Trait<T>, when a type might reasonably implement the trait more than once, once per T. Reach for an associated type when a type has exactly one sensible choice, such as Countdown always iterating i32, and you want callers to write Countdown instead of naming the item type every time.

Operator Overloading

Writing a + b on your own type is not built into the language for every type. It works because i32, String, and the other types that support + all implement std::ops::Add, a trait like any other. Implementing it for your own type makes + work on that type too.

use std::ops::Add;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 3, y: 4 };
    println!("{:?}", a + b);
}
Point { x: 4, y: 6 }
  • Add has its own associated type, Output, set here to Point: the type a + b produces.

  • fn add(self, other: Point) -> Point is the method the compiler calls whenever it sees + between two Point values. a + b is shorthand for a.add(b).

  • The comparison operators work the same way, through PartialOrd and PartialEq instead of Add. Sub, Mul, and the other arithmetic operators each follow this same pattern, one trait per operator, in std::ops.

Leaving Output out is refused, the same as leaving out any other required item of a trait.

use std::ops::Add;

struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}
error[E0046]: not all trait items implemented, missing:
              `Output`
 --> src/main.rs:7:1
  |
7 | impl Add for Point {
  | ^^^^^^^^^^^^^^^^^^ missing `Output` in
  |                    implementation
  |
  = help: implement the missing item:
    `type Output = /* Type */;`

Common Mistakes

Reaching for a Macro Where a Function Would Do

A macro is harder to read than a function: its arguments are pieces of syntax, not values, and nothing about it shows up when you look at a type’s methods. Write a function first. Reach for macro_rules! only once you need something a function cannot do, such as taking a different number of arguments the way sum! does, or accepting syntax that is not a plain value.

Forgetting an Associated Type in an impl

Iterator needs Item. Add needs Output. Every trait with an associated type refuses an impl that does not fill it in, the same as a missing method, with an error naming exactly which one is missing. Add the line it suggests before looking for any other problem.

Expecting to Implement an Associated-Type Trait Twice

Wanting a type to convert to more than one other type, or iterate more than one way, is a sign that a generic parameter, Trait<T>, is what the type needs, not an associated type. An associated-type trait can only be implemented once per type, on purpose.

Reference

Written asWhat it does
macro_rules! m { … }Defines a macro named m.
$x:exprMatches one expression, binds it to $x.
$(…),*Matches zero or more, separated by commas.
$(…)*Repeats the piece inside once per match above.
#[derive(…)]A procedural macro, generating code from a type’s shape.
type Item;Declares an associated type inside a trait.
type Item = T;Fills in an associated type inside an impl.
Self::ItemThe associated type, used elsewhere in the trait.
Trait<T>A generic trait, implementable once per T.
std::ops::AddImplement to make + work on your own type.

Check what stuck

The practice sheet for this lesson has 42 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →