719 lines
53 KiB
HTML
719 lines
53 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en" class="light sidebar-visible" dir="ltr">
|
||
<head>
|
||
<!-- Book generated using mdBook -->
|
||
<meta charset="UTF-8">
|
||
<title>Macros - The Rust Programming Language</title>
|
||
|
||
|
||
<!-- Custom HTML head -->
|
||
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<meta name="theme-color" content="#ffffff">
|
||
|
||
<link rel="icon" href="favicon-de23e50b.svg">
|
||
<link rel="shortcut icon" href="favicon-8114d1fc.png">
|
||
<link rel="stylesheet" href="css/variables-8adf115d.css">
|
||
<link rel="stylesheet" href="css/general-0392ca55.css">
|
||
<link rel="stylesheet" href="css/chrome-fc474251.css">
|
||
<link rel="stylesheet" href="css/print-9e4910d8.css" media="print">
|
||
|
||
<!-- Fonts -->
|
||
<link rel="stylesheet" href="fonts/fonts-9644e21d.css">
|
||
|
||
<!-- Highlight.js Stylesheets -->
|
||
<link rel="stylesheet" id="mdbook-highlight-css" href="highlight-493f70e1.css">
|
||
<link rel="stylesheet" id="mdbook-tomorrow-night-css" href="tomorrow-night-4c0ae647.css">
|
||
<link rel="stylesheet" id="mdbook-ayu-highlight-css" href="ayu-highlight-3fdfc3ac.css">
|
||
|
||
<!-- Custom theme stylesheets -->
|
||
<link rel="stylesheet" href="ferris-d33b75bf.css">
|
||
<link rel="stylesheet" href="theme/2018-edition-4e126c62.css">
|
||
<link rel="stylesheet" href="theme/semantic-notes-9b5766c0.css">
|
||
<link rel="stylesheet" href="theme/listing-cab26221.css">
|
||
|
||
|
||
<!-- Provide site root and default themes to javascript -->
|
||
<script>
|
||
const path_to_root = "";
|
||
const default_light_theme = "light";
|
||
const default_dark_theme = "navy";
|
||
window.path_to_searchindex_js = "searchindex-6a1da8cc.js";
|
||
</script>
|
||
<!-- Start loading toc.js asap -->
|
||
<script src="toc-0e4ce700.js"></script>
|
||
</head>
|
||
<body>
|
||
<div id="mdbook-help-container">
|
||
<div id="mdbook-help-popup">
|
||
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
|
||
<div>
|
||
<p>Press <kbd>←</kbd> or <kbd>→</kbd> to navigate between chapters</p>
|
||
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
|
||
<p>Press <kbd>?</kbd> to show this help</p>
|
||
<p>Press <kbd>Esc</kbd> to hide this help</p>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div id="mdbook-body-container">
|
||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||
<script>
|
||
try {
|
||
let theme = localStorage.getItem('mdbook-theme');
|
||
let sidebar = localStorage.getItem('mdbook-sidebar');
|
||
|
||
if (theme.startsWith('"') && theme.endsWith('"')) {
|
||
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
||
}
|
||
|
||
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
||
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
||
}
|
||
} catch (e) { }
|
||
</script>
|
||
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script>
|
||
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
|
||
let theme;
|
||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||
if (theme === null || theme === undefined) { theme = default_theme; }
|
||
const html = document.documentElement;
|
||
html.classList.remove('light')
|
||
html.classList.add(theme);
|
||
html.classList.add("js");
|
||
</script>
|
||
|
||
<input type="checkbox" id="mdbook-sidebar-toggle-anchor" class="hidden">
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script>
|
||
let sidebar = null;
|
||
const sidebar_toggle = document.getElementById("mdbook-sidebar-toggle-anchor");
|
||
if (document.body.clientWidth >= 1080) {
|
||
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
||
sidebar = sidebar || 'visible';
|
||
} else {
|
||
sidebar = 'hidden';
|
||
sidebar_toggle.checked = false;
|
||
}
|
||
if (sidebar === 'visible') {
|
||
sidebar_toggle.checked = true;
|
||
} else {
|
||
html.classList.remove('sidebar-visible');
|
||
}
|
||
</script>
|
||
|
||
<nav id="mdbook-sidebar" class="sidebar" aria-label="Table of contents">
|
||
<!-- populated by js -->
|
||
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
|
||
<noscript>
|
||
<iframe class="sidebar-iframe-outer" src="toc.html"></iframe>
|
||
</noscript>
|
||
<div id="mdbook-sidebar-resize-handle" class="sidebar-resize-handle">
|
||
<div class="sidebar-resize-indicator"></div>
|
||
</div>
|
||
</nav>
|
||
|
||
<div id="mdbook-page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="mdbook-menu-bar-hover-placeholder"></div>
|
||
<div id="mdbook-menu-bar" class="menu-bar sticky">
|
||
<div class="left-buttons">
|
||
<label id="mdbook-sidebar-toggle" class="icon-button" for="mdbook-sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="mdbook-sidebar">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M0 96C0 78.3 14.3 64 32 64H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 128 0 113.7 0 96zM0 256c0-17.7 14.3-32 32-32H416c17.7 0 32 14.3 32 32s-14.3 32-32 32H32c-17.7 0-32-14.3-32-32zM448 416c0 17.7-14.3 32-32 32H32c-17.7 0-32-14.3-32-32s14.3-32 32-32H416c17.7 0 32 14.3 32 32z"/></svg></span>
|
||
</label>
|
||
<button id="mdbook-theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="mdbook-theme-list">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M371.3 367.1c27.3-3.9 51.9-19.4 67.2-42.9L600.2 74.1c12.6-19.5 9.4-45.3-7.6-61.2S549.7-4.4 531.1 9.6L294.4 187.2c-24 18-38.2 46.1-38.4 76.1L371.3 367.1zm-19.6 25.4l-116-104.4C175.9 290.3 128 339.6 128 400c0 3.9 .2 7.8 .6 11.6c1.8 17.5-10.2 36.4-27.8 36.4H96c-17.7 0-32 14.3-32 32s14.3 32 32 32H240c61.9 0 112-50.1 112-112c0-2.5-.1-5-.2-7.5z"/></svg></span>
|
||
</button>
|
||
<ul id="mdbook-theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-default_theme">Auto</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-light">Light</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-rust">Rust</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-coal">Coal</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-navy">Navy</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="mdbook-theme-ayu">Ayu</button></li>
|
||
</ul>
|
||
<button id="mdbook-search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="mdbook-searchbar">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M416 208c0 45.9-14.9 88.3-40 122.7L502.6 457.4c12.5 12.5 12.5 32.8 0 45.3s-32.8 12.5-45.3 0L330.7 376c-34.4 25.2-76.8 40-122.7 40C93.1 416 0 322.9 0 208S93.1 0 208 0S416 93.1 416 208zM208 352c79.5 0 144-64.5 144-144s-64.5-144-144-144S64 128.5 64 208s64.5 144 144 144z"/></svg></span>
|
||
</button>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Rust Programming Language</h1>
|
||
|
||
<div class="right-buttons">
|
||
<a href="print.html" title="Print this book" aria-label="Print this book">
|
||
<span class=fa-svg id="print-button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M128 0C92.7 0 64 28.7 64 64v96h64V64H354.7L384 93.3V160h64V93.3c0-17-6.7-33.3-18.7-45.3L400 18.7C388 6.7 371.7 0 354.7 0H128zM384 352v32 64H128V384 368 352H384zm64 32h32c17.7 0 32-14.3 32-32V256c0-35.3-28.7-64-64-64H64c-35.3 0-64 28.7-64 64v96c0 17.7 14.3 32 32 32H64v64c0 35.3 28.7 64 64 64H384c35.3 0 64-28.7 64-64V384zm-16-88c-13.3 0-24-10.7-24-24s10.7-24 24-24s24 10.7 24 24s-10.7 24-24 24z"/></svg></span>
|
||
</a>
|
||
<a href="https://github.com/rust-lang/book" title="Git repository" aria-label="Git repository">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 496 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span>
|
||
</a>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
<div id="mdbook-search-wrapper" class="hidden">
|
||
<form id="mdbook-searchbar-outer" class="searchbar-outer">
|
||
<div class="search-wrapper">
|
||
<input type="search" id="mdbook-searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="mdbook-searchresults-outer" aria-describedby="searchresults-header">
|
||
<div class="spinner-wrapper">
|
||
<span class=fa-svg id="fa-spin"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M304 48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zm0 416c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM48 304c26.5 0 48-21.5 48-48s-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48zm464-48c0-26.5-21.5-48-48-48s-48 21.5-48 48s21.5 48 48 48s48-21.5 48-48zM142.9 437c18.7-18.7 18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zm0-294.2c18.7-18.7 18.7-49.1 0-67.9S93.7 56.2 75 75s-18.7 49.1 0 67.9s49.1 18.7 67.9 0zM369.1 437c18.7 18.7 49.1 18.7 67.9 0s18.7-49.1 0-67.9s-49.1-18.7-67.9 0s-18.7 49.1 0 67.9z"/></svg></span>
|
||
</div>
|
||
</div>
|
||
</form>
|
||
<div id="mdbook-searchresults-outer" class="searchresults-outer hidden">
|
||
<div id="mdbook-searchresults-header" class="searchresults-header"></div>
|
||
<ul id="mdbook-searchresults">
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
||
<script>
|
||
document.getElementById('mdbook-sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
||
document.getElementById('mdbook-sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
||
Array.from(document.querySelectorAll('#mdbook-sidebar a')).forEach(function(link) {
|
||
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
||
});
|
||
</script>
|
||
|
||
<div id="mdbook-content" class="content">
|
||
<main>
|
||
<h2 id="macros"><a class="header" href="#macros">Macros</a></h2>
|
||
<p>We’ve used macros like <code>println!</code> throughout this book, but we haven’t fully
|
||
explored what a macro is and how it works. The term <em>macro</em> refers to a family
|
||
of features in Rust—declarative macros with <code>macro_rules!</code> and three kinds of
|
||
procedural macros:</p>
|
||
<ul>
|
||
<li>Custom <code>#[derive]</code> macros that specify code added with the <code>derive</code> attribute
|
||
used on structs and enums</li>
|
||
<li>Attribute-like macros that define custom attributes usable on any item</li>
|
||
<li>Function-like macros that look like function calls but operate on the tokens
|
||
specified as their argument</li>
|
||
</ul>
|
||
<p>We’ll talk about each of these in turn, but first, let’s look at why we even
|
||
need macros when we already have functions.</p>
|
||
<h3 id="the-difference-between-macros-and-functions"><a class="header" href="#the-difference-between-macros-and-functions">The Difference Between Macros and Functions</a></h3>
|
||
<p>Fundamentally, macros are a way of writing code that writes other code, which
|
||
is known as <em>metaprogramming</em>. In Appendix C, we discuss the <code>derive</code>
|
||
attribute, which generates an implementation of various traits for you. We’ve
|
||
also used the <code>println!</code> and <code>vec!</code> macros throughout the book. All of these
|
||
macros <em>expand</em> to produce more code than the code you’ve written manually.</p>
|
||
<p>Metaprogramming is useful for reducing the amount of code you have to write and
|
||
maintain, which is also one of the roles of functions. However, macros have
|
||
some additional powers that functions don’t have.</p>
|
||
<p>A function signature must declare the number and type of parameters the
|
||
function has. Macros, on the other hand, can take a variable number of
|
||
parameters: We can call <code>println!("hello")</code> with one argument or
|
||
<code>println!("hello {}", name)</code> with two arguments. Also, macros are expanded
|
||
before the compiler interprets the meaning of the code, so a macro can, for
|
||
example, implement a trait on a given type. A function can’t, because it gets
|
||
called at runtime and a trait needs to be implemented at compile time.</p>
|
||
<p>The downside to implementing a macro instead of a function is that macro
|
||
definitions are more complex than function definitions because you’re writing
|
||
Rust code that writes Rust code. Due to this indirection, macro definitions are
|
||
generally more difficult to read, understand, and maintain than function
|
||
definitions.</p>
|
||
<p>Another important difference between macros and functions is that you must
|
||
define macros or bring them into scope <em>before</em> you call them in a file, as
|
||
opposed to functions you can define anywhere and call anywhere.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="declarative-macros-with-macro_rules-for-general-metaprogramming"></a></p>
|
||
<h3 id="declarative-macros-for-general-metaprogramming"><a class="header" href="#declarative-macros-for-general-metaprogramming">Declarative Macros for General Metaprogramming</a></h3>
|
||
<p>The most widely used form of macros in Rust is the <em>declarative macro</em>. These
|
||
are also sometimes referred to as “macros by example,” “<code>macro_rules!</code> macros,”
|
||
or just plain “macros.” At their core, declarative macros allow you to write
|
||
something similar to a Rust <code>match</code> expression. As discussed in Chapter 6,
|
||
<code>match</code> expressions are control structures that take an expression, compare the
|
||
resultant value of the expression to patterns, and then run the code associated
|
||
with the matching pattern. Macros also compare a value to patterns that are
|
||
associated with particular code: In this situation, the value is the literal
|
||
Rust source code passed to the macro; the patterns are compared with the
|
||
structure of that source code; and the code associated with each pattern, when
|
||
matched, replaces the code passed to the macro. This all happens during
|
||
compilation.</p>
|
||
<p>To define a macro, you use the <code>macro_rules!</code> construct. Let’s explore how to
|
||
use <code>macro_rules!</code> by looking at how the <code>vec!</code> macro is defined. Chapter 8
|
||
covered how we can use the <code>vec!</code> macro to create a new vector with particular
|
||
values. For example, the following macro creates a new vector containing three
|
||
integers:</p>
|
||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>let v: Vec<u32> = vec![1, 2, 3];
|
||
<span class="boring">}</span></code></pre>
|
||
<p>We could also use the <code>vec!</code> macro to make a vector of two integers or a vector
|
||
of five string slices. We wouldn’t be able to use a function to do the same
|
||
because we wouldn’t know the number or type of values up front.</p>
|
||
<p>Listing 20-35 shows a slightly simplified definition of the <code>vec!</code> macro.</p>
|
||
<figure class="listing" id="listing-20-35">
|
||
<span class="file-name">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust noplayground">#[macro_export]
|
||
macro_rules! vec {
|
||
( $( $x:expr ),* ) => {
|
||
{
|
||
let mut temp_vec = Vec::new();
|
||
$(
|
||
temp_vec.push($x);
|
||
)*
|
||
temp_vec
|
||
}
|
||
};
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-35">Listing 20-35</a>: A simplified version of the <code>vec!</code> macro definition</figcaption>
|
||
</figure>
|
||
<section class="note" aria-role="note">
|
||
<p>Note: The actual definition of the <code>vec!</code> macro in the standard library
|
||
includes code to pre-allocate the correct amount of memory up front. That code
|
||
is an optimization that we don’t include here, to make the example simpler.</p>
|
||
</section>
|
||
<p>The <code>#[macro_export]</code> annotation indicates that this macro should be made
|
||
available whenever the crate in which the macro is defined is brought into
|
||
scope. Without this annotation, the macro can’t be brought into scope.</p>
|
||
<p>We then start the macro definition with <code>macro_rules!</code> and the name of the
|
||
macro we’re defining <em>without</em> the exclamation mark. The name, in this case
|
||
<code>vec</code>, is followed by curly brackets denoting the body of the macro definition.</p>
|
||
<p>The structure in the <code>vec!</code> body is similar to the structure of a <code>match</code>
|
||
expression. Here we have one arm with the pattern <code>( $( $x:expr ),* )</code>,
|
||
followed by <code>=></code> and the block of code associated with this pattern. If the
|
||
pattern matches, the associated block of code will be emitted. Given that this
|
||
is the only pattern in this macro, there is only one valid way to match; any
|
||
other pattern will result in an error. More complex macros will have more than
|
||
one arm.</p>
|
||
<p>Valid pattern syntax in macro definitions is different from the pattern syntax
|
||
covered in Chapter 19 because macro patterns are matched against Rust code
|
||
structure rather than values. Let’s walk through what the pattern pieces in
|
||
Listing 20-29 mean; for the full macro pattern syntax, see the <a href="../reference/macros-by-example.html">Rust
|
||
Reference</a>.</p>
|
||
<p>First, we use a set of parentheses to encompass the whole pattern. We use a
|
||
dollar sign (<code>$</code>) to declare a variable in the macro system that will contain
|
||
the Rust code matching the pattern. The dollar sign makes it clear this is a
|
||
macro variable as opposed to a regular Rust variable. Next comes a set of
|
||
parentheses that captures values that match the pattern within the parentheses
|
||
for use in the replacement code. Within <code>$()</code> is <code>$x:expr</code>, which matches any
|
||
Rust expression and gives the expression the name <code>$x</code>.</p>
|
||
<p>The comma following <code>$()</code> indicates that a literal comma separator character
|
||
must appear between each instance of the code that matches the code in <code>$()</code>.
|
||
The <code>*</code> specifies that the pattern matches zero or more of whatever precedes
|
||
the <code>*</code>.</p>
|
||
<p>When we call this macro with <code>vec![1, 2, 3];</code>, the <code>$x</code> pattern matches three
|
||
times with the three expressions <code>1</code>, <code>2</code>, and <code>3</code>.</p>
|
||
<p>Now let’s look at the pattern in the body of the code associated with this arm:
|
||
<code>temp_vec.push()</code> within <code>$()*</code> is generated for each part that matches <code>$()</code>
|
||
in the pattern zero or more times depending on how many times the pattern
|
||
matches. The <code>$x</code> is replaced with each expression matched. When we call this
|
||
macro with <code>vec![1, 2, 3];</code>, the code generated that replaces this macro call
|
||
will be the following:</p>
|
||
<pre><code class="language-rust ignore">{
|
||
let mut temp_vec = Vec::new();
|
||
temp_vec.push(1);
|
||
temp_vec.push(2);
|
||
temp_vec.push(3);
|
||
temp_vec
|
||
}</code></pre>
|
||
<p>We’ve defined a macro that can take any number of arguments of any type and can
|
||
generate code to create a vector containing the specified elements.</p>
|
||
<p>To learn more about how to write macros, consult the online documentation or
|
||
other resources, such as <a href="https://veykril.github.io/tlborm/">“The Little Book of Rust Macros”</a> started by
|
||
Daniel Keep and continued by Lukas Wirth.</p>
|
||
<h3 id="procedural-macros-for-generating-code-from-attributes"><a class="header" href="#procedural-macros-for-generating-code-from-attributes">Procedural Macros for Generating Code from Attributes</a></h3>
|
||
<p>The second form of macros is the procedural macro, which acts more like a
|
||
function (and is a type of procedure). <em>Procedural macros</em> accept some code as
|
||
an input, operate on that code, and produce some code as an output rather than
|
||
matching against patterns and replacing the code with other code as declarative
|
||
macros do. The three kinds of procedural macros are custom <code>derive</code>,
|
||
attribute-like, and function-like, and all work in a similar fashion.</p>
|
||
<p>When creating procedural macros, the definitions must reside in their own crate
|
||
with a special crate type. This is for complex technical reasons that we hope
|
||
to eliminate in the future. In Listing 20-36, we show how to define a
|
||
procedural macro, where <code>some_attribute</code> is a placeholder for using a specific
|
||
macro variety.</p>
|
||
<figure class="listing" id="listing-20-36">
|
||
<span class="file-name">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust ignore">use proc_macro::TokenStream;
|
||
|
||
#[some_attribute]
|
||
pub fn some_name(input: TokenStream) -> TokenStream {
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-36">Listing 20-36</a>: An example of defining a procedural macro</figcaption>
|
||
</figure>
|
||
<p>The function that defines a procedural macro takes a <code>TokenStream</code> as an input
|
||
and produces a <code>TokenStream</code> as an output. The <code>TokenStream</code> type is defined by
|
||
the <code>proc_macro</code> crate that is included with Rust and represents a sequence of
|
||
tokens. This is the core of the macro: The source code that the macro is
|
||
operating on makes up the input <code>TokenStream</code>, and the code the macro produces
|
||
is the output <code>TokenStream</code>. The function also has an attribute attached to it
|
||
that specifies which kind of procedural macro we’re creating. We can have
|
||
multiple kinds of procedural macros in the same crate.</p>
|
||
<p>Let’s look at the different kinds of procedural macros. We’ll start with a
|
||
custom <code>derive</code> macro and then explain the small dissimilarities that make the
|
||
other forms different.</p>
|
||
<!-- Old headings. Do not remove or links may break. -->
|
||
<p><a id="how-to-write-a-custom-derive-macro"></a></p>
|
||
<h3 id="custom-derive-macros"><a class="header" href="#custom-derive-macros">Custom <code>derive</code> Macros</a></h3>
|
||
<p>Let’s create a crate named <code>hello_macro</code> that defines a trait named
|
||
<code>HelloMacro</code> with one associated function named <code>hello_macro</code>. Rather than
|
||
making our users implement the <code>HelloMacro</code> trait for each of their types,
|
||
we’ll provide a procedural macro so that users can annotate their type with
|
||
<code>#[derive(HelloMacro)]</code> to get a default implementation of the <code>hello_macro</code>
|
||
function. The default implementation will print <code>Hello, Macro! My name is TypeName!</code> where <code>TypeName</code> is the name of the type on which this trait has
|
||
been defined. In other words, we’ll write a crate that enables another
|
||
programmer to write code like Listing 20-37 using our crate.</p>
|
||
<figure class="listing" id="listing-20-37">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile">use hello_macro::HelloMacro;
|
||
use hello_macro_derive::HelloMacro;
|
||
|
||
#[derive(HelloMacro)]
|
||
struct Pancakes;
|
||
|
||
fn main() {
|
||
Pancakes::hello_macro();
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-37">Listing 20-37</a>: The code a user of our crate will be able to write when using our procedural macro</figcaption>
|
||
</figure>
|
||
<p>This code will print <code>Hello, Macro! My name is Pancakes!</code> when we’re done. The
|
||
first step is to make a new library crate, like this:</p>
|
||
<pre><code class="language-console">$ cargo new hello_macro --lib
|
||
</code></pre>
|
||
<p>Next, in Listing 20-38, we’ll define the <code>HelloMacro</code> trait and its associated
|
||
function.</p>
|
||
<figure class="listing" id="listing-20-38">
|
||
<span class="file-name">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust noplayground">pub trait HelloMacro {
|
||
fn hello_macro();
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-38">Listing 20-38</a>: A simple trait that we will use with the <code>derive</code> macro</figcaption>
|
||
</figure>
|
||
<p>We have a trait and its function. At this point, our crate user could implement
|
||
the trait to achieve the desired functionality, as in Listing 20-39.</p>
|
||
<figure class="listing" id="listing-20-39">
|
||
<span class="file-name">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust ignore">use hello_macro::HelloMacro;
|
||
|
||
struct Pancakes;
|
||
|
||
impl HelloMacro for Pancakes {
|
||
fn hello_macro() {
|
||
println!("Hello, Macro! My name is Pancakes!");
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
Pancakes::hello_macro();
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-39">Listing 20-39</a>: How it would look if users wrote a manual implementation of the <code>HelloMacro</code> trait</figcaption>
|
||
</figure>
|
||
<p>However, they would need to write the implementation block for each type they
|
||
wanted to use with <code>hello_macro</code>; we want to spare them from having to do this
|
||
work.</p>
|
||
<p>Additionally, we can’t yet provide the <code>hello_macro</code> function with default
|
||
implementation that will print the name of the type the trait is implemented
|
||
on: Rust doesn’t have reflection capabilities, so it can’t look up the type’s
|
||
name at runtime. We need a macro to generate code at compile time.</p>
|
||
<p>The next step is to define the procedural macro. At the time of this writing,
|
||
procedural macros need to be in their own crate. Eventually, this restriction
|
||
might be lifted. The convention for structuring crates and macro crates is as
|
||
follows: For a crate named <code>foo</code>, a custom <code>derive</code> procedural macro crate is
|
||
called <code>foo_derive</code>. Let’s start a new crate called <code>hello_macro_derive</code> inside
|
||
our <code>hello_macro</code> project:</p>
|
||
<pre><code class="language-console">$ cargo new hello_macro_derive --lib
|
||
</code></pre>
|
||
<p>Our two crates are tightly related, so we create the procedural macro crate
|
||
within the directory of our <code>hello_macro</code> crate. If we change the trait
|
||
definition in <code>hello_macro</code>, we’ll have to change the implementation of the
|
||
procedural macro in <code>hello_macro_derive</code> as well. The two crates will need to
|
||
be published separately, and programmers using these crates will need to add
|
||
both as dependencies and bring them both into scope. We could instead have the
|
||
<code>hello_macro</code> crate use <code>hello_macro_derive</code> as a dependency and re-export the
|
||
procedural macro code. However, the way we’ve structured the project makes it
|
||
possible for programmers to use <code>hello_macro</code> even if they don’t want the
|
||
<code>derive</code> functionality.</p>
|
||
<p>We need to declare the <code>hello_macro_derive</code> crate as a procedural macro crate.
|
||
We’ll also need functionality from the <code>syn</code> and <code>quote</code> crates, as you’ll see
|
||
in a moment, so we need to add them as dependencies. Add the following to the
|
||
<em>Cargo.toml</em> file for <code>hello_macro_derive</code>:</p>
|
||
<figure class="listing">
|
||
<span class="file-name">Filename: hello_macro_derive/Cargo.toml</span>
|
||
<pre><code class="language-toml">[lib]
|
||
proc-macro = true
|
||
|
||
[dependencies]
|
||
syn = "2.0"
|
||
quote = "1.0"
|
||
</code></pre>
|
||
</figure>
|
||
<p>To start defining the procedural macro, place the code in Listing 20-40 into
|
||
your <em>src/lib.rs</em> file for the <code>hello_macro_derive</code> crate. Note that this code
|
||
won’t compile until we add a definition for the <code>impl_hello_macro</code> function.</p>
|
||
<figure class="listing" id="listing-20-40">
|
||
<span class="file-name">Filename: hello_macro_derive/src/lib.rs</span>
|
||
<pre><code class="language-rust ignore does_not_compile">use proc_macro::TokenStream;
|
||
use quote::quote;
|
||
|
||
#[proc_macro_derive(HelloMacro)]
|
||
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
|
||
// Construct a representation of Rust code as a syntax tree
|
||
// that we can manipulate.
|
||
let ast = syn::parse(input).unwrap();
|
||
|
||
// Build the trait implementation.
|
||
impl_hello_macro(&ast)
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-40">Listing 20-40</a>: Code that most procedural macro crates will require in order to process Rust code</figcaption>
|
||
</figure>
|
||
<p>Notice that we’ve split the code into the <code>hello_macro_derive</code> function, which
|
||
is responsible for parsing the <code>TokenStream</code>, and the <code>impl_hello_macro</code>
|
||
function, which is responsible for transforming the syntax tree: This makes
|
||
writing a procedural macro more convenient. The code in the outer function
|
||
(<code>hello_macro_derive</code> in this case) will be the same for almost every
|
||
procedural macro crate you see or create. The code you specify in the body of
|
||
the inner function (<code>impl_hello_macro</code> in this case) will be different
|
||
depending on your procedural macro’s purpose.</p>
|
||
<p>We’ve introduced three new crates: <code>proc_macro</code>, <a href="https://crates.io/crates/syn"><code>syn</code></a><!-- ignore -->,
|
||
and <a href="https://crates.io/crates/quote"><code>quote</code></a><!-- ignore -->. The <code>proc_macro</code> crate comes with Rust,
|
||
so we didn’t need to add that to the dependencies in <em>Cargo.toml</em>. The
|
||
<code>proc_macro</code> crate is the compiler’s API that allows us to read and manipulate
|
||
Rust code from our code.</p>
|
||
<p>The <code>syn</code> crate parses Rust code from a string into a data structure that we
|
||
can perform operations on. The <code>quote</code> crate turns <code>syn</code> data structures back
|
||
into Rust code. These crates make it much simpler to parse any sort of Rust
|
||
code we might want to handle: Writing a full parser for Rust code is no simple
|
||
task.</p>
|
||
<p>The <code>hello_macro_derive</code> function will be called when a user of our library
|
||
specifies <code>#[derive(HelloMacro)]</code> on a type. This is possible because we’ve
|
||
annotated the <code>hello_macro_derive</code> function here with <code>proc_macro_derive</code> and
|
||
specified the name <code>HelloMacro</code>, which matches our trait name; this is the
|
||
convention most procedural macros follow.</p>
|
||
<p>The <code>hello_macro_derive</code> function first converts the <code>input</code> from a
|
||
<code>TokenStream</code> to a data structure that we can then interpret and perform
|
||
operations on. This is where <code>syn</code> comes into play. The <code>parse</code> function in
|
||
<code>syn</code> takes a <code>TokenStream</code> and returns a <code>DeriveInput</code> struct representing the
|
||
parsed Rust code. Listing 20-41 shows the relevant parts of the <code>DeriveInput</code>
|
||
struct we get from parsing the <code>struct Pancakes;</code> string.</p>
|
||
<figure class="listing" id="listing-20-41">
|
||
<pre><code class="language-rust ignore">DeriveInput {
|
||
// --snip--
|
||
|
||
ident: Ident {
|
||
ident: "Pancakes",
|
||
span: #0 bytes(95..103)
|
||
},
|
||
data: Struct(
|
||
DataStruct {
|
||
struct_token: Struct,
|
||
fields: Unit,
|
||
semi_token: Some(
|
||
Semi
|
||
)
|
||
}
|
||
)
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-41">Listing 20-41</a>: The <code>DeriveInput</code> instance we get when parsing the code that has the macro’s attribute in Listing 20-37</figcaption>
|
||
</figure>
|
||
<p>The fields of this struct show that the Rust code we’ve parsed is a unit struct
|
||
with the <code>ident</code> (<em>identifier</em>, meaning the name) of <code>Pancakes</code>. There are more
|
||
fields on this struct for describing all sorts of Rust code; check the <a href="https://docs.rs/syn/2.0/syn/struct.DeriveInput.html"><code>syn</code>
|
||
documentation for <code>DeriveInput</code></a> for more information.</p>
|
||
<p>Soon we’ll define the <code>impl_hello_macro</code> function, which is where we’ll build
|
||
the new Rust code we want to include. But before we do, note that the output
|
||
for our <code>derive</code> macro is also a <code>TokenStream</code>. The returned <code>TokenStream</code> is
|
||
added to the code that our crate users write, so when they compile their crate,
|
||
they’ll get the extra functionality that we provide in the modified
|
||
<code>TokenStream</code>.</p>
|
||
<p>You might have noticed that we’re calling <code>unwrap</code> to cause the
|
||
<code>hello_macro_derive</code> function to panic if the call to the <code>syn::parse</code> function
|
||
fails here. It’s necessary for our procedural macro to panic on errors because
|
||
<code>proc_macro_derive</code> functions must return <code>TokenStream</code> rather than <code>Result</code> to
|
||
conform to the procedural macro API. We’ve simplified this example by using
|
||
<code>unwrap</code>; in production code, you should provide more specific error messages
|
||
about what went wrong by using <code>panic!</code> or <code>expect</code>.</p>
|
||
<p>Now that we have the code to turn the annotated Rust code from a <code>TokenStream</code>
|
||
into a <code>DeriveInput</code> instance, let’s generate the code that implements the
|
||
<code>HelloMacro</code> trait on the annotated type, as shown in Listing 20-42.</p>
|
||
<figure class="listing" id="listing-20-42">
|
||
<span class="file-name">Filename: hello_macro_derive/src/lib.rs</span>
|
||
<pre><code class="language-rust ignore"><span class="boring">use proc_macro::TokenStream;
|
||
</span><span class="boring">use quote::quote;
|
||
</span><span class="boring">
|
||
</span><span class="boring">#[proc_macro_derive(HelloMacro)]
|
||
</span><span class="boring">pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
|
||
</span><span class="boring"> // Construct a representation of Rust code as a syntax tree
|
||
</span><span class="boring"> // that we can manipulate
|
||
</span><span class="boring"> let ast = syn::parse(input).unwrap();
|
||
</span><span class="boring">
|
||
</span><span class="boring"> // Build the trait implementation
|
||
</span><span class="boring"> impl_hello_macro(&ast)
|
||
</span><span class="boring">}
|
||
</span><span class="boring">
|
||
</span>fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
|
||
let name = &ast.ident;
|
||
let generated = quote! {
|
||
impl HelloMacro for #name {
|
||
fn hello_macro() {
|
||
println!("Hello, Macro! My name is {}!", stringify!(#name));
|
||
}
|
||
}
|
||
};
|
||
generated.into()
|
||
}</code></pre>
|
||
<figcaption><a href="#listing-20-42">Listing 20-42</a>: Implementing the <code>HelloMacro</code> trait using the parsed Rust code</figcaption>
|
||
</figure>
|
||
<p>We get an <code>Ident</code> struct instance containing the name (identifier) of the
|
||
annotated type using <code>ast.ident</code>. The struct in Listing 20-41 shows that when
|
||
we run the <code>impl_hello_macro</code> function on the code in Listing 20-37, the
|
||
<code>ident</code> we get will have the <code>ident</code> field with a value of <code>"Pancakes"</code>. Thus,
|
||
the <code>name</code> variable in Listing 20-42 will contain an <code>Ident</code> struct instance
|
||
that, when printed, will be the string <code>"Pancakes"</code>, the name of the struct in
|
||
Listing 20-37.</p>
|
||
<p>The <code>quote!</code> macro lets us define the Rust code that we want to return. The
|
||
compiler expects something different from the direct result of the <code>quote!</code>
|
||
macro’s execution, so we need to convert it to a <code>TokenStream</code>. We do this by
|
||
calling the <code>into</code> method, which consumes this intermediate representation and
|
||
returns a value of the required <code>TokenStream</code> type.</p>
|
||
<p>The <code>quote!</code> macro also provides some very cool templating mechanics: We can
|
||
enter <code>#name</code>, and <code>quote!</code> will replace it with the value in the variable
|
||
<code>name</code>. You can even do some repetition similar to the way regular macros work.
|
||
Check out <a href="https://docs.rs/quote">the <code>quote</code> crate’s docs</a> for a thorough introduction.</p>
|
||
<p>We want our procedural macro to generate an implementation of our <code>HelloMacro</code>
|
||
trait for the type the user annotated, which we can get by using <code>#name</code>. The
|
||
trait implementation has the one function <code>hello_macro</code>, whose body contains the
|
||
functionality we want to provide: printing <code>Hello, Macro! My name is</code> and then
|
||
the name of the annotated type.</p>
|
||
<p>The <code>stringify!</code> macro used here is built into Rust. It takes a Rust
|
||
expression, such as <code>1 + 2</code>, and at compile time turns the expression into a
|
||
string literal, such as <code>"1 + 2"</code>. This is different from <code>format!</code> or
|
||
<code>println!</code>, which are macros that evaluate the expression and then turn the
|
||
result into a <code>String</code>. There is a possibility that the <code>#name</code> input might be
|
||
an expression to print literally, so we use <code>stringify!</code>. Using <code>stringify!</code>
|
||
also saves an allocation by converting <code>#name</code> to a string literal at compile
|
||
time.</p>
|
||
<p>At this point, <code>cargo build</code> should complete successfully in both <code>hello_macro</code>
|
||
and <code>hello_macro_derive</code>. Let’s hook up these crates to the code in Listing
|
||
20-37 to see the procedural macro in action! Create a new binary project in
|
||
your <em>projects</em> directory using <code>cargo new pancakes</code>. We need to add
|
||
<code>hello_macro</code> and <code>hello_macro_derive</code> as dependencies in the <code>pancakes</code>
|
||
crate’s <em>Cargo.toml</em>. If you’re publishing your versions of <code>hello_macro</code> and
|
||
<code>hello_macro_derive</code> to <a href="https://crates.io/">crates.io</a><!-- ignore -->, they
|
||
would be regular dependencies; if not, you can specify them as <code>path</code>
|
||
dependencies as follows:</p>
|
||
<pre><code class="language-toml">[dependencies]
|
||
hello_macro = { path = "../hello_macro" }
|
||
hello_macro_derive = { path = "../hello_macro/hello_macro_derive" }
|
||
</code></pre>
|
||
<p>Put the code in Listing 20-37 into <em>src/main.rs</em>, and run <code>cargo run</code>: It
|
||
should print <code>Hello, Macro! My name is Pancakes!</code>. The implementation of the
|
||
<code>HelloMacro</code> trait from the procedural macro was included without the
|
||
<code>pancakes</code> crate needing to implement it; the <code>#[derive(HelloMacro)]</code> added the
|
||
trait implementation.</p>
|
||
<p>Next, let’s explore how the other kinds of procedural macros differ from custom
|
||
<code>derive</code> macros.</p>
|
||
<h3 id="attribute-like-macros"><a class="header" href="#attribute-like-macros">Attribute-Like Macros</a></h3>
|
||
<p>Attribute-like macros are similar to custom <code>derive</code> macros, but instead of
|
||
generating code for the <code>derive</code> attribute, they allow you to create new
|
||
attributes. They’re also more flexible: <code>derive</code> only works for structs and
|
||
enums; attributes can be applied to other items as well, such as functions.
|
||
Here’s an example of using an attribute-like macro. Say you have an attribute
|
||
named <code>route</code> that annotates functions when using a web application framework:</p>
|
||
<pre><code class="language-rust ignore">#[route(GET, "/")]
|
||
fn index() {</code></pre>
|
||
<p>This <code>#[route]</code> attribute would be defined by the framework as a procedural
|
||
macro. The signature of the macro definition function would look like this:</p>
|
||
<pre><code class="language-rust ignore">#[proc_macro_attribute]
|
||
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {</code></pre>
|
||
<p>Here, we have two parameters of type <code>TokenStream</code>. The first is for the
|
||
contents of the attribute: the <code>GET, "/"</code> part. The second is the body of the
|
||
item the attribute is attached to: in this case, <code>fn index() {}</code> and the rest
|
||
of the function’s body.</p>
|
||
<p>Other than that, attribute-like macros work the same way as custom <code>derive</code>
|
||
macros: You create a crate with the <code>proc-macro</code> crate type and implement a
|
||
function that generates the code you want!</p>
|
||
<h3 id="function-like-macros"><a class="header" href="#function-like-macros">Function-Like Macros</a></h3>
|
||
<p>Function-like macros define macros that look like function calls. Similarly to
|
||
<code>macro_rules!</code> macros, they’re more flexible than functions; for example, they
|
||
can take an unknown number of arguments. However, <code>macro_rules!</code> macros can
|
||
only be defined using the match-like syntax we discussed in the <a href="#declarative-macros-with-macro_rules-for-general-metaprogramming">“Declarative
|
||
Macros for General Metaprogramming”</a><!-- ignore --> section earlier.
|
||
Function-like macros take a <code>TokenStream</code> parameter, and their definition
|
||
manipulates that <code>TokenStream</code> using Rust code as the other two types of
|
||
procedural macros do. An example of a function-like macro is an <code>sql!</code> macro
|
||
that might be called like so:</p>
|
||
<pre><code class="language-rust ignore">let sql = sql!(SELECT * FROM posts WHERE id=1);</code></pre>
|
||
<p>This macro would parse the SQL statement inside it and check that it’s
|
||
syntactically correct, which is much more complex processing than a
|
||
<code>macro_rules!</code> macro can do. The <code>sql!</code> macro would be defined like this:</p>
|
||
<pre><code class="language-rust ignore">#[proc_macro]
|
||
pub fn sql(input: TokenStream) -> TokenStream {</code></pre>
|
||
<p>This definition is similar to the custom <code>derive</code> macro’s signature: We receive
|
||
the tokens that are inside the parentheses and return the code we wanted to
|
||
generate.</p>
|
||
<h2 id="summary"><a class="header" href="#summary">Summary</a></h2>
|
||
<p>Whew! Now you have some Rust features in your toolbox that you likely won’t use
|
||
often, but you’ll know they’re available in very particular circumstances.
|
||
We’ve introduced several complex topics so that when you encounter them in
|
||
error message suggestions or in other people’s code, you’ll be able to
|
||
recognize these concepts and syntax. Use this chapter as a reference to guide
|
||
you to solutions.</p>
|
||
<p>Next, we’ll put everything we’ve discussed throughout the book into practice
|
||
and do one more project!</p>
|
||
|
||
</main>
|
||
|
||
<nav class="nav-wrapper" aria-label="Page navigation">
|
||
<!-- Mobile navigation buttons -->
|
||
<a rel="prev" href="ch20-04-advanced-functions-and-closures.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
||
</a>
|
||
|
||
<a rel="next prefetch" href="ch21-00-final-project-a-web-server.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
||
</a>
|
||
|
||
<div style="clear: both"></div>
|
||
</nav>
|
||
</div>
|
||
</div>
|
||
|
||
<nav class="nav-wide-wrapper" aria-label="Page navigation">
|
||
<a rel="prev" href="ch20-04-advanced-functions-and-closures.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M41.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 256 246.6 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/></svg></span>
|
||
</a>
|
||
|
||
<a rel="next prefetch" href="ch21-00-final-project-a-web-server.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
|
||
<span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M278.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-160 160c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L210.7 256 73.4 118.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l160 160z"/></svg></span>
|
||
</a>
|
||
</nav>
|
||
|
||
</div>
|
||
|
||
<template id=fa-eye><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM432 256c0 79.5-64.5 144-144 144s-144-64.5-144-144s64.5-144 144-144s144 64.5 144 144zM288 192c0 35.3-28.7 64-64 64c-11.5 0-22.3-3-31.6-8.4c-.2 2.8-.4 5.5-.4 8.4c0 53 43 96 96 96s96-43 96-96s-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6z"/></svg></span></template>
|
||
<template id=fa-eye-slash><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M38.8 5.1C28.4-3.1 13.3-1.2 5.1 9.2S-1.2 34.7 9.2 42.9l592 464c10.4 8.2 25.5 6.3 33.7-4.1s6.3-25.5-4.1-33.7L525.6 386.7c39.6-40.6 66.4-86.1 79.9-118.4c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C465.5 68.8 400.8 32 320 32c-68.2 0-125 26.3-169.3 60.8L38.8 5.1zM223.1 149.5C248.6 126.2 282.7 112 320 112c79.5 0 144 64.5 144 144c0 24.9-6.3 48.3-17.4 68.7L408 294.5c5.2-11.8 8-24.8 8-38.5c0-53-43-96-96-96c-2.8 0-5.6 .1-8.4 .4c5.3 9.3 8.4 20.1 8.4 31.6c0 10.2-2.4 19.8-6.6 28.3l-90.3-70.8zm223.1 298L373 389.9c-16.4 6.5-34.3 10.1-53 10.1c-79.5 0-144-64.5-144-144c0-6.9 .5-13.6 1.4-20.2L83.1 161.5C60.3 191.2 44 220.8 34.5 243.7c-3.3 7.9-3.3 16.7 0 24.6c14.9 35.7 46.2 87.7 93 131.1C174.5 443.2 239.2 480 320 480c47.8 0 89.9-12.9 126.2-32.5z"/></svg></span></template>
|
||
<template id=fa-copy><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg></span></template>
|
||
<template id=fa-play><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M73 39c-14.8-9.1-33.4-9.4-48.5-.9S0 62.6 0 80V432c0 17.4 9.4 33.4 24.5 41.9s33.7 8.1 48.5-.9L361 297c14.3-8.7 23-24.2 23-41s-8.7-32.2-23-41L73 39z"/></svg></span></template>
|
||
<template id=fa-clock-rotate-left><span class=fa-svg><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.2.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M75 75L41 41C25.9 25.9 0 36.6 0 57.9V168c0 13.3 10.7 24 24 24H134.1c21.4 0 32.1-25.9 17-41l-30.8-30.8C155 85.5 203 64 256 64c106 0 192 86 192 192s-86 192-192 192c-40.8 0-78.6-12.7-109.7-34.4c-14.5-10.1-34.4-6.6-44.6 7.9s-6.6 34.4 7.9 44.6C151.2 495 201.7 512 256 512c141.4 0 256-114.6 256-256S397.4 0 256 0C185.3 0 121.3 28.7 75 75zm181 53c-13.3 0-24 10.7-24 24V256c0 6.4 2.5 12.5 7 17l72 72c9.4 9.4 24.6 9.4 33.9 0s9.4-24.6 0-33.9l-65-65V152c0-13.3-10.7-24-24-24z"/></svg></span></template>
|
||
|
||
|
||
|
||
<script>
|
||
window.playground_copyable = true;
|
||
</script>
|
||
|
||
|
||
<script src="elasticlunr-ef4e11c1.min.js"></script>
|
||
<script src="mark-09e88c2c.min.js"></script>
|
||
<script src="searcher-09f2665d.js"></script>
|
||
|
||
<script src="clipboard-1626706a.min.js"></script>
|
||
<script src="highlight-abc7f01d.js"></script>
|
||
<script src="book-c22b7243.js"></script>
|
||
|
||
<!-- Custom JS scripts -->
|
||
<script src="ferris-2317480c.js"></script>
|
||
|
||
|
||
|
||
</div>
|
||
</body>
|
||
</html>
|