liveBook · Manning

Chapter 22: Writing your own macros

What you will learn in chapter 22 of Learn Rust in a Month of Lunches

The introduction explains why writing macros can be useful while warning that their unfamiliar syntax takes practice.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction explains why writing macros can be useful while warning that their unfamiliar syntax takes practice.

Key terms: macros, syntax

22.1 Why macros exist

This section explains why Rust macros are useful for generating code that ordinary functions cannot produce.

Key terms: macro, compiler, regular function, structs

22.2 Writing basic macros

This section shows how to define basic Rust macros that match tokens, capture different kinds of input, and handle repeated inputs.

Key terms: macro_rules!, token parser, token, match statement, no rules expected the token, $input:expr, fragment specifiers, expr, stmt, ident

22.3 Reading macros from the standard library

The section reads standard-library macros to show how their input patterns, recursive calls, and optional syntax explain what the macros accept and do.

Key terms: write!, $dst, $($arg:tt)*, write_fmt, format_args!, todo!, panic!, token trees, macro arms, my_macro!

22.4 Using macros to keep your code clean

Shows how a macro can remove repeated code for String-holding types, while cautioning when writing a macro is worthwhile.

Key terms: macro, TryFrom, String, type name, length, simple function, repetitive code

22.5 Summary

Concepts explained in this chapter

← Chapter 21: Continuing the tour Chapter 23: Unfinished projects: Projects for you to finish →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.