Files
book/print.html
T

5525 lines
248 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="{% block description %}{% endblock %}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Font Awesome -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<!-- MathJax -->
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<!-- Fetch JQuery from CDN but have a local fallback -->
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
}
</script>
</head>
<body>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme = localStorage.getItem('theme');
if (theme == null) { theme = 'light'; }
$('body').removeClass().addClass(theme);
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var sidebar = localStorage.getItem('sidebar');
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
</script>
<div id="sidebar" class="sidebar">
<ul class="chapter"><li><a href="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><a href="tutorial.html"><strong>2.</strong> Tutorial</a></li><li><a href="basics.html"><strong>3.</strong> The Basics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> `if`</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li></ul></li><li><a href="ownership-and-borrowing.html"><strong>4.</strong> Ownership & borrowing</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="lifetimes.html"><strong>4.3.</strong> Lifetimes</a></li></ul></li><li><a href="basic-data-types.html"><strong>5.</strong> Basic Data Types</a></li><li><ul class="section"><li><a href="structs.html"><strong>5.1.</strong> Structs</a></li><li><a href="enums.html"><strong>5.2.</strong> Enums</a></li></ul></li><li><a href="crates-and-modules.html"><strong>6.</strong> Crates & Modules</a></li><li><a href="error-handling.html"><strong>7.</strong> Error Handling</a></li><li><a href="basic-collections.html"><strong>8.</strong> Basic Collections</a></li><li><ul class="section"><li><a href="vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="hashmap.html"><strong>8.3.</strong> `HashMap<K, V>`</a></li></ul></li><li><a href="traits.html"><strong>9.</strong> Traits</a></li><li><a href="closures.html"><strong>10.</strong> Closures</a></li><li><a href="iterators.html"><strong>11.</strong> Iterators</a></li><li><a href="io.html"><strong>12.</strong> I/O</a></li><li><ul class="section"><li><a href="read-and-write.html"><strong>12.1.</strong> `Read` & `Write`</a></li><li><a href="fs.html"><strong>12.2.</strong> `std::fs`</a></li><li><a href="path.html"><strong>12.3.</strong> `std::path`</a></li><li><a href="env.html"><strong>12.4.</strong> `std::env`</a></li></ul></li><li><a href="testing.html"><strong>13.</strong> Testing</a></li><li><a href="smart-pointers.html"><strong>14.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="deref.html"><strong>14.1.</strong> `Deref`</a></li><li><a href="deref-coercions.html"><strong>14.2.</strong> `Deref` coercions</a></li><li><a href="box.html"><strong>14.3.</strong> `Box<T>`</a></li><li><a href="rc.html"><strong>14.4.</strong> `Rc<T>`</a></li></ul></li><li><a href="concurrency.html"><strong>15.</strong> Concurrency</a></li><li><ul class="section"><li><a href="threads.html"><strong>15.1.</strong> Threads</a></li><li><a href="send-and-sync.html"><strong>15.2.</strong> `Send` & `Sync`</a></li><li><a href="arc.html"><strong>15.3.</strong> `Arc<T>`</a></li><li><a href="mutex.html"><strong>15.4.</strong> `Mutex<T>`</a></li><li><a href="channels.html"><strong>15.5.</strong> `Channels`</a></li></ul></li><li><a href="unsafe-rust.html"><strong>16.</strong> Unsafe Rust</a></li><li><ul class="section"><li><a href="raw-pointers.html"><strong>16.1.</strong> Raw Pointers</a></li><li><a href="transmute.html"><strong>16.2.</strong> transmute</a></li></ul></li><li><a href="ffi.html"><strong>17.</strong> FFI</a></li><li><ul class="section"><li><a href="conditional-compilation.html"><strong>17.1.</strong> Conditional Compilation</a></li><li><a href="bindings-to-c.html"><strong>17.2.</strong> Bindings to C</a></li><li><a href="using-rust-from-other-languages.html"><strong>17.3.</strong> Using Rust from Other Languages</a></li><li><a href="static.html"><strong>17.4.</strong> `static`</a></li></ul></li><li><a href="cargo.html"><strong>18.</strong> Cargo</a></li><li><ul class="section"><li><a href="cratesio.html"><strong>18.1.</strong> Crates.io</a></li></ul></li><li><a href="advanced-type-system-features.html"><strong>19.</strong> Advanced Type System Features</a></li><li><ul class="section"><li><a href="associated-types.html"><strong>19.1.</strong> Associated Types</a></li><li><a href="trait-objects.html"><strong>19.2.</strong> Trait Objects</a></li><li><a href="ufcs.html"><strong>19.3.</strong> UFCS</a></li><li><a href="coherence.html"><strong>19.4.</strong> Coherence</a></li></ul></li><li><a href="interior-mutability.html"><strong>20.</strong> Interior mutability</a></li><li><ul class="section"><li><a href="cell.html"><strong>20.1.</strong> `Cell<T>`</a></li><li><a href="refcell.html"><strong>20.2.</strong> `RefCell<T>`</a></li></ul></li><li><a href="macros.html"><strong>21.</strong> Macros</a></li><li><a href="nightly-rust.html"><strong>22.</strong> Nightly Rust</a></li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar" class="menu-bar">
<div class="left-buttons">
<i id="sidebar-toggle" class="fa fa-bars"></i>
<i id="theme-toggle" class="fa fa-paint-brush"></i>
</div>
<h1 class="menu-title"></h1>
<div class="right-buttons">
<i id="print-button" class="fa fa-print" title="Print this book"></i>
</div>
</div>
<div id="content" class="content">
<h1>Introduction</h1>
<p>Welcome to “The Rust Programming Language,” an introductory book about Rust.
Rust is a programming language that’s focused on safety, concurrency, and
speed. It maintains these goals without having a garbage collector, making it a
useful language for a number of use cases other languages aren’t good at:
embedding in other languages, programs with specific space and time
requirements, and writing low-level code, like device drivers and operating
systems. It improves on current languages targeting this space by having a
number of compile-time safety checks that produce no runtime overhead, while
eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’
even though some of these abstractions feel like those of a high-level
language. Even then, Rust still allows precise control like a low-level
language would.</p>
<p>This book is written for a reader who already knows how to program in at least
one programming language. Which language that is does not matter very much,
though you may have an easier time if you’ve programmed in a low-level language
with manual memory allocation.</p>
<p>After reading this book, you should be comfortable writing Rust programs. We’ll
be learning Rust through small, focused examples that demonstrate each topic.
The chapters build upon each other, so if you skip ahead, you may have to skip
back to refer to a previous concept.</p>
<h2>Contributing to the book</h2>
<p>This book is open source. If you find an error, please don’t hesitate to file an
issue or send a pull request <a href="https://github.com/rust-lang/book">on GitHub</a>.</p>
<h1>Installation</h1>
<p>The first step to using Rust is to install it. Generally speaking, you’ll need
an Internet connection to run the commands in this chapter, as we’ll be
downloading Rust from the internet.</p>
<p>We’ll be showing off a number of commands using a terminal, and those lines all
start with <code>$</code>. We don't need to type in the <code>$</code>s, they are there to indicate
the start of each command. We’ll see many tutorials and examples around the web
that follow this convention: <code>$</code> for commands run as our regular user, and <code>#</code>
for commands we should be running as an administrator.</p>
<h2>Installing on Linux or Mac</h2>
<p>If we're on Linux or a Mac, all we need to do is open a terminal and type this:</p>
<pre><code class="language-bash">$ curl -sSf https://static.rust-lang.org/rustup.sh | sh
</code></pre>
<p>This will download a script, and stat the installation. If it all goes well,
you’ll see this appear:</p>
<pre><code class="language-text">Welcome to Rust.
This script will download the Rust compiler and its package manager, Cargo, and
install them to /usr/local. You may install elsewhere by running this script
with the --prefix=&lt;path&gt; option.
The installer will run under ‘sudo’ and may ask you for your password. If you do
not want the script to run ‘sudo’ then pass it the --disable-sudo flag.
You may uninstall later by running /usr/local/lib/rustlib/uninstall.sh,
or by running this script again with the --uninstall flag.
Continue? (y/N)
</code></pre>
<p>From here, press <code>y</code> for ‘yes’, and then follow the rest of the prompts.</p>
<h2>Installing on Windows</h2>
<p>If you're on Windows, please download the appropriate <a href="https://www.rust-lang.org/install.html">installer</a>.</p>
<h2>Uninstalling</h2>
<p>Uninstalling Rust is as easy as installing it. On Linux or Mac, just run
the uninstall script:</p>
<pre><code class="language-bash">$ sudo /usr/local/lib/rustlib/uninstall.sh
</code></pre>
<p>If we used the Windows installer, we can re-run the <code>.msi</code> and it will give us
an uninstall option.</p>
<h2>Troubleshooting</h2>
<p>If we've got Rust installed, we can open up a shell, and type this:</p>
<pre><code class="language-bash">$ rustc --version
</code></pre>
<p>You should see the version number, commit hash, and commit date.</p>
<p>If you do, Rust has been installed successfully! Congrats!</p>
<p>If you don't and you're on Windows, check that Rust is in your %PATH% system
variable. If it isn't, run the installer again, select &quot;Change&quot; on the &quot;Change,
repair, or remove installation&quot; page and ensure &quot;Add to PATH&quot; is checked.</p>
<p>If not, there are a number of places where we can get help. The easiest is
<a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a>, which we can access through
<a href="http://chat.mibbit.com/?server=irc.mozilla.org&amp;channel=%23rust">Mibbit</a>. Click that link, and we'll be chatting with other Rustaceans
(a silly nickname we call ourselves) who can help us out. Other great resources
include <a href="https://users.rust-lang.org/">the user’s forum</a>, and <a href="http://stackoverflow.com/questions/tagged/rust">Stack Overflow</a>.</p>
<p>This installer also installs a copy of the documentation locally, so we can
read it offline. On UNIX systems, <code>/usr/local/share/doc/rust</code> is the location.
On Windows, it's in a <code>share/doc</code> directory, inside the directory to which Rust
was installed.</p>
<h1>Hello, world!</h1>
<p>Now that you have Rust installed, let’s write your first Rust program. It's
traditional when learning a new language to write a little program to print the
text “Hello, world!” to the screen, and in this section, we'll follow that
tradition.</p>
<p>The nice thing about starting with such a simple program is that you can
quickly verify that your compiler is installed, and that it's working properly.
Printing information to the screen is also just a pretty common thing to do, so
practicing it early on is good.</p>
<blockquote>
<p>Note: This book assumes basic familiarity with the command line. Rust itself
makes no specific demands about your editing, tooling, or where your code
lives, so if you prefer an IDE to the command line, that's an option.</p>
</blockquote>
<h2>Creating a Project File</h2>
<p>First, make a file to put your Rust code in. Rust doesn't care where your code
lives, but for this book, I suggest making a <em>projects</em> directory in your home
directory, and keeping all your projects there. Open a terminal and enter the
following commands to make a directory for this particular project:</p>
<pre><code class="language-bash">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<blockquote>
<p>Note: If you’re on Windows and not using PowerShell, the <code>~</code> may not work.
Consult the documentation for your shell for more details.</p>
</blockquote>
<h2>Writing and Running a Rust Program</h2>
<p>Next, make a new source file and call it <em>main.rs</em>. Rust files always end
in a <em>.rs</em> extension. If you’re using more than one word in your filename, use
an underscore to separate them; for example, you'd use <em>hello_world.rs</em> rather
than <em>helloworld.rs</em>.</p>
<p>Now open the <em>main.rs</em> file you just created, and type the following code:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Save the file, and go back to your terminal window. On Linux or OSX, enter the
following commands:</p>
<pre><code class="language-bash">$ rustc main.rs
$ ./main
Hello, world!
</code></pre>
<p>In Windows, just replace <code>main</code> with <code>main.exe</code>. Regardless of your operating
system, you should see the string <code>Hello, world!</code> print to the terminal. If you
did, then congratulations! You've officially written a Rust program. That makes
you a Rust programmer! Welcome.</p>
<h2>Anatomy of a Rust Program</h2>
<p>Now, let’s go over what just happened in your &quot;Hello, world!&quot; program in
detail. Here's the first piece of the puzzle:</p>
<pre><code class="language-rust">fn main() {
}
</code></pre>
<p>These lines define a <em>function</em> in Rust. The <code>main</code> function is special: it's
the beginning of every Rust program. The first line says, “I’m declaring a
function named <code>main</code> that takes no arguments and returns nothing.” If there
were arguments, they would go inside the parentheses (<code>(</code> and <code>)</code>), and because
we aren’t returning anything from this function, we can omit the return type
entirely.</p>
<p>Also note that the function body is wrapped in curly braces (<code>{</code> and <code>}</code>). Rust
requires these around all function bodies. It's considered good style to put
the opening curly brace on the same line as the function declaration, with one
space in between.</p>
<p>Inside the <code>main()</code> function:</p>
<pre><code class="language-rust"> println!(&quot;Hello, world!&quot;);
</code></pre>
<p>This line does all of the work in this little program: it prints text to the
screen. There are a number of details that are important here. The first is
that it’s indented with four spaces, not tabs.</p>
<p>The second important part is the <code>println!()</code> line. This is calling a Rust
<em><a href="macros.html">macro</a></em>, which is how metaprogramming is done in Rust. If it were calling a
function instead, it would look like this: <code>println()</code> (without the !). We'll
discuss Rust macros in more detail later, but for now you just need to
know that when you see a <code>!</code> that means that you’re calling a macro instead of
a normal function.</p>
<p>Next is <code>&quot;Hello, world!&quot;</code> which is a <em>string</em>. We pass this string as an
argument to <code>println!</code>, which prints the string to the screen. Easy enough!</p>
<p>The line ends with a semicolon (<code>;</code>). Rust is an <em>expression oriented</em>
language, which means that most things are expressions, rather than statements.
The <code>;</code> indicates that this expression is over, and the next one is ready to
begin. Most lines of Rust code end with a <code>;</code>.</p>
<h2>Compiling and Running Are Separate Steps</h2>
<p>In &quot;Writing and Running a Rust Program&quot;, we showed you how to run a newly
created program. We'll break that process down and examine each step now.</p>
<p>Before running a Rust program, you have to compile it. You can use the Rust
compiler by entering the <code>rustc</code> command and passing it the name of your source
file, like this:</p>
<pre><code class="language-bash">$ rustc main.rs
</code></pre>
<p>If you come from a C or C++ background, you'll notice that this is similar to
<code>gcc</code> or <code>clang</code>. After compiling successfully, Rust should output a binary
executable, which you can see on Linux or OSX by entering the <code>ls</code> command in
your shell as follows:</p>
<pre><code class="language-bash">$ ls
main main.rs
</code></pre>
<p>On Windows, you'd enter:</p>
<pre><code class="language-bash">$ dir
main.exe main.rs
</code></pre>
<p>This shows we have two files: the source code, with an <code>.rs</code> extension, and the
executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else). All that's left to
do from here is run the <code>main</code> or <code>main.exe</code> file, like this:</p>
<pre><code class="language-bash">$ ./main # or main.exe on Windows
</code></pre>
<p>If <em>main.rs</em> were your &quot;Hello, world!&quot; program, this would print <code>Hello, world!</code> to your terminal.</p>
<p>If you come from a dynamic language like Ruby, Python, or JavaScript, you may
not be used to compiling and running a program being separate steps. Rust is an
<em>ahead-of-time compiled</em> language, which means that you can compile a program,
give it to someone else, and they can run it even without Rust installed. If
you give someone a <code>.rb</code> or <code>.py</code> or <code>.js</code> file, on the other hand, they need
to have a Ruby, Python, or JavaScript implementation installed (respectively),
but you only need one command to both compile and run your program. Everything
is a tradeoff in language design.</p>
<p>Just compiling with <code>rustc</code> is fine for simple programs, but as your project
grows, you'll want to be able to manage all of the options your project has,
and make it easy to share your code with other people and projects. Next, I'll
introduce you to a tool called Cargo, which will help you write real-world Rust
programs.</p>
<h1>Hello, Cargo!</h1>
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
manage their Rust projects. Cargo manages three things: building your code,
downloading the libraries your code depends on, and building those libraries.
We call libraries your code needs ‘dependencies’ since your code depends on
them.</p>
<p>The simplest Rust programs don’t have any dependencies, so right now, you'd
only use the first part of its functionality. As you write more complex Rust
programs, you’ll want to add dependencies, and if you start off using Cargo,
that will be a lot easier to do.</p>
<p>As the vast, vast majority of Rust projects use Cargo, we will assume that
you’re using it for the rest of the book. Cargo comes installed with Rust
itself, if you used the official installers. If you installed Rust through some
other means, you can check if you have Cargo installed by typing:</p>
<pre><code class="language-bash">$ cargo --version
</code></pre>
<p>Into a terminal. If you see a version number, great! If you see an error like
‘<code>command not found</code>’, then you should look at the documentation for the system
in which you installed Rust, to determine if Cargo is separate.</p>
<h2>Converting to Cargo</h2>
<p>Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
to do three things:</p>
<ol>
<li>Put your source file in the right directory.</li>
<li>Get rid of the old executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else)
and make a new one.</li>
<li>Make a Cargo configuration file.</li>
</ol>
<p>Let's get started!</p>
<h3>Creating a new Executable and Source Directory</h3>
<p>First, go back to your terminal, move to your <em>hello_world</em> directory, and
enter the following commands:</p>
<pre><code class="language-bash">$ mkdir src
$ mv main.rs src/main.rs
$ rm main # or 'del main.exe' on Windows
</code></pre>
<p>Cargo expects your source files to live inside a <em>src</em> directory, so do that
first. This leaves the top-level project directory (in this case,
<em>hello_world</em>) for READMEs, license information, and anything else not related
to your code. In this way, using Cargo helps you keep your projects nice and
tidy. There's a place for everything, and everything is in its place.</p>
<p>Now, copy <em>main.rs</em> to the <em>src</em> directory, and delete the compiled file you
created with <code>rustc</code>. As usual, replace <code>main</code> with <code>main.exe</code> if you're on
Windows.</p>
<p>This example retains <code>main.rs</code> as the source filename because it's creating an
executable. If you wanted to make a library instead, you'd name the file
<code>lib.rs</code>. This convention is used by Cargo to successfully compile your
projects, but it can be overridden if you wish.</p>
<h3>Creating a Configuration File</h3>
<p>Next, create a new file inside your <em>hello_world</em> directory, and call it
<code>Cargo.toml</code>.</p>
<p>Make sure to capitalize the <code>C</code> in <code>Cargo.toml</code>, or Cargo won't know what to do
with the configuration file.</p>
<p>This file is in the <em><a href="https://github.com/toml-lang/toml">TOML</a></em> (Tom's Obvious, Minimal Language) format. TOML is
similar to INI, but has some extra goodies, and is used as Cargo’s
configuration format.</p>
<p>Inside this file, type the following information:</p>
<pre><code class="language-toml">[package]
name = &quot;hello_world&quot;
version = &quot;0.0.1&quot;
authors = [ &quot;Your name &lt;you@example.com&gt;&quot; ]
</code></pre>
<p>The first line, <code>[package]</code>, indicates that the following statements are
configuring a package. As we add more information to this file, we’ll add other
sections, but for now, we just have the package configuration.</p>
<p>The other three lines set the three bits of configuration that Cargo needs to
know to compile your program: its name, what version it is, and who wrote it.</p>
<p>Once you've added this information to the <em>Cargo.toml</em> file, save it to finish
creating the configuration file.</p>
<h2>Building and Running a Cargo Project</h2>
<p>With your <em>Cargo.toml</em> file in place in your project's root directory, you
should be ready to build and run your Hello World program! To do so, enter the
following commands:</p>
<pre><code class="language-bash">$ cargo build
Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
$ ./target/debug/hello_world
Hello, world!
</code></pre>
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
<p>You just built a project with <code>cargo build</code> and ran it with
<code>./target/debug/hello_world</code>, but you can actually do both in one step with
<code>cargo run</code> as follows:</p>
<pre><code class="language-bash">$ cargo run
Running `target/debug/hello_world`
Hello, world!
</code></pre>
<p>Notice that this example didn’t re-build the project. Cargo figured out that
the file hasn’t changed, and so it just ran the binary. If you'd modified your
source code, Cargo would have rebuilt the project before running it, and you
would have seen something like this:</p>
<pre><code class="language-bash">$ cargo run
Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
Running `target/debug/hello_world`
Hello, world!
</code></pre>
<p>Cargo checks to see if any of your project’s files have been modified, and only
rebuilds your project if they’ve changed since the last time you built it.</p>
<p>With simple projects, Cargo doesn't bring a whole lot over just using <code>rustc</code>,
but it will become useful in future. With complex projects composed of multiple
crates, it’s much easier to let Cargo coordinate the build. With Cargo, you can
just run <code>cargo build</code>, and it should work the right way.</p>
<h2>Building for Release</h2>
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. These optimizations make
your Rust code run faster, but turning them on makes your program take longer
to compile. This is why there are two different profiles, one for development,
and one for building the final program you’ll give to a user.</p>
<p>Running this command also causes Cargo to create a new file called
<em>Cargo.lock</em>, which looks like this:</p>
<pre><code class="language-toml">[root]
name = &quot;hello_world&quot;
version = &quot;0.0.1&quot;
</code></pre>
<p>Cargo uses the <em>Cargo.lock</em> file to keep track of dependencies in your
application. This is the Hello World project's <em>Cargo.lock</em> file. This project
doesn't have dependencies, so the file is a bit sparse. Realistically, you
won't ever need to touch this file yourself; just let Cargo handle it.</p>
<p>That’s it! If you've been following along, you should have successfully built
<code>hello_world</code> with Cargo.</p>
<p>Even though the project is simple, it now uses much of the real tooling you’ll
use for the rest of your Rust career. In fact, you can expect to start
virtually all Rust projects with some variation on the following commands:</p>
<pre><code class="language-bash">$ git clone someurl.com/foo
$ cd foo
$ cargo build
</code></pre>
<h2>Making A New Cargo Project the Easy Way</h2>
<p>You don’t have to go through that previous process every time you want to start
a new project! Cargo can quickly make a bare-bones project directory that you
can start developing in right away.</p>
<p>To start a new project with Cargo, enter <code>cargo new</code> at the command line:</p>
<pre><code class="language-bash">$ cargo new hello_world --bin
</code></pre>
<p>This command passes <code>--bin</code> because the goal is to get straight to making an
executable application, as opposed to a library. Executables are often called
<em>binaries</em> (as in <code>/usr/bin</code>, if you’re on a Unix system).</p>
<p>Cargo has generated two files and one directory for us: a <code>Cargo.toml</code> and a
<em>src</em> directory with a <em>main.rs</em> file inside. These should look familliar,
they’re exactly what we created by hand, above.</p>
<p>This output is all you need to get started. First, open <code>Cargo.toml</code>. It should
look something like this:</p>
<pre><code class="language-toml">[package]
name = &quot;hello_world&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]
</code></pre>
<p>Cargo has populated <em>Cargo.toml</em> with reasonable defaults based on the arguments
you gave it and your <code>git</code> global configuration. You may notice that Cargo has
also initialized the <code>hello_world</code> directory as a <code>git</code> repository.</p>
<p>Here’s what should be in <code>src/main.rs</code>:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Cargo has generated a &quot;Hello World!&quot; for you, and you’re ready to start coding!</p>
<blockquote>
<p>Note: If you want to look at Cargo in more detail, check out the official <a href="http://doc.crates.io/guide.html">Cargo
guide</a>, which covers all of its features.</p>
</blockquote>
<h1>The Design of Rust</h1>
<h1>Tutorial</h1>
<h1>The Basics</h1>
<p>We’ll start our journey with Rust by talking about the absolute basics.
Many programming languages have lots in common at their core.
Much of this may feel similar to other languages you’ve used, but some parts are different.
If you want to skip this section, you can, but you may end up coming back later to find out small details.
These foundations will be in every single useful Rust program, and learning them gives us a strong core to start from.</p>
<h1>Variable Bindings</h1>
<p>The foundation of virtually every program is the ability to store and modify data.
Rust programs are no different.
Let’s start with a short example.</p>
<h2>The basics of bindings</h2>
<p>First, we’ll generate a new project with Cargo.
Open a terminal, and navigate to the directory where you’d like to keep your projects.
From there, let’s generate a new project:</p>
<pre><code class="language-bash">$ cargo new --bin bindings
$ cd bindings
</code></pre>
<p>This creates a new project, ‘bindings’, and sets up our <code>Cargo.toml</code> and <code>src/main.rs</code> files.
As we saw in “Hello, World!”, Cargo will generate these files and create a little ‘hello world’ program for us:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Let’s replace that program with this one:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>And finally, run it:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
Running `target/debug/bindings`
The value of x is: 5
</code></pre>
<p>If you see an error instead, double check that you have copied the program exactly as written.
Let’s break this down, line by line.</p>
<pre><code class="language-rust,ignore">fn main() {
</code></pre>
<p>The <code>main()</code> function is the entry point of every Rust program.
We’ll talk more about functions in the next section, but for now, all we need to know is that this is where our program begins.
The opening curly brace, <code>{</code>, indicates the start of the function’s body.</p>
<pre><code class="language-rust,ignore"> let x = 5;
</code></pre>
<p>This is our first ‘variable binding’.
This looks like many languages, but there are some subtleties.
We create variable bindings with a ‘<code>let</code> statement’, which looks like this:</p>
<pre><code class="language-text">let PATTERN = VALUE;
</code></pre>
<p>In our example, the <code>PATTERN</code> is a humble <code>x</code>, and the <code>VALUE</code> is a simple <code>5</code>.
The <code>let</code> statement takes the <code>VALUE</code>, and matches it to the <code>PATTERN</code>, creating new bindings.
Therefore, our example creates a new binding, <code>x</code>, and gives it an initial value of <code>5</code>.
Patterns are a big part of Rust, we will see them in many places.</p>
<p>That seems like a lot of explanation for a basic assignment statement!
The trick is that these patterns can become more complex, and have a lot of power.
We’ll explore more complex patterns as we learn more.</p>
<p>Before we do that, though, let’s finish investigating this example.
Here’s the next line:</p>
<pre><code class="language-rust,ignore"> println!(&quot;The value of x is: {}&quot;, x);
</code></pre>
<p>The <code>println!</code> macro prints text to the screen.
We can tell that it’s a macro due to the <code>!</code>.
We won’t learn how to write macros until much later in the book, but we’ll use macros provided by the standard library throughout.
Every time you see a <code>!</code>, remember that it signifies a macro.
Macros can add new syntax to the language, and the <code>!</code> is a reminder that things may look slightly unusual.</p>
<p><code>println!</code>, specifically, has one required argument, a ‘format string’, and zero or more optional arguments.
This is why it’s a macro; Rust does not support optional arguments for regular functions.
The format string can contain the special text <code>{}</code>.
If it does, it fills in that place in the string with the values of the other arguments.
In this case, we’ve passed <code>x</code>.
You can think of <code>{}</code> as little crab pincers, holding the value in place.
This placeholder has a number of more advanced formatting options that we’ll discuss later.</p>
<pre><code class="language-rust,ignore">}
</code></pre>
<p>Finally, a closing curly brace matches up with the opening curly brace that declared the <code>main()</code> function, and declares its end.</p>
<p>This explains our output:</p>
<pre><code class="language-text">The value of x is: 5
</code></pre>
<p>We assign <code>5</code> to a binding, <code>x</code>, and then print it to the screen with <code>println!</code>.</p>
<h2>Multiple assignment</h2>
<p>Let’s try a more complex pattern.
Change our example program to this:</p>
<pre><code class="language-rust">fn main() {
let (x, y) = (5, 6);
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>And run it with <code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
Running `target/debug/bindings`
The value of x is: 5
The value of y is: 6
</code></pre>
<p>We’ve created two bindings with one <code>let</code>!
Here’s our pattern:</p>
<pre><code class="language-text">(x, y)
</code></pre>
<p>And here’s the value:</p>
<pre><code class="language-text">(5, 6)
</code></pre>
<p>As you can see, the two line up visually, and so <code>let</code> binds <code>5</code> to <code>x</code> and <code>6</code> to <code>y</code>.
We could have used two <code>let</code> statements as well:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = 6;
}
</code></pre>
<p>In simple cases like this, two <code>let</code>s may be clearer, but in others, creating multiple bindings at once is nice.
As we become more proficient in Rust, we’ll figure out which style is better, but it’s mostly a judgement call.</p>
<h2>Type annotations</h2>
<p>You may have noticed that we didn’t declare the type of <code>x</code> or <code>y</code> in our previous examples.
Rust is a <em>statically typed</em> language, which means that at compile time, we must know the types of all bindings.
But annotating every single binding with a type can feel like busywork, and make code noisy.
To solve this issue, Rust uses ‘type inference’, meaning that it attempts to infer the types of your bindings.</p>
<p>The primary way that the type is inferred is by looking at how it is used.
Let’s look at the example again:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
}
</code></pre>
<p>When we bind <code>x</code> to <code>5</code>, the compiler knows that <code>x</code> should be a numeric type.
Without any other information, it defaults to <code>i32</code>, a thirty-two bit integer type.
We’ll talk more about Rust’s basic types in section 3.3.</p>
<p>Here’s what a <code>let</code> statement with a ‘type annotation’ looks like:</p>
<pre><code class="language-rust">fn main() {
let x: i32 = 5;
}
</code></pre>
<p>We can add a colon, followed by the type name.
Here’s the structure of a <code>let</code> statement with a type annotation:</p>
<pre><code class="language-text">let PATTERN: TYPE = VALUE;
</code></pre>
<p>Note that the colon and the <code>TYPE</code> go <em>after</em> the <code>PATTERN</code>, not in the pattern itself.
As an example, here’s our more complex pattern with two bindings:</p>
<pre><code class="language-rust">fn main() {
let (x, y): (i32, i32) = (5, 6);
}
</code></pre>
<p>Just like we match up the <code>VALUE</code> with the <code>PATTERN</code>, we match up the <code>TYPE</code> with the <code>PATTERN</code>.</p>
<h2>Initialization</h2>
<p>We do not have to provide bindings with an initial value, and can assign it later. Try this program:</p>
<pre><code class="language-rust">fn main() {
let x;
x = 5;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>And run it with <code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
Running `target/debug/bindings`
The value of x is: 5
</code></pre>
<p>It’s all good.
This raises a question, though: what if we try to print out a binding before we declare a value?
Here’s a program that demonstrates this question:</p>
<pre><code class="language-rust,ignore">fn main() {
let x;
println!(&quot;The value of x is: {}&quot;, x);
x = 5;
}
</code></pre>
<p>We can find out the answer with <code>cargo run</code>:</p>
<pre><code class="language-text"> Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` [E0381]
src/main.rs:4 println!(“The value of x is: {}”, x);
^
&lt;std macros&gt;:2:25: 2:56 note: in this expansion of format_args!
&lt;std macros&gt;:3:1: 3:54 note: in this expansion of print! (defined in &lt;std macros&gt;)
src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in &lt;std macros&gt;)
src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
error: aborting due to previous error
Could not compile `bindings`.
To learn more, run the command again with --verbose.
</code></pre>
<p>An error!
The compiler won’t let us write a program like this.
This is our first example of the compiler helping us find an error in our program.
Different programming languages have different ways of approaching this problem.
Some languages always initialize values with some sort of default.
Other languages leave the value uninitialized, and make no promises about what happens if you try to use something before initialization.
Rust chooses something else: error and force the programmer to explain what they want.
We must do some sort of initialization before we can use <code>x</code>.</p>
<h3>Extended error explanations</h3>
<p>There’s one more interesting part of this error message:</p>
<pre><code class="language-text">src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
</code></pre>
<p>We can see an extended explanation by passing the <code>--explain</code> flag to <code>rustc</code>.
Not every error has a longer explanation, but many of them do.
These extended explanations try to show off common ways that the error occurs, and common solutions to the issue.
Here’s <code>E0381</code>:</p>
<pre><code class="language-bash">$ rustc --explain E0381
It is not allowed to use or capture an uninitialized variable. For example:
fn main() {
let x: i32;
let y = x; // error, use of possibly uninitialized variable
To fix this, ensure that any declared variables are initialized before being
used.
</code></pre>
<p>These explanations can really help if you’re stuck on an error.
The compiler is your friend, and is here to help.</p>
<h2>Mutable bindings</h2>
<p>What about changing the value of a binding? Here’s another sample program that asks this question:</p>
<pre><code class="language-rust,ignore">fn main() {
let x = 5;
x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p><code>cargo run</code> has the answer for us:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:4:5: 4:10 error: re-assignment of immutable variable `x` [E0384]
src/main.rs:4 x = 6;
^~~~~
src/main.rs:4:5: 4:10 help: run `rustc --explain E0384` to see a detailed explanation
src/main.rs:2:9: 2:10 note: prior assignment occurs here
src/main.rs:2 let x = 5;
^
</code></pre>
<p>The error mentions <code>re-assigment of immutable variable</code>.
That’s right: bindings are immutable.
But they’re only immutable by default.
In a pattern, when we’re creating a new name, we can add <code>mut</code> in front to make the binding a mutable one.
Here’s an example:</p>
<pre><code class="language-rust">fn main() {
let mut x = 5;
println!(&quot;The value of x is: {}&quot;, x);
x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Running this, we get:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
Running `target/debug/bindings`
The value of x is: 5
The value of x is: 6
</code></pre>
<p>We can now change the value that <code>x</code> binds to.
Note that the syntax is not <code>let mut</code> exactly; it’s using <code>mut</code> in a pattern.
This becomes more obvious with our <code>()</code> pattern:</p>
<pre><code class="language-rust,ignore">fn main() {
let (mut x, y) = (5, 6);
x = 7;
y = 8;
}
</code></pre>
<p>The compiler will complain about this program:</p>
<pre><code class="language-bash">$ cargo build
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:5:5: 5:10 error: re-assignment of immutable variable `y` [E0384]
src/main.rs:5 y = 8;
^~~~~
src/main.rs:5:5: 5:10 help: run `rustc --explain E0384` to see a detailed explanation
src/main.rs:2:17: 2:18 note: prior assignment occurs here
src/main.rs:2 let (mut x, y) = (5, 6);
^
</code></pre>
<p>It’s fine with re-assigning <code>x</code>, but not <code>y</code>.
The <code>mut</code> only applies to the name that follows it, not the whole pattern.</p>
<h3>Reassignment, not mutation</h3>
<p>There is one subtlety we haven’t covered yet: <code>mut</code> allows you to mutate <em>the binding</em>, but not <em>what the binding binds to</em>.
In other words:</p>
<pre><code class="language-rust">fn main() {
let mut x = 5;
x = 6;
}
</code></pre>
<p>This is not changing the value that <code>x</code> is bound to, but creating a new value, <code>6</code>, and changing the binding to bind to it instead.
It’s a subtle but important difference.
Well, for now, it does not make a lot of difference, but when our programs get more complex, it will.
Specifically, passing arguments to functions will illustrate the difference.
We’ll talk about that in the next section, when we discuss functions.</p>
<h2>Scope</h2>
<p>Variable bindings have a ‘scope’ in which they’re valid.
That scope begins from the point at which the binding is declared, and ends at the end of the next block of code.
We can only access bindings which are ‘in scope’.
We cannot access them ‘before they come into scope’ or ‘after they go out of scope’.
Here’s an example:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;x is not yet in scope&quot;);
let x = 5;
println!(&quot;x is now in scope&quot;);
println!(&quot;In real code, we’d now do a bunch of work.&quot;);
println!(&quot;x will go out of scope now! The next curly brace is ending the main function.&quot;);
}
</code></pre>
<p>We can create arbitrary scopes through the use of <code>{</code> and <code>}</code>:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;x is not yet in scope&quot;);
let x = 5;
println!(&quot;x is now in scope&quot;);
println!(&quot;Let’s start a new scope!&quot;);
{
let y = 5;
println!(&quot;y is now in scope&quot;);
println!(&quot;x is also still in scope&quot;);
println!(&quot;y will go out of scope now!&quot;);
println!(&quot;The next curly brace is ending the scope we started.&quot;);
}
println!(&quot;x is still in scope, but y is now out of scope and is not usable&quot;);
println!(&quot;x will go out of scope now! The next curly brace is ending the main function.&quot;);
}
</code></pre>
<p>What bindings are in and out of scope will become much more important later, once we learn about ‘references’ and ‘traits’.</p>
<h2>Shadowing</h2>
<p>A final thing about bindings: they can ‘shadow’ previous bindings with the same name.
Here’s a sample program:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Running it, we can see the shadowing in action:</p>
<pre><code class="language-text">src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
src/main.rs:2 let x = 5;
^
Running `target/debug/bindings`
The value of x is: 6
</code></pre>
<p>There are two interesting things in this output.
First, Rust will compile and run this program, no problem.
And as we can see, the value of <code>x</code> is <code>6</code>.
But we didn’t declare <code>x</code> as mutable.
Instead, we declared a <em>new</em> binding that is <em>also</em> named <code>x</code>, and gave it a new value.
The older value that we bound <code>x</code> to is inaccessible as soon as the new <code>x</code> is declared.
This can be useful if you’d like to perform a few transformations on a value, and leave it immutable.
For example:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>This will print:</p>
<pre><code class="language-bash"> Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
Running `target/debug/bindings`
The value of x is: 12
</code></pre>
<p>This lets us modify <code>x</code>, but not deal with mutation.
This is nice because we know that the compiler will let us know if we try to modify it later.
Let’s assume that after we calculate <code>12</code>, we don’t want to modify <code>x</code> again.
If we had written this program in a mutable style, like this:</p>
<pre><code>fn main() {
let mut x = 5;
x = x + 1;
x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
x = 15;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Rust is happy to let us mutate it again, to <code>15</code>.
A similar program in our immutable style will let us know about that accidental mutation, however:</p>
<pre><code class="language-rust,ignore">fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
x = 15;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>If we try to compile, we get an error:</p>
<pre><code class="language-bash">$ cargo build
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:8:5: 8:11 error: re-assignment of immutable variable `x` [E0384]
src/main.rs:8 x = 15;
^~~~~~
src/main.rs:8:5: 8:11 help: run `rustc --explain E0384` to see a detailed explanation
src/main.rs:4:9: 4:10 note: prior assignment occurs here
src/main.rs:4 let x = x * 2;
^
error: aborting due to previous error
Could not compile `bindings`.
</code></pre>
<p>Exactly what we wanted.</p>
<p>Shadowing can take some time to get used to, but it’s very powerful, and works well with immutability.</p>
<p>There was one more thing we should talk about in the output from compiling our initial program.
It’s this part:</p>
<pre><code class="language-text">src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
</code></pre>
<p>Here’s the two lines of relevant code:</p>
<pre><code class="language-rust">let x = 5;
let x = 6;
</code></pre>
<p>Rust knows that we shadowed <code>x</code>, but we never ended up using the initial value.
This isn’t <em>wrong</em>, exactly, it just may not have been what we wanted.
In this case, the compiler issues a ‘warning’, but still compiles our program.
The <code>#[warn(unused_variables)]</code> syntax is called an ‘attribute’, which we’ll discuss in a later section.
More specifically, a warning like this is called a ‘lint’, which is an old term for the bits of sheep’s wool that you wouldn’t want to put in cloth.
Similarly, this lint is telling us that we may have an extra bit of code we don’t need.
Our program would work just fine without it.
It’s worth listening to these warnings, and fixing the problems they point out.
They can be signs of a larger problem.
In this case, we may not have realized that we were shadowing <code>x</code>.</p>
<h3>Shadowing and scopes</h3>
<p>Like any binding, a binding that shadows another binding will go away at the end of a scope.
Here’s an example program:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
println!(&quot;Before shadowing, x is: {}&quot;, x);
{
let x = 6;
println!(&quot;Now that x is shadowed, x is: {}&quot;, x);
}
println!(&quot;After shadowing, x is: {}&quot;, x);
}
</code></pre>
<p>If we run this example, we can see the shadow appear and disappear:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
Running `target/debug/bindings`
Before shadowing, x is: 5
Now that x is shadowed, x is: 6
After shadowing, x is: 5
</code></pre>
<h1>Functions</h1>
<h1>Primitive Types</h1>
<h1>Comments</h1>
<h1>if</h1>
<h1>Loops</h1>
<h1>Ownership &amp; borrowing</h1>
<h1>Ownership</h1>
<p>This guide is one of three presenting Rust’s ownership system. This is one of
Rust’s most unique and compelling features, with which Rust developers should
become quite acquainted. Ownership is how Rust achieves its largest goal,
memory safety. There are a few distinct concepts, each with its own
chapter:</p>
<ul>
<li>ownership, which you’re reading now</li>
<li><a href="references-and-borrowing.html">borrowing</a>, and their associated feature ‘references’</li>
<li><a href="lifetimes.html">lifetimes</a>, an advanced concept of borrowing</li>
</ul>
<p>These three chapters are related, and in order. You’ll need all three to fully
understand the ownership system.</p>
<h1>Meta</h1>
<p>Before we get to the details, two important notes about the ownership system.</p>
<p>Rust has a focus on safety and speed. It accomplishes these goals through many
‘zero-cost abstractions’, which means that in Rust, abstractions cost as little
as possible in order to make them work. The ownership system is a prime example
of a zero-cost abstraction. All of the analysis we’ll talk about in this guide
is <em>done at compile time</em>. You do not pay any run-time cost for any of these
features.</p>
<p>However, this system does have a certain cost: learning curve. Many new users
to Rust experience something we like to call ‘fighting with the borrow
checker’, where the Rust compiler refuses to compile a program that the author
thinks is valid. This often happens because the programmer’s mental model of
how ownership should work doesn’t match the actual rules that Rust implements.
You probably will experience similar things at first. There is good news,
however: more experienced Rust developers report that once they work with the
rules of the ownership system for a period of time, they fight the borrow
checker less and less.</p>
<p>With that in mind, let’s learn about ownership.</p>
<h1>Ownership</h1>
<p><a href="variable-bindings.html">Variable bindings</a> have a property in Rust: they ‘have ownership’
of what they’re bound to. This means that when a binding goes out of scope,
Rust will free the bound resources. For example:</p>
<pre><code class="language-rust">fn foo() {
let v = vec![1, 2, 3];
}
</code></pre>
<p>When <code>v</code> comes into scope, a new [<code>Vec&lt;T&gt;</code>]<a href="../std/vec/struct.Vec.html">vect</a> is created. In this case, the
vector also allocates space on <a href="the-stack-and-the-heap.html">the heap</a>, for the three elements. When
<code>v</code> goes out of scope at the end of <code>foo()</code>, Rust will clean up everything
related to the vector, even the heap-allocated memory. This happens
deterministically, at the end of the scope.</p>
<h1>Move semantics</h1>
<p>There’s some more subtlety here, though: Rust ensures that there is <em>exactly
one</em> binding to any given resource. For example, if we have a vector, we can
assign it to another binding:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3];
let v2 = v;
</code></pre>
<p>But, if we try to use <code>v</code> afterwards, we get an error:</p>
<pre><code class="language-rust,ignore">let v = vec![1, 2, 3];
let v2 = v;
println!(&quot;v[0] is: {}&quot;, v[0]);
</code></pre>
<p>It looks like this:</p>
<pre><code class="language-text">error: use of moved value: `v`
println!(&quot;v[0] is: {}&quot;, v[0]);
^
</code></pre>
<p>A similar thing happens if we define a function which takes ownership, and
try to use something after we’ve passed it as an argument:</p>
<pre><code class="language-rust,ignore">fn take(v: Vec&lt;i32&gt;) {
// what happens here isn’t important.
}
let v = vec![1, 2, 3];
take(v);
println!(&quot;v[0] is: {}&quot;, v[0]);
</code></pre>
<p>Same error: ‘use of moved value’. When we transfer ownership to something else,
we say that we’ve ‘moved’ the thing we refer to. You don’t need some sort of
special annotation here, it’s the default thing that Rust does.</p>
<h2>The details</h2>
<p>The reason that we cannot use a binding after we’ve moved it is subtle, but
important. When we write code like this:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3];
let v2 = v;
</code></pre>
<p>The first line allocates memory for the vector object, <code>v</code>, and for the data it
contains. The vector object is stored on the <a href="the-stack-and-the-heap.html">stack</a> and contains a pointer
to the content (<code>[1, 2, 3]</code>) stored on the <a href="the-stack-and-the-heap.html">heap</a>. When we move <code>v</code> to <code>v2</code>,
it creates a copy of that pointer, for <code>v2</code>. Which means that there would be two
pointers to the content of the vector on the heap. It would violate Rust’s
safety guarantees by introducing a data race. Therefore, Rust forbids using <code>v</code>
after we’ve done the move.</p>
<p>It’s also important to note that optimizations may remove the actual copy of
the bytes on the stack, depending on circumstances. So it may not be as
inefficient as it initially seems.</p>
<h2><code>Copy</code> types</h2>
<p>We’ve established that when ownership is transferred to another binding, you
cannot use the original binding. However, there’s a <a href="traits.html">trait</a> that changes this
behavior, and it’s called <code>Copy</code>. We haven’t discussed traits yet, but for now,
you can think of them as an annotation to a particular type that adds extra
behavior. For example:</p>
<pre><code class="language-rust">let v = 1;
let v2 = v;
println!(&quot;v is: {}&quot;, v);
</code></pre>
<p>In this case, <code>v</code> is an <code>i32</code>, which implements the <code>Copy</code> trait. This means
that, just like a move, when we assign <code>v</code> to <code>v2</code>, a copy of the data is made.
But, unlike a move, we can still use <code>v</code> afterward. This is because an <code>i32</code>
has no pointers to data somewhere else, copying it is a full copy.</p>
<p>All primitive types implement the <code>Copy</code> trait and their ownership is
therefore not moved like one would assume, following the ´ownership rules´.
To give an example, the two following snippets of code only compile because the
<code>i32</code> and <code>bool</code> types implement the <code>Copy</code> trait.</p>
<pre><code class="language-rust">fn main() {
let a = 5;
let _y = double(a);
println!(&quot;{}&quot;, a);
}
fn double(x: i32) -&gt; i32 {
x * 2
}
</code></pre>
<pre><code class="language-rust">fn main() {
let a = true;
let _y = change_truth(a);
println!(&quot;{}&quot;, a);
}
fn change_truth(x: bool) -&gt; bool {
!x
}
</code></pre>
<p>If we had used types that do not implement the <code>Copy</code> trait,
we would have gotten a compile error because we tried to use a moved value.</p>
<pre><code class="language-text">error: use of moved value: `a`
println!(&quot;{}&quot;, a);
^
</code></pre>
<p>We will discuss how to make your own types <code>Copy</code> in the <a href="traits.html">traits</a>
section.</p>
<h1>More than ownership</h1>
<p>Of course, if we had to hand ownership back with every function we wrote:</p>
<pre><code class="language-rust">fn foo(v: Vec&lt;i32&gt;) -&gt; Vec&lt;i32&gt; {
// do stuff with v
// hand back ownership
v
}
</code></pre>
<p>This would get very tedious. It gets worse the more things we want to take ownership of:</p>
<pre><code class="language-rust">fn foo(v1: Vec&lt;i32&gt;, v2: Vec&lt;i32&gt;) -&gt; (Vec&lt;i32&gt;, Vec&lt;i32&gt;, i32) {
// do stuff with v1 and v2
// hand back ownership, and the result of our function
(v1, v2, 42)
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let (v1, v2, answer) = foo(v1, v2);
</code></pre>
<p>Ugh! The return type, return line, and calling the function gets way more
complicated.</p>
<p>Luckily, Rust offers a feature, borrowing, which helps us solve this problem.
It’s the topic of the next section!</p>
<h1>References and Borrowing</h1>
<p>This guide is two of three presenting Rust’s ownership system. This is one of
Rust’s most unique and compelling features, with which Rust developers should
become quite acquainted. Ownership is how Rust achieves its largest goal,
memory safety. There are a few distinct concepts, each with its own
chapter:</p>
<ul>
<li><a href="ownership.html">ownership</a>, the key concept</li>
<li>borrowing, which you’re reading now</li>
<li><a href="lifetimes.html">lifetimes</a>, an advanced concept of borrowing</li>
</ul>
<p>These three chapters are related, and in order. You’ll need all three to fully
understand the ownership system.</p>
<h1>Meta</h1>
<p>Before we get to the details, two important notes about the ownership system.</p>
<p>Rust has a focus on safety and speed. It accomplishes these goals through many
‘zero-cost abstractions’, which means that in Rust, abstractions cost as little
as possible in order to make them work. The ownership system is a prime example
of a zero cost abstraction. All of the analysis we’ll talk about in this guide
is <em>done at compile time</em>. You do not pay any run-time cost for any of these
features.</p>
<p>However, this system does have a certain cost: learning curve. Many new users
to Rust experience something we like to call ‘fighting with the borrow
checker’, where the Rust compiler refuses to compile a program that the author
thinks is valid. This often happens because the programmer’s mental model of
how ownership should work doesn’t match the actual rules that Rust implements.
You probably will experience similar things at first. There is good news,
however: more experienced Rust developers report that once they work with the
rules of the ownership system for a period of time, they fight the borrow
checker less and less.</p>
<p>With that in mind, let’s learn about borrowing.</p>
<h1>Borrowing</h1>
<p>At the end of the <a href="ownership.html">ownership</a> section, we had a nasty function that looked
like this:</p>
<pre><code class="language-rust">fn foo(v1: Vec&lt;i32&gt;, v2: Vec&lt;i32&gt;) -&gt; (Vec&lt;i32&gt;, Vec&lt;i32&gt;, i32) {
// do stuff with v1 and v2
// hand back ownership, and the result of our function
(v1, v2, 42)
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let (v1, v2, answer) = foo(v1, v2);
</code></pre>
<p>This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s
the first step:</p>
<pre><code class="language-rust">fn foo(v1: &amp;Vec&lt;i32&gt;, v2: &amp;Vec&lt;i32&gt;) -&gt; i32 {
// do stuff with v1 and v2
// return the answer
42
}
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
let answer = foo(&amp;v1, &amp;v2);
// we can use v1 and v2 here!
</code></pre>
<p>Instead of taking <code>Vec&lt;i32&gt;</code>s as our arguments, we take a reference:
<code>&amp;Vec&lt;i32&gt;</code>. And instead of passing <code>v1</code> and <code>v2</code> directly, we pass <code>&amp;v1</code> and
<code>&amp;v2</code>. We call the <code>&amp;T</code> type a ‘reference’, and rather than owning the resource,
it borrows ownership. A binding that borrows something does not deallocate the
resource when it goes out of scope. This means that after the call to <code>foo()</code>,
we can use our original bindings again.</p>
<p>References are immutable, just like bindings. This means that inside of <code>foo()</code>,
the vectors can’t be changed at all:</p>
<pre><code class="language-rust,ignore">fn foo(v: &amp;Vec&lt;i32&gt;) {
v.push(5);
}
let v = vec![];
foo(&amp;v);
</code></pre>
<p>errors with:</p>
<pre><code class="language-text">error: cannot borrow immutable borrowed content `*v` as mutable
v.push(5);
^
</code></pre>
<p>Pushing a value mutates the vector, and so we aren’t allowed to do it.</p>
<h1>&amp;mut references</h1>
<p>There’s a second kind of reference: <code>&amp;mut T</code>. A ‘mutable reference’ allows you
to mutate the resource you’re borrowing. For example:</p>
<pre><code class="language-rust">let mut x = 5;
{
let y = &amp;mut x;
*y += 1;
}
println!(&quot;{}&quot;, x);
</code></pre>
<p>This will print <code>6</code>. We make <code>y</code> a mutable reference to <code>x</code>, then add one to
the thing <code>y</code> points at. You’ll notice that <code>x</code> had to be marked <code>mut</code> as well.
If it wasn’t, we couldn’t take a mutable borrow to an immutable value.</p>
<p>You'll also notice we added an asterisk (<code>*</code>) in front of <code>y</code>, making it <code>*y</code>,
this is because <code>y</code> is an <code>&amp;mut</code> reference. You'll also need to use them for
accessing the contents of a reference as well.</p>
<p>Otherwise, <code>&amp;mut</code> references are just like references. There <em>is</em> a large
difference between the two, and how they interact, though. You can tell
something is fishy in the above example, because we need that extra scope, with
the <code>{</code> and <code>}</code>. If we remove them, we get an error:</p>
<pre><code class="language-text">error: cannot borrow `x` as immutable because it is also borrowed as mutable
println!(&quot;{}&quot;, x);
^
note: previous borrow of `x` occurs here; the mutable borrow prevents
subsequent moves, borrows, or modification of `x` until the borrow ends
let y = &amp;mut x;
^
note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>As it turns out, there are rules.</p>
<h1>The Rules</h1>
<p>Here’s the rules about borrowing in Rust:</p>
<p>First, any borrow must last for a scope no greater than that of the owner.
Second, you may have one or the other of these two kinds of borrows, but not
both at the same time:</p>
<ul>
<li>one or more references (<code>&amp;T</code>) to a resource,</li>
<li>exactly one mutable reference (<code>&amp;mut T</code>).</li>
</ul>
<p>You may notice that this is very similar, though not exactly the same as,
to the definition of a data race:</p>
<blockquote>
<p>There is a ‘data race’ when two or more pointers access the same memory
location at the same time, where at least one of them is writing, and the
operations are not synchronized.</p>
</blockquote>
<p>With references, you may have as many as you’d like, since none of them are
writing. However, as we can only have one <code>&amp;mut</code> at a time, it is impossible to
have a data race. This is how Rust prevents data races at compile time: we’ll
get errors if we break the rules.</p>
<p>With this in mind, let’s consider our example again.</p>
<h2>Thinking in scopes</h2>
<p>Here’s the code:</p>
<pre><code class="language-rust,ignore">let mut x = 5;
let y = &amp;mut x;
*y += 1;
println!(&quot;{}&quot;, x);
</code></pre>
<p>This code gives us this error:</p>
<pre><code class="language-text">error: cannot borrow `x` as immutable because it is also borrowed as mutable
println!(&quot;{}&quot;, x);
^
</code></pre>
<p>This is because we’ve violated the rules: we have a <code>&amp;mut T</code> pointing to <code>x</code>,
and so we aren’t allowed to create any <code>&amp;T</code>s. One or the other. The note
hints at how to think about this problem:</p>
<pre><code class="language-text">note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>In other words, the mutable borrow is held through the rest of our example. What
we want is for the mutable borrow to end <em>before</em> we try to call <code>println!</code> and
make an immutable borrow. In Rust, borrowing is tied to the scope that the
borrow is valid for. And our scopes look like this:</p>
<pre><code class="language-rust,ignore">let mut x = 5;
let y = &amp;mut x; // -+ &amp;mut borrow of x starts here
// |
*y += 1; // |
// |
println!(&quot;{}&quot;, x); // -+ - try to borrow x here
// -+ &amp;mut borrow of x ends here
</code></pre>
<p>The scopes conflict: we can’t make an <code>&amp;x</code> while <code>y</code> is in scope.</p>
<p>So when we add the curly braces:</p>
<pre><code class="language-rust">let mut x = 5;
{
let y = &amp;mut x; // -+ &amp;mut borrow starts here
*y += 1; // |
} // -+ ... and ends here
println!(&quot;{}&quot;, x); // &lt;- try to borrow x here
</code></pre>
<p>There’s no problem. Our mutable borrow goes out of scope before we create an
immutable one. But scope is the key to seeing how long a borrow lasts for.</p>
<h2>Issues borrowing prevents</h2>
<p>Why have these restrictive rules? Well, as we noted, these rules prevent data
races. What kinds of issues do data races cause? Here’s a few.</p>
<h3>Iterator invalidation</h3>
<p>One example is ‘iterator invalidation’, which happens when you try to mutate a
collection that you’re iterating over. Rust’s borrow checker prevents this from
happening:</p>
<pre><code class="language-rust">let mut v = vec![1, 2, 3];
for i in &amp;v {
println!(&quot;{}&quot;, i);
}
</code></pre>
<p>This prints out one through three. As we iterate through the vectors, we’re
only given references to the elements. And <code>v</code> is itself borrowed as immutable,
which means we can’t change it while we’re iterating:</p>
<pre><code class="language-rust,ignore">let mut v = vec![1, 2, 3];
for i in &amp;v {
println!(&quot;{}&quot;, i);
v.push(34);
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error: cannot borrow `v` as mutable because it is also borrowed as immutable
v.push(34);
^
note: previous borrow of `v` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `v` until the borrow ends
for i in &amp;v {
^
note: previous borrow ends here
for i in &amp;v {
println!(“{}”, i);
v.push(34);
}
^
</code></pre>
<p>We can’t modify <code>v</code> because it’s borrowed by the loop.</p>
<h3>use after free</h3>
<p>References must not live longer than the resource they refer to. Rust will
check the scopes of your references to ensure that this is true.</p>
<p>If Rust didn’t check this property, we could accidentally use a reference
which was invalid. For example:</p>
<pre><code class="language-rust,ignore">let y: &amp;i32;
{
let x = 5;
y = &amp;x;
}
println!(&quot;{}&quot;, y);
</code></pre>
<p>We get this error:</p>
<pre><code class="language-text">error: `x` does not live long enough
y = &amp;x;
^
note: reference must be valid for the block suffix following statement 0 at
2:16...
let y: &amp;i32;
{
let x = 5;
y = &amp;x;
}
note: ...but borrowed value is only valid for the block suffix following
statement 0 at 4:18
let x = 5;
y = &amp;x;
}
</code></pre>
<p>In other words, <code>y</code> is only valid for the scope where <code>x</code> exists. As soon as
<code>x</code> goes away, it becomes invalid to refer to it. As such, the error says that
the borrow ‘doesn’t live long enough’ because it’s not valid for the right
amount of time.</p>
<p>The same problem occurs when the reference is declared <em>before</em> the variable it
refers to. This is because resources within the same scope are freed in the
opposite order they were declared:</p>
<pre><code class="language-rust,ignore">let y: &amp;i32;
let x = 5;
y = &amp;x;
println!(&quot;{}&quot;, y);
</code></pre>
<p>We get this error:</p>
<pre><code class="language-text">error: `x` does not live long enough
y = &amp;x;
^
note: reference must be valid for the block suffix following statement 0 at
2:16...
let y: &amp;i32;
let x = 5;
y = &amp;x;
println!(&quot;{}&quot;, y);
}
note: ...but borrowed value is only valid for the block suffix following
statement 1 at 3:14
let x = 5;
y = &amp;x;
println!(&quot;{}&quot;, y);
}
</code></pre>
<p>In the above example, <code>y</code> is declared before <code>x</code>, meaning that <code>y</code> lives longer
than <code>x</code>, which is not allowed.</p>
<h1>Lifetimes</h1>
<p>This guide is three of three presenting Rust’s ownership system. This is one of
Rust’s most unique and compelling features, with which Rust developers should
become quite acquainted. Ownership is how Rust achieves its largest goal,
memory safety. There are a few distinct concepts, each with its own chapter:</p>
<ul>
<li><a href="ownership.html">ownership</a>, the key concept</li>
<li><a href="references-and-borrowing.html">borrowing</a>, and their associated feature ‘references’</li>
<li>lifetimes, which you’re reading now</li>
</ul>
<p>These three chapters are related, and in order. You’ll need all three to fully
understand the ownership system.</p>
<h1>Meta</h1>
<p>Before we get to the details, two important notes about the ownership system.</p>
<p>Rust has a focus on safety and speed. It accomplishes these goals through many
‘zero-cost abstractions’, which means that in Rust, abstractions cost as little
as possible in order to make them work. The ownership system is a prime example
of a zero-cost abstraction. All of the analysis we’ll talk about in this guide
is <em>done at compile time</em>. You do not pay any run-time cost for any of these
features.</p>
<p>However, this system does have a certain cost: learning curve. Many new users
to Rust experience something we like to call ‘fighting with the borrow
checker’, where the Rust compiler refuses to compile a program that the author
thinks is valid. This often happens because the programmer’s mental model of
how ownership should work doesn’t match the actual rules that Rust implements.
You probably will experience similar things at first. There is good news,
however: more experienced Rust developers report that once they work with the
rules of the ownership system for a period of time, they fight the borrow
checker less and less.</p>
<p>With that in mind, let’s learn about lifetimes.</p>
<h1>Lifetimes</h1>
<p>Lending out a reference to a resource that someone else owns can be
complicated. For example, imagine this set of operations:</p>
<ol>
<li>I acquire a handle to some kind of resource.</li>
<li>I lend you a reference to the resource.</li>
<li>I decide I’m done with the resource, and deallocate it, while you still have
your reference.</li>
<li>You decide to use the resource.</li>
</ol>
<p>Uh oh! Your reference is pointing to an invalid resource. This is called a
dangling pointer or ‘use after free’, when the resource is memory.</p>
<p>To fix this, we have to make sure that step four never happens after step
three. The ownership system in Rust does this through a concept called
lifetimes, which describe the scope that a reference is valid for.</p>
<p>When we have a function that takes a reference by argument, we can be implicit
or explicit about the lifetime of the reference:</p>
<pre><code class="language-rust">// implicit
fn foo(x: &amp;i32) {
}
// explicit
fn bar&lt;'a&gt;(x: &amp;'a i32) {
}
</code></pre>
<p>The <code>'a</code> reads ‘the lifetime a’. Technically, every reference has some lifetime
associated with it, but the compiler lets you elide (i.e. omit, see
<a href="#lifetime-elision">&quot;Lifetime Elision&quot;</a> below) them in common cases.
Before we get to that, though, let’s break the explicit example down:</p>
<pre><code class="language-rust,ignore">fn bar&lt;'a&gt;(...)
</code></pre>
<p>We previously talked a little about <a href="functions.html">function syntax</a>, but we didn’t
discuss the <code>&lt;&gt;</code>s after a function’s name. A function can have ‘generic
parameters’ between the <code>&lt;&gt;</code>s, of which lifetimes are one kind. We’ll discuss
other kinds of generics <a href="generics.html">later in the book</a>, but for now, let’s
just focus on the lifetimes aspect.</p>
<p>We use <code>&lt;&gt;</code> to declare our lifetimes. This says that <code>bar</code> has one lifetime,
<code>'a</code>. If we had two reference parameters, it would look like this:</p>
<pre><code class="language-rust,ignore">fn bar&lt;'a, 'b&gt;(...)
</code></pre>
<p>Then in our parameter list, we use the lifetimes we’ve named:</p>
<pre><code class="language-rust,ignore">...(x: &amp;'a i32)
</code></pre>
<p>If we wanted an <code>&amp;mut</code> reference, we’d do this:</p>
<pre><code class="language-rust,ignore">...(x: &amp;'a mut i32)
</code></pre>
<p>If you compare <code>&amp;mut i32</code> to <code>&amp;'a mut i32</code>, they’re the same, it’s just that
the lifetime <code>'a</code> has snuck in between the <code>&amp;</code> and the <code>mut i32</code>. We read <code>&amp;mut i32</code> as ‘a mutable reference to an <code>i32</code>’ and <code>&amp;'a mut i32</code> as ‘a mutable
reference to an <code>i32</code> with the lifetime <code>'a</code>’.</p>
<h1>In <code>struct</code>s</h1>
<p>You’ll also need explicit lifetimes when working with [<code>struct</code>]<a href="structs.html">structs</a>s that
contain references:</p>
<pre><code class="language-rust">struct Foo&lt;'a&gt; {
x: &amp;'a i32,
}
fn main() {
let y = &amp;5; // this is the same as `let _y = 5; let y = &amp;_y;`
let f = Foo { x: y };
println!(&quot;{}&quot;, f.x);
}
</code></pre>
<p>As you can see, <code>struct</code>s can also have lifetimes. In a similar way to functions,</p>
<pre><code class="language-rust">struct Foo&lt;'a&gt; {
# x: &amp;'a i32,
# }
</code></pre>
<p>declares a lifetime, and</p>
<pre><code class="language-rust"># struct Foo&lt;'a&gt; {
x: &amp;'a i32,
# }
</code></pre>
<p>uses it. So why do we need a lifetime here? We need to ensure that any reference
to a <code>Foo</code> cannot outlive the reference to an <code>i32</code> it contains.</p>
<h2><code>impl</code> blocks</h2>
<p>Let’s implement a method on <code>Foo</code>:</p>
<pre><code class="language-rust">struct Foo&lt;'a&gt; {
x: &amp;'a i32,
}
impl&lt;'a&gt; Foo&lt;'a&gt; {
fn x(&amp;self) -&gt; &amp;'a i32 { self.x }
}
fn main() {
let y = &amp;5; // this is the same as `let _y = 5; let y = &amp;_y;`
let f = Foo { x: y };
println!(&quot;x is: {}&quot;, f.x());
}
</code></pre>
<p>As you can see, we need to declare a lifetime for <code>Foo</code> in the <code>impl</code> line. We repeat
<code>'a</code> twice, just like on functions: <code>impl&lt;'a&gt;</code> defines a lifetime <code>'a</code>, and <code>Foo&lt;'a&gt;</code>
uses it.</p>
<h2>Multiple lifetimes</h2>
<p>If you have multiple references, you can use the same lifetime multiple times:</p>
<pre><code class="language-rust">fn x_or_y&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
# x
# }
</code></pre>
<p>This says that <code>x</code> and <code>y</code> both are alive for the same scope, and that the
return value is also alive for that scope. If you wanted <code>x</code> and <code>y</code> to have
different lifetimes, you can use multiple lifetime parameters:</p>
<pre><code class="language-rust">fn x_or_y&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;'a str {
# x
# }
</code></pre>
<p>In this example, <code>x</code> and <code>y</code> have different valid scopes, but the return value
has the same lifetime as <code>x</code>.</p>
<h2>Thinking in scopes</h2>
<p>A way to think about lifetimes is to visualize the scope that a reference is
valid for. For example:</p>
<pre><code class="language-rust">fn main() {
let y = &amp;5; // -+ y goes into scope
// |
// stuff // |
// |
} // -+ y goes out of scope
</code></pre>
<p>Adding in our <code>Foo</code>:</p>
<pre><code class="language-rust">struct Foo&lt;'a&gt; {
x: &amp;'a i32,
}
fn main() {
let y = &amp;5; // -+ y goes into scope
let f = Foo { x: y }; // -+ f goes into scope
// stuff // |
// |
} // -+ f and y go out of scope
</code></pre>
<p>Our <code>f</code> lives within the scope of <code>y</code>, so everything works. What if it didn’t?
This code won’t work:</p>
<pre><code class="language-rust,ignore">struct Foo&lt;'a&gt; {
x: &amp;'a i32,
}
fn main() {
let x; // -+ x goes into scope
// |
{ // |
let y = &amp;5; // ---+ y goes into scope
let f = Foo { x: y }; // ---+ f goes into scope
x = &amp;f.x; // | | error here
} // ---+ f and y go out of scope
// |
println!(&quot;{}&quot;, x); // |
} // -+ x goes out of scope
</code></pre>
<p>Whew! As you can see here, the scopes of <code>f</code> and <code>y</code> are smaller than the scope
of <code>x</code>. But when we do <code>x = &amp;f.x</code>, we make <code>x</code> a reference to something that’s
about to go out of scope.</p>
<p>Named lifetimes are a way of giving these scopes a name. Giving something a
name is the first step towards being able to talk about it.</p>
<h2>'static</h2>
<p>The lifetime named ‘static’ is a special lifetime. It signals that something
has the lifetime of the entire program. Most Rust programmers first come across
<code>'static</code> when dealing with strings:</p>
<pre><code class="language-rust">let x: &amp;'static str = &quot;Hello, world.&quot;;
</code></pre>
<p>String literals have the type <code>&amp;'static str</code> because the reference is always
alive: they are baked into the data segment of the final binary. Another
example are globals:</p>
<pre><code class="language-rust">static FOO: i32 = 5;
let x: &amp;'static i32 = &amp;FOO;
</code></pre>
<p>This adds an <code>i32</code> to the data segment of the binary, and <code>x</code> is a reference
to it.</p>
<h2>Lifetime Elision</h2>
<p>Rust supports powerful local type inference in function bodies, but it’s
forbidden in item signatures to allow reasoning about the types based on
the item signature alone. However, for ergonomic reasons a very restricted
secondary inference algorithm called “lifetime elision” applies in function
signatures. It infers only based on the signature components themselves and not
based on the body of the function, only infers lifetime parameters, and does
this with only three easily memorizable and unambiguous rules. This makes
lifetime elision a shorthand for writing an item signature, while not hiding
away the actual types involved as full local inference would if applied to it.</p>
<p>When talking about lifetime elision, we use the term <em>input lifetime</em> and
<em>output lifetime</em>. An <em>input lifetime</em> is a lifetime associated with a parameter
of a function, and an <em>output lifetime</em> is a lifetime associated with the return
value of a function. For example, this function has an input lifetime:</p>
<pre><code class="language-rust,ignore">fn foo&lt;'a&gt;(bar: &amp;'a str)
</code></pre>
<p>This one has an output lifetime:</p>
<pre><code class="language-rust,ignore">fn foo&lt;'a&gt;() -&gt; &amp;'a str
</code></pre>
<p>This one has a lifetime in both positions:</p>
<pre><code class="language-rust,ignore">fn foo&lt;'a&gt;(bar: &amp;'a str) -&gt; &amp;'a str
</code></pre>
<p>Here are the three rules:</p>
<ul>
<li>
<p>Each elided lifetime in a function’s arguments becomes a distinct lifetime
parameter.</p>
</li>
<li>
<p>If there is exactly one input lifetime, elided or not, that lifetime is
assigned to all elided lifetimes in the return values of that function.</p>
</li>
<li>
<p>If there are multiple input lifetimes, but one of them is <code>&amp;self</code> or <code>&amp;mut self</code>, the lifetime of <code>self</code> is assigned to all elided output lifetimes.</p>
</li>
</ul>
<p>Otherwise, it is an error to elide an output lifetime.</p>
<h3>Examples</h3>
<p>Here are some examples of functions with elided lifetimes. We’ve paired each
example of an elided lifetime with its expanded form.</p>
<pre><code class="language-rust,ignore">fn print(s: &amp;str); // elided
fn print&lt;'a&gt;(s: &amp;'a str); // expanded
fn debug(lvl: u32, s: &amp;str); // elided
fn debug&lt;'a&gt;(lvl: u32, s: &amp;'a str); // expanded
// In the preceding example, `lvl` doesn’t need a lifetime because it’s not a
// reference (`&amp;`). Only things relating to references (such as a `struct`
// which contains a reference) need lifetimes.
fn substr(s: &amp;str, until: u32) -&gt; &amp;str; // elided
fn substr&lt;'a&gt;(s: &amp;'a str, until: u32) -&gt; &amp;'a str; // expanded
fn get_str() -&gt; &amp;str; // ILLEGAL, no inputs
fn frob(s: &amp;str, t: &amp;str) -&gt; &amp;str; // ILLEGAL, two inputs
fn frob&lt;'a, 'b&gt;(s: &amp;'a str, t: &amp;'b str) -&gt; &amp;str; // Expanded: Output lifetime is ambiguous
fn get_mut(&amp;mut self) -&gt; &amp;mut T; // elided
fn get_mut&lt;'a&gt;(&amp;'a mut self) -&gt; &amp;'a mut T; // expanded
fn args&lt;T:ToCStr&gt;(&amp;mut self, args: &amp;[T]) -&gt; &amp;mut Command; // elided
fn args&lt;'a, 'b, T:ToCStr&gt;(&amp;'a mut self, args: &amp;'b [T]) -&gt; &amp;'a mut Command; // expanded
fn new(buf: &amp;mut [u8]) -&gt; BufWriter; // elided
fn new&lt;'a&gt;(buf: &amp;'a mut [u8]) -&gt; BufWriter&lt;'a&gt;; // expanded
</code></pre>
<h1>Basic Data Types</h1>
<h1>Structs</h1>
<p><code>struct</code>s are a way of creating more complex data types. For example, if we were
doing calculations involving coordinates in 2D space, we would need both an <code>x</code>
and a <code>y</code> value:</p>
<pre><code class="language-rust">let origin_x = 0;
let origin_y = 0;
</code></pre>
<p>A <code>struct</code> lets us combine these two into a single, unified datatype with <code>x</code>
and <code>y</code> as field labels:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
}
fn main() {
let origin = Point { x: 0, y: 0 }; // origin: Point
println!(&quot;The origin is at ({}, {})&quot;, origin.x, origin.y);
}
</code></pre>
<p>There’s a lot going on here, so let’s break it down. We declare a <code>struct</code> with
the <code>struct</code> keyword, and then with a name. By convention, <code>struct</code>s begin with
a capital letter and are camel cased: <code>PointInSpace</code>, not <code>Point_In_Space</code>.</p>
<p>We can create an instance of our <code>struct</code> via <code>let</code>, as usual, but we use a <code>key: value</code> style syntax to set each field. The order doesn’t need to be the same as
in the original declaration.</p>
<p>Finally, because fields have names, we can access them through dot
notation: <code>origin.x</code>.</p>
<p>The values in <code>struct</code>s are immutable by default, like other bindings in Rust.
Use <code>mut</code> to make them mutable:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
}
fn main() {
let mut point = Point { x: 0, y: 0 };
point.x = 5;
println!(&quot;The point is at ({}, {})&quot;, point.x, point.y);
}
</code></pre>
<p>This will print <code>The point is at (5, 0)</code>.</p>
<p>Rust does not support field mutability at the language level, so you cannot
write something like this:</p>
<pre><code class="language-rust,ignore">struct Point {
mut x: i32,
y: i32,
}
</code></pre>
<p>Mutability is a property of the binding, not of the structure itself. If you’re
used to field-level mutability, this may seem strange at first, but it
significantly simplifies things. It even lets you make things mutable on a temporary
basis:</p>
<pre><code class="language-rust,ignore">struct Point {
x: i32,
y: i32,
}
fn main() {
let mut point = Point { x: 0, y: 0 };
point.x = 5;
let point = point; // now immutable
point.y = 6; // this causes an error
}
</code></pre>
<h1>Update syntax</h1>
<p>A <code>struct</code> can include <code>..</code> to indicate that you want to use a copy of some
other <code>struct</code> for some of the values. For example:</p>
<pre><code class="language-rust">struct Point3d {
x: i32,
y: i32,
z: i32,
}
let mut point = Point3d { x: 0, y: 0, z: 0 };
point = Point3d { y: 1, .. point };
</code></pre>
<p>This gives <code>point</code> a new <code>y</code>, but keeps the old <code>x</code> and <code>z</code> values. It doesn’t
have to be the same <code>struct</code> either, you can use this syntax when making new
ones, and it will copy the values you don’t specify:</p>
<pre><code class="language-rust"># struct Point3d {
# x: i32,
# y: i32,
# z: i32,
# }
let origin = Point3d { x: 0, y: 0, z: 0 };
let point = Point3d { z: 1, x: 2, .. origin };
</code></pre>
<h1>Tuple structs</h1>
<p>Rust has another data type that’s like a hybrid between a <a href="primitive-types.html#tuples">tuple</a> and a
<code>struct</code>, called a ‘tuple struct’. Tuple structs have a name, but their fields
don't. They are declared with the <code>struct</code> keyword, and then with a name
followed by a tuple:</p>
<pre><code class="language-rust">struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
</code></pre>
<p>Here, <code>black</code> and <code>origin</code> are not equal, even though they contain the same
values.</p>
<p>It is almost always better to use a <code>struct</code> than a tuple struct. We
would write <code>Color</code> and <code>Point</code> like this instead:</p>
<pre><code class="language-rust">struct Color {
red: i32,
blue: i32,
green: i32,
}
struct Point {
x: i32,
y: i32,
z: i32,
}
</code></pre>
<p>Good names are important, and while values in a tuple struct can be
referenced with dot notation as well, a <code>struct</code> gives us actual names,
rather than positions.</p>
<p>There <em>is</em> one case when a tuple struct is very useful, though, and that is when
it has only one element. We call this the ‘newtype’ pattern, because
it allows you to create a new type that is distinct from its contained value
and also expresses its own semantic meaning:</p>
<pre><code class="language-rust">struct Inches(i32);
let length = Inches(10);
let Inches(integer_length) = length;
println!(&quot;length is {} inches&quot;, integer_length);
</code></pre>
<p>As you can see here, you can extract the inner integer type through a
destructuring <code>let</code>, just as with regular tuples. In this case, the
<code>let Inches(integer_length)</code> assigns <code>10</code> to <code>integer_length</code>.</p>
<h1>Unit-like structs</h1>
<p>You can define a <code>struct</code> with no members at all:</p>
<pre><code class="language-rust">struct Electron;
let x = Electron;
</code></pre>
<p>Such a <code>struct</code> is called ‘unit-like’ because it resembles the empty
tuple, <code>()</code>, sometimes called ‘unit’. Like a tuple struct, it defines a
new type.</p>
<p>This is rarely useful on its own (although sometimes it can serve as a
marker type), but in combination with other features, it can become
useful. For instance, a library may ask you to create a structure that
implements a certain <a href="traits.html">trait</a> to handle events. If you don’t have
any data you need to store in the structure, you can just create a
unit-like <code>struct</code>.</p>
<h1>Enums</h1>
<p>An <code>enum</code> in Rust is a type that represents data that is one of
several possible variants. Each variant in the <code>enum</code> can optionally
have data associated with it:</p>
<pre><code class="language-rust">enum Message {
Quit,
ChangeColor(i32, i32, i32),
Move { x: i32, y: i32 },
Write(String),
}
</code></pre>
<p>The syntax for defining variants resembles the syntaxes used to define structs:
you can have variants with no data (like unit-like structs), variants with named
data, and variants with unnamed data (like tuple structs). Unlike
separate struct definitions, however, an <code>enum</code> is a single type. A
value of the enum can match any of the variants. For this reason, an
enum is sometimes called a ‘sum type’: the set of possible values of the
enum is the sum of the sets of possible values for each variant.</p>
<p>We use the <code>::</code> syntax to use the name of each variant: they’re scoped by the name
of the <code>enum</code> itself. This allows both of these to work:</p>
<pre><code class="language-rust"># enum Message {
# Move { x: i32, y: i32 },
# }
let x: Message = Message::Move { x: 3, y: 4 };
enum BoardGameTurn {
Move { squares: i32 },
Pass,
}
let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };
</code></pre>
<p>Both variants are named <code>Move</code>, but since they’re scoped to the name of
the enum, they can both be used without conflict.</p>
<p>A value of an <code>enum</code> type contains information about which variant it is,
in addition to any data associated with that variant. This is sometimes
referred to as a ‘tagged union’, since the data includes a ‘tag’
indicating what type it is. The compiler uses this information to
enforce that you’re accessing the data in the enum safely. For instance,
you can’t simply try to destructure a value as if it were one of the
possible variants:</p>
<pre><code class="language-rust,ignore">fn process_color_change(msg: Message) {
let Message::ChangeColor(r, g, b) = msg; // compile-time error
}
</code></pre>
<p>Not supporting these operations may seem rather limiting, but it’s a limitation
which we can overcome. There are two ways: by implementing equality ourselves,
or by pattern matching variants with [<code>match</code>]<a href="match.html">match</a> expressions, which you’ll
learn in the next section. We don’t know enough about Rust to implement
equality yet, but we’ll find out in the [<code>traits</code>]<a href="traits.html">traits</a> section.</p>
<h1>Constructors as functions</h1>
<p>An <code>enum</code> constructor can also be used like a function. For example:</p>
<pre><code class="language-rust"># enum Message {
# Write(String),
# }
let m = Message::Write(&quot;Hello, world&quot;.to_string());
</code></pre>
<p>is the same as</p>
<pre><code class="language-rust"># enum Message {
# Write(String),
# }
fn foo(x: String) -&gt; Message {
Message::Write(x)
}
let x = foo(&quot;Hello, world&quot;.to_string());
</code></pre>
<p>This is not immediately useful to us, but when we get to
[<code>closures</code>]<a href="closures.html">closures</a>, we’ll talk about passing functions as arguments to
other functions. For example, with [<code>iterators</code>]<a href="iterators.html">iterators</a>, we can do this
to convert a vector of <code>String</code>s into a vector of <code>Message::Write</code>s:</p>
<pre><code class="language-rust"># enum Message {
# Write(String),
# }
let v = vec![&quot;Hello&quot;.to_string(), &quot;World&quot;.to_string()];
let v1: Vec&lt;Message&gt; = v.into_iter().map(Message::Write).collect();
</code></pre>
<h1>Crates and Modules</h1>
<p>When a project starts getting large, it’s considered good software
engineering practice to split it up into a bunch of smaller pieces, and then
fit them together. It’s also important to have a well-defined interface, so
that some of your functionality is private, and some is public. To facilitate
these kinds of things, Rust has a module system.</p>
<h1>Basic terminology: Crates and Modules</h1>
<p>Rust has two distinct terms that relate to the module system: ‘crate’ and
‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other
languages. Hence “Cargo” as the name of Rust’s package management tool: you
ship your crates to others with Cargo. Crates can produce an executable or a
library, depending on the project.</p>
<p>Each crate has an implicit <em>root module</em> that contains the code for that crate.
You can then define a tree of sub-modules under that root module. Modules allow
you to partition your code within the crate itself.</p>
<p>As an example, let’s make a <em>phrases</em> crate, which will give us various phrases
in different languages. To keep things simple, we’ll stick to ‘greetings’ and
‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as
two languages for those phrases to be in. We’ll use this module layout:</p>
<pre><code class="language-text"> +-----------+
+---| greetings |
| +-----------+
+---------+ |
+---| english |---+
| +---------+ | +-----------+
| +---| farewells |
+---------+ | +-----------+
| phrases |---+
+---------+ | +-----------+
| +---| greetings |
| +----------+ | +-----------+
+---| japanese |--+
+----------+ |
| +-----------+
+---| farewells |
+-----------+
</code></pre>
<p>In this example, <code>phrases</code> is the name of our crate. All of the rest are
modules. You can see that they form a tree, branching out from the crate
<em>root</em>, which is the root of the tree: <code>phrases</code> itself.</p>
<p>Now that we have a plan, let’s define these modules in code. To start,
generate a new crate with Cargo:</p>
<pre><code class="language-bash">$ cargo new phrases
$ cd phrases
</code></pre>
<p>If you remember, this generates a simple project for us:</p>
<pre><code class="language-bash">$ tree .
.
├── Cargo.toml
└── src
└── lib.rs
1 directory, 2 files
</code></pre>
<p><code>src/lib.rs</code> is our crate root, corresponding to the <code>phrases</code> in our diagram
above.</p>
<h1>Defining Modules</h1>
<p>To define each of our modules, we use the <code>mod</code> keyword. Let’s make our
<code>src/lib.rs</code> look like this:</p>
<pre><code class="language-rust">mod english {
mod greetings {
}
mod farewells {
}
}
mod japanese {
mod greetings {
}
mod farewells {
}
}
</code></pre>
<p>After the <code>mod</code> keyword, you give the name of the module. Module names follow
the conventions for other Rust identifiers: <code>lower_snake_case</code>. The contents of
each module are within curly braces (<code>{}</code>).</p>
<p>Within a given <code>mod</code>, you can declare sub-<code>mod</code>s. We can refer to sub-modules
with double-colon (<code>::</code>) notation: our four nested modules are
<code>english::greetings</code>, <code>english::farewells</code>, <code>japanese::greetings</code>, and
<code>japanese::farewells</code>. Because these sub-modules are namespaced under their
parent module, the names don’t conflict: <code>english::greetings</code> and
<code>japanese::greetings</code> are distinct, even though their names are both
<code>greetings</code>.</p>
<p>Because this crate does not have a <code>main()</code> function, and is called <code>lib.rs</code>,
Cargo will build this crate as a library:</p>
<pre><code class="language-bash">$ cargo build
Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
$ ls target/debug
build deps examples libphrases-a7448e02a0468eaa.rlib native
</code></pre>
<p><code>libphrases-hash.rlib</code> is the compiled crate. Before we see how to use this
crate from another crate, let’s break it up into multiple files.</p>
<h1>Multiple file crates</h1>
<p>If each crate were just one file, these files would get very large. It’s often
easier to split up crates into multiple files, and Rust supports this in two
ways.</p>
<p>Instead of declaring a module like this:</p>
<pre><code class="language-rust,ignore">mod english {
// contents of our module go here
}
</code></pre>
<p>We can instead declare our module like this:</p>
<pre><code class="language-rust,ignore">mod english;
</code></pre>
<p>If we do that, Rust will expect to find either a <code>english.rs</code> file, or a
<code>english/mod.rs</code> file with the contents of our module.</p>
<p>Note that in these files, you don’t need to re-declare the module: that’s
already been done with the initial <code>mod</code> declaration.</p>
<p>Using these two techniques, we can break up our crate into two directories and
seven files:</p>
<pre><code class="language-bash">$ tree .
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── english
│   │   ├── farewells.rs
│   │   ├── greetings.rs
│   │   └── mod.rs
│   ├── japanese
│   │   ├── farewells.rs
│   │   ├── greetings.rs
│   │   └── mod.rs
│   └── lib.rs
└── target
└── debug
├── build
├── deps
├── examples
├── libphrases-a7448e02a0468eaa.rlib
└── native
</code></pre>
<p><code>src/lib.rs</code> is our crate root, and looks like this:</p>
<pre><code class="language-rust,ignore">mod english;
mod japanese;
</code></pre>
<p>These two declarations tell Rust to look for either <code>src/english.rs</code> and
<code>src/japanese.rs</code>, or <code>src/english/mod.rs</code> and <code>src/japanese/mod.rs</code>, depending
on our preference. In this case, because our modules have sub-modules, we’ve
chosen the second. Both <code>src/english/mod.rs</code> and <code>src/japanese/mod.rs</code> look
like this:</p>
<pre><code class="language-rust,ignore">mod greetings;
mod farewells;
</code></pre>
<p>Again, these declarations tell Rust to look for either
<code>src/english/greetings.rs</code> and <code>src/japanese/greetings.rs</code> or
<code>src/english/farewells/mod.rs</code> and <code>src/japanese/farewells/mod.rs</code>. Because
these sub-modules don’t have their own sub-modules, we’ve chosen to make them
<code>src/english/greetings.rs</code> and <code>src/japanese/farewells.rs</code>. Whew!</p>
<p>The contents of <code>src/english/greetings.rs</code> and <code>src/japanese/farewells.rs</code> are
both empty at the moment. Let’s add some functions.</p>
<p>Put this in <code>src/english/greetings.rs</code>:</p>
<pre><code class="language-rust">fn hello() -&gt; String {
&quot;Hello!&quot;.to_string()
}
</code></pre>
<p>Put this in <code>src/english/farewells.rs</code>:</p>
<pre><code class="language-rust">fn goodbye() -&gt; String {
&quot;Goodbye.&quot;.to_string()
}
</code></pre>
<p>Put this in <code>src/japanese/greetings.rs</code>:</p>
<pre><code class="language-rust">fn hello() -&gt; String {
&quot;こんにちは&quot;.to_string()
}
</code></pre>
<p>Of course, you can copy and paste this from this web page, or just type
something else. It’s not important that you actually put ‘konnichiwa’ to learn
about the module system.</p>
<p>Put this in <code>src/japanese/farewells.rs</code>:</p>
<pre><code class="language-rust">fn goodbye() -&gt; String {
&quot;さようなら&quot;.to_string()
}
</code></pre>
<p>(This is ‘Sayōnara’, if you’re curious.)</p>
<p>Now that we have some functionality in our crate, let’s try to use it from
another crate.</p>
<h1>Importing External Crates</h1>
<p>We have a library crate. Let’s make an executable crate that imports and uses
our library.</p>
<p>Make a <code>src/main.rs</code> and put this in it (it won’t quite compile yet):</p>
<pre><code class="language-rust,ignore">extern crate phrases;
fn main() {
println!(&quot;Hello in English: {}&quot;, phrases::english::greetings::hello());
println!(&quot;Goodbye in English: {}&quot;, phrases::english::farewells::goodbye());
println!(&quot;Hello in Japanese: {}&quot;, phrases::japanese::greetings::hello());
println!(&quot;Goodbye in Japanese: {}&quot;, phrases::japanese::farewells::goodbye());
}
</code></pre>
<p>The <code>extern crate</code> declaration tells Rust that we need to compile and link to
the <code>phrases</code> crate. We can then use <code>phrases</code>’ modules in this one. As we
mentioned earlier, you can use double colons to refer to sub-modules and the
functions inside of them.</p>
<p>(Note: when importing a crate that has dashes in its name &quot;like-this&quot;, which is
not a valid Rust identifier, it will be converted by changing the dashes to
underscores, so you would write <code>extern crate like_this;</code>.)</p>
<p>Also, Cargo assumes that <code>src/main.rs</code> is the crate root of a binary crate,
rather than a library crate. Our package now has two crates: <code>src/lib.rs</code> and
<code>src/main.rs</code>. This pattern is quite common for executable crates: most
functionality is in a library crate, and the executable crate uses that
library. This way, other programs can also use the library crate, and it’s also
a nice separation of concerns.</p>
<p>This doesn’t quite work yet, though. We get four errors that look similar to
this:</p>
<pre><code class="language-bash">$ cargo build
Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
src/main.rs:4:38: 4:72 error: function `hello` is private
src/main.rs:4 println!(&quot;Hello in English: {}&quot;, phrases::english::greetings::hello());
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in expansion of format_args!
&lt;std macros&gt;:2:25: 2:58 note: expansion site
&lt;std macros&gt;:1:1: 2:62 note: in expansion of print!
&lt;std macros&gt;:3:1: 3:54 note: expansion site
&lt;std macros&gt;:1:1: 3:58 note: in expansion of println!
phrases/src/main.rs:4:5: 4:76 note: expansion site
</code></pre>
<p>By default, everything is private in Rust. Let’s talk about this in some more
depth.</p>
<h1>Exporting a Public Interface</h1>
<p>Rust allows you to precisely control which aspects of your interface are
public, and so private is the default. To make things public, you use the <code>pub</code>
keyword. Let’s focus on the <code>english</code> module first, so let’s reduce our <code>src/main.rs</code>
to just this:</p>
<pre><code class="language-rust,ignore">extern crate phrases;
fn main() {
println!(&quot;Hello in English: {}&quot;, phrases::english::greetings::hello());
println!(&quot;Goodbye in English: {}&quot;, phrases::english::farewells::goodbye());
}
</code></pre>
<p>In our <code>src/lib.rs</code>, let’s add <code>pub</code> to the <code>english</code> module declaration:</p>
<pre><code class="language-rust,ignore">pub mod english;
mod japanese;
</code></pre>
<p>And in our <code>src/english/mod.rs</code>, let’s make both <code>pub</code>:</p>
<pre><code class="language-rust,ignore">pub mod greetings;
pub mod farewells;
</code></pre>
<p>In our <code>src/english/greetings.rs</code>, let’s add <code>pub</code> to our <code>fn</code> declaration:</p>
<pre><code class="language-rust,ignore">pub fn hello() -&gt; String {
&quot;Hello!&quot;.to_string()
}
</code></pre>
<p>And also in <code>src/english/farewells.rs</code>:</p>
<pre><code class="language-rust,ignore">pub fn goodbye() -&gt; String {
&quot;Goodbye.&quot;.to_string()
}
</code></pre>
<p>Now, our crate compiles, albeit with warnings about not using the <code>japanese</code>
functions:</p>
<pre><code class="language-bash">$ cargo run
Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
src/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default
src/japanese/greetings.rs:1 fn hello() -&gt; String {
src/japanese/greetings.rs:2 &quot;こんにちは&quot;.to_string()
src/japanese/greetings.rs:3 }
src/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default
src/japanese/farewells.rs:1 fn goodbye() -&gt; String {
src/japanese/farewells.rs:2 &quot;さようなら&quot;.to_string()
src/japanese/farewells.rs:3 }
Running `target/debug/phrases`
Hello in English: Hello!
Goodbye in English: Goodbye.
</code></pre>
<p><code>pub</code> also applies to <code>struct</code>s and their member fields. In keeping with Rust’s
tendency toward safety, simply making a <code>struct</code> public won't automatically
make its members public: you must mark the fields individually with <code>pub</code>.</p>
<p>Now that our functions are public, we can use them. Great! However, typing out
<code>phrases::english::greetings::hello()</code> is very long and repetitive. Rust has
another keyword for importing names into the current scope, so that you can
refer to them with shorter names. Let’s talk about <code>use</code>.</p>
<h1>Importing Modules with <code>use</code></h1>
<p>Rust has a <code>use</code> keyword, which allows us to import names into our local scope.
Let’s change our <code>src/main.rs</code> to look like this:</p>
<pre><code class="language-rust,ignore">extern crate phrases;
use phrases::english::greetings;
use phrases::english::farewells;
fn main() {
println!(&quot;Hello in English: {}&quot;, greetings::hello());
println!(&quot;Goodbye in English: {}&quot;, farewells::goodbye());
}
</code></pre>
<p>The two <code>use</code> lines import each module into the local scope, so we can refer to
the functions by a much shorter name. By convention, when importing functions, it’s
considered best practice to import the module, rather than the function directly. In
other words, you <em>can</em> do this:</p>
<pre><code class="language-rust,ignore">extern crate phrases;
use phrases::english::greetings::hello;
use phrases::english::farewells::goodbye;
fn main() {
println!(&quot;Hello in English: {}&quot;, hello());
println!(&quot;Goodbye in English: {}&quot;, goodbye());
}
</code></pre>
<p>But it is not idiomatic. This is significantly more likely to introduce a
naming conflict. In our short program, it’s not a big deal, but as it grows, it
becomes a problem. If we have conflicting names, Rust will give a compilation
error. For example, if we made the <code>japanese</code> functions public, and tried to do
this:</p>
<pre><code class="language-rust,ignore">extern crate phrases;
use phrases::english::greetings::hello;
use phrases::japanese::greetings::hello;
fn main() {
println!(&quot;Hello in English: {}&quot;, hello());
println!(&quot;Hello in Japanese: {}&quot;, hello());
}
</code></pre>
<p>Rust will give us a compile-time error:</p>
<pre><code class="language-text"> Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
src/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252]
src/main.rs:4 use phrases::japanese::greetings::hello;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `phrases`.
</code></pre>
<p>If we’re importing multiple names from the same module, we don’t have to type it out
twice. Instead of this:</p>
<pre><code class="language-rust,ignore">use phrases::english::greetings;
use phrases::english::farewells;
</code></pre>
<p>We can use this shortcut:</p>
<pre><code class="language-rust,ignore">use phrases::english::{greetings, farewells};
</code></pre>
<h2>Re-exporting with <code>pub use</code></h2>
<p>You don’t just use <code>use</code> to shorten identifiers. You can also use it inside of your crate
to re-export a function inside another module. This allows you to present an external
interface that may not directly map to your internal code organization.</p>
<p>Let’s look at an example. Modify your <code>src/main.rs</code> to read like this:</p>
<pre><code class="language-rust,ignore">extern crate phrases;
use phrases::english::{greetings,farewells};
use phrases::japanese;
fn main() {
println!(&quot;Hello in English: {}&quot;, greetings::hello());
println!(&quot;Goodbye in English: {}&quot;, farewells::goodbye());
println!(&quot;Hello in Japanese: {}&quot;, japanese::hello());
println!(&quot;Goodbye in Japanese: {}&quot;, japanese::goodbye());
}
</code></pre>
<p>Then, modify your <code>src/lib.rs</code> to make the <code>japanese</code> mod public:</p>
<pre><code class="language-rust,ignore">pub mod english;
pub mod japanese;
</code></pre>
<p>Next, make the two functions public, first in <code>src/japanese/greetings.rs</code>:</p>
<pre><code class="language-rust,ignore">pub fn hello() -&gt; String {
&quot;こんにちは&quot;.to_string()
}
</code></pre>
<p>And then in <code>src/japanese/farewells.rs</code>:</p>
<pre><code class="language-rust,ignore">pub fn goodbye() -&gt; String {
&quot;さようなら&quot;.to_string()
}
</code></pre>
<p>Finally, modify your <code>src/japanese/mod.rs</code> to read like this:</p>
<pre><code class="language-rust,ignore">pub use self::greetings::hello;
pub use self::farewells::goodbye;
mod greetings;
mod farewells;
</code></pre>
<p>The <code>pub use</code> declaration brings the function into scope at this part of our
module hierarchy. Because we’ve <code>pub use</code>d this inside of our <code>japanese</code>
module, we now have a <code>phrases::japanese::hello()</code> function and a
<code>phrases::japanese::goodbye()</code> function, even though the code for them lives in
<code>phrases::japanese::greetings::hello()</code> and
<code>phrases::japanese::farewells::goodbye()</code>. Our internal organization doesn’t
define our external interface.</p>
<p>Here we have a <code>pub use</code> for each function we want to bring into the
<code>japanese</code> scope. We could alternatively use the wildcard syntax to include
everything from <code>greetings</code> into the current scope: <code>pub use self::greetings::*</code>.</p>
<p>What about the <code>self</code>? Well, by default, <code>use</code> declarations are absolute paths,
starting from your crate root. <code>self</code> makes that path relative to your current
place in the hierarchy instead. There’s one more special form of <code>use</code>: you can
<code>use super::</code> to reach one level up the tree from your current location. Some
people like to think of <code>self</code> as <code>.</code> and <code>super</code> as <code>..</code>, from many shells’
display for the current directory and the parent directory.</p>
<p>Outside of <code>use</code>, paths are relative: <code>foo::bar()</code> refers to a function inside
of <code>foo</code> relative to where we are. If that’s prefixed with <code>::</code>, as in
<code>::foo::bar()</code>, it refers to a different <code>foo</code>, an absolute path from your
crate root.</p>
<p>This will build and run:</p>
<pre><code class="language-bash">$ cargo run
Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
Running `target/debug/phrases`
Hello in English: Hello!
Goodbye in English: Goodbye.
Hello in Japanese: こんにちは
Goodbye in Japanese: さようなら
</code></pre>
<h2>Complex imports</h2>
<p>Rust offers several advanced options that can add compactness and
convenience to your <code>extern crate</code> and <code>use</code> statements. Here is an example:</p>
<pre><code class="language-rust,ignore">extern crate phrases as sayings;
use sayings::japanese::greetings as ja_greetings;
use sayings::japanese::farewells::*;
use sayings::english::{self, greetings as en_greetings, farewells as en_farewells};
fn main() {
println!(&quot;Hello in English; {}&quot;, en_greetings::hello());
println!(&quot;And in Japanese: {}&quot;, ja_greetings::hello());
println!(&quot;Goodbye in English: {}&quot;, english::farewells::goodbye());
println!(&quot;Again: {}&quot;, en_farewells::goodbye());
println!(&quot;And in Japanese: {}&quot;, goodbye());
}
</code></pre>
<p>What's going on here?</p>
<p>First, both <code>extern crate</code> and <code>use</code> allow renaming the thing that is being
imported. So the crate is still called &quot;phrases&quot;, but here we will refer
to it as &quot;sayings&quot;. Similarly, the first <code>use</code> statement pulls in the
<code>japanese::greetings</code> module from the crate, but makes it available as
<code>ja_greetings</code> as opposed to simply <code>greetings</code>. This can help to avoid
ambiguity when importing similarly-named items from different places.</p>
<p>The second <code>use</code> statement uses a star glob to bring in <em>all</em> symbols from the
<code>sayings::japanese::farewells</code> module. As you can see we can later refer to
the Japanese <code>goodbye</code> function with no module qualifiers. This kind of glob
should be used sparingly.</p>
<p>The third <code>use</code> statement bears more explanation. It's using &quot;brace expansion&quot;
globbing to compress three <code>use</code> statements into one (this sort of syntax
may be familiar if you've written Linux shell scripts before). The
uncompressed form of this statement would be:</p>
<pre><code class="language-rust,ignore">use sayings::english;
use sayings::english::greetings as en_greetings;
use sayings::english::farewells as en_farewells;
</code></pre>
<p>As you can see, the curly brackets compress <code>use</code> statements for several items
under the same path, and in this context <code>self</code> just refers back to that path.
Note: The curly brackets cannot be nested or mixed with star globbing.</p>
<h1>Error Handling</h1>
<h1>Basic Collections</h1>
<h1>Vectors</h1>
<p>A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard
library type [<code>Vec&lt;T&gt;</code>]<a href="../std/vec/index.html">vec</a>. The <code>T</code> means that we can have vectors
of any type (see the chapter on <a href="generics.html">generics</a> for more).
Vectors always allocate their data on the heap.
You can create them with the <code>vec!</code> macro:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3, 4, 5]; // v: Vec&lt;i32&gt;
</code></pre>
<p>(Notice that unlike the <code>println!</code> macro we’ve used in the past, we use square
brackets <code>[]</code> with <code>vec!</code> macro. Rust allows you to use either in either situation,
this is just convention.)</p>
<p>There’s an alternate form of <code>vec!</code> for repeating an initial value:</p>
<pre><code class="language-rust">let v = vec![0; 10]; // ten zeroes
</code></pre>
<h2>Accessing elements</h2>
<p>To get the value at a particular index in the vector, we use <code>[]</code>s:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3, 4, 5];
println!(&quot;The third element of v is {}&quot;, v[2]);
</code></pre>
<p>The indices count from <code>0</code>, so the third element is <code>v[2]</code>.</p>
<p>It’s also important to note that you must index with the <code>usize</code> type:</p>
<pre><code class="language-ignore">let v = vec![1, 2, 3, 4, 5];
let i: usize = 0;
let j: i32 = 0;
// works
v[i];
// doesn’t
v[j];
</code></pre>
<p>Indexing with a non-<code>usize</code> type gives an error that looks like this:</p>
<pre><code class="language-text">error: the trait `core::ops::Index&lt;i32&gt;` is not implemented for the type
`collections::vec::Vec&lt;_&gt;` [E0277]
v[j];
^~~~
note: the type `collections::vec::Vec&lt;_&gt;` cannot be indexed by `i32`
error: aborting due to previous error
</code></pre>
<p>There’s a lot of punctuation in that message, but the core of it makes sense:
you cannot index with an <code>i32</code>.</p>
<h2>Iterating</h2>
<p>Once you have a vector, you can iterate through its elements with <code>for</code>. There
are three versions:</p>
<pre><code class="language-rust">let mut v = vec![1, 2, 3, 4, 5];
for i in &amp;v {
println!(&quot;A reference to {}&quot;, i);
}
for i in &amp;mut v {
println!(&quot;A mutable reference to {}&quot;, i);
}
for i in v {
println!(&quot;Take ownership of the vector and its element {}&quot;, i);
}
</code></pre>
<p>Vectors have many more useful methods, which you can read about in <a href="../std/vec/index.html">their
API documentation</a>.</p>
<h1>Strings</h1>
<h1><code>HashMap&lt;K, V&gt;</code></h1>
<h1>Traits</h1>
<p>A trait is a language feature that tells the Rust compiler about
functionality a type must provide.</p>
<p>Recall the <code>impl</code> keyword, used to call a function with <a href="method-syntax.html">method
syntax</a>:</p>
<pre><code class="language-rust">struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl Circle {
fn area(&amp;self) -&gt; f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
</code></pre>
<p>Traits are similar, except that we first define a trait with a method
signature, then implement the trait for a type. In this example, we implement the trait <code>HasArea</code> for <code>Circle</code>:</p>
<pre><code class="language-rust">struct Circle {
x: f64,
y: f64,
radius: f64,
}
trait HasArea {
fn area(&amp;self) -&gt; f64;
}
impl HasArea for Circle {
fn area(&amp;self) -&gt; f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
</code></pre>
<p>As you can see, the <code>trait</code> block looks very similar to the <code>impl</code> block,
but we don’t define a body, just a type signature. When we <code>impl</code> a trait,
we use <code>impl Trait for Item</code>, rather than just <code>impl Item</code>.</p>
<h2>Trait bounds on generic functions</h2>
<p>Traits are useful because they allow a type to make certain promises about its
behavior. Generic functions can exploit this to constrain, or <a href="glossary.html#bounds">bound</a>, the types they
accept. Consider this function, which does not compile:</p>
<pre><code class="language-rust,ignore">fn print_area&lt;T&gt;(shape: T) {
println!(&quot;This shape has an area of {}&quot;, shape.area());
}
</code></pre>
<p>Rust complains:</p>
<pre><code class="language-text">error: no method named `area` found for type `T` in the current scope
</code></pre>
<p>Because <code>T</code> can be any type, we can’t be sure that it implements the <code>area</code>
method. But we can add a trait bound to our generic <code>T</code>, ensuring
that it does:</p>
<pre><code class="language-rust"># trait HasArea {
# fn area(&amp;self) -&gt; f64;
# }
fn print_area&lt;T: HasArea&gt;(shape: T) {
println!(&quot;This shape has an area of {}&quot;, shape.area());
}
</code></pre>
<p>The syntax <code>&lt;T: HasArea&gt;</code> means “any type that implements the <code>HasArea</code> trait.”
Because traits define function type signatures, we can be sure that any type
which implements <code>HasArea</code> will have an <code>.area()</code> method.</p>
<p>Here’s an extended example of how this works:</p>
<pre><code class="language-rust">trait HasArea {
fn area(&amp;self) -&gt; f64;
}
struct Circle {
x: f64,
y: f64,
radius: f64,
}
impl HasArea for Circle {
fn area(&amp;self) -&gt; f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
}
struct Square {
x: f64,
y: f64,
side: f64,
}
impl HasArea for Square {
fn area(&amp;self) -&gt; f64 {
self.side * self.side
}
}
fn print_area&lt;T: HasArea&gt;(shape: T) {
println!(&quot;This shape has an area of {}&quot;, shape.area());
}
fn main() {
let c = Circle {
x: 0.0f64,
y: 0.0f64,
radius: 1.0f64,
};
let s = Square {
x: 0.0f64,
y: 0.0f64,
side: 1.0f64,
};
print_area(c);
print_area(s);
}
</code></pre>
<p>This program outputs:</p>
<pre><code class="language-text">This shape has an area of 3.141593
This shape has an area of 1
</code></pre>
<p>As you can see, <code>print_area</code> is now generic, but also ensures that we have
passed in the correct types. If we pass in an incorrect type:</p>
<pre><code class="language-rust,ignore">print_area(5);
</code></pre>
<p>We get a compile-time error:</p>
<pre><code class="language-text">error: the trait `HasArea` is not implemented for the type `_` [E0277]
</code></pre>
<h2>Trait bounds on generic structs</h2>
<p>Your generic structs can also benefit from trait bounds. All you need to
do is append the bound when you declare type parameters. Here is a new
type <code>Rectangle&lt;T&gt;</code> and its operation <code>is_square()</code>:</p>
<pre><code class="language-rust">struct Rectangle&lt;T&gt; {
x: T,
y: T,
width: T,
height: T,
}
impl&lt;T: PartialEq&gt; Rectangle&lt;T&gt; {
fn is_square(&amp;self) -&gt; bool {
self.width == self.height
}
}
fn main() {
let mut r = Rectangle {
x: 0,
y: 0,
width: 47,
height: 47,
};
assert!(r.is_square());
r.height = 42;
assert!(!r.is_square());
}
</code></pre>
<p><code>is_square()</code> needs to check that the sides are equal, so the sides must be of
a type that implements the [<code>core::cmp::PartialEq</code>]<a href="../core/cmp/trait.PartialEq.html">PartialEq</a> trait:</p>
<pre><code class="language-ignore">impl&lt;T: PartialEq&gt; Rectangle&lt;T&gt; { ... }
</code></pre>
<p>Now, a rectangle can be defined in terms of any type that can be compared for
equality.</p>
<p>Here we defined a new struct <code>Rectangle</code> that accepts numbers of any
precision—really, objects of pretty much any type—as long as they can be
compared for equality. Could we do the same for our <code>HasArea</code> structs, <code>Square</code>
and <code>Circle</code>? Yes, but they need multiplication, and to work with that we need
to know more about <a href="operators-and-overloading.html">operator traits</a>.</p>
<h1>Rules for implementing traits</h1>
<p>So far, we’ve only added trait implementations to structs, but you can
implement a trait for any type. So technically, we <em>could</em> implement <code>HasArea</code>
for <code>i32</code>:</p>
<pre><code class="language-rust">trait HasArea {
fn area(&amp;self) -&gt; f64;
}
impl HasArea for i32 {
fn area(&amp;self) -&gt; f64 {
println!(&quot;this is silly&quot;);
*self as f64
}
}
5.area();
</code></pre>
<p>It is considered poor style to implement methods on such primitive types, even
though it is possible.</p>
<p>This may seem like the Wild West, but there are two restrictions around
implementing traits that prevent this from getting out of hand. The first is
that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an
example: the standard library provides a [<code>Write</code>]<a href="../std/io/trait.Write.html">write</a> trait which adds
extra functionality to <code>File</code>s, for doing file I/O. By default, a <code>File</code>
won’t have its methods:</p>
<pre><code class="language-rust,ignore">let mut f = std::fs::File::open(&quot;foo.txt&quot;).expect(&quot;Couldn’t open foo.txt&quot;);
let buf = b&quot;whatever&quot;; // byte string literal. buf: &amp;[u8; 8]
let result = f.write(buf);
# result.unwrap(); // ignore the error
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error: type `std::fs::File` does not implement any method in scope named `write`
let result = f.write(buf);
^~~~~~~~~~
</code></pre>
<p>We need to <code>use</code> the <code>Write</code> trait first:</p>
<pre><code class="language-rust,ignore">use std::io::Write;
let mut f = std::fs::File::open(&quot;foo.txt&quot;).expect(&quot;Couldn’t open foo.txt&quot;);
let buf = b&quot;whatever&quot;;
let result = f.write(buf);
# result.unwrap(); // ignore the error
</code></pre>
<p>This will compile without error.</p>
<p>This means that even if someone does something bad like add methods to <code>i32</code>,
it won’t affect you, unless you <code>use</code> that trait.</p>
<p>There’s one more restriction on implementing traits: either the trait, or the
type you’re writing the <code>impl</code> for, must be defined by you. So, we could
implement the <code>HasArea</code> type for <code>i32</code>, because <code>HasArea</code> is in our code. But
if we tried to implement <code>ToString</code>, a trait provided by Rust, for <code>i32</code>, we could
not, because neither the trait nor the type are in our code.</p>
<p>One last thing about traits: generic functions with a trait bound use
‘monomorphization’ (mono: one, morph: form), so they are statically dispatched.
What’s that mean? Check out the chapter on <a href="trait-objects.html">trait objects</a> for more details.</p>
<h1>Multiple trait bounds</h1>
<p>You’ve seen that you can bound a generic type parameter with a trait:</p>
<pre><code class="language-rust">fn foo&lt;T: Clone&gt;(x: T) {
x.clone();
}
</code></pre>
<p>If you need more than one bound, you can use <code>+</code>:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn foo&lt;T: Clone + Debug&gt;(x: T) {
x.clone();
println!(&quot;{:?}&quot;, x);
}
</code></pre>
<p><code>T</code> now needs to be both <code>Clone</code> as well as <code>Debug</code>.</p>
<h1>Where clause</h1>
<p>Writing functions with only a few generic types and a small number of trait
bounds isn’t too bad, but as the number increases, the syntax gets increasingly
awkward:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn foo&lt;T: Clone, K: Clone + Debug&gt;(x: T, y: K) {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
</code></pre>
<p>The name of the function is on the far left, and the parameter list is on the
far right. The bounds are getting in the way.</p>
<p>Rust has a solution, and it’s called a ‘<code>where</code> clause’:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn foo&lt;T: Clone, K: Clone + Debug&gt;(x: T, y: K) {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
fn bar&lt;T, K&gt;(x: T, y: K) where T: Clone, K: Clone + Debug {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
fn main() {
foo(&quot;Hello&quot;, &quot;world&quot;);
bar(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p><code>foo()</code> uses the syntax we showed earlier, and <code>bar()</code> uses a <code>where</code> clause.
All you need to do is leave off the bounds when defining your type parameters,
and then add <code>where</code> after the parameter list. For longer lists, whitespace can
be added:</p>
<pre><code class="language-rust">use std::fmt::Debug;
fn bar&lt;T, K&gt;(x: T, y: K)
where T: Clone,
K: Clone + Debug {
x.clone();
y.clone();
println!(&quot;{:?}&quot;, y);
}
</code></pre>
<p>This flexibility can add clarity in complex situations.</p>
<p><code>where</code> is also more powerful than the simpler syntax. For example:</p>
<pre><code class="language-rust">trait ConvertTo&lt;Output&gt; {
fn convert(&amp;self) -&gt; Output;
}
impl ConvertTo&lt;i64&gt; for i32 {
fn convert(&amp;self) -&gt; i64 { *self as i64 }
}
// can be called with T == i32
fn normal&lt;T: ConvertTo&lt;i64&gt;&gt;(x: &amp;T) -&gt; i64 {
x.convert()
}
// can be called with T == i64
fn inverse&lt;T&gt;() -&gt; T
// this is using ConvertTo as if it were &quot;ConvertTo&lt;i64&gt;&quot;
where i32: ConvertTo&lt;T&gt; {
42.convert()
}
</code></pre>
<p>This shows off the additional feature of <code>where</code> clauses: they allow bounds
on the left-hand side not only of type parameters <code>T</code>, but also of types (<code>i32</code> in this case). In this example, <code>i32</code> must implement
<code>ConvertTo&lt;T&gt;</code>. Rather than defining what <code>i32</code> is (since that's obvious), the
<code>where</code> clause here constrains <code>T</code>.</p>
<h1>Default methods</h1>
<p>A default method can be added to a trait definition if it is already known how a typical implementor will define a method. For example, <code>is_invalid()</code> is defined as the opposite of <code>is_valid()</code>:</p>
<pre><code class="language-rust">trait Foo {
fn is_valid(&amp;self) -&gt; bool;
fn is_invalid(&amp;self) -&gt; bool { !self.is_valid() }
}
</code></pre>
<p>Implementors of the <code>Foo</code> trait need to implement <code>is_valid()</code> but not <code>is_invalid()</code> due to the added default behavior. This default behavior can still be overridden as in:</p>
<pre><code class="language-rust"># trait Foo {
# fn is_valid(&amp;self) -&gt; bool;
#
# fn is_invalid(&amp;self) -&gt; bool { !self.is_valid() }
# }
struct UseDefault;
impl Foo for UseDefault {
fn is_valid(&amp;self) -&gt; bool {
println!(&quot;Called UseDefault.is_valid.&quot;);
true
}
}
struct OverrideDefault;
impl Foo for OverrideDefault {
fn is_valid(&amp;self) -&gt; bool {
println!(&quot;Called OverrideDefault.is_valid.&quot;);
true
}
fn is_invalid(&amp;self) -&gt; bool {
println!(&quot;Called OverrideDefault.is_invalid!&quot;);
true // overrides the expected value of is_invalid()
}
}
let default = UseDefault;
assert!(!default.is_invalid()); // prints &quot;Called UseDefault.is_valid.&quot;
let over = OverrideDefault;
assert!(over.is_invalid()); // prints &quot;Called OverrideDefault.is_invalid!&quot;
</code></pre>
<h1>Inheritance</h1>
<p>Sometimes, implementing a trait requires implementing another trait:</p>
<pre><code class="language-rust">trait Foo {
fn foo(&amp;self);
}
trait FooBar : Foo {
fn foobar(&amp;self);
}
</code></pre>
<p>Implementors of <code>FooBar</code> must also implement <code>Foo</code>, like this:</p>
<pre><code class="language-rust"># trait Foo {
# fn foo(&amp;self);
# }
# trait FooBar : Foo {
# fn foobar(&amp;self);
# }
struct Baz;
impl Foo for Baz {
fn foo(&amp;self) { println!(&quot;foo&quot;); }
}
impl FooBar for Baz {
fn foobar(&amp;self) { println!(&quot;foobar&quot;); }
}
</code></pre>
<p>If we forget to implement <code>Foo</code>, Rust will tell us:</p>
<pre><code class="language-text">error: the trait `main::Foo` is not implemented for the type `main::Baz` [E0277]
</code></pre>
<h1>Deriving</h1>
<p>Implementing traits like <code>Debug</code> and <code>Default</code> repeatedly can become
quite tedious. For that reason, Rust provides an <a href="attributes.html">attribute</a> that
allows you to let Rust automatically implement traits for you:</p>
<pre><code class="language-rust">#[derive(Debug)]
struct Foo;
fn main() {
println!(&quot;{:?}&quot;, Foo);
}
</code></pre>
<p>However, deriving is limited to a certain set of traits:</p>
<ul>
<li>[<code>Clone</code>](../core/clone/trait.Clone.html)</li>
<li>[<code>Copy</code>](../core/marker/trait.Copy.html)</li>
<li>[<code>Debug</code>](../core/fmt/trait.Debug.html)</li>
<li>[<code>Default</code>](../core/default/trait.Default.html)</li>
<li>[<code>Eq</code>](../core/cmp/trait.Eq.html)</li>
<li>[<code>Hash</code>](../core/hash/trait.Hash.html)</li>
<li>[<code>Ord</code>](../core/cmp/trait.Ord.html)</li>
<li>[<code>PartialEq</code>](../core/cmp/trait.PartialEq.html)</li>
<li>[<code>PartialOrd</code>](../core/cmp/trait.PartialOrd.html)</li>
</ul>
<h1>Closures</h1>
<p>Sometimes it is useful to wrap up a function and <em>free variables</em> for better
clarity and reuse. The free variables that can be used come from the
enclosing scope and are ‘closed over’ when used in the function. From this, we
get the name ‘closures’ and Rust provides a really great implementation of
them, as we’ll see.</p>
<h1>Syntax</h1>
<p>Closures look like this:</p>
<pre><code class="language-rust">let plus_one = |x: i32| x + 1;
assert_eq!(2, plus_one(1));
</code></pre>
<p>We create a binding, <code>plus_one</code>, and assign it to a closure. The closure’s
arguments go between the pipes (<code>|</code>), and the body is an expression, in this
case, <code>x + 1</code>. Remember that <code>{ }</code> is an expression, so we can have multi-line
closures too:</p>
<pre><code class="language-rust">let plus_two = |x| {
let mut result: i32 = x;
result += 1;
result += 1;
result
};
assert_eq!(4, plus_two(2));
</code></pre>
<p>You’ll notice a few things about closures that are a bit different from regular
named functions defined with <code>fn</code>. The first is that we did not need to
annotate the types of arguments the closure takes or the values it returns. We
can:</p>
<pre><code class="language-rust">let plus_one = |x: i32| -&gt; i32 { x + 1 };
assert_eq!(2, plus_one(1));
</code></pre>
<p>But we don’t have to. Why is this? Basically, it was chosen for ergonomic
reasons. While specifying the full type for named functions is helpful with
things like documentation and type inference, the full type signatures of
closures are rarely documented since they’re anonymous, and they don’t cause
the kinds of error-at-a-distance problems that inferring named function types
can.</p>
<p>The second is that the syntax is similar, but a bit different. I’ve added
spaces here for easier comparison:</p>
<pre><code class="language-rust">fn plus_one_v1 (x: i32) -&gt; i32 { x + 1 }
let plus_one_v2 = |x: i32| -&gt; i32 { x + 1 };
let plus_one_v3 = |x: i32| x + 1 ;
</code></pre>
<p>Small differences, but they’re similar.</p>
<h1>Closures and their environment</h1>
<p>The environment for a closure can include bindings from its enclosing scope in
addition to parameters and local bindings. It looks like this:</p>
<pre><code class="language-rust">let num = 5;
let plus_num = |x: i32| x + num;
assert_eq!(10, plus_num(5));
</code></pre>
<p>This closure, <code>plus_num</code>, refers to a <code>let</code> binding in its scope: <code>num</code>. More
specifically, it borrows the binding. If we do something that would conflict
with that binding, we get an error. Like this one:</p>
<pre><code class="language-rust,ignore">let mut num = 5;
let plus_num = |x: i32| x + num;
let y = &amp;mut num;
</code></pre>
<p>Which errors with:</p>
<pre><code class="language-text">error: cannot borrow `num` as mutable because it is also borrowed as immutable
let y = &amp;mut num;
^~~
note: previous borrow of `num` occurs here due to use in closure; the immutable
borrow prevents subsequent moves or mutable borrows of `num` until the borrow
ends
let plus_num = |x| x + num;
^~~~~~~~~~~
note: previous borrow ends here
fn main() {
let mut num = 5;
let plus_num = |x| x + num;
let y = &amp;mut num;
}
^
</code></pre>
<p>A verbose yet helpful error message! As it says, we can’t take a mutable borrow
on <code>num</code> because the closure is already borrowing it. If we let the closure go
out of scope, we can:</p>
<pre><code class="language-rust">let mut num = 5;
{
let plus_num = |x: i32| x + num;
} // plus_num goes out of scope, borrow of num ends
let y = &amp;mut num;
</code></pre>
<p>If your closure requires it, however, Rust will take ownership and move
the environment instead. This doesn’t work:</p>
<pre><code class="language-rust,ignore">let nums = vec![1, 2, 3];
let takes_nums = || nums;
println!(&quot;{:?}&quot;, nums);
</code></pre>
<p>We get this error:</p>
<pre><code class="language-text">note: `nums` moved into closure environment here because it has type
`[closure(()) -&gt; collections::vec::Vec&lt;i32&gt;]`, which is non-copyable
let takes_nums = || nums;
^~~~~~~
</code></pre>
<p><code>Vec&lt;T&gt;</code> has ownership over its contents, and therefore, when we refer to it
in our closure, we have to take ownership of <code>nums</code>. It’s the same as if we’d
passed <code>nums</code> to a function that took ownership of it.</p>
<h2><code>move</code> closures</h2>
<p>We can force our closure to take ownership of its environment with the <code>move</code>
keyword:</p>
<pre><code class="language-rust">let num = 5;
let owns_num = move |x: i32| x + num;
</code></pre>
<p>Now, even though the keyword is <code>move</code>, the variables follow normal move semantics.
In this case, <code>5</code> implements <code>Copy</code>, and so <code>owns_num</code> takes ownership of a copy
of <code>num</code>. So what’s the difference?</p>
<pre><code class="language-rust">let mut num = 5;
{
let mut add_num = |x: i32| num += x;
add_num(5);
}
assert_eq!(10, num);
</code></pre>
<p>So in this case, our closure took a mutable reference to <code>num</code>, and then when
we called <code>add_num</code>, it mutated the underlying value, as we’d expect. We also
needed to declare <code>add_num</code> as <code>mut</code> too, because we’re mutating its
environment.</p>
<p>If we change to a <code>move</code> closure, it’s different:</p>
<pre><code class="language-rust">let mut num = 5;
{
let mut add_num = move |x: i32| num += x;
add_num(5);
}
assert_eq!(5, num);
</code></pre>
<p>We only get <code>5</code>. Rather than taking a mutable borrow out on our <code>num</code>, we took
ownership of a copy.</p>
<p>Another way to think about <code>move</code> closures: they give a closure its own stack
frame. Without <code>move</code>, a closure may be tied to the stack frame that created
it, while a <code>move</code> closure is self-contained. This means that you cannot
generally return a non-<code>move</code> closure from a function, for example.</p>
<p>But before we talk about taking and returning closures, we should talk some
more about the way that closures are implemented. As a systems language, Rust
gives you tons of control over what your code does, and closures are no
different.</p>
<h1>Closure implementation</h1>
<p>Rust’s implementation of closures is a bit different than other languages. They
are effectively syntax sugar for traits. You’ll want to make sure to have read
the <a href="traits.html">traits chapter</a> before this one, as well as the chapter on <a href="trait-objects.html">trait
objects</a>.</p>
<p>Got all that? Good.</p>
<p>The key to understanding how closures work under the hood is something a bit
strange: Using <code>()</code> to call a function, like <code>foo()</code>, is an overloadable
operator. From this, everything else clicks into place. In Rust, we use the
trait system to overload operators. Calling functions is no different. We have
three separate traits to overload with:</p>
<pre><code class="language-rust"># mod foo {
pub trait Fn&lt;Args&gt; : FnMut&lt;Args&gt; {
extern &quot;rust-call&quot; fn call(&amp;self, args: Args) -&gt; Self::Output;
}
pub trait FnMut&lt;Args&gt; : FnOnce&lt;Args&gt; {
extern &quot;rust-call&quot; fn call_mut(&amp;mut self, args: Args) -&gt; Self::Output;
}
pub trait FnOnce&lt;Args&gt; {
type Output;
extern &quot;rust-call&quot; fn call_once(self, args: Args) -&gt; Self::Output;
}
# }
</code></pre>
<p>You’ll notice a few differences between these traits, but a big one is <code>self</code>:
<code>Fn</code> takes <code>&amp;self</code>, <code>FnMut</code> takes <code>&amp;mut self</code>, and <code>FnOnce</code> takes <code>self</code>. This
covers all three kinds of <code>self</code> via the usual method call syntax. But we’ve
split them up into three traits, rather than having a single one. This gives us
a large amount of control over what kind of closures we can take.</p>
<p>The <code>|| {}</code> syntax for closures is sugar for these three traits. Rust will
generate a struct for the environment, <code>impl</code> the appropriate trait, and then
use it.</p>
<h1>Taking closures as arguments</h1>
<p>Now that we know that closures are traits, we already know how to accept and
return closures: just like any other trait!</p>
<p>This also means that we can choose static vs dynamic dispatch as well. First,
let’s write a function which takes something callable, calls it, and returns
the result:</p>
<pre><code class="language-rust">fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32
where F : Fn(i32) -&gt; i32 {
some_closure(1)
}
let answer = call_with_one(|x| x + 2);
assert_eq!(3, answer);
</code></pre>
<p>We pass our closure, <code>|x| x + 2</code>, to <code>call_with_one</code>. It just does what it
suggests: it calls the closure, giving it <code>1</code> as an argument.</p>
<p>Let’s examine the signature of <code>call_with_one</code> in more depth:</p>
<pre><code class="language-rust">fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32
# where F : Fn(i32) -&gt; i32 {
# some_closure(1) }
</code></pre>
<p>We take one parameter, and it has the type <code>F</code>. We also return a <code>i32</code>. This part
isn’t interesting. The next part is:</p>
<pre><code class="language-rust"># fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32
where F : Fn(i32) -&gt; i32 {
# some_closure(1) }
</code></pre>
<p>Because <code>Fn</code> is a trait, we can bound our generic with it. In this case, our
closure takes a <code>i32</code> as an argument and returns an <code>i32</code>, and so the generic
bound we use is <code>Fn(i32) -&gt; i32</code>.</p>
<p>There’s one other key point here: because we’re bounding a generic with a
trait, this will get monomorphized, and therefore, we’ll be doing static
dispatch into the closure. That’s pretty neat. In many languages, closures are
inherently heap allocated, and will always involve dynamic dispatch. In Rust,
we can stack allocate our closure environment, and statically dispatch the
call. This happens quite often with iterators and their adapters, which often
take closures as arguments.</p>
<p>Of course, if we want dynamic dispatch, we can get that too. A trait object
handles this case, as usual:</p>
<pre><code class="language-rust">fn call_with_one(some_closure: &amp;Fn(i32) -&gt; i32) -&gt; i32 {
some_closure(1)
}
let answer = call_with_one(&amp;|x| x + 2);
assert_eq!(3, answer);
</code></pre>
<p>Now we take a trait object, a <code>&amp;Fn</code>. And we have to make a reference
to our closure when we pass it to <code>call_with_one</code>, so we use <code>&amp;||</code>.</p>
<h1>Function pointers and closures</h1>
<p>A function pointer is kind of like a closure that has no environment. As such,
you can pass a function pointer to any function expecting a closure argument,
and it will work:</p>
<pre><code class="language-rust">fn call_with_one(some_closure: &amp;Fn(i32) -&gt; i32) -&gt; i32 {
some_closure(1)
}
fn add_one(i: i32) -&gt; i32 {
i + 1
}
let f = add_one;
let answer = call_with_one(&amp;f);
assert_eq!(2, answer);
</code></pre>
<p>In this example, we don’t strictly need the intermediate variable <code>f</code>,
the name of the function works just fine too:</p>
<pre><code class="language-ignore">let answer = call_with_one(&amp;add_one);
</code></pre>
<h1>Returning closures</h1>
<p>It’s very common for functional-style code to return closures in various
situations. If you try to return a closure, you may run into an error. At
first, it may seem strange, but we’ll figure it out. Here’s how you’d probably
try to return a closure from a function:</p>
<pre><code class="language-rust,ignore">fn factory() -&gt; (Fn(i32) -&gt; i32) {
let num = 5;
|x| x + num
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
</code></pre>
<p>This gives us these long, related errors:</p>
<pre><code class="language-text">error: the trait `core::marker::Sized` is not implemented for the type
`core::ops::Fn(i32) -&gt; i32` [E0277]
fn factory() -&gt; (Fn(i32) -&gt; i32) {
^~~~~~~~~~~~~~~~
note: `core::ops::Fn(i32) -&gt; i32` does not have a constant size known at compile-time
fn factory() -&gt; (Fn(i32) -&gt; i32) {
^~~~~~~~~~~~~~~~
error: the trait `core::marker::Sized` is not implemented for the type `core::ops::Fn(i32) -&gt; i32` [E0277]
let f = factory();
^
note: `core::ops::Fn(i32) -&gt; i32` does not have a constant size known at compile-time
let f = factory();
^
</code></pre>
<p>In order to return something from a function, Rust needs to know what
size the return type is. But since <code>Fn</code> is a trait, it could be various
things of various sizes: many different types can implement <code>Fn</code>. An easy
way to give something a size is to take a reference to it, as references
have a known size. So we’d write this:</p>
<pre><code class="language-rust,ignore">fn factory() -&gt; &amp;(Fn(i32) -&gt; i32) {
let num = 5;
|x| x + num
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
</code></pre>
<p>But we get another error:</p>
<pre><code class="language-text">error: missing lifetime specifier [E0106]
fn factory() -&gt; &amp;(Fn(i32) -&gt; i32) {
^~~~~~~~~~~~~~~~~
</code></pre>
<p>Right. Because we have a reference, we need to give it a lifetime. But
our <code>factory()</code> function takes no arguments, so
<a href="lifetimes.html#lifetime-elision">elision</a> doesn’t kick in here. Then what
choices do we have? Try <code>'static</code>:</p>
<pre><code class="language-rust,ignore">fn factory() -&gt; &amp;'static (Fn(i32) -&gt; i32) {
let num = 5;
|x| x + num
}
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
</code></pre>
<p>But we get another error:</p>
<pre><code class="language-text">error: mismatched types:
expected `&amp;'static core::ops::Fn(i32) -&gt; i32`,
found `[closure@&lt;anon&gt;:7:9: 7:20]`
(expected &amp;-ptr,
found closure) [E0308]
|x| x + num
^~~~~~~~~~~
</code></pre>
<p>This error is letting us know that we don’t have a <code>&amp;'static Fn(i32) -&gt; i32</code>,
we have a <code>[closure@&lt;anon&gt;:7:9: 7:20]</code>. Wait, what?</p>
<p>Because each closure generates its own environment <code>struct</code> and implementation
of <code>Fn</code> and friends, these types are anonymous. They exist just solely for
this closure. So Rust shows them as <code>closure@&lt;anon&gt;</code>, rather than some
autogenerated name.</p>
<p>The error also points out that the return type is expected to be a reference,
but what we are trying to return is not. Further, we cannot directly assign a
<code>'static</code> lifetime to an object. So we'll take a different approach and return
a ‘trait object’ by <code>Box</code>ing up the <code>Fn</code>. This <em>almost</em> works:</p>
<pre><code class="language-rust,ignore">fn factory() -&gt; Box&lt;Fn(i32) -&gt; i32&gt; {
let num = 5;
Box::new(|x| x + num)
}
# fn main() {
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
# }
</code></pre>
<p>There’s just one last problem:</p>
<pre><code class="language-text">error: closure may outlive the current function, but it borrows `num`,
which is owned by the current function [E0373]
Box::new(|x| x + num)
^~~~~~~~~~~
</code></pre>
<p>Well, as we discussed before, closures borrow their environment. And in this
case, our environment is based on a stack-allocated <code>5</code>, the <code>num</code> variable
binding. So the borrow has a lifetime of the stack frame. So if we returned
this closure, the function call would be over, the stack frame would go away,
and our closure is capturing an environment of garbage memory! With one last
fix, we can make this work:</p>
<pre><code class="language-rust">fn factory() -&gt; Box&lt;Fn(i32) -&gt; i32&gt; {
let num = 5;
Box::new(move |x| x + num)
}
# fn main() {
let f = factory();
let answer = f(1);
assert_eq!(6, answer);
# }
</code></pre>
<p>By making the inner closure a <code>move Fn</code>, we create a new stack frame for our
closure. By <code>Box</code>ing it up, we’ve given it a known size, and allowing it to
escape our stack frame.</p>
<h1>Iterators</h1>
<p>Let's talk about loops.</p>
<p>Remember Rust's <code>for</code> loop? Here's an example:</p>
<pre><code class="language-rust">for x in 0..10 {
println!(&quot;{}&quot;, x);
}
</code></pre>
<p>Now that you know more Rust, we can talk in detail about how this works.
Ranges (the <code>0..10</code>) are 'iterators'. An iterator is something that we can
call the <code>.next()</code> method on repeatedly, and it gives us a sequence of things.</p>
<p>Like this:</p>
<pre><code class="language-rust">let mut range = 0..10;
loop {
match range.next() {
Some(x) =&gt; {
println!(&quot;{}&quot;, x);
},
None =&gt; { break }
}
}
</code></pre>
<p>We make a mutable binding to the range, which is our iterator. We then <code>loop</code>,
with an inner <code>match</code>. This <code>match</code> is used on the result of <code>range.next()</code>,
which gives us a reference to the next value of the iterator. <code>next</code> returns an
<code>Option&lt;i32&gt;</code>, in this case, which will be <code>Some(i32)</code> when we have a value and
<code>None</code> once we run out. If we get <code>Some(i32)</code>, we print it out, and if we get
<code>None</code>, we <code>break</code> out of the loop.</p>
<p>This code sample is basically the same as our <code>for</code> loop version. The <code>for</code>
loop is just a handy way to write this <code>loop</code>/<code>match</code>/<code>break</code> construct.</p>
<p><code>for</code> loops aren't the only thing that uses iterators, however. Writing your
own iterator involves implementing the <code>Iterator</code> trait. While doing that is
outside of the scope of this guide, Rust provides a number of useful iterators
to accomplish various tasks. But first, a few notes about limitations of ranges.</p>
<p>Ranges are very primitive, and we often can use better alternatives. Consider the
following Rust anti-pattern: using ranges to emulate a C-style <code>for</code> loop. Let’s
suppose you needed to iterate over the contents of a vector. You may be tempted
to write this:</p>
<pre><code class="language-rust">let nums = vec![1, 2, 3];
for i in 0..nums.len() {
println!(&quot;{}&quot;, nums[i]);
}
</code></pre>
<p>This is strictly worse than using an actual iterator. You can iterate over vectors
directly, so write this:</p>
<pre><code class="language-rust">let nums = vec![1, 2, 3];
for num in &amp;nums {
println!(&quot;{}&quot;, num);
}
</code></pre>
<p>There are two reasons for this. First, this more directly expresses what we
mean. We iterate through the entire vector, rather than iterating through
indexes, and then indexing the vector. Second, this version is more efficient:
the first version will have extra bounds checking because it used indexing,
<code>nums[i]</code>. But since we yield a reference to each element of the vector in turn
with the iterator, there's no bounds checking in the second example. This is
very common with iterators: we can ignore unnecessary bounds checks, but still
know that we're safe.</p>
<p>There's another detail here that's not 100% clear because of how <code>println!</code>
works. <code>num</code> is actually of type <code>&amp;i32</code>. That is, it's a reference to an <code>i32</code>,
not an <code>i32</code> itself. <code>println!</code> handles the dereferencing for us, so we don't
see it. This code works fine too:</p>
<pre><code class="language-rust">let nums = vec![1, 2, 3];
for num in &amp;nums {
println!(&quot;{}&quot;, *num);
}
</code></pre>
<p>Now we're explicitly dereferencing <code>num</code>. Why does <code>&amp;nums</code> give us
references? Firstly, because we explicitly asked it to with
<code>&amp;</code>. Secondly, if it gave us the data itself, we would have to be its
owner, which would involve making a copy of the data and giving us the
copy. With references, we're just borrowing a reference to the data,
and so it's just passing a reference, without needing to do the move.</p>
<p>So, now that we've established that ranges are often not what you want, let's
talk about what you do want instead.</p>
<p>There are three broad classes of things that are relevant here: iterators,
<em>iterator adaptors</em>, and <em>consumers</em>. Here's some definitions:</p>
<ul>
<li><em>iterators</em> give you a sequence of values.</li>
<li><em>iterator adaptors</em> operate on an iterator, producing a new iterator with a
different output sequence.</li>
<li><em>consumers</em> operate on an iterator, producing some final set of values.</li>
</ul>
<p>Let's talk about consumers first, since you've already seen an iterator, ranges.</p>
<h2>Consumers</h2>
<p>A <em>consumer</em> operates on an iterator, returning some kind of value or values.
The most common consumer is <code>collect()</code>. This code doesn't quite compile,
but it shows the intention:</p>
<pre><code class="language-rust,ignore">let one_to_one_hundred = (1..101).collect();
</code></pre>
<p>As you can see, we call <code>collect()</code> on our iterator. <code>collect()</code> takes
as many values as the iterator will give it, and returns a collection
of the results. So why won't this compile? Rust can't determine what
type of things you want to collect, and so you need to let it know.
Here's the version that does compile:</p>
<pre><code class="language-rust">let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;i32&gt;&gt;();
</code></pre>
<p>If you remember, the <code>::&lt;&gt;</code> syntax allows us to give a type hint,
and so we tell it that we want a vector of integers. You don't always
need to use the whole type, though. Using a <code>_</code> will let you provide
a partial hint:</p>
<pre><code class="language-rust">let one_to_one_hundred = (1..101).collect::&lt;Vec&lt;_&gt;&gt;();
</code></pre>
<p>This says &quot;Collect into a <code>Vec&lt;T&gt;</code>, please, but infer what the <code>T</code> is for me.&quot;
<code>_</code> is sometimes called a &quot;type placeholder&quot; for this reason.</p>
<p><code>collect()</code> is the most common consumer, but there are others too. <code>find()</code>
is one:</p>
<pre><code class="language-rust">let greater_than_forty_two = (0..100)
.find(|x| *x &gt; 42);
match greater_than_forty_two {
Some(_) =&gt; println!(&quot;Found a match!&quot;),
None =&gt; println!(&quot;No match found :(&quot;),
}
</code></pre>
<p><code>find</code> takes a closure, and works on a reference to each element of an
iterator. This closure returns <code>true</code> if the element is the element we're
looking for, and <code>false</code> otherwise. <code>find</code> returns the first element satisfying
the specified predicate. Because we might not find a matching element, <code>find</code>
returns an <code>Option</code> rather than the element itself.</p>
<p>Another important consumer is <code>fold</code>. Here's what it looks like:</p>
<pre><code class="language-rust">let sum = (1..4).fold(0, |sum, x| sum + x);
</code></pre>
<p><code>fold()</code> is a consumer that looks like this:
<code>fold(base, |accumulator, element| ...)</code>. It takes two arguments: the first
is an element called the <em>base</em>. The second is a closure that itself takes two
arguments: the first is called the <em>accumulator</em>, and the second is an
<em>element</em>. Upon each iteration, the closure is called, and the result is the
value of the accumulator on the next iteration. On the first iteration, the
base is the value of the accumulator.</p>
<p>Okay, that's a bit confusing. Let's examine the values of all of these things
in this iterator:</p>
<p>| base | accumulator | element | closure result |
|------|-------------|---------|----------------|
| 0 | 0 | 1 | 1 |
| 0 | 1 | 2 | 3 |
| 0 | 3 | 3 | 6 |</p>
<p>We called <code>fold()</code> with these arguments:</p>
<pre><code class="language-rust"># (1..4)
.fold(0, |sum, x| sum + x);
</code></pre>
<p>So, <code>0</code> is our base, <code>sum</code> is our accumulator, and <code>x</code> is our element. On the
first iteration, we set <code>sum</code> to <code>0</code>, and <code>x</code> is the first element of <code>nums</code>,
<code>1</code>. We then add <code>sum</code> and <code>x</code>, which gives us <code>0 + 1 = 1</code>. On the second
iteration, that value becomes our accumulator, <code>sum</code>, and the element is
the second element of the array, <code>2</code>. <code>1 + 2 = 3</code>, and so that becomes
the value of the accumulator for the last iteration. On that iteration,
<code>x</code> is the last element, <code>3</code>, and <code>3 + 3 = 6</code>, which is our final
result for our sum. <code>1 + 2 + 3 = 6</code>, and that's the result we got.</p>
<p>Whew. <code>fold</code> can be a bit strange the first few times you see it, but once it
clicks, you can use it all over the place. Any time you have a list of things,
and you want a single result, <code>fold</code> is appropriate.</p>
<p>Consumers are important due to one additional property of iterators we haven't
talked about yet: laziness. Let's talk some more about iterators, and you'll
see why consumers matter.</p>
<h2>Iterators</h2>
<p>As we've said before, an iterator is something that we can call the
<code>.next()</code> method on repeatedly, and it gives us a sequence of things.
Because you need to call the method, this means that iterators
can be <em>lazy</em> and not generate all of the values upfront. This code,
for example, does not actually generate the numbers <code>1-99</code>, instead
creating a value that merely represents the sequence:</p>
<pre><code class="language-rust">let nums = 1..100;
</code></pre>
<p>Since we didn't do anything with the range, it didn't generate the sequence.
Let's add the consumer:</p>
<pre><code class="language-rust">let nums = (1..100).collect::&lt;Vec&lt;i32&gt;&gt;();
</code></pre>
<p>Now, <code>collect()</code> will require that the range gives it some numbers, and so
it will do the work of generating the sequence.</p>
<p>Ranges are one of two basic iterators that you'll see. The other is <code>iter()</code>.
<code>iter()</code> can turn a vector into a simple iterator that gives you each element
in turn:</p>
<pre><code class="language-rust">let nums = vec![1, 2, 3];
for num in nums.iter() {
println!(&quot;{}&quot;, num);
}
</code></pre>
<p>These two basic iterators should serve you well. There are some more
advanced iterators, including ones that are infinite.</p>
<p>That's enough about iterators. Iterator adaptors are the last concept
we need to talk about with regards to iterators. Let's get to it!</p>
<h2>Iterator adaptors</h2>
<p><em>Iterator adaptors</em> take an iterator and modify it somehow, producing
a new iterator. The simplest one is called <code>map</code>:</p>
<pre><code class="language-rust,ignore">(1..100).map(|x| x + 1);
</code></pre>
<p><code>map</code> is called upon another iterator, and produces a new iterator where each
element reference has the closure it's been given as an argument called on it.
So this would give us the numbers from <code>2-100</code>. Well, almost! If you
compile the example, you'll get a warning:</p>
<pre><code class="language-text">warning: unused result which must be used: iterator adaptors are lazy and
do nothing unless consumed, #[warn(unused_must_use)] on by default
(1..100).map(|x| x + 1);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Laziness strikes again! That closure will never execute. This example
doesn't print any numbers:</p>
<pre><code class="language-rust,ignore">(1..100).map(|x| println!(&quot;{}&quot;, x));
</code></pre>
<p>If you are trying to execute a closure on an iterator for its side effects,
just use <code>for</code> instead.</p>
<p>There are tons of interesting iterator adaptors. <code>take(n)</code> will return an
iterator over the next <code>n</code> elements of the original iterator. Let's try it out
with an infinite iterator:</p>
<pre><code class="language-rust">for i in (1..).take(5) {
println!(&quot;{}&quot;, i);
}
</code></pre>
<p>This will print</p>
<pre><code class="language-text">1
2
3
4
5
</code></pre>
<p><code>filter()</code> is an adapter that takes a closure as an argument. This closure
returns <code>true</code> or <code>false</code>. The new iterator <code>filter()</code> produces
only the elements that the closure returns <code>true</code> for:</p>
<pre><code class="language-rust">for i in (1..100).filter(|&amp;x| x % 2 == 0) {
println!(&quot;{}&quot;, i);
}
</code></pre>
<p>This will print all of the even numbers between one and a hundred.
(Note that because <code>filter</code> doesn't consume the elements that are
being iterated over, it is passed a reference to each element, and
thus the filter predicate uses the <code>&amp;x</code> pattern to extract the integer
itself.)</p>
<p>You can chain all three things together: start with an iterator, adapt it
a few times, and then consume the result. Check it out:</p>
<pre><code class="language-rust">(1..)
.filter(|&amp;x| x % 2 == 0)
.filter(|&amp;x| x % 3 == 0)
.take(5)
.collect::&lt;Vec&lt;i32&gt;&gt;();
</code></pre>
<p>This will give you a vector containing <code>6</code>, <code>12</code>, <code>18</code>, <code>24</code>, and <code>30</code>.</p>
<p>This is just a small taste of what iterators, iterator adaptors, and consumers
can help you with. There are a number of really useful iterators, and you can
write your own as well. Iterators provide a safe, efficient way to manipulate
all kinds of lists. They're a little unusual at first, but if you play with
them, you'll get hooked. For a full list of the different iterators and
consumers, check out the <a href="../std/iter/index.html">iterator module documentation</a>.</p>
<h1>I/O</h1>
<h1><code>Read</code> &amp; <code>Write</code></h1>
<h1><code>std::fs</code></h1>
<h1><code>std::path</code></h1>
<h1><code>std::env</code></h1>
<h1>Testing</h1>
<blockquote>
<p>Program testing can be a very effective way to show the presence of bugs, but
it is hopelessly inadequate for showing their absence.</p>
<p>Edsger W. Dijkstra, &quot;The Humble Programmer&quot; (1972)</p>
</blockquote>
<p>Let's talk about how to test Rust code. What we will not be talking about is
the right way to test Rust code. There are many schools of thought regarding
the right and wrong way to write tests. All of these approaches use the same
basic tools, and so we'll show you the syntax for using them.</p>
<h1>The <code>test</code> attribute</h1>
<p>At its simplest, a test in Rust is a function that's annotated with the <code>test</code>
attribute. Let's make a new project with Cargo called <code>adder</code>:</p>
<pre><code class="language-bash">$ cargo new adder
$ cd adder
</code></pre>
<p>Cargo will automatically generate a simple test when you make a new project.
Here's the contents of <code>src/lib.rs</code>:</p>
<pre><code class="language-rust">#[test]
fn it_works() {
}
</code></pre>
<p>Note the <code>#[test]</code>. This attribute indicates that this is a test function. It
currently has no body. That's good enough to pass! We can run the tests with
<code>cargo test</code>:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Cargo compiled and ran our tests. There are two sets of output here: one
for the test we wrote, and another for documentation tests. We'll talk about
those later. For now, see this line:</p>
<pre><code class="language-text">test it_works ... ok
</code></pre>
<p>Note the <code>it_works</code>. This comes from the name of our function:</p>
<pre><code class="language-rust">fn it_works() {
# }
</code></pre>
<p>We also get a summary line:</p>
<pre><code class="language-text">test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>So why does our do-nothing test pass? Any test which doesn't <code>panic!</code> passes,
and any test that does <code>panic!</code> fails. Let's make our test fail:</p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert!(false);
}
</code></pre>
<p><code>assert!</code> is a macro provided by Rust which takes one argument: if the argument
is <code>true</code>, nothing happens. If the argument is <code>false</code>, it <code>panic!</code>s. Let's run
our tests again:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... FAILED
failures:
---- it_works stdout ----
thread 'it_works' panicked at 'assertion failed: false', /home/steve/tmp/adder/src/lib.rs:3
failures:
it_works
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
thread '&lt;main&gt;' panicked at 'Some tests failed', /home/steve/src/rust/src/libtest/lib.rs:247
</code></pre>
<p>Rust indicates that our test failed:</p>
<pre><code class="language-text">test it_works ... FAILED
</code></pre>
<p>And that's reflected in the summary line:</p>
<pre><code class="language-text">test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<p>We also get a non-zero status code. We can use <code>$?</code> on OS X and Linux:</p>
<pre><code class="language-bash">$ echo $?
101
</code></pre>
<p>On Windows, if you’re using <code>cmd</code>:</p>
<pre><code class="language-bash">&gt; echo %ERRORLEVEL%
</code></pre>
<p>And if you’re using PowerShell:</p>
<pre><code class="language-bash">&gt; echo $LASTEXITCODE # the code itself
&gt; echo $? # a boolean, fail or succeed
</code></pre>
<p>This is useful if you want to integrate <code>cargo test</code> into other tooling.</p>
<p>We can invert our test's failure with another attribute: <code>should_panic</code>:</p>
<pre><code class="language-rust">#[test]
#[should_panic]
fn it_works() {
assert!(false);
}
</code></pre>
<p>This test will now succeed if we <code>panic!</code> and fail if we complete. Let's try it:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Rust provides another macro, <code>assert_eq!</code>, that compares two arguments for
equality:</p>
<pre><code class="language-rust">#[test]
#[should_panic]
fn it_works() {
assert_eq!(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p>Does this test pass or fail? Because of the <code>should_panic</code> attribute, it
passes:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p><code>should_panic</code> tests can be fragile, as it's hard to guarantee that the test
didn't fail for an unexpected reason. To help with this, an optional <code>expected</code>
parameter can be added to the <code>should_panic</code> attribute. The test harness will
make sure that the failure message contains the provided text. A safer version
of the example above would be:</p>
<pre><code class="language-rust">#[test]
#[should_panic(expected = &quot;assertion failed&quot;)]
fn it_works() {
assert_eq!(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p>That's all there is to the basics! Let's write one 'real' test:</p>
<pre><code class="language-rust,ignore">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
</code></pre>
<p>This is a very common use of <code>assert_eq!</code>: call some function with
some known arguments and compare it to the expected output.</p>
<h1>The <code>ignore</code> attribute</h1>
<p>Sometimes a few specific tests can be very time-consuming to execute. These
can be disabled by default by using the <code>ignore</code> attribute:</p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
#[test]
#[ignore]
fn expensive_test() {
// code that takes an hour to run
}
</code></pre>
<p>Now we run our tests and see that <code>it_works</code> is run, but <code>expensive_test</code> is
not:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 2 tests
test expensive_test ... ignored
test it_works ... ok
test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>The expensive tests can be run explicitly using <code>cargo test -- --ignored</code>:</p>
<pre><code class="language-bash">$ cargo test -- --ignored
Running target/adder-91b3e234d4ed382a
running 1 test
test expensive_test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>The <code>--ignored</code> argument is an argument to the test binary, and not to Cargo,
which is why the command is <code>cargo test -- --ignored</code>.</p>
<h1>The <code>tests</code> module</h1>
<p>There is one way in which our existing example is not idiomatic: it's
missing the <code>tests</code> module. The idiomatic way of writing our example
looks like this:</p>
<pre><code class="language-rust,ignore">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::add_two;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p>There's a few changes here. The first is the introduction of a <code>mod tests</code> with
a <code>cfg</code> attribute. The module allows us to group all of our tests together, and
to also define helper functions if needed, that don't become a part of the rest
of our crate. The <code>cfg</code> attribute only compiles our test code if we're
currently trying to run the tests. This can save compile time, and also ensures
that our tests are entirely left out of a normal build.</p>
<p>The second change is the <code>use</code> declaration. Because we're in an inner module,
we need to bring our test function into scope. This can be annoying if you have
a large module, and so this is a common use of globs. Let's change our
<code>src/lib.rs</code> to make use of it:</p>
<pre><code class="language-rust,ignore">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p>Note the different <code>use</code> line. Now we run our tests:</p>
<pre><code class="language-bash">$ cargo test
Updating registry `https://github.com/rust-lang/crates.io-index`
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>It works!</p>
<p>The current convention is to use the <code>tests</code> module to hold your &quot;unit-style&quot;
tests. Anything that just tests one small bit of functionality makes sense to
go here. But what about &quot;integration-style&quot; tests instead? For that, we have
the <code>tests</code> directory.</p>
<h1>The <code>tests</code> directory</h1>
<p>To write an integration test, let's make a <code>tests</code> directory, and
put a <code>tests/lib.rs</code> file inside, with this as its contents:</p>
<pre><code class="language-rust,ignore">extern crate adder;
#[test]
fn it_works() {
assert_eq!(4, adder::add_two(2));
}
</code></pre>
<p>This looks similar to our previous tests, but slightly different. We now have
an <code>extern crate adder</code> at the top. This is because the tests in the <code>tests</code>
directory are an entirely separate crate, and so we need to import our library.
This is also why <code>tests</code> is a suitable place to write integration-style tests:
they use the library like any other consumer of it would.</p>
<p>Let's run them:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/you/projects/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Running target/lib-c18e7d3494509e74
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Now we have three sections: our previous test is also run, as well as our new
one.</p>
<p>That's all there is to the <code>tests</code> directory. The <code>tests</code> module isn't needed
here, since the whole thing is focused on tests.</p>
<p>Let's finally check out that third section: documentation tests.</p>
<h1>Documentation tests</h1>
<p>Nothing is better than documentation with examples. Nothing is worse than
examples that don't actually work, because the code has changed since the
documentation has been written. To this end, Rust supports automatically
running examples in your documentation (<strong>note:</strong> this only works in library
crates, not binary crates). Here's a fleshed-out <code>src/lib.rs</code> with examples:</p>
<pre><code class="language-rust,ignore">//! The `adder` crate provides functions that add numbers to other numbers.
//!
//! # Examples
//!
//! ```
//! assert_eq!(4, adder::add_two(2));
//! ```
/// This function adds two to its argument.
///
/// # Examples
///
/// ```
/// use adder::add_two;
///
/// assert_eq!(4, add_two(2));
/// ```
pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<p>Note the module-level documentation with <code>//!</code> and the function-level
documentation with <code>///</code>. Rust's documentation supports Markdown in comments,
and so triple graves mark code blocks. It is conventional to include the
<code># Examples</code> section, exactly like that, with examples following.</p>
<p>Let's run the tests again:</p>
<pre><code class="language-bash">$ cargo test
Compiling adder v0.0.1 (file:///home/steve/tmp/adder)
Running target/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Running target/lib-c18e7d3494509e74
running 1 test
test it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests adder
running 2 tests
test add_two_0 ... ok
test _0 ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Now we have all three kinds of tests running! Note the names of the
documentation tests: the <code>_0</code> is generated for the module test, and <code>add_two_0</code>
for the function test. These will auto increment with names like <code>add_two_1</code> as
you add more examples.</p>
<p>We haven’t covered all of the details with writing documentation tests. For more,
please see the <a href="documentation.html">Documentation chapter</a></p>
<p>One final note: documentation tests <em>cannot</em> be run on binary crates.
To see more on file arrangement see the <a href="crates-and-modules.html">Crates and
Modules</a> section.</p>
<h1>Smart Pointers</h1>
<h1><code>Deref</code></h1>
<h1><code>Deref</code> coercions</h1>
<h1><code>Box&lt;T&gt;</code></h1>
<h1><code>Rc&lt;T&gt;</code></h1>
<h1>Concurrency</h1>
<h1>Threads</h1>
<h1><code>Send</code> &amp; <code>Sync</code></h1>
<h1><code>Arc&lt;T&gt;</code></h1>
<h1><code>Mutex&lt;T&gt;</code></h1>
<h1><code>Channels</code></h1>
<h1>Unsafe</h1>
<p>Rust’s main draw is its powerful static guarantees about behavior. But safety
checks are conservative by nature: there are some programs that are actually
safe, but the compiler is not able to verify this is true. To write these kinds
of programs, we need to tell the compiler to relax its restrictions a bit. For
this, Rust has a keyword, <code>unsafe</code>. Code using <code>unsafe</code> has less restrictions
than normal code does.</p>
<p>Let’s go over the syntax, and then we’ll talk semantics. <code>unsafe</code> is used in
four contexts. The first one is to mark a function as unsafe:</p>
<pre><code class="language-rust">unsafe fn danger_will_robinson() {
// scary stuff
}
</code></pre>
<p>All functions called from <a href="ffi.html">FFI</a> must be marked as <code>unsafe</code>, for example.
The second use of <code>unsafe</code> is an unsafe block:</p>
<pre><code class="language-rust">unsafe {
// scary stuff
}
</code></pre>
<p>The third is for unsafe traits:</p>
<pre><code class="language-rust">unsafe trait Scary { }
</code></pre>
<p>And the fourth is for <code>impl</code>ementing one of those traits:</p>
<pre><code class="language-rust"># unsafe trait Scary { }
unsafe impl Scary for i32 {}
</code></pre>
<p>It’s important to be able to explicitly delineate code that may have bugs that
cause big problems. If a Rust program segfaults, you can be sure it’s somewhere
in the sections marked <code>unsafe</code>.</p>
<h1>What does ‘safe’ mean?</h1>
<p>Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also
important to know that there are certain behaviors that are probably not
desirable in your code, but are expressly <em>not</em> unsafe:</p>
<ul>
<li>Deadlocks</li>
<li>Leaks of memory or other resources</li>
<li>Exiting without calling destructors</li>
<li>Integer overflow</li>
</ul>
<p>Rust cannot prevent all kinds of software problems. Buggy code can and will be
written in Rust. These things aren’t great, but they don’t qualify as <code>unsafe</code>
specifically.</p>
<p>In addition, the following are all undefined behaviors in Rust, and must be
avoided, even when writing <code>unsafe</code> code:</p>
<ul>
<li>Data races</li>
<li>Dereferencing a null/dangling raw pointer</li>
<li>Reads of <a href="http://llvm.org/docs/LangRef.html#undefined-values">undef</a> (uninitialized) memory</li>
<li>Breaking the <a href="http://llvm.org/docs/LangRef.html#pointer-aliasing-rules">pointer aliasing rules</a> with raw pointers.</li>
<li><code>&amp;mut T</code> and <code>&amp;T</code> follow LLVM’s scoped <a href="http://llvm.org/docs/LangRef.html#noalias">noalias</a> model, except if
the <code>&amp;T</code> contains an <code>UnsafeCell&lt;U&gt;</code>. Unsafe code must not violate these
aliasing guarantees.</li>
<li>Mutating an immutable value/reference without <code>UnsafeCell&lt;U&gt;</code></li>
<li>Invoking undefined behavior via compiler intrinsics:
<ul>
<li>Indexing outside of the bounds of an object with <code>std::ptr::offset</code>
(<code>offset</code> intrinsic), with
the exception of one byte past the end which is permitted.</li>
<li>Using <code>std::ptr::copy_nonoverlapping_memory</code> (<code>memcpy32</code>/<code>memcpy64</code>
intrinsics) on overlapping buffers</li>
</ul>
</li>
<li>Invalid values in primitive types, even in private fields/locals:
<ul>
<li>Null/dangling references or boxes</li>
<li>A value other than <code>false</code> (0) or <code>true</code> (1) in a <code>bool</code></li>
<li>A discriminant in an <code>enum</code> not included in its type definition</li>
<li>A value in a <code>char</code> which is a surrogate or above <code>char::MAX</code></li>
<li>Non-UTF-8 byte sequences in a <code>str</code></li>
</ul>
</li>
<li>Unwinding into Rust from foreign code or unwinding from Rust into foreign
code.</li>
</ul>
<h1>Unsafe Superpowers</h1>
<p>In both unsafe functions and unsafe blocks, Rust will let you do three things
that you normally can not do. Just three. Here they are:</p>
<ol>
<li>Access or update a <a href="const-and-static.html#static">static mutable variable</a>.</li>
<li>Dereference a raw pointer.</li>
<li>Call unsafe functions. This is the most powerful ability.</li>
</ol>
<p>That’s it. It’s important that <code>unsafe</code> does not, for example, ‘turn off the
borrow checker’. Adding <code>unsafe</code> to some random Rust code doesn’t change its
semantics, it won’t just start accepting anything. But it will let you write
things that <em>do</em> break some of the rules.</p>
<p>You will also encounter the <code>unsafe</code> keyword when writing bindings to foreign
(non-Rust) interfaces. You're encouraged to write a safe, native Rust interface
around the methods provided by the library.</p>
<p>Let’s go over the basic three abilities listed, in order.</p>
<h2>Access or update a <code>static mut</code></h2>
<p>Rust has a feature called ‘<code>static mut</code>’ which allows for mutable global state.
Doing so can cause a data race, and as such is inherently not safe. For more
details, see the <a href="const-and-static.html#static">static</a> section of the book.</p>
<h2>Dereference a raw pointer</h2>
<p>Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of
different memory safety and security issues. In some senses, the ability to
dereference an arbitrary pointer is one of the most dangerous things you can
do. For more on raw pointers, see <a href="raw-pointers.html">their section of the book</a>.</p>
<h2>Call unsafe functions</h2>
<p>This last ability works with both aspects of <code>unsafe</code>: you can only call
functions marked <code>unsafe</code> from inside an unsafe block.</p>
<p>This ability is powerful and varied. Rust exposes some <a href="intrinsics.html">compiler
intrinsics</a> as unsafe functions, and some unsafe functions bypass
safety checks, trading safety for speed.</p>
<p>I’ll repeat again: even though you <em>can</em> do arbitrary things in unsafe blocks
and functions doesn’t mean you should. The compiler will act as though you’re
upholding its invariants, so be careful!</p>
<h1>Raw Pointers</h1>
<p>Rust has a number of different smart pointer types in its standard library, but
there are two types that are extra-special. Much of Rust’s safety comes from
compile-time checks, but raw pointers don’t have such guarantees, and are
<a href="unsafe.html">unsafe</a> to use.</p>
<p><code>*const T</code> and <code>*mut T</code> are called ‘raw pointers’ in Rust. Sometimes, when
writing certain kinds of libraries, you’ll need to get around Rust’s safety
guarantees for some reason. In this case, you can use raw pointers to implement
your library, while exposing a safe interface for your users. For example, <code>*</code>
pointers are allowed to alias, allowing them to be used to write
shared-ownership types, and even thread-safe shared memory types (the <code>Rc&lt;T&gt;</code>
and <code>Arc&lt;T&gt;</code> types are both implemented entirely in Rust).</p>
<p>Here are some things to remember about raw pointers that are different than
other pointer types. They:</p>
<ul>
<li>are not guaranteed to point to valid memory and are not even
guaranteed to be non-null (unlike both <code>Box</code> and <code>&amp;</code>);</li>
<li>do not have any automatic clean-up, unlike <code>Box</code>, and so require
manual resource management;</li>
<li>are plain-old-data, that is, they don't move ownership, again unlike
<code>Box</code>, hence the Rust compiler cannot protect against bugs like
use-after-free;</li>
<li>lack any form of lifetimes, unlike <code>&amp;</code>, and so the compiler cannot
reason about dangling pointers; and</li>
<li>have no guarantees about aliasing or mutability other than mutation
not being allowed directly through a <code>*const T</code>.</li>
</ul>
<h1>Basics</h1>
<p>Creating a raw pointer is perfectly safe:</p>
<pre><code class="language-rust">let x = 5;
let raw = &amp;x as *const i32;
let mut y = 10;
let raw_mut = &amp;mut y as *mut i32;
</code></pre>
<p>However, dereferencing one is not. This won’t work:</p>
<pre><code class="language-rust,ignore">let x = 5;
let raw = &amp;x as *const i32;
println!(&quot;raw points at {}&quot;, *raw);
</code></pre>
<p>It gives this error:</p>
<pre><code class="language-text">error: dereference of raw pointer requires unsafe function or block [E0133]
println!(&quot;raw points at {}&quot;, *raw);
^~~~
</code></pre>
<p>When you dereference a raw pointer, you’re taking responsibility that it’s not
pointing somewhere that would be incorrect. As such, you need <code>unsafe</code>:</p>
<pre><code class="language-rust">let x = 5;
let raw = &amp;x as *const i32;
let points_at = unsafe { *raw };
println!(&quot;raw points at {}&quot;, points_at);
</code></pre>
<p>For more operations on raw pointers, see <a href="../std/primitive.pointer.html">their API documentation</a>.</p>
<h1>FFI</h1>
<p>Raw pointers are useful for FFI: Rust’s <code>*const T</code> and <code>*mut T</code> are similar to
C’s <code>const T*</code> and <code>T*</code>, respectively. For more about this use, consult the
<a href="ffi.html">FFI chapter</a>.</p>
<h1>References and raw pointers</h1>
<p>At runtime, a raw pointer <code>*</code> and a reference pointing to the same piece of
data have an identical representation. In fact, an <code>&amp;T</code> reference will
implicitly coerce to an <code>*const T</code> raw pointer in safe code and similarly for
the <code>mut</code> variants (both coercions can be performed explicitly with,
respectively, <code>value as *const T</code> and <code>value as *mut T</code>).</p>
<p>Going the opposite direction, from <code>*const</code> to a reference <code>&amp;</code>, is not safe. A
<code>&amp;T</code> is always valid, and so, at a minimum, the raw pointer <code>*const T</code> has to
point to a valid instance of type <code>T</code>. Furthermore, the resulting pointer must
satisfy the aliasing and mutability laws of references. The compiler assumes
these properties are true for any references, no matter how they are created,
and so any conversion from raw pointers is asserting that they hold. The
programmer <em>must</em> guarantee this.</p>
<p>The recommended method for the conversion is:</p>
<pre><code class="language-rust">// explicit cast
let i: u32 = 1;
let p_imm: *const u32 = &amp;i as *const u32;
// implicit coercion
let mut m: u32 = 2;
let p_mut: *mut u32 = &amp;mut m;
unsafe {
let ref_imm: &amp;u32 = &amp;*p_imm;
let ref_mut: &amp;mut u32 = &amp;mut *p_mut;
}
</code></pre>
<p>The <code>&amp;*x</code> dereferencing style is preferred to using a <code>transmute</code>. The latter
is far more powerful than necessary, and the more restricted operation is
harder to use incorrectly; for example, it requires that <code>x</code> is a pointer
(unlike <code>transmute</code>).</p>
<h1>transmute</h1>
<h1>FFI</h1>
<h1>Conditional Compilation</h1>
<p>Rust has a special attribute, <code>#[cfg]</code>, which allows you to compile code
based on a flag passed to the compiler. It has two forms:</p>
<pre><code class="language-rust">#[cfg(foo)]
# fn foo() {}
#[cfg(bar = &quot;baz&quot;)]
# fn bar() {}
</code></pre>
<p>They also have some helpers:</p>
<pre><code class="language-rust">#[cfg(any(unix, windows))]
# fn foo() {}
#[cfg(all(unix, target_pointer_width = &quot;32&quot;))]
# fn bar() {}
#[cfg(not(foo))]
# fn not_foo() {}
</code></pre>
<p>These can nest arbitrarily:</p>
<pre><code class="language-rust">#[cfg(any(not(unix), all(target_os=&quot;macos&quot;, target_arch = &quot;powerpc&quot;)))]
# fn foo() {}
</code></pre>
<p>As for how to enable or disable these switches, if you’re using Cargo,
they get set in the <a href="http://doc.crates.io/manifest.html#the-features-section"><code>[features]</code> section</a> of your <code>Cargo.toml</code>:</p>
<pre><code class="language-toml">[features]
# no features by default
default = []
# The “secure-password” feature depends on the bcrypt package.
secure-password = [&quot;bcrypt&quot;]
</code></pre>
<p>When you do this, Cargo passes along a flag to <code>rustc</code>:</p>
<pre><code class="language-text">--cfg feature=&quot;${feature_name}&quot;
</code></pre>
<p>The sum of these <code>cfg</code> flags will determine which ones get activated, and
therefore, which code gets compiled. Let’s take this code:</p>
<pre><code class="language-rust">#[cfg(feature = &quot;foo&quot;)]
mod foo {
}
</code></pre>
<p>If we compile it with <code>cargo build --features &quot;foo&quot;</code>, it will send the <code>--cfg feature=&quot;foo&quot;</code> flag to <code>rustc</code>, and the output will have the <code>mod foo</code> in it.
If we compile it with a regular <code>cargo build</code>, no extra flags get passed on,
and so, no <code>foo</code> module will exist.</p>
<h1>cfg_attr</h1>
<p>You can also set another attribute based on a <code>cfg</code> variable with <code>cfg_attr</code>:</p>
<pre><code class="language-rust">#[cfg_attr(a, b)]
# fn foo() {}
</code></pre>
<p>Will be the same as <code>#[b]</code> if <code>a</code> is set by <code>cfg</code> attribute, and nothing otherwise.</p>
<h1>cfg!</h1>
<p>The <code>cfg!</code> <a href="compiler-plugins.html">syntax extension</a> lets you use these kinds of flags
elsewhere in your code, too:</p>
<pre><code class="language-rust">if cfg!(target_os = &quot;macos&quot;) || cfg!(target_os = &quot;ios&quot;) {
println!(&quot;Think Different!&quot;);
}
</code></pre>
<p>These will be replaced by a <code>true</code> or <code>false</code> at compile-time, depending on the
configuration settings.</p>
<h1>Bindings to C</h1>
<h1>Using Rust From Other Languages</h1>
<p>For our third project, we’re going to choose something that shows off one of
Rust’s greatest strengths: a lack of a substantial runtime.</p>
<p>As organizations grow, they increasingly rely on a multitude of programming
languages. Different programming languages have different strengths and
weaknesses, and a polyglot stack lets you use a particular language where
its strengths make sense and a different one where it’s weak.</p>
<p>A very common area where many programming languages are weak is in runtime
performance of programs. Often, using a language that is slower, but offers
greater programmer productivity, is a worthwhile trade-off. To help mitigate
this, they provide a way to write some of your system in C and then call
that C code as though it were written in the higher-level language. This is
called a ‘foreign function interface’, often shortened to ‘FFI’.</p>
<p>Rust has support for FFI in both directions: it can call into C code easily,
but crucially, it can also be called <em>into</em> as easily as C. Combined with
Rust’s lack of a garbage collector and low runtime requirements, this makes
Rust a great candidate to embed inside of other languages when you need
that extra oomph.</p>
<p>There is a whole <a href="ffi.html">chapter devoted to FFI</a> and its specifics elsewhere in
the book, but in this chapter, we’ll examine this particular use-case of FFI,
with examples in Ruby, Python, and JavaScript.</p>
<h1>The problem</h1>
<p>There are many different projects we could choose here, but we’re going to
pick an example where Rust has a clear advantage over many other languages:
numeric computing and threading.</p>
<p>Many languages, for the sake of consistency, place numbers on the heap, rather
than on the stack. Especially in languages that focus on object-oriented
programming and use garbage collection, heap allocation is the default. Sometimes
optimizations can stack allocate particular numbers, but rather than relying
on an optimizer to do its job, we may want to ensure that we’re always using
primitive number types rather than some sort of object type.</p>
<p>Second, many languages have a ‘global interpreter lock’ (GIL), which limits
concurrency in many situations. This is done in the name of safety, which is
a positive effect, but it limits the amount of work that can be done at the
same time, which is a big negative.</p>
<p>To emphasize these two aspects, we’re going to create a little project that
uses these two aspects heavily. Since the focus of the example is to embed
Rust into other languages, rather than the problem itself, we’ll just use a
toy example:</p>
<blockquote>
<p>Start ten threads. Inside each thread, count from one to five million. After
all ten threads are finished, print out ‘done!’.</p>
</blockquote>
<p>I chose five million based on my particular computer. Here’s an example of this
code in Ruby:</p>
<pre><code class="language-ruby">threads = []
10.times do
threads &lt;&lt; Thread.new do
count = 0
5_000_000.times do
count += 1
end
count
end
end
threads.each do |t|
puts &quot;Thread finished with count=#{t.value}&quot;
end
puts &quot;done!&quot;
</code></pre>
<p>Try running this example, and choose a number that runs for a few seconds.
Depending on your computer’s hardware, you may have to increase or decrease the
number.</p>
<p>On my system, running this program takes <code>2.156</code> seconds. And, if I use some
sort of process monitoring tool, like <code>top</code>, I can see that it only uses one
core on my machine. That’s the GIL kicking in.</p>
<p>While it’s true that this is a synthetic program, one can imagine many problems
that are similar to this in the real world. For our purposes, spinning up a few
busy threads represents some sort of parallel, expensive computation.</p>
<h1>A Rust library</h1>
<p>Let’s rewrite this problem in Rust. First, let’s make a new project with
Cargo:</p>
<pre><code class="language-bash">$ cargo new embed
$ cd embed
</code></pre>
<p>This program is fairly easy to write in Rust:</p>
<pre><code class="language-rust">use std::thread;
fn process() {
let handles: Vec&lt;_&gt; = (0..10).map(|_| {
thread::spawn(|| {
let mut x = 0;
for _ in 0..5_000_000 {
x += 1
}
x
})
}).collect();
for h in handles {
println!(&quot;Thread finished with count={}&quot;,
h.join().map_err(|_| &quot;Could not join a thread!&quot;).unwrap());
}
}
</code></pre>
<p>Some of this should look familiar from previous examples. We spin up ten
threads, collecting them into a <code>handles</code> vector. Inside of each thread, we
loop five million times, and add one to <code>x</code> each time. Finally, we join on
each thread.</p>
<p>Right now, however, this is a Rust library, and it doesn’t expose anything
that’s callable from C. If we tried to hook this up to another language right
now, it wouldn’t work. We only need to make two small changes to fix this,
though. The first is to modify the beginning of our code:</p>
<pre><code class="language-rust,ignore">#[no_mangle]
pub extern fn process() {
</code></pre>
<p>We have to add a new attribute, <code>no_mangle</code>. When you create a Rust library, it
changes the name of the function in the compiled output. The reasons for this
are outside the scope of this tutorial, but in order for other languages to
know how to call the function, we can’t do that. This attribute turns
that behavior off.</p>
<p>The other change is the <code>pub extern</code>. The <code>pub</code> means that this function should
be callable from outside of this module, and the <code>extern</code> says that it should
be able to be called from C. That’s it! Not a whole lot of change.</p>
<p>The second thing we need to do is to change a setting in our <code>Cargo.toml</code>. Add
this at the bottom:</p>
<pre><code class="language-toml">[lib]
name = &quot;embed&quot;
crate-type = [&quot;dylib&quot;]
</code></pre>
<p>This tells Rust that we want to compile our library into a standard dynamic
library. By default, Rust compiles an ‘rlib’, a Rust-specific format.</p>
<p>Let’s build the project now:</p>
<pre><code class="language-bash">$ cargo build --release
Compiling embed v0.1.0 (file:///home/steve/src/embed)
</code></pre>
<p>We’ve chosen <code>cargo build --release</code>, which builds with optimizations on. We
want this to be as fast as possible! You can find the output of the library in
<code>target/release</code>:</p>
<pre><code class="language-bash">$ ls target/release/
build deps examples libembed.so native
</code></pre>
<p>That <code>libembed.so</code> is our ‘shared object’ library. We can use this file
just like any shared object library written in C! As an aside, this may be
<code>embed.dll</code> (Microsoft Windows) or <code>libembed.dylib</code> (Mac OS X), depending on
your operating system.</p>
<p>Now that we’ve got our Rust library built, let’s use it from our Ruby.</p>
<h1>Ruby</h1>
<p>Open up an <code>embed.rb</code> file inside of our project, and do this:</p>
<pre><code class="language-ruby">require 'ffi'
module Hello
extend FFI::Library
ffi_lib 'target/release/libembed.so'
attach_function :process, [], :void
end
Hello.process
puts 'done!'
</code></pre>
<p>Before we can run this, we need to install the <code>ffi</code> gem:</p>
<pre><code class="language-bash">$ gem install ffi # this may need sudo
Fetching: ffi-1.9.8.gem (100%)
Building native extensions. This could take a while...
Successfully installed ffi-1.9.8
Parsing documentation for ffi-1.9.8
Installing ri documentation for ffi-1.9.8
Done installing documentation for ffi after 0 seconds
1 gem installed
</code></pre>
<p>And finally, we can try running it:</p>
<pre><code class="language-bash">$ ruby embed.rb
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
done!
done!
$
</code></pre>
<p>Whoa, that was fast! On my system, this took <code>0.086</code> seconds, rather than
the two seconds the pure Ruby version took. Let’s break down this Ruby
code:</p>
<pre><code class="language-ruby">require 'ffi'
</code></pre>
<p>We first need to require the <code>ffi</code> gem. This lets us interface with our
Rust library like a C library.</p>
<pre><code class="language-ruby">module Hello
extend FFI::Library
ffi_lib 'target/release/libembed.so'
</code></pre>
<p>The <code>Hello</code> module is used to attach the native functions from the shared
library. Inside, we <code>extend</code> the necessary <code>FFI::Library</code> module and then call
<code>ffi_lib</code> to load up our shared object library. We just pass it the path that
our library is stored, which, as we saw before, is
<code>target/release/libembed.so</code>.</p>
<pre><code class="language-ruby">attach_function :process, [], :void
</code></pre>
<p>The <code>attach_function</code> method is provided by the FFI gem. It’s what
connects our <code>process()</code> function in Rust to a Ruby function of the
same name. Since <code>process()</code> takes no arguments, the second parameter
is an empty array, and since it returns nothing, we pass <code>:void</code> as
the final argument.</p>
<pre><code class="language-ruby">Hello.process
</code></pre>
<p>This is the actual call into Rust. The combination of our <code>module</code>
and the call to <code>attach_function</code> sets this all up. It looks like
a Ruby function but is actually Rust!</p>
<pre><code class="language-ruby">puts 'done!'
</code></pre>
<p>Finally, as per our project’s requirements, we print out <code>done!</code>.</p>
<p>That’s it! As we’ve seen, bridging between the two languages is really easy,
and buys us a lot of performance.</p>
<p>Next, let’s try Python!</p>
<h1>Python</h1>
<p>Create an <code>embed.py</code> file in this directory, and put this in it:</p>
<pre><code class="language-python">from ctypes import cdll
lib = cdll.LoadLibrary(&quot;target/release/libembed.so&quot;)
lib.process()
print(&quot;done!&quot;)
</code></pre>
<p>Even easier! We use <code>cdll</code> from the <code>ctypes</code> module. A quick call
to <code>LoadLibrary</code> later, and we can call <code>process()</code>.</p>
<p>On my system, this takes <code>0.017</code> seconds. Speedy!</p>
<h1>Node.js</h1>
<p>Node isn’t a language, but it’s currently the dominant implementation of
server-side JavaScript.</p>
<p>In order to do FFI with Node, we first need to install the library:</p>
<pre><code class="language-bash">$ npm install ffi
</code></pre>
<p>After that installs, we can use it:</p>
<pre><code class="language-javascript">var ffi = require('ffi');
var lib = ffi.Library('target/release/libembed', {
'process': ['void', []]
});
lib.process();
console.log(&quot;done!&quot;);
</code></pre>
<p>It looks more like the Ruby example than the Python example. We use
the <code>ffi</code> module to get access to <code>ffi.Library()</code>, which loads up
our shared object. We need to annotate the return type and argument
types of the function, which are <code>void</code> for return and an empty
array to signify no arguments. From there, we just call it and
print the result.</p>
<p>On my system, this takes a quick <code>0.092</code> seconds.</p>
<h1>Conclusion</h1>
<p>As you can see, the basics of doing this are <em>very</em> easy. Of course,
there's a lot more that we could do here. Check out the <a href="ffi.html">FFI</a>
chapter for more details.</p>
<h1><code>static</code></h1>
<h1>Cargo</h1>
<h1>Crates.io</h1>
<h1>Advanced Type System Features</h1>
<h1>Associated Types</h1>
<p>Associated types are a powerful part of Rust’s type system. They’re related to
the idea of a ‘type family’, in other words, grouping multiple types together. That
description is a bit abstract, so let’s dive right into an example. If you want
to write a <code>Graph</code> trait, you have two types to be generic over: the node type
and the edge type. So you might write a trait, <code>Graph&lt;N, E&gt;</code>, that looks like
this:</p>
<pre><code class="language-rust">trait Graph&lt;N, E&gt; {
fn has_edge(&amp;self, &amp;N, &amp;N) -&gt; bool;
fn edges(&amp;self, &amp;N) -&gt; Vec&lt;E&gt;;
// etc
}
</code></pre>
<p>While this sort of works, it ends up being awkward. For example, any function
that wants to take a <code>Graph</code> as a parameter now <em>also</em> needs to be generic over
the <code>N</code>ode and <code>E</code>dge types too:</p>
<pre><code class="language-rust,ignore">fn distance&lt;N, E, G: Graph&lt;N, E&gt;&gt;(graph: &amp;G, start: &amp;N, end: &amp;N) -&gt; u32 { ... }
</code></pre>
<p>Our distance calculation works regardless of our <code>Edge</code> type, so the <code>E</code> stuff in
this signature is just a distraction.</p>
<p>What we really want to say is that a certain <code>E</code>dge and <code>N</code>ode type come together
to form each kind of <code>Graph</code>. We can do that with associated types:</p>
<pre><code class="language-rust">trait Graph {
type N;
type E;
fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool;
fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;;
// etc
}
</code></pre>
<p>Now, our clients can be abstract over a given <code>Graph</code>:</p>
<pre><code class="language-rust,ignore">fn distance&lt;G: Graph&gt;(graph: &amp;G, start: &amp;G::N, end: &amp;G::N) -&gt; u32 { ... }
</code></pre>
<p>No need to deal with the <code>E</code>dge type here!</p>
<p>Let’s go over all this in more detail.</p>
<h2>Defining associated types</h2>
<p>Let’s build that <code>Graph</code> trait. Here’s the definition:</p>
<pre><code class="language-rust">trait Graph {
type N;
type E;
fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool;
fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;;
}
</code></pre>
<p>Simple enough. Associated types use the <code>type</code> keyword, and go inside the body
of the trait, with the functions.</p>
<p>These <code>type</code> declarations can have all the same thing as functions do. For example,
if we wanted our <code>N</code> type to implement <code>Display</code>, so we can print the nodes out,
we could do this:</p>
<pre><code class="language-rust">use std::fmt;
trait Graph {
type N: fmt::Display;
type E;
fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool;
fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;;
}
</code></pre>
<h2>Implementing associated types</h2>
<p>Just like any trait, traits that use associated types use the <code>impl</code> keyword to
provide implementations. Here’s a simple implementation of Graph:</p>
<pre><code class="language-rust"># trait Graph {
# type N;
# type E;
# fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool;
# fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;;
# }
struct Node;
struct Edge;
struct MyGraph;
impl Graph for MyGraph {
type N = Node;
type E = Edge;
fn has_edge(&amp;self, n1: &amp;Node, n2: &amp;Node) -&gt; bool {
true
}
fn edges(&amp;self, n: &amp;Node) -&gt; Vec&lt;Edge&gt; {
Vec::new()
}
}
</code></pre>
<p>This silly implementation always returns <code>true</code> and an empty <code>Vec&lt;Edge&gt;</code>, but it
gives you an idea of how to implement this kind of thing. We first need three
<code>struct</code>s, one for the graph, one for the node, and one for the edge. If it made
more sense to use a different type, that would work as well, we’re just going to
use <code>struct</code>s for all three here.</p>
<p>Next is the <code>impl</code> line, which is just like implementing any other trait.</p>
<p>From here, we use <code>=</code> to define our associated types. The name the trait uses
goes on the left of the <code>=</code>, and the concrete type we’re <code>impl</code>ementing this
for goes on the right. Finally, we use the concrete types in our function
declarations.</p>
<h2>Trait objects with associated types</h2>
<p>There’s one more bit of syntax we should talk about: trait objects. If you
try to create a trait object from an associated type, like this:</p>
<pre><code class="language-rust,ignore"># trait Graph {
# type N;
# type E;
# fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool;
# fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;;
# }
# struct Node;
# struct Edge;
# struct MyGraph;
# impl Graph for MyGraph {
# type N = Node;
# type E = Edge;
# fn has_edge(&amp;self, n1: &amp;Node, n2: &amp;Node) -&gt; bool {
# true
# }
# fn edges(&amp;self, n: &amp;Node) -&gt; Vec&lt;Edge&gt; {
# Vec::new()
# }
# }
let graph = MyGraph;
let obj = Box::new(graph) as Box&lt;Graph&gt;;
</code></pre>
<p>You’ll get two errors:</p>
<pre><code class="language-text">error: the value of the associated type `E` (from the trait `main::Graph`) must
be specified [E0191]
let obj = Box::new(graph) as Box&lt;Graph&gt;;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24:44 error: the value of the associated type `N` (from the trait
`main::Graph`) must be specified [E0191]
let obj = Box::new(graph) as Box&lt;Graph&gt;;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>We can’t create a trait object like this, because we don’t know the associated
types. Instead, we can write this:</p>
<pre><code class="language-rust"># trait Graph {
# type N;
# type E;
# fn has_edge(&amp;self, &amp;Self::N, &amp;Self::N) -&gt; bool;
# fn edges(&amp;self, &amp;Self::N) -&gt; Vec&lt;Self::E&gt;;
# }
# struct Node;
# struct Edge;
# struct MyGraph;
# impl Graph for MyGraph {
# type N = Node;
# type E = Edge;
# fn has_edge(&amp;self, n1: &amp;Node, n2: &amp;Node) -&gt; bool {
# true
# }
# fn edges(&amp;self, n: &amp;Node) -&gt; Vec&lt;Edge&gt; {
# Vec::new()
# }
# }
let graph = MyGraph;
let obj = Box::new(graph) as Box&lt;Graph&lt;N=Node, E=Edge&gt;&gt;;
</code></pre>
<p>The <code>N=Node</code> syntax allows us to provide a concrete type, <code>Node</code>, for the <code>N</code>
type parameter. Same with <code>E=Edge</code>. If we didn’t provide this constraint, we
couldn’t be sure which <code>impl</code> to match this trait object to.</p>
<h1>Trait Objects</h1>
<p>When code involves polymorphism, there needs to be a mechanism to determine
which specific version is actually run. This is called ‘dispatch’. There are
two major forms of dispatch: static dispatch and dynamic dispatch. While Rust
favors static dispatch, it also supports dynamic dispatch through a mechanism
called ‘trait objects’.</p>
<h2>Background</h2>
<p>For the rest of this chapter, we’ll need a trait and some implementations.
Let’s make a simple one, <code>Foo</code>. It has one method that is expected to return a
<code>String</code>.</p>
<pre><code class="language-rust">trait Foo {
fn method(&amp;self) -&gt; String;
}
</code></pre>
<p>We’ll also implement this trait for <code>u8</code> and <code>String</code>:</p>
<pre><code class="language-rust"># trait Foo { fn method(&amp;self) -&gt; String; }
impl Foo for u8 {
fn method(&amp;self) -&gt; String { format!(&quot;u8: {}&quot;, *self) }
}
impl Foo for String {
fn method(&amp;self) -&gt; String { format!(&quot;string: {}&quot;, *self) }
}
</code></pre>
<h2>Static dispatch</h2>
<p>We can use this trait to perform static dispatch with trait bounds:</p>
<pre><code class="language-rust"># trait Foo { fn method(&amp;self) -&gt; String; }
# impl Foo for u8 { fn method(&amp;self) -&gt; String { format!(&quot;u8: {}&quot;, *self) } }
# impl Foo for String { fn method(&amp;self) -&gt; String { format!(&quot;string: {}&quot;, *self) } }
fn do_something&lt;T: Foo&gt;(x: T) {
x.method();
}
fn main() {
let x = 5u8;
let y = &quot;Hello&quot;.to_string();
do_something(x);
do_something(y);
}
</code></pre>
<p>Rust uses ‘monomorphization’ to perform static dispatch here. This means that
Rust will create a special version of <code>do_something()</code> for both <code>u8</code> and
<code>String</code>, and then replace the call sites with calls to these specialized
functions. In other words, Rust generates something like this:</p>
<pre><code class="language-rust"># trait Foo { fn method(&amp;self) -&gt; String; }
# impl Foo for u8 { fn method(&amp;self) -&gt; String { format!(&quot;u8: {}&quot;, *self) } }
# impl Foo for String { fn method(&amp;self) -&gt; String { format!(&quot;string: {}&quot;, *self) } }
fn do_something_u8(x: u8) {
x.method();
}
fn do_something_string(x: String) {
x.method();
}
fn main() {
let x = 5u8;
let y = &quot;Hello&quot;.to_string();
do_something_u8(x);
do_something_string(y);
}
</code></pre>
<p>This has a great upside: static dispatch allows function calls to be
inlined because the callee is known at compile time, and inlining is
the key to good optimization. Static dispatch is fast, but it comes at
a tradeoff: ‘code bloat’, due to many copies of the same function
existing in the binary, one for each type.</p>
<p>Furthermore, compilers aren’t perfect and may “optimize” code to become slower.
For example, functions inlined too eagerly will bloat the instruction cache
(cache rules everything around us). This is part of the reason that <code>#[inline]</code>
and <code>#[inline(always)]</code> should be used carefully, and one reason why using a
dynamic dispatch is sometimes more efficient.</p>
<p>However, the common case is that it is more efficient to use static dispatch,
and one can always have a thin statically-dispatched wrapper function that does
a dynamic dispatch, but not vice versa, meaning static calls are more flexible.
The standard library tries to be statically dispatched where possible for this
reason.</p>
<h2>Dynamic dispatch</h2>
<p>Rust provides dynamic dispatch through a feature called ‘trait objects’. Trait
objects, like <code>&amp;Foo</code> or <code>Box&lt;Foo&gt;</code>, are normal values that store a value of
<em>any</em> type that implements the given trait, where the precise type can only be
known at runtime.</p>
<p>A trait object can be obtained from a pointer to a concrete type that
implements the trait by <em>casting</em> it (e.g. <code>&amp;x as &amp;Foo</code>) or <em>coercing</em> it
(e.g. using <code>&amp;x</code> as an argument to a function that takes <code>&amp;Foo</code>).</p>
<p>These trait object coercions and casts also work for pointers like <code>&amp;mut T</code> to
<code>&amp;mut Foo</code> and <code>Box&lt;T&gt;</code> to <code>Box&lt;Foo&gt;</code>, but that’s all at the moment. Coercions
and casts are identical.</p>
<p>This operation can be seen as ‘erasing’ the compiler’s knowledge about the
specific type of the pointer, and hence trait objects are sometimes referred to
as ‘type erasure’.</p>
<p>Coming back to the example above, we can use the same trait to perform dynamic
dispatch with trait objects by casting:</p>
<pre><code class="language-rust"># trait Foo { fn method(&amp;self) -&gt; String; }
# impl Foo for u8 { fn method(&amp;self) -&gt; String { format!(&quot;u8: {}&quot;, *self) } }
# impl Foo for String { fn method(&amp;self) -&gt; String { format!(&quot;string: {}&quot;, *self) } }
fn do_something(x: &amp;Foo) {
x.method();
}
fn main() {
let x = 5u8;
do_something(&amp;x as &amp;Foo);
}
</code></pre>
<p>or by coercing:</p>
<pre><code class="language-rust"># trait Foo { fn method(&amp;self) -&gt; String; }
# impl Foo for u8 { fn method(&amp;self) -&gt; String { format!(&quot;u8: {}&quot;, *self) } }
# impl Foo for String { fn method(&amp;self) -&gt; String { format!(&quot;string: {}&quot;, *self) } }
fn do_something(x: &amp;Foo) {
x.method();
}
fn main() {
let x = &quot;Hello&quot;.to_string();
do_something(&amp;x);
}
</code></pre>
<p>A function that takes a trait object is not specialized to each of the types
that implements <code>Foo</code>: only one copy is generated, often (but not always)
resulting in less code bloat. However, this comes at the cost of requiring
slower virtual function calls, and effectively inhibiting any chance of
inlining and related optimizations from occurring.</p>
<h3>Why pointers?</h3>
<p>Rust does not put things behind a pointer by default, unlike many managed
languages, so types can have different sizes. Knowing the size of the value at
compile time is important for things like passing it as an argument to a
function, moving it about on the stack and allocating (and deallocating) space
on the heap to store it.</p>
<p>For <code>Foo</code>, we would need to have a value that could be at least either a
<code>String</code> (24 bytes) or a <code>u8</code> (1 byte), as well as any other type for which
dependent crates may implement <code>Foo</code> (any number of bytes at all). There’s no
way to guarantee that this last point can work if the values are stored without
a pointer, because those other types can be arbitrarily large.</p>
<p>Putting the value behind a pointer means the size of the value is not relevant
when we are tossing a trait object around, only the size of the pointer itself.</p>
<h3>Representation</h3>
<p>The methods of the trait can be called on a trait object via a special record
of function pointers traditionally called a ‘vtable’ (created and managed by
the compiler).</p>
<p>Trait objects are both simple and complicated: their core representation and
layout is quite straight-forward, but there are some curly error messages and
surprising behaviors to discover.</p>
<p>Let’s start simple, with the runtime representation of a trait object. The
<code>std::raw</code> module contains structs with layouts that are the same as the
complicated built-in types, <a href="../std/raw/struct.TraitObject.html">including trait objects</a>:</p>
<pre><code class="language-rust"># mod foo {
pub struct TraitObject {
pub data: *mut (),
pub vtable: *mut (),
}
# }
</code></pre>
<p>That is, a trait object like <code>&amp;Foo</code> consists of a ‘data’ pointer and a ‘vtable’
pointer.</p>
<p>The data pointer addresses the data (of some unknown type <code>T</code>) that the trait
object is storing, and the vtable pointer points to the vtable (‘virtual method
table’) corresponding to the implementation of <code>Foo</code> for <code>T</code>.</p>
<p>A vtable is essentially a struct of function pointers, pointing to the concrete
piece of machine code for each method in the implementation. A method call like
<code>trait_object.method()</code> will retrieve the correct pointer out of the vtable and
then do a dynamic call of it. For example:</p>
<pre><code class="language-rust,ignore">struct FooVtable {
destructor: fn(*mut ()),
size: usize,
align: usize,
method: fn(*const ()) -&gt; String,
}
// u8:
fn call_method_on_u8(x: *const ()) -&gt; String {
// the compiler guarantees that this function is only called
// with `x` pointing to a u8
let byte: &amp;u8 = unsafe { &amp;*(x as *const u8) };
byte.method()
}
static Foo_for_u8_vtable: FooVtable = FooVtable {
destructor: /* compiler magic */,
size: 1,
align: 1,
// cast to a function pointer
method: call_method_on_u8 as fn(*const ()) -&gt; String,
};
// String:
fn call_method_on_String(x: *const ()) -&gt; String {
// the compiler guarantees that this function is only called
// with `x` pointing to a String
let string: &amp;String = unsafe { &amp;*(x as *const String) };
string.method()
}
static Foo_for_String_vtable: FooVtable = FooVtable {
destructor: /* compiler magic */,
// values for a 64-bit computer, halve them for 32-bit ones
size: 24,
align: 8,
method: call_method_on_String as fn(*const ()) -&gt; String,
};
</code></pre>
<p>The <code>destructor</code> field in each vtable points to a function that will clean up
any resources of the vtable’s type: for <code>u8</code> it is trivial, but for <code>String</code> it
will free the memory. This is necessary for owning trait objects like
<code>Box&lt;Foo&gt;</code>, which need to clean-up both the <code>Box</code> allocation as well as the
internal type when they go out of scope. The <code>size</code> and <code>align</code> fields store
the size of the erased type, and its alignment requirements; these are
essentially unused at the moment since the information is embedded in the
destructor, but will be used in the future, as trait objects are progressively
made more flexible.</p>
<p>Suppose we’ve got some values that implement <code>Foo</code>. The explicit form of
construction and use of <code>Foo</code> trait objects might look a bit like (ignoring the
type mismatches: they’re all just pointers anyway):</p>
<pre><code class="language-rust,ignore">let a: String = &quot;foo&quot;.to_string();
let x: u8 = 1;
// let b: &amp;Foo = &amp;a;
let b = TraitObject {
// store the data
data: &amp;a,
// store the methods
vtable: &amp;Foo_for_String_vtable
};
// let y: &amp;Foo = x;
let y = TraitObject {
// store the data
data: &amp;x,
// store the methods
vtable: &amp;Foo_for_u8_vtable
};
// b.method();
(b.vtable.method)(b.data);
// y.method();
(y.vtable.method)(y.data);
</code></pre>
<h2>Object Safety</h2>
<p>Not every trait can be used to make a trait object. For example, vectors implement
<code>Clone</code>, but if we try to make a trait object:</p>
<pre><code class="language-ignore">let v = vec![1, 2, 3];
let o = &amp;v as &amp;Clone;
</code></pre>
<p>We get an error:</p>
<pre><code class="language-text">error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]
let o = &amp;v as &amp;Clone;
^~
note: the trait cannot require that `Self : Sized`
let o = &amp;v as &amp;Clone;
^~
</code></pre>
<p>The error says that <code>Clone</code> is not ‘object-safe’. Only traits that are
object-safe can be made into trait objects. A trait is object-safe if both of
these are true:</p>
<ul>
<li>the trait does not require that <code>Self: Sized</code></li>
<li>all of its methods are object-safe</li>
</ul>
<p>So what makes a method object-safe? Each method must require that <code>Self: Sized</code>
or all of the following:</p>
<ul>
<li>must not have any type parameters</li>
<li>must not use <code>Self</code></li>
</ul>
<p>Whew! As we can see, almost all of these rules talk about <code>Self</code>. A good intuition
is “except in special circumstances, if your trait’s method uses <code>Self</code>, it is not
object-safe.”</p>
<h1>Universal Function Call Syntax</h1>
<p>Sometimes, functions can have the same names. Consider this code:</p>
<pre><code class="language-rust">trait Foo {
fn f(&amp;self);
}
trait Bar {
fn f(&amp;self);
}
struct Baz;
impl Foo for Baz {
fn f(&amp;self) { println!(&quot;Baz’s impl of Foo&quot;); }
}
impl Bar for Baz {
fn f(&amp;self) { println!(&quot;Baz’s impl of Bar&quot;); }
}
let b = Baz;
</code></pre>
<p>If we were to try to call <code>b.f()</code>, we’d get an error:</p>
<pre><code class="language-text">error: multiple applicable methods in scope [E0034]
b.f();
^~~
note: candidate #1 is defined in an impl of the trait `main::Foo` for the type
`main::Baz`
fn f(&amp;self) { println!(&quot;Baz’s impl of Foo&quot;); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: candidate #2 is defined in an impl of the trait `main::Bar` for the type
`main::Baz`
fn f(&amp;self) { println!(&quot;Baz’s impl of Bar&quot;); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>We need a way to disambiguate which method we need. This feature is called
‘universal function call syntax’, and it looks like this:</p>
<pre><code class="language-rust"># trait Foo {
# fn f(&amp;self);
# }
# trait Bar {
# fn f(&amp;self);
# }
# struct Baz;
# impl Foo for Baz {
# fn f(&amp;self) { println!(&quot;Baz’s impl of Foo&quot;); }
# }
# impl Bar for Baz {
# fn f(&amp;self) { println!(&quot;Baz’s impl of Bar&quot;); }
# }
# let b = Baz;
Foo::f(&amp;b);
Bar::f(&amp;b);
</code></pre>
<p>Let’s break it down.</p>
<pre><code class="language-rust,ignore">Foo::
Bar::
</code></pre>
<p>These halves of the invocation are the types of the two traits: <code>Foo</code> and
<code>Bar</code>. This is what ends up actually doing the disambiguation between the two:
Rust calls the one from the trait name you use.</p>
<pre><code class="language-rust,ignore">f(&amp;b)
</code></pre>
<p>When we call a method like <code>b.f()</code> using <a href="method-syntax.html">method syntax</a>, Rust
will automatically borrow <code>b</code> if <code>f()</code> takes <code>&amp;self</code>. In this case, Rust will
not, and so we need to pass an explicit <code>&amp;b</code>.</p>
<h1>Angle-bracket Form</h1>
<p>The form of UFCS we just talked about:</p>
<pre><code class="language-rust,ignore">Trait::method(args);
</code></pre>
<p>Is a short-hand. There’s an expanded form of this that’s needed in some
situations:</p>
<pre><code class="language-rust,ignore">&lt;Type as Trait&gt;::method(args);
</code></pre>
<p>The <code>&lt;&gt;::</code> syntax is a means of providing a type hint. The type goes inside
the <code>&lt;&gt;</code>s. In this case, the type is <code>Type as Trait</code>, indicating that we want
<code>Trait</code>’s version of <code>method</code> to be called here. The <code>as Trait</code> part is
optional if it’s not ambiguous. Same with the angle brackets, hence the
shorter form.</p>
<p>Here’s an example of using the longer form.</p>
<pre><code class="language-rust">trait Foo {
fn foo() -&gt; i32;
}
struct Bar;
impl Bar {
fn foo() -&gt; i32 {
20
}
}
impl Foo for Bar {
fn foo() -&gt; i32 {
10
}
}
fn main() {
assert_eq!(10, &lt;Bar as Foo&gt;::foo());
assert_eq!(20, Bar::foo());
}
</code></pre>
<p>Using the angle bracket syntax lets you call the trait method instead of the
inherent one.</p>
<h1>Coherence</h1>
<h1>Interior mutability</h1>
<h1><code>Cell&lt;T&gt;</code></h1>
<h1><code>RefCell&lt;T&gt;</code></h1>
<h1>Macros</h1>
<p>By now you’ve learned about many of the tools Rust provides for abstracting and
reusing code. These units of code reuse have a rich semantic structure. For
example, functions have a type signature, type parameters have trait bounds,
and overloaded functions must belong to a particular trait.</p>
<p>This structure means that Rust’s core abstractions have powerful compile-time
correctness checking. But this comes at the price of reduced flexibility. If
you visually identify a pattern of repeated code, you may find it’s difficult
or cumbersome to express that pattern as a generic function, a trait, or
anything else within Rust’s semantics.</p>
<p>Macros allow us to abstract at a syntactic level. A macro invocation is
shorthand for an &quot;expanded&quot; syntactic form. This expansion happens early in
compilation, before any static checking. As a result, macros can capture many
patterns of code reuse that Rust’s core abstractions cannot.</p>
<p>The drawback is that macro-based code can be harder to understand, because
fewer of the built-in rules apply. Like an ordinary function, a well-behaved
macro can be used without understanding its implementation. However, it can be
difficult to design a well-behaved macro! Additionally, compiler errors in
macro code are harder to interpret, because they describe problems in the
expanded code, not the source-level form that developers use.</p>
<p>These drawbacks make macros something of a &quot;feature of last resort&quot;. That’s not
to say that macros are bad; they are part of Rust because sometimes they’re
needed for truly concise, well-abstracted code. Just keep this tradeoff in
mind.</p>
<h1>Defining a macro</h1>
<p>You may have seen the <code>vec!</code> macro, used to initialize a <a href="vectors.html">vector</a> with
any number of elements.</p>
<pre><code class="language-rust">let x: Vec&lt;u32&gt; = vec![1, 2, 3];
# assert_eq!(x, [1, 2, 3]);
</code></pre>
<p>This can’t be an ordinary function, because it takes any number of arguments.
But we can imagine it as syntactic shorthand for</p>
<pre><code class="language-rust">let x: Vec&lt;u32&gt; = {
let mut temp_vec = Vec::new();
temp_vec.push(1);
temp_vec.push(2);
temp_vec.push(3);
temp_vec
};
# assert_eq!(x, [1, 2, 3]);
</code></pre>
<p>We can implement this shorthand, using a macro: [^actual]</p>
<p>[^actual]: The actual definition of <code>vec!</code> in libcollections differs from the
one presented here, for reasons of efficiency and reusability.</p>
<pre><code class="language-rust">macro_rules! vec {
( $( $x:expr ),* ) =&gt; {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
# fn main() {
# assert_eq!(vec![1,2,3], [1, 2, 3]);
# }
</code></pre>
<p>Whoa, that’s a lot of new syntax! Let’s break it down.</p>
<pre><code class="language-ignore">macro_rules! vec { ... }
</code></pre>
<p>This says we’re defining a macro named <code>vec</code>, much as <code>fn vec</code> would define a
function named <code>vec</code>. In prose, we informally write a macro’s name with an
exclamation point, e.g. <code>vec!</code>. The exclamation point is part of the invocation
syntax and serves to distinguish a macro from an ordinary function.</p>
<h2>Matching</h2>
<p>The macro is defined through a series of rules, which are pattern-matching
cases. Above, we had</p>
<pre><code class="language-ignore">( $( $x:expr ),* ) =&gt; { ... };
</code></pre>
<p>This is like a <code>match</code> expression arm, but the matching happens on Rust syntax
trees, at compile time. The semicolon is optional on the last (here, only)
case. The &quot;pattern&quot; on the left-hand side of <code>=&gt;</code> is known as a ‘matcher’.
These have <a href="../reference.html#macros">their own little grammar</a> within the language.</p>
<p>The matcher <code>$x:expr</code> will match any Rust expression, binding that syntax tree
to the ‘metavariable’ <code>$x</code>. The identifier <code>expr</code> is a ‘fragment specifier’;
the full possibilities are enumerated later in this chapter.
Surrounding the matcher with <code>$(...),*</code> will match zero or more expressions,
separated by commas.</p>
<p>Aside from the special matcher syntax, any Rust tokens that appear in a matcher
must match exactly. For example,</p>
<pre><code class="language-rust">macro_rules! foo {
(x =&gt; $e:expr) =&gt; (println!(&quot;mode X: {}&quot;, $e));
(y =&gt; $e:expr) =&gt; (println!(&quot;mode Y: {}&quot;, $e));
}
fn main() {
foo!(y =&gt; 3);
}
</code></pre>
<p>will print</p>
<pre><code class="language-text">mode Y: 3
</code></pre>
<p>With</p>
<pre><code class="language-rust,ignore">foo!(z =&gt; 3);
</code></pre>
<p>we get the compiler error</p>
<pre><code class="language-text">error: no rules expected the token `z`
</code></pre>
<h2>Expansion</h2>
<p>The right-hand side of a macro rule is ordinary Rust syntax, for the most part.
But we can splice in bits of syntax captured by the matcher. From the original
example:</p>
<pre><code class="language-ignore">$(
temp_vec.push($x);
)*
</code></pre>
<p>Each matched expression <code>$x</code> will produce a single <code>push</code> statement in the
macro expansion. The repetition in the expansion proceeds in &quot;lockstep&quot; with
repetition in the matcher (more on this in a moment).</p>
<p>Because <code>$x</code> was already declared as matching an expression, we don’t repeat
<code>:expr</code> on the right-hand side. Also, we don’t include a separating comma as
part of the repetition operator. Instead, we have a terminating semicolon
within the repeated block.</p>
<p>Another detail: the <code>vec!</code> macro has <em>two</em> pairs of braces on the right-hand
side. They are often combined like so:</p>
<pre><code class="language-ignore">macro_rules! foo {
() =&gt; {{
...
}}
}
</code></pre>
<p>The outer braces are part of the syntax of <code>macro_rules!</code>. In fact, you can use
<code>()</code> or <code>[]</code> instead. They simply delimit the right-hand side as a whole.</p>
<p>The inner braces are part of the expanded syntax. Remember, the <code>vec!</code> macro is
used in an expression context. To write an expression with multiple statements,
including <code>let</code>-bindings, we use a block. If your macro expands to a single
expression, you don’t need this extra layer of braces.</p>
<p>Note that we never <em>declared</em> that the macro produces an expression. In fact,
this is not determined until we use the macro as an expression. With care, you
can write a macro whose expansion works in several contexts. For example,
shorthand for a data type could be valid as either an expression or a pattern.</p>
<h2>Repetition</h2>
<p>The repetition operator follows two principal rules:</p>
<ol>
<li><code>$(...)*</code> walks through one &quot;layer&quot; of repetitions, for all of the <code>$name</code>s
it contains, in lockstep, and</li>
<li>each <code>$name</code> must be under at least as many <code>$(...)*</code>s as it was matched
against. If it is under more, it’ll be duplicated, as appropriate.</li>
</ol>
<p>This baroque macro illustrates the duplication of variables from outer
repetition levels.</p>
<pre><code class="language-rust">macro_rules! o_O {
(
$(
$x:expr; [ $( $y:expr ),* ]
);*
) =&gt; {
&amp;[ $($( $x + $y ),*),* ]
}
}
fn main() {
let a: &amp;[i32]
= o_O!(10; [1, 2, 3];
20; [4, 5, 6]);
assert_eq!(a, [11, 12, 13, 24, 25, 26]);
}
</code></pre>
<p>That’s most of the matcher syntax. These examples use <code>$(...)*</code>, which is a
&quot;zero or more&quot; match. Alternatively you can write <code>$(...)+</code> for a &quot;one or
more&quot; match. Both forms optionally include a separator, which can be any token
except <code>+</code> or <code>*</code>.</p>
<p>This system is based on
&quot;<a href="https://www.cs.indiana.edu/ftp/techreports/TR206.pdf">Macro-by-Example</a>&quot;
(PDF link).</p>
<h1>Hygiene</h1>
<p>Some languages implement macros using simple text substitution, which leads to
various problems. For example, this C program prints <code>13</code> instead of the
expected <code>25</code>.</p>
<pre><code class="language-text">#define FIVE_TIMES(x) 5 * x
int main() {
printf(&quot;%d\n&quot;, FIVE_TIMES(2 + 3));
return 0;
}
</code></pre>
<p>After expansion we have <code>5 * 2 + 3</code>, and multiplication has greater precedence
than addition. If you’ve used C macros a lot, you probably know the standard
idioms for avoiding this problem, as well as five or six others. In Rust, we
don’t have to worry about it.</p>
<pre><code class="language-rust">macro_rules! five_times {
($x:expr) =&gt; (5 * $x);
}
fn main() {
assert_eq!(25, five_times!(2 + 3));
}
</code></pre>
<p>The metavariable <code>$x</code> is parsed as a single expression node, and keeps its
place in the syntax tree even after substitution.</p>
<p>Another common problem in macro systems is ‘variable capture’. Here’s a C
macro, using <a href="https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html">a GNU C extension</a> to emulate Rust’s expression blocks.</p>
<pre><code class="language-text">#define LOG(msg) ({ \
int state = get_log_state(); \
if (state &gt; 0) { \
printf(&quot;log(%d): %s\n&quot;, state, msg); \
} \
})
</code></pre>
<p>Here’s a simple use case that goes terribly wrong:</p>
<pre><code class="language-text">const char *state = &quot;reticulating splines&quot;;
LOG(state)
</code></pre>
<p>This expands to</p>
<pre><code class="language-text">const char *state = &quot;reticulating splines&quot;;
int state = get_log_state();
if (state &gt; 0) {
printf(&quot;log(%d): %s\n&quot;, state, state);
}
</code></pre>
<p>The second variable named <code>state</code> shadows the first one. This is a problem
because the print statement should refer to both of them.</p>
<p>The equivalent Rust macro has the desired behavior.</p>
<pre><code class="language-rust"># fn get_log_state() -&gt; i32 { 3 }
macro_rules! log {
($msg:expr) =&gt; {{
let state: i32 = get_log_state();
if state &gt; 0 {
println!(&quot;log({}): {}&quot;, state, $msg);
}
}};
}
fn main() {
let state: &amp;str = &quot;reticulating splines&quot;;
log!(state);
}
</code></pre>
<p>This works because Rust has a <a href="https://en.wikipedia.org/wiki/Hygienic_macro">hygienic macro system</a>. Each macro expansion
happens in a distinct ‘syntax context’, and each variable is tagged with the
syntax context where it was introduced. It’s as though the variable <code>state</code>
inside <code>main</code> is painted a different &quot;color&quot; from the variable <code>state</code> inside
the macro, and therefore they don’t conflict.</p>
<p>This also restricts the ability of macros to introduce new bindings at the
invocation site. Code such as the following will not work:</p>
<pre><code class="language-rust,ignore">macro_rules! foo {
() =&gt; (let x = 3);
}
fn main() {
foo!();
println!(&quot;{}&quot;, x);
}
</code></pre>
<p>Instead you need to pass the variable name into the invocation, so it’s tagged
with the right syntax context.</p>
<pre><code class="language-rust">macro_rules! foo {
($v:ident) =&gt; (let $v = 3);
}
fn main() {
foo!(x);
println!(&quot;{}&quot;, x);
}
</code></pre>
<p>This holds for <code>let</code> bindings and loop labels, but not for <a href="../reference.html#items">items</a>.
So the following code does compile:</p>
<pre><code class="language-rust">macro_rules! foo {
() =&gt; (fn x() { });
}
fn main() {
foo!();
x();
}
</code></pre>
<h1>Recursive macros</h1>
<p>A macro’s expansion can include more macro invocations, including invocations
of the very same macro being expanded. These recursive macros are useful for
processing tree-structured input, as illustrated by this (simplistic) HTML
shorthand:</p>
<pre><code class="language-rust"># #![allow(unused_must_use)]
macro_rules! write_html {
($w:expr, ) =&gt; (());
($w:expr, $e:tt) =&gt; (write!($w, &quot;{}&quot;, $e));
($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) =&gt; {{
write!($w, &quot;&lt;{}&gt;&quot;, stringify!($tag));
write_html!($w, $($inner)*);
write!($w, &quot;&lt;/{}&gt;&quot;, stringify!($tag));
write_html!($w, $($rest)*);
}};
}
fn main() {
# // FIXME(#21826)
use std::fmt::Write;
let mut out = String::new();
write_html!(&amp;mut out,
html[
head[title[&quot;Macros guide&quot;]]
body[h1[&quot;Macros are the best!&quot;]]
]);
assert_eq!(out,
&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Macros guide&lt;/title&gt;&lt;/head&gt;\
&lt;body&gt;&lt;h1&gt;Macros are the best!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;);
}
</code></pre>
<h1>Debugging macro code</h1>
<p>To see the results of expanding macros, run <code>rustc --pretty expanded</code>. The
output represents a whole crate, so you can also feed it back in to <code>rustc</code>,
which will sometimes produce better error messages than the original
compilation. Note that the <code>--pretty expanded</code> output may have a different
meaning if multiple variables of the same name (but different syntax contexts)
are in play in the same scope. In this case <code>--pretty expanded,hygiene</code> will
tell you about the syntax contexts.</p>
<p><code>rustc</code> provides two syntax extensions that help with macro debugging. For now,
they are unstable and require feature gates.</p>
<ul>
<li>
<p><code>log_syntax!(...)</code> will print its arguments to standard output, at compile
time, and &quot;expand&quot; to nothing.</p>
</li>
<li>
<p><code>trace_macros!(true)</code> will enable a compiler message every time a macro is
expanded. Use <code>trace_macros!(false)</code> later in expansion to turn it off.</p>
</li>
</ul>
<h1>Syntactic requirements</h1>
<p>Even when Rust code contains un-expanded macros, it can be parsed as a full
<a href="glossary.html#abstract-syntax-tree">syntax tree</a>. This property can be very useful for editors and other
tools that process code. It also has a few consequences for the design of
Rust’s macro system.</p>
<p>One consequence is that Rust must determine, when it parses a macro invocation,
whether the macro stands in for</p>
<ul>
<li>zero or more items,</li>
<li>zero or more methods,</li>
<li>an expression,</li>
<li>a statement, or</li>
<li>a pattern.</li>
</ul>
<p>A macro invocation within a block could stand for some items, or for an
expression / statement. Rust uses a simple rule to resolve this ambiguity. A
macro invocation that stands for items must be either</p>
<ul>
<li>delimited by curly braces, e.g. <code>foo! { ... }</code>, or</li>
<li>terminated by a semicolon, e.g. <code>foo!(...);</code></li>
</ul>
<p>Another consequence of pre-expansion parsing is that the macro invocation must
consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces
must be balanced within a macro invocation. For example, <code>foo!([)</code> is
forbidden. This allows Rust to know where the macro invocation ends.</p>
<p>More formally, the macro invocation body must be a sequence of ‘token trees’.
A token tree is defined recursively as either</p>
<ul>
<li>a sequence of token trees surrounded by matching <code>()</code>, <code>[]</code>, or <code>{}</code>, or</li>
<li>any other single token.</li>
</ul>
<p>Within a matcher, each metavariable has a ‘fragment specifier’, identifying
which syntactic form it matches.</p>
<ul>
<li><code>ident</code>: an identifier. Examples: <code>x</code>; <code>foo</code>.</li>
<li><code>path</code>: a qualified name. Example: <code>T::SpecialA</code>.</li>
<li><code>expr</code>: an expression. Examples: <code>2 + 2</code>; <code>if true { 1 } else { 2 }</code>; <code>f(42)</code>.</li>
<li><code>ty</code>: a type. Examples: <code>i32</code>; <code>Vec&lt;(char, String)&gt;</code>; <code>&amp;T</code>.</li>
<li><code>pat</code>: a pattern. Examples: <code>Some(t)</code>; <code>(17, 'a')</code>; <code>_</code>.</li>
<li><code>stmt</code>: a single statement. Example: <code>let x = 3</code>.</li>
<li><code>block</code>: a brace-delimited sequence of statements. Example:
<code>{ log(error, &quot;hi&quot;); return 12; }</code>.</li>
<li><code>item</code>: an <a href="../reference.html#items">item</a>. Examples: <code>fn foo() { }</code>; <code>struct Bar;</code>.</li>
<li><code>meta</code>: a &quot;meta item&quot;, as found in attributes. Example: <code>cfg(target_os = &quot;windows&quot;)</code>.</li>
<li><code>tt</code>: a single token tree.</li>
</ul>
<p>There are additional rules regarding the next token after a metavariable:</p>
<ul>
<li><code>expr</code> variables may only be followed by one of: <code>=&gt; , ;</code></li>
<li><code>ty</code> and <code>path</code> variables may only be followed by one of: <code>=&gt; , : = &gt; as</code></li>
<li><code>pat</code> variables may only be followed by one of: <code>=&gt; , = if in</code></li>
<li>Other variables may be followed by any token.</li>
</ul>
<p>These rules provide some flexibility for Rust’s syntax to evolve without
breaking existing macros.</p>
<p>The macro system does not deal with parse ambiguity at all. For example, the
grammar <code>$($t:ty)* $e:expr</code> will always fail to parse, because the parser would
be forced to choose between parsing <code>$t</code> and parsing <code>$e</code>. Changing the
invocation syntax to put a distinctive token in front can solve the problem. In
this case, you can write <code>$(T $t:ty)* E $e:exp</code>.</p>
<h1>Scoping and macro import/export</h1>
<p>Macros are expanded at an early stage in compilation, before name resolution.
One downside is that scoping works differently for macros, compared to other
constructs in the language.</p>
<p>Definition and expansion of macros both happen in a single depth-first,
lexical-order traversal of a crate’s source. So a macro defined at module scope
is visible to any subsequent code in the same module, which includes the body
of any subsequent child <code>mod</code> items.</p>
<p>A macro defined within the body of a single <code>fn</code>, or anywhere else not at
module scope, is visible only within that item.</p>
<p>If a module has the <code>macro_use</code> attribute, its macros are also visible in its
parent module after the child’s <code>mod</code> item. If the parent also has <code>macro_use</code>
then the macros will be visible in the grandparent after the parent’s <code>mod</code>
item, and so forth.</p>
<p>The <code>macro_use</code> attribute can also appear on <code>extern crate</code>. In this context
it controls which macros are loaded from the external crate, e.g.</p>
<pre><code class="language-rust,ignore">#[macro_use(foo, bar)]
extern crate baz;
</code></pre>
<p>If the attribute is given simply as <code>#[macro_use]</code>, all macros are loaded. If
there is no <code>#[macro_use]</code> attribute then no macros are loaded. Only macros
defined with the <code>#[macro_export]</code> attribute may be loaded.</p>
<p>To load a crate’s macros without linking it into the output, use <code>#[no_link]</code>
as well.</p>
<p>An example:</p>
<pre><code class="language-rust">macro_rules! m1 { () =&gt; (()) }
// visible here: m1
mod foo {
// visible here: m1
#[macro_export]
macro_rules! m2 { () =&gt; (()) }
// visible here: m1, m2
}
// visible here: m1
macro_rules! m3 { () =&gt; (()) }
// visible here: m1, m3
#[macro_use]
mod bar {
// visible here: m1, m3
macro_rules! m4 { () =&gt; (()) }
// visible here: m1, m3, m4
}
// visible here: m1, m3, m4
# fn main() { }
</code></pre>
<p>When this library is loaded with <code>#[macro_use] extern crate</code>, only <code>m2</code> will
be imported.</p>
<p>The Rust Reference has a <a href="../reference.html#macro-related-attributes">listing of macro-related
attributes</a>.</p>
<h1>The variable <code>$crate</code></h1>
<p>A further difficulty occurs when a macro is used in multiple crates. Say that
<code>mylib</code> defines</p>
<pre><code class="language-rust">pub fn increment(x: u32) -&gt; u32 {
x + 1
}
#[macro_export]
macro_rules! inc_a {
($x:expr) =&gt; ( ::increment($x) )
}
#[macro_export]
macro_rules! inc_b {
($x:expr) =&gt; ( ::mylib::increment($x) )
}
# fn main() { }
</code></pre>
<p><code>inc_a</code> only works within <code>mylib</code>, while <code>inc_b</code> only works outside the
library. Furthermore, <code>inc_b</code> will break if the user imports <code>mylib</code> under
another name.</p>
<p>Rust does not (yet) have a hygiene system for crate references, but it does
provide a simple workaround for this problem. Within a macro imported from a
crate named <code>foo</code>, the special macro variable <code>$crate</code> will expand to <code>::foo</code>.
By contrast, when a macro is defined and then used in the same crate, <code>$crate</code>
will expand to nothing. This means we can write</p>
<pre><code class="language-rust">#[macro_export]
macro_rules! inc {
($x:expr) =&gt; ( $crate::increment($x) )
}
# fn main() { }
</code></pre>
<p>to define a single macro that works both inside and outside our library. The
function name will expand to either <code>::increment</code> or <code>::mylib::increment</code>.</p>
<p>To keep this system simple and correct, <code>#[macro_use] extern crate ...</code> may
only appear at the root of your crate, not inside <code>mod</code>. This ensures that
<code>$crate</code> is a single identifier.</p>
<h1>The deep end</h1>
<p>The introductory chapter mentioned recursive macros, but it did not give the
full story. Recursive macros are useful for another reason: Each recursive
invocation gives you another opportunity to pattern-match the macro’s
arguments.</p>
<p>As an extreme example, it is possible, though hardly advisable, to implement
the <a href="https://esolangs.org/wiki/Bitwise_Cyclic_Tag">Bitwise Cyclic Tag</a> automaton
within Rust’s macro system.</p>
<pre><code class="language-rust">macro_rules! bct {
// cmd 0: d ... =&gt; ...
(0, $($ps:tt),* ; $_d:tt)
=&gt; (bct!($($ps),*, 0 ; ));
(0, $($ps:tt),* ; $_d:tt, $($ds:tt),*)
=&gt; (bct!($($ps),*, 0 ; $($ds),*));
// cmd 1p: 1 ... =&gt; 1 ... p
(1, $p:tt, $($ps:tt),* ; 1)
=&gt; (bct!($($ps),*, 1, $p ; 1, $p));
(1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*)
=&gt; (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p));
// cmd 1p: 0 ... =&gt; 0 ...
(1, $p:tt, $($ps:tt),* ; $($ds:tt),*)
=&gt; (bct!($($ps),*, 1, $p ; $($ds),*));
// halt on empty data string
( $($ps:tt),* ; )
=&gt; (());
}
</code></pre>
<p>Exercise: use macros to reduce duplication in the above definition of the
<code>bct!</code> macro.</p>
<h1>Common macros</h1>
<p>Here are some common macros you’ll see in Rust code.</p>
<h2>panic!</h2>
<p>This macro causes the current thread to panic. You can give it a message
to panic with:</p>
<pre><code class="language-rust,no_run">panic!(&quot;oh no!&quot;);
</code></pre>
<h2>vec!</h2>
<p>The <code>vec!</code> macro is used throughout the book, so you’ve probably seen it
already. It creates <code>Vec&lt;T&gt;</code>s with ease:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3, 4, 5];
</code></pre>
<p>It also lets you make vectors with repeating values. For example, a hundred
zeroes:</p>
<pre><code class="language-rust">let v = vec![0; 100];
</code></pre>
<h2>assert! and assert_eq!</h2>
<p>These two macros are used in tests. <code>assert!</code> takes a boolean. <code>assert_eq!</code>
takes two values and checks them for equality. <code>true</code> passes, <code>false</code> <code>panic!</code>s.
Like this:</p>
<pre><code class="language-rust,no_run">// A-ok!
assert!(true);
assert_eq!(5, 3 + 2);
// nope :(
assert!(5 &lt; 3);
assert_eq!(5, 3);
</code></pre>
<h2>try!</h2>
<p><code>try!</code> is used for error handling. It takes something that can return a
<code>Result&lt;T, E&gt;</code>, and gives <code>T</code> if it’s a <code>Ok&lt;T&gt;</code>, and <code>return</code>s with the
<code>Err(E)</code> if it’s that. Like this:</p>
<pre><code class="language-rust,no_run">use std::fs::File;
fn foo() -&gt; std::io::Result&lt;()&gt; {
let f = try!(File::create(&quot;foo.txt&quot;));
Ok(())
}
</code></pre>
<p>This is cleaner than doing this:</p>
<pre><code class="language-rust,no_run">use std::fs::File;
fn foo() -&gt; std::io::Result&lt;()&gt; {
let f = File::create(&quot;foo.txt&quot;);
let f = match f {
Ok(t) =&gt; t,
Err(e) =&gt; return Err(e),
};
Ok(())
}
</code></pre>
<h2>unreachable!</h2>
<p>This macro is used when you think some code should never execute:</p>
<pre><code class="language-rust">if false {
unreachable!();
}
</code></pre>
<p>Sometimes, the compiler may make you have a different branch that you know
will never, ever run. In these cases, use this macro, so that if you end
up wrong, you’ll get a <code>panic!</code> about it.</p>
<pre><code class="language-rust">let x: Option&lt;i32&gt; = None;
match x {
Some(_) =&gt; unreachable!(),
None =&gt; println!(&quot;I know x is None!&quot;),
}
</code></pre>
<h2>unimplemented!</h2>
<p>The <code>unimplemented!</code> macro can be used when you’re trying to get your functions
to typecheck, and don’t want to worry about writing out the body of the
function. One example of this situation is implementing a trait with multiple
required methods, where you want to tackle one at a time. Define the others
as <code>unimplemented!</code> until you’re ready to write them.</p>
<h1>Procedural macros</h1>
<p>If Rust’s macro system can’t do what you need, you may want to write a
<a href="compiler-plugins.html">compiler plugin</a> instead. Compared to <code>macro_rules!</code>
macros, this is significantly more work, the interfaces are much less stable,
and bugs can be much harder to track down. In exchange you get the
flexibility of running arbitrary Rust code within the compiler. Syntax
extension plugins are sometimes called ‘procedural macros’ for this reason.</p>
<h1>Nightly Rust</h1>
</div>
<!-- Mobile navigation buttons -->
</div>
</div>
<!-- Local fallback for Font Awesome -->
<script>
if ($(".fa").css("font-family") !== "FontAwesome") {
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
}
</script>
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>