Files
book/print.html
T

9202 lines
472 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>The Rust Programming Language</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="favicon.png">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://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="https://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 class="light">
<!-- 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="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums</a></li><li><ul class="section"><li><a href="ch06-01-option.html"><strong>6.1.</strong> Option</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> Match</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-fundamental-collections.html"><strong>8.</strong> Fundamental Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generics</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Syntax</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Lifetime syntax</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><strong>12.</strong> I/O</li><li><ul class="section"><li><strong>12.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>12.2.</strong> <code>std::fs</code></li><li><strong>12.3.</strong> <code>std::path</code></li><li><strong>12.4.</strong> <code>std::env</code></li></ul></li><li><strong>13.</strong> Composition</li><li><ul class="section"><li><strong>13.1.</strong> Instead of Inheritance</li><li><strong>13.2.</strong> Trait Objects?</li></ul></li><li><strong>14.</strong> Creating a Library</li><li><ul class="section"><li><strong>14.1.</strong> Cargo</li><li><strong>14.2.</strong> Crates.io</li><li><a href="chYY-YY-public-api.html"><strong>14.3.</strong> Organizing your Public API</a></li><li><a href="chYY-YY-documentation.html"><strong>14.4.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>14.5.</strong> Workspaces and Multiple Related Crates</a></li></ul></li><li><strong>15.</strong> Closures</li><li><strong>16.</strong> Zero-cost Abstractions</li><li><ul class="section"><li><strong>16.1.</strong> Iterators as a Case Study</li></ul></li><li><strong>17.</strong> Smart Pointers</li><li><ul class="section"><li><strong>17.1.</strong> <code>Box&lt;T&gt;</code></li><li><strong>17.2.</strong> <code>Rc&lt;T&gt;</code></li><li><strong>17.3.</strong> <code>Cell</code></li><li><strong>17.4.</strong> <code>RefCell</code></li><li><strong>17.5.</strong> Interior Mutability</li></ul></li><li><a href="ch18-00-concurrency.html"><strong>18.</strong> Concurrency</a></li><li><ul class="section"><li><strong>18.1.</strong> Threads</li><li><strong>18.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>18.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>18.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>18.5.</strong> <code>Channels</code></li></ul></li><li><a href="chXX-patterns.html"><strong>19.</strong> Patterns</a></li><li><strong>20.</strong> More Lifetimes</li><li><strong>21.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>21.1.</strong> Raw Pointers</li><li><strong>21.2.</strong> <code>transmute</code></li></ul></li><li><strong>22.</strong> Foreign Function Interface</li><li><ul class="section"><li><strong>22.1.</strong> Conditional Compilation</li><li><strong>22.2.</strong> Bindings to C</li><li><strong>22.3.</strong> Using Rust from Other Languages</li><li><strong>22.4.</strong> <code>static</code></li></ul></li><li><strong>23.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>23.1.</strong> Associated Types</li><li><strong>23.2.</strong> Trait Objects</li><li><strong>23.3.</strong> UFCS</li><li><strong>23.4.</strong> Coherence</li></ul></li><li><strong>24.</strong> Macros</li><li><ul class="section"><li><strong>24.1.</strong> Writing Your Own Macros</li></ul></li><li><strong>25.</strong> Nightly Rust</li><li><ul class="section"><li><strong>25.1.</strong> Nightly Features</li><li><strong>25.2.</strong> How to Find Out About Nightly Features</li></ul></li><li><a href="appendix-00.html"><strong>26.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>26.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>26.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>26.3.</strong> Derivable Traits</a></li></ul></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">The Rust Programming Language</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, speed, and
concurrency. Its design lets you create programs that have the performance and
control of a low-level language, but with the powerful abstractions of a
high-level language. These properties make Rust suitable for programmers who
have experience in languages like C and are looking for a safer alternative, as
well as those from languages like Python who are looking for ways to write code
that performs better without sacrificing expressiveness.</p>
<p>Rust performs the majority of its safety checks and memory management decisions
at compile time, so that your program's runtime performance isn't impacted. This
makes it useful in a number of use cases that other languages aren’t good at:
programs with predictable space and time requirements, embedding in other
languages, and writing low-level code, like device drivers and operating
systems. It's also great for web applications: it powers the Rust package
registry site, crates.io! We're excited to see what <em>you</em> create with Rust.</p>
<p>This book is written for a reader who already knows how to program in at least
one programming language. After reading this book, you should be comfortable
writing Rust programs. We’ll be learning Rust through small, focused examples
that build on each other to demonstrate how to use various features of Rust as
well as how they work behind the scenes.</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>
<h2>Installation</h2>
<p>The first step to using Rust is to install it. 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>. You don't need to type in the <code>$</code> character; they are there to indicate
the start of each command. You’ll see many tutorials and examples around the web
that follow this convention: <code>$</code> for commands run as a regular user, and <code>#</code>
for commands you should be running as an administrator. Lines that don't start
with <code>$</code> are typically showing the output of the previous command.</p>
<h3>Installing on Linux or Mac</h3>
<p>If you're on Linux or a Mac, all you need to do is open a terminal and type
this:</p>
<pre><code class="language-text">$ curl https://sh.rustup.rs -sSf | sh
</code></pre>
<p>This will download a script and start the installation. You may be prompted for
your password. If it all goes well, you’ll see this appear:</p>
<pre><code class="language-text">Rust is installed now. Great!
</code></pre>
<h3>Installing on Windows</h3>
<p>On Windows, go to <a href="https://rustup.rs/">https://rustup.rs</a><!-- ignore --> and
follow the instructions to download rustup-init.exe. Run that and follow the
rest of the instructions it gives you.</p>
<p>The rest of the Windows-specific commands in the book will assume that you are
using <code>cmd</code> as your shell. If you use a different shell, you may be able to run
the same commands that Linux and Mac users do. If neither work, consult the
documentation for the shell you are using.</p>
<h3>Custom installations</h3>
<p>If you have reasons for preferring not to use rustup.rs, please see <a href="https://www.rust-lang.org/install.html">the Rust
installation page</a> for other options.</p>
<h3>Uninstalling</h3>
<p>Uninstalling Rust is as easy as installing it. From your shell, run
the uninstall script:</p>
<pre><code class="language-text">$ rustup self uninstall
</code></pre>
<h3>Troubleshooting</h3>
<p>If you've got Rust installed, you can open up a shell, and type this:</p>
<pre><code class="language-text">$ rustc --version
</code></pre>
<p>You should see the version number, commit hash, and commit date in a format
similar to this for the latest stable version at the time you install:</p>
<pre><code class="language-text">rustc x.y.z (abcabcabc yyyy-mm-dd)
</code></pre>
<p>If you see this, Rust has been installed successfully!
Congrats!</p>
<p>If you don't and you're on Windows, check that Rust is in your <code>%PATH%</code> system
variable.</p>
<p>If it still isn't working, there are a number of places where you can get help.
The easiest is <a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a><!-- ignore -->,
which you can access through <a href="http://chat.mibbit.com/?server=irc.mozilla.org&amp;channel=%23rust">Mibbit</a>. Go to that address, and you'll
be chatting with other Rustaceans (a silly nickname we call ourselves) who can
help you 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>
<h3>Local documentation</h3>
<p>The installer also includes a copy of the documentation locally, so you can
read it offline. Run <code>rustup doc</code> to open the local documentation in your
browser.</p>
<p>Any time there's a type or function provided by the standard library and you're
not sure what it does, use the API documentation to find out!</p>
<h2>Hello, World!</h2>
<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>
<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, feel free to use your
favorite IDE.</p>
</blockquote>
<h3>Creating a Project File</h3>
<p>First, make a file to put your Rust code in. Rust doesn't care where your code
lives, but for this book, we'd 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>
<p>Linux and Mac:</p>
<pre><code class="language-text">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<p>Windows:</p>
<pre><code class="language-cmd">&gt; mkdir %USERPROFILE%\projects
&gt; cd %USERPROFILE%\projects
&gt; mkdir hello_world
&gt; cd hello_world
</code></pre>
<h3>Writing and Running a Rust Program</h3>
<p>Next, make a new source file and call it <em>main.rs</em>. Rust files always end with
the <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>
<p><span class="filename">Filename: main.rs</span></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-text">$ rustc main.rs
$ ./main
Hello, world!
</code></pre>
<p>On 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>
<h3>Anatomy of a Rust Program</h3>
<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 first thing that is run for every executable 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>.</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 to notice here. The first is that Rust
style is to indent with four spaces, not a tab.</p>
<p>The second important part is <code>println!</code>. This is calling a Rust <em>macro</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 <code>!</code>). We'll discuss
Rust macros in more detail in Chapter 24, 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>). 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>
<h3>Compiling and Running Are Separate Steps</h3>
<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-text">$ 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-text">$ ls
main main.rs
</code></pre>
<p>On Windows, you'd enter:</p>
<pre><code class="language-cmd">&gt; dir /B %= the /B option says to only show the file names =%
main.exe
main.rs
</code></pre>
<p>This shows we have two files: the source code, with the <em>.rs</em> extension, and the
executable (<em>main.exe</em> on Windows, <em>main</em> everywhere else). All that's left to
do from here is run the <em>main</em> or <em>main.exe</em> file, like this:</p>
<pre><code class="language-text">$ ./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 having Rust
installed. If you give someone a <code>.rb</code>, <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, we'll
introduce you to a tool called Cargo, which will help you write real-world Rust
programs.</p>
<h2>Hello, Cargo!</h2>
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
manage their Rust projects because it makes a lot of tasks easier. For example,
Cargo takes care of building your code, downloading the libraries your code
depends on, and building those libraries. We call libraries your code needs
<em>dependencies</em>.</p>
<p>The simplest Rust programs, like the one we've written so far, don’t have any
dependencies, so right now, you'd only be using the part of Cargo that can take
care of building your code. 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 as covered in the Installation
chapter. If you installed Rust through some other means, you can check if you
have Cargo installed by typing the following into your terminal:</p>
<pre><code class="language-text">$ cargo --version
</code></pre>
<p>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 your method of
installation to determine how to install Cargo separately.</p>
<h3>Creating a Project with Cargo</h3>
<p>Let's create a new project using Cargo and look at how it differs from our
project in <code>hello_world</code>. Go back to your projects directory (or wherever you
decided to put your code):</p>
<p>Linux and Mac:</p>
<pre><code class="language-text">$ cd ~/projects
</code></pre>
<p>Windows:</p>
<pre><code class="language-cmd">&gt; cd %USERPROFILE%\projects
</code></pre>
<p>And then on any operating system run:</p>
<pre><code class="language-text">$ cargo new hello_cargo --bin
$ cd hello_cargo
</code></pre>
<p>We passed the <code>--bin</code> argument to <code>cargo new</code> because our goal is to make an
executable application, as opposed to a library. Executables are binary
executable files often called just <em>binaries</em>. We've given <code>hello_cargo</code>
as the name for our project, and Cargo creates its files in a directory
of the same name that we can then go into.</p>
<p>If we list the files in the <em>hello_cargo</em> directory, we can see that Cargo has
generated two files and one directory for us: a <em>Cargo.toml</em> and a <em>src</em>
directory with a <em>main.rs</em> file inside. It has also initialized a new git
repository in the <em>hello_cargo</em> directory for us, along with a <em>.gitignore</em>
file; you can change this to use a different version control system, or no
version control system, by using the <code>--vcs</code> flag.</p>
<p>Open up <em>Cargo.toml</em> in your text editor of choice. It should look something
like this:</p>
<p><span class="filename">Filename: Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = &quot;hello_cargo&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]
[dependencies]
</code></pre>
<p>This file is in the <a href="https://github.com/toml-lang/toml"><em>TOML</em></a><!-- ignore --> (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>The first line, <code>[package]</code>, is a section heading that indicates that the
following statements are configuring a package. As we add more information to
this file, we’ll add other sections.</p>
<p>The next three lines set the three bits of configuration that Cargo needs to
see in order to know that it should compile your program: its name, what
version it is, and who wrote it. Cargo gets your name and email information
from your environment. If it’s not correct, go ahead and fix that and save the
file.</p>
<p>The last line, <code>[dependencies]</code>, is the start of a section for you to list any
<em>crates</em> (which is what we call packages of Rust code) that your project will
depend on so that Cargo knows to download and compile those too. We won't need
any other crates for this project, but we will in the guessing game tutorial in
the next chapter.</p>
<p>Now let's look at <em>src/main.rs</em>:</p>
<p><span class="filename">Filename: src/main.rs</span></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, just like the one we wrote
earlier! So that part is the same. The differences between our previous project
and the project generated by Cargo that we've seen so far are:</p>
<ul>
<li>Our code goes in the <em>src</em> directory</li>
<li>The top level contains a <em>Cargo.toml</em> configuration file</li>
</ul>
<p>Cargo expects your source files to live inside the <em>src</em> directory so that the
top-level project directory is just for READMEs, license information,
configuration files, 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>If you started a project that doesn't use Cargo, as we did with our project in
the <em>hello_world</em> directory, you can convert it to a project that does use
Cargo by moving your code into the <em>src</em> directory and creating an appropriate
<em>Cargo.toml</em>.</p>
<h3>Building and Running a Cargo Project</h3>
<p>Now let's look at what's different about building and running your Hello World
program through Cargo! To do so, enter the following commands:</p>
<pre><code class="language-text">$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
</code></pre>
<p>This should have created an executable file in <em>target/debug/hello_cargo</em> (or
<em>target\debug\hello_cargo.exe</em> on Windows), which you can run with this command:</p>
<pre><code class="language-text">$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!
</code></pre>
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
<p>Running <code>cargo build</code> for the first time also causes Cargo to create a new file
at the top level called <em>Cargo.lock</em>, which looks like this:</p>
<p><span class="filename">Filename: Cargo.lock</span></p>
<pre><code class="language-toml">[root]
name = &quot;hello_cargo&quot;
version = &quot;0.1.0&quot;
</code></pre>
<p>Cargo uses the <em>Cargo.lock</em> to keep track of dependencies in your application.
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>We just built a project with <code>cargo build</code> and ran it with
<code>./target/debug/hello_cargo</code>, but we can also use <code>cargo run</code> to compile
and then run:</p>
<pre><code class="language-text">$ cargo run
Running `target/debug/hello_cargo`
Hello, world!
</code></pre>
<p>Notice that this time, we didn't see the output telling us that Cargo was
compiling <code>hello_cargo</code>. Cargo figured out that the files haven’t changed, so
it just ran the binary. If you had 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-text">$ cargo run
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Running `target/debug/hello_cargo`
Hello, world!
</code></pre>
<p>So a few more differences we've now seen:</p>
<ul>
<li>Instead of using <code>rustc</code>, build a project using <code>cargo build</code> (or build and
run it in one step with <code>cargo run</code>)</li>
<li>Instead of the result of the build being put in the same directory as our
code, Cargo will put it in the <em>target/debug</em> directory.</li>
</ul>
<p>The other advantage of using Cargo is that the commands are the same no matter
what operating system you're on, so at this point we will no longer be
providing specific instructions for Linux and Mac versus Windows.</p>
<h3>Building for Release</h3>
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. This will create an
executable in <em>target/release</em> instead of <em>target/debug</em>. 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 when you want to be able to rebuild quickly and often, and one for
building the final program you’ll give to a user that won't be rebuilt and
that we want to run as fast as possible. If you're benchmarking the running
time of your code, be sure to run <code>cargo build --release</code> and benchmark with
the executable in <em>target/release</em>.</p>
<h3>Cargo as Convention</h3>
<p>With simple projects, Cargo doesn't provide a whole lot of value over just
using <code>rustc</code>, but it will prove its worth as you continue. 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. Even though this 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 get
started with virtually all Rust projects you want to work
on with the following commands:</p>
<pre><code class="language-text">$ git clone someurl.com/someproject
$ cd someproject
$ cargo build
</code></pre>
<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>Guessing Game</h1>
<p>Let’s jump into Rust by working through a hands-on project together! This
chapter introduces you to a few common Rust concepts by showing you how to use
them in a real program. You’ll learn about <code>let</code>, <code>match</code>, methods, associated
functions, using external crates, and more! The following chapters will explore
these ideas in more detail. In this chapter, you’ll practice the fundamentals.</p>
<p>We’ll implement a classic beginner programming problem: a guessing game. Here’s
how it works: the program will generate a random integer between 1 and 100. It
will then prompt the player to enter a guess. After entering a guess, it will
indicate whether the guess is too low or too high. If the guess is correct, the
game will print congratulations and exit.</p>
<h2>Setting Up a New Project</h2>
<p>To set up a new project, go to the <em>projects</em> directory that you created in
Chapter 1, and make a new project using Cargo, like so:</p>
<pre><code class="language-text">$ cargo new guessing_game --bin
$ cd guessing_game
</code></pre>
<p>The first command, <code>cargo new</code>, takes the name of the project (<code>guessing_game</code>)
as the first argument. The <code>--bin</code> flag tells Cargo to make a binary project,
similar to the one in Chapter 1. The second command changes to the new
project’s directory.</p>
<p>Look at the generated <em>Cargo.toml</em> file:</p>
<p><span class="filename">Filename: Cargo.toml</span></p>
<pre><code class="language-toml">[package]
name = &quot;guessing_game&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]
[dependencies]
</code></pre>
<p>If the author information that Cargo obtained from your environment is not
correct, fix that in the file and save it again.</p>
<p>As you saw in Chapter 1, <code>cargo new</code> generates a “Hello, world!” program for
you. Check out the <em>src/main.rs</em> file:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Now let’s compile this “Hello, world!” program and run it in the same step
using the <code>cargo run</code> command:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/debug/guessing_game`
Hello, world!
</code></pre>
<p>The <code>run</code> command comes in handy when you need to rapidly iterate on a project,
and this game is such a project: we want to quickly test each iteration
before moving on to the next one.</p>
<p>Reopen the <em>src/main.rs</em> file. You’ll be writing all the code in this file.</p>
<h2>Processing a Guess</h2>
<p>The first part of the program will ask for user input, process that input, and
check that the input is in the expected form. To start, we’ll allow the player
to input a guess. Enter the code in Listing 2-1 into <em>src/main.rs</em>.</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">use std::io;
fn main() {
println!(&quot;Guess the number!&quot;);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
println!(&quot;You guessed: {}&quot;, guess);
}
</code></pre>
<figcaption>
<p>Listing 2-1: Code to get a guess from the user and print it out</p>
</figcaption>
</figure>
<p>This code contains a lot of information, so let’s go over it bit by bit. To
obtain user input and then print the result as output, we need to import the
<code>io</code> (input/output) library from the standard library (which is known as <code>std</code>):</p>
<pre><code class="language-rust,ignore">use std::io;
</code></pre>
<p>By default, Rust imports only a few types into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
<em>prelude</em></a><!-- ignore -->. If a type you want to use isn’t in the
prelude, you have to import that type into your program explicitly with a <code>use</code>
statement. Using the <code>std::io</code> library provides you with a number of useful
<code>io</code>-related features, including the functionality to accept user input.</p>
<p>As you saw in Chapter 1, the <code>main</code> function is the entry point into the
program:</p>
<pre><code class="language-rust,ignore">fn main() {
</code></pre>
<p>The <code>fn</code> syntax declares a new function, the <code>()</code> indicate there are no
arguments, and <code>{</code> starts the body of the function.</p>
<p>As you also learned in Chapter 1, <code>println!</code> is a macro that prints a string to
the screen:</p>
<pre><code class="language-rust,ignore">println!(&quot;Guess the number!&quot;);
println!(&quot;Please input your guess.&quot;);
</code></pre>
<p>This code is just printing a prompt stating what the game is and requesting
input from the user.</p>
<h3>Storing Values with Variables</h3>
<p>Next, we’ll create a place to store the user input, like this:</p>
<pre><code class="language-rust,ignore">let mut guess = String::new();
</code></pre>
<p>Now the program is getting interesting! There’s a lot going on in this little
line. Notice that this is a <code>let</code> statement, which is used to create
<em>variables</em>. Here’s another example:</p>
<pre><code class="language-rust,ignore">let foo = bar;
</code></pre>
<p>This line will create a new variable named <code>foo</code> and bind it to the value
<code>bar</code>. In Rust, variables are immutable by default. The following example shows
how to use <code>mut</code> before the variable name to make a variable mutable:</p>
<pre><code class="language-rust">let foo = 5; // immutable
let mut bar = 5; // mutable
</code></pre>
<blockquote>
<p>Note: The <code>//</code> syntax starts a comment that continues until the end of the
line. Rust ignores everything in comments.</p>
</blockquote>
<p>Now you know that <code>let mut guess</code> will introduce a mutable variable named
<code>guess</code>. On the other side of the equal sign (<code>=</code>) is the value that <code>guess</code> is
bound to, which is the result of calling <code>String::new</code>, a function that returns
a new instance of a <code>String</code>. <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a string
type provided by the standard library that is a growable, UTF-8 encoded bit of
text.</p>
<p>The <code>::</code> syntax in the <code>::new</code> line indicates that <code>new</code> is an <em>associated
function</em> of the <code>String</code> type. An associated function is implemented on a type,
in this case <code>String</code>, rather than on a particular instance of a <code>String</code>. Some
languages call this a <em>static method</em>.</p>
<p>This <code>new</code> function creates a new, empty <code>String</code>. You’ll find a <code>new</code> function
on many types, because it’s a common name for a function that makes a new value
of some kind.</p>
<p>To summarize, the <code>let mut guess = String::new();</code> line has created a mutable
variable that is currently bound to a new, empty instance of a <code>String</code>. Whew!</p>
<p>Recall that we included the input/output functionality from the standard
library with <code>use std::io;</code> on the first line of the program. Now we’ll call an
associated function, <code>stdin</code>, on <code>io</code>:</p>
<pre><code class="language-rust,ignore">io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
</code></pre>
<p>If we didn’t have the <code>use std::io</code> line at the beginning of the program, we
could have written this function call as <code>std::io::stdin</code>. The <code>stdin</code> function
returns an instance of <a href="../std/io/struct.Stdin.html"><code>std::io::Stdin</code></a><!-- ignore -->, which is a
type that represents a handle to the standard input for your terminal.</p>
<p>The next part of the code, <code>.read_line(&amp;mut guess)</code>, calls the
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle to
get input from the user. We’re also passing one argument to <code>read_line</code>: <code>&amp;mut guess</code>.</p>
<p>The job of <code>read_line</code> is to take whatever the user types into standard input
and place that into a string, so it takes that string as an argument. The
string argument needs to be mutable so the method can change the string’s
content by adding the user input.</p>
<p>The <code>&amp;</code> indicates that this argument is a <em>reference</em>, which gives you a way to
let multiple parts of your code access one piece of data without needing to
copy that data into memory multiple times. References are a complex feature,
and one of Rust’s major advantages is how safe and easy it is to use
references. You don’t need to know a lot of those details to finish this
program: Chapter 4 will explain references more thoroughly. For now, all you
need to know is that like variables, references are immutable by default.
Hence, we need to write <code>&amp;mut guess</code> rather than <code>&amp;guess</code> to make it mutable.</p>
<p>We’re not quite done with this line of code. Although it’s a single line of
text, it’s only the first part of the single logical line of code. The second
part is this method:</p>
<pre><code class="language-rust,ignore">.expect(&quot;Failed to read line&quot;);
</code></pre>
<p>When you call a method with the <code>.foo()</code> syntax, it’s often wise to introduce a
newline and other whitespace to help break up long lines. We could have
written this code as:</p>
<pre><code class="language-rust,ignore">io::stdin().read_line(&amp;mut guess).expect(&quot;Failed to read line&quot;);
</code></pre>
<p>However, one long line is difficult to read, so it’s best to divide it, two
lines for two method calls. Now let’s discuss what this line does.</p>
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
<p>As mentioned earlier, <code>read_line</code> puts what the user types into the string we’re
passing it, but it also returns a value—in this case, an
<a href="../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore --> as
well as specific versions for submodules, such as <code>io::Result</code>.</p>
<p>The <code>Result</code> types are <a href="ch06-00-enums.html"><em>enumerations</em></a><!-- ignore -->, often referred
to as <em>enums</em>. An enumeration is a type that can have a fixed set of values,
and those values are called the enum’s <em>variants</em>. Chapter 6 will cover enums
in more detail.</p>
<p>For <code>Result</code>, the variants are <code>Ok</code> or <code>Err</code>. <code>Ok</code> indicates the operation was
successful, and inside the <code>Ok</code> variant is the successfully generated value.
<code>Err</code> means the operation failed, and <code>Err</code> contains information about how or
why the operation failed.</p>
<p>The purpose of these <code>Result</code> types is to encode error handling information.
Values of the <code>Result</code> type, like any type, have methods defined on them. An
instance of <code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that
you can call. If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will
cause the program to crash and display the message that you passed as an
argument to <code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would
likely be the result of an error coming from the underlying operating system.
If this instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the
return value that <code>Ok</code> is holding and return just that value to you so you
could use it. In this case, that value is the number of characters the user
entered into standard input.</p>
<p>If we don’t call <code>expect</code>, the program will compile, but we’ll get a warning:</p>
<pre><code class="language-text">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
src/main.rs:10:5: 10:39 warning: unused result which must be used,
#[warn(unused_must_use)] on by default
src/main.rs:10 io::stdin().read_line(&amp;mut guess);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Rust warns that we haven’t used the <code>Result</code> value returned from <code>read_line</code>,
indicating that the program hasn’t handled a possible error. The right way to
suppress the warning is to actually write error handling, but since we just
want to crash this program when a problem occurs, we can use <code>expect</code>. You’ll
learn about recovering from errors in Chapter 9.</p>
<h3>Printing Values with <code>println!</code> Placeholders</h3>
<p>Aside from the closing curly brace, there’s only one more line to discuss in
the code added so far, which is the following:</p>
<pre><code class="language-rust,ignore">println!(&quot;You guessed: {}&quot;, guess);
</code></pre>
<p>This line prints out the string we saved the user’s input in. The set of <code>{}</code>
is a placeholder that holds a value in place. You can print more than one value
using <code>{}</code>: the first set of <code>{}</code> holds the first value listed after the format
string, the second set holds the second value, and so on. Printing out multiple
values in one call to <code>println!</code> would look like this:</p>
<pre><code class="language-rust">let x = 5;
let y = 10;
println!(&quot;x = {} and y = {}&quot;, x, y);
</code></pre>
<p>This code would print out <code>x = 5 and y = 10</code>.</p>
<h3>Testing the First Part</h3>
<p>Let’s test the first part of the guessing game. You can run it using <code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/debug/guessing_game`
Guess the number!
Please input your guess.
6
You guessed: 6
</code></pre>
<p>At this point, the first part of the game is done: we’re getting input from the
keyboard and then printing it.</p>
<h2>Generating a Secret Number</h2>
<p>Next, we need to generate a secret number that the user will try to guess. The
secret number should be different every time so the game is fun to play more
than once. Let’s use a random number between 1 and 100 so the game isn’t too
difficult. Rust doesn’t yet include random number functionality in its standard
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
<h3>Using a Crate to Get More Functionality</h3>
<p>Remember that a <em>crate</em> is a package of Rust code. The project we’ve been
building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is a
<em>library crate</em>, which contains code intended to be used in other programs.</p>
<p>Cargo’s use of external crates is where it really shines. Before we can write
code that uses <code>rand</code>, we need to modify the <em>Cargo.toml</em> file to include the
<code>rand</code> crate as a dependency. Open that file now and add the following line to
the bottom beneath the <code>[dependencies]</code> section header that Cargo created for
you:</p>
<p><span class="filename">Filename: Cargo.toml</span></p>
<pre><code class="language-toml">[dependencies]
rand = &quot;0.3.14&quot;
</code></pre>
<p>In the <em>Cargo.toml</em> file, everything that follows a header is part of a section
that continues until another section starts. The <code>[dependencies]</code> section is
where you tell Cargo which external crates your project depends on and which
versions of those crates you require. In this case, we’ll specify the <code>rand</code>
crate with the semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
Versioning</a><!-- ignore --> (sometimes called <em>SemVer</em>), which is a
standard for writing version numbers. The number <code>0.3.14</code> is actually shorthand
for <code>^0.3.14</code>, which means “any version that has a public API compatible with
version 0.3.14.”</p>
<p>Now, without changing any of the code, let’s build the project, as shown in
Listing 2-2:</p>
<figure>
<pre><code class="language-text">$ cargo build
Updating registry `https://github.com/rust-lang/crates.io-index`
Downloading rand v0.3.14
Downloading libc v0.2.14
Compiling libc v0.2.14
Compiling rand v0.3.14
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
</code></pre>
<figcaption>
<p>Listing 2-2: The output from running <code>cargo build</code> after adding the rand crate
as a dependency</p>
</figcaption>
</figure>
<p>You may see different version numbers (but they will all be compatible with
the code, thanks to SemVer!), and the lines may be in a different order.</p>
<p>Now that we have an external dependency, Cargo fetches the latest versions of
everything from the <em>registry</em>, which is a copy of data from
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem post
their open source Rust projects for others to use.</p>
<p>After updating the registry, Cargo checks the <code>[dependencies]</code> section and
downloads any you don’t have yet. In this case, although we only listed <code>rand</code>
as a dependency, Cargo also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
<code>libc</code> to work. After downloading them, Rust compiles them and then compiles
the project with the dependencies available.</p>
<p>If you immediately run <code>cargo build</code> again without making any changes, you won’t
get any output. Cargo knows it has already downloaded and compiled the
dependencies, and you haven't changed anything about them in your <em>Cargo.toml</em>
file. Cargo also knows that you haven't changed anything about your code, so it
doesn't recompile that either. With nothing to do, it simply exits. If you open
up the <em>src/main.rs</em> file, make a trivial change, then save it and build again,
you’ll only see one line of output:</p>
<pre><code class="language-text">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
</code></pre>
<p>This line shows Cargo only updates the build with your tiny change to the
<em>src/main.rs</em> file. Your dependencies haven't changed, so Cargo knows it can
reuse what it has already downloaded and compiled for those. It just rebuilds
your part of the code.</p>
<h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4>
<p>Cargo has a mechanism that ensures you can rebuild the same artifact every time
you or anyone else builds your code: Cargo will use only the versions of the
dependencies you specified until you indicate otherwise. For example, what
happens if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out and
contains an important bug fix but also contains a regression that will break
your code?</p>
<p>The answer to this problem is the <em>Cargo.lock</em> file, which was created the
first time you ran <code>cargo build</code> and is now in your <em>guessing_game</em> directory.
When you build a project for the first time, Cargo figures out all the
versions of the dependencies that fit the criteria and then writes them to
the <em>Cargo.lock</em> file. When you build your project in the future, Cargo will
see that the <em>Cargo.lock</em> file exists and use the versions specified there
rather than doing all the work of figuring out versions again. This lets you
have a reproducible build automatically. In other words, your project will
remain at <code>0.3.14</code> until you explicitly upgrade, thanks to the <em>Cargo.lock</em>
file.</p>
<h4>Updating a Crate to Get a New Version</h4>
<p>When you <em>do</em> want to update a crate, Cargo provides another command, <code>update</code>,
which will:</p>
<ol>
<li>Ignore the <em>Cargo.lock</em> file and figure out all the latest versions that fit
your specifications in <em>Cargo.toml</em>.</li>
<li>If that works, Cargo will write those versions to the <em>Cargo.lock</em> file.</li>
</ol>
<p>But by default, Cargo will only look for versions larger than <code>0.3.0</code> and
smaller than <code>0.4.0</code>. If the <code>rand</code> crate has released two new versions,
<code>0.3.15</code> and <code>0.4.0</code>, you would see the following if you ran <code>cargo update</code>:</p>
<pre><code class="language-text">$ cargo update
Updating registry `https://github.com/rust-lang/crates.io-index`
Updating rand v0.3.14 -&gt; v0.3.15
</code></pre>
<p>At this point, you would also notice a change in your <em>Cargo.lock</em> file noting
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</p>
<p>If you wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
series, you’d have to update the <em>Cargo.toml</em> file to look like this instead:</p>
<pre><code class="language-toml">[dependencies]
rand = &quot;0.4.0&quot;
</code></pre>
<p>The next time you run <code>cargo build</code>, Cargo will update the registry of crates
available and reevaluate your <code>rand</code> requirements according to the new version
you specified.</p>
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a><!-- ignore --> and <a href="http://doc.crates.io/crates-io.html">its
ecosystem</a><!-- ignore --> that Chapter 14 will discuss, but for
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
so Rustaceans are able to write smaller projects that are assembled from a
number of packages.</p>
<h3>Generating a Random Number</h3>
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <em>src/main.rs</em>, as shown
in Listing 2-3:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
println!(&quot;You guessed: {}&quot;, guess);
}
</code></pre>
<figcaption>
<p>Listing 2-3: Code changes needed in order to generate a random number</p>
</figcaption>
</figure>
<p>We’re adding a <code>extern crate rand;</code> line to the top that lets Rust know we’ll be
using that external dependency. This also does the equivalent of calling <code>use rand</code>, so now we can call anything in the <code>rand</code> crate by prefixing it with
<code>rand::</code>.</p>
<p>Next, we’re adding another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
defines methods that random number generators implement, and this trait must be
in scope for us to use those methods. Chapter 10 will cover traits in detail.</p>
<p>Also, we’re adding two more lines in the middle. The <code>rand::thread_rng</code> function
will give us the particular random number generator that we’re going to use:
one that is local to the current thread of execution and seeded by the
operating system. Next, we call the <code>gen_range</code> method on the random number
generator. This method is defined by the <code>Rng</code> trait that we brought into
scope with the <code>use rand::Rng</code> statement. The <code>gen_range</code> method takes two
numbers as arguments and generates a random number between them. It’s inclusive
on the lower bound but exclusive on the upper bound, so we need to specify <code>1</code>
and <code>101</code> to request a number between 1 and 100.</p>
<p>Knowing which traits to import and which functions and methods to use from a
crate isn’t something that you’ll just <em>know</em>. Instructions for using a crate
are in each crate’s documentation. Another neat feature of Cargo is that you
can run the <code>cargo doc --open</code> command that will build documentation provided
by all of your dependencies locally and open it in your browser. If you’re
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> and click <code>rand</code> in the sidebar on the left.</p>
<p>The second line that we added to the code prints the secret number. This is
useful while we’re developing the program to be able to test it, but we’ll
delete it from the final version. It’s not much of a game if the program prints
the answer as soon as it starts!</p>
<p>Try running the program a few times:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 7
Please input your guess.
4
You guessed: 4
$ cargo run
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 83
Please input your guess.
5
You guessed: 5
</code></pre>
<p>You should get different random numbers, and they should all be numbers between
1 and 100. Great job!</p>
<h2>Comparing the Guess to the Secret Number</h2>
<p>Now that we have user input and a random number, we can compare them. That
step is shown in Listing 2-4:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
}
</code></pre>
<figcaption>
<p>Listing 2-4: Handling the possible return values of comparing two numbers</p>
</figcaption>
</figure>
<p>The first new bit here is another <code>use</code>, bringing a type called
<code>std::cmp::Ordering</code> into scope from the standard library. <code>Ordering</code> is
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
<code>Greater</code>, and <code>Equal</code>. These are the three outcomes that are possible when you
compare two values.</p>
<p>Then we add five new lines at the bottom that use the <code>Ordering</code> type:</p>
<pre><code class="language-rust,ignore">match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
</code></pre>
<p>The <code>cmp</code> method compares two values and can be called on anything that can be
compared. It takes a reference to whatever you want to compare with: here it’s
comparing the <code>guess</code> to the <code>secret_number</code>. <code>cmp</code> returns a variant of the
<code>Ordering</code> enum we imported with the <code>use</code> statement. We use a
<a href="ch06-02-match.html"><code>match</code></a><!-- ignore --> expression to decide what to do next based on
which variant of <code>Ordering</code> was returned from the call to <code>cmp</code> with the values
in <code>guess</code> and <code>secret_number</code>.</p>
<p>A <code>match</code> expression is made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
the code that should be run if the value given to the beginning of the <code>match</code>
expression fits that arm’s pattern. Rust takes the value given to <code>match</code> and
looks through each arm’s pattern in turn. The <code>match</code> construct and patterns
are powerful features in Rust that let you express a variety of situations your
code might encounter and helps ensure that you handle them all. These features
will be covered in detail in Chapter 6 and Chapter 19, respectively.</p>
<p>Let’s walk through an example of what would happen with the <code>match</code> expression
used here. Say that the user has guessed 50, and the randomly generated secret
number this time is 38. When the code compares 50 to 38, the <code>cmp</code> method will
return <code>Ordering::Greater</code>, because 50 is greater than 38. <code>Ordering::Greater</code>
is the value that the <code>match</code> expression gets. It looks at the first arm’s
pattern, <code>Ordering::Less</code>, but the value <code>Ordering::Greater</code> does not match
<code>Ordering::Less</code>. So it ignores the code in that arm and moves to the next arm.
The next arm’s pattern, <code>Ordering::Greater</code>, <em>does</em> match
<code>Ordering::Greater</code>! The associated code in that arm will execute and print
<code>Too big!</code> to the screen. The <code>match</code> expression ends because it has no need to
look at the last arm in this particular scenario.</p>
<p>However, the code in Listing 2-4 won’t compile yet. Let’s try it:</p>
<pre><code class="language-text">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
error[E0308]: mismatched types
--&gt; src/main.rs:23:21
|
23 | match guess.cmp(&amp;secret_number) {
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integral variable
|
= note: expected type `&amp;std::string::String`
= note: found type `&amp;{integer}`
error: aborting due to previous error
Could not compile `guessing_game`.
</code></pre>
<p>The core of the error states that there are <em>mismatched types</em>. Rust has a
strong, static type system. However, it also has type inference. When we wrote
<code>let guess = String::new()</code>, Rust was able to infer that <code>guess</code> should be a
<code>String</code> and didn’t make us write the type. The <code>secret_number</code>, on the other
hand, is a number type. A few number types can have a value between 1 and 100:
<code>i32</code>, a 32-bit number; <code>u32</code>, an unsigned 32-bit number; <code>i64</code>, a 64-bit
number; as well as others. Rust defaults to an <code>i32</code>, which is the type of
<code>secret_number</code> unless we add type information elsewhere that would cause Rust
to infer a different numerical type. The reason for the error is that Rust will
not compare a string and a number type.</p>
<p>Ultimately, we want to convert the <code>String</code> the program reads as input into a
real number type so we can compare it to the guess numerically. We can do
that by adding the following two lines to the <code>main</code> function body:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
}
</code></pre>
<p>The two new lines are:</p>
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
</code></pre>
<p>We create a variable named <code>guess</code>. But wait, doesn’t the program
already have a variable named <code>guess</code>? It does, but Rust allows us to
<em>shadow</em> the previous value of <code>guess</code> with a new one. This feature is often
used in similar situations in which you want to convert a value from one type
to another type. Shadowing lets us reuse the <code>guess</code> variable name rather than
forcing us to create two unique variables, like <code>guess_str</code> and <code>guess</code> for
example. (Chapter 3 covers shadowing in more detail.)</p>
<p>We bind <code>guess</code> to the expression <code>guess.trim().parse()</code>. The <code>guess</code> in the
expression refers to the original <code>guess</code> that was a <code>String</code> with the input in
it. The <code>trim</code> method on a <code>String</code> instance will eliminate any whitespace at
the beginning and end. <code>u32</code> can only contain numerical characters, but the
user must press the Return key to satisfy <code>read_line</code>. When the user presses
Return, a newline character is added to the string. For example, if the user
types 5 and presses return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents
“newline,” the return key. The <code>trim</code> method eliminates <code>\n</code>, resulting in just
<code>5</code>.</p>
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into some
kind of number. Because this method can parse a variety of number types, we
need to tell Rust the exact number type we want by using <code>let guess: u32</code>. The
colon (<code>:</code>) after <code>guess</code> tells Rust we’ll annotate the variable’s type. Rust
has a few built-in number types; the <code>u32</code> seen here is an unsigned, 32-bit
integer. It’s a good default choice for a small positive number. You’ll learn
about other number types in Chapter 3. Additionally, the <code>u32</code> annotation in
this example program and the comparison with <code>secret_number</code> means that Rust
will infer that <code>secret_number</code> should be a <code>u32</code> as well. So now the
comparison will be between two values of the same type!</p>
<p>The call to <code>parse</code> could easily cause an error. If, for example, the string
contained <code>A👍%</code>, there would be no way to convert that to a number. Because it
might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
<code>read_line</code> method does as discussed earlier in “Handling Potential Failure
with the Result Type” on page XX. We’ll treat this <code>Result</code> the same way by
using the <code>expect</code> method again. If <code>parse</code> returns an <code>Err</code> <code>Result</code> variant
because it couldn’t create a number from the string, the <code>expect</code> call will
crash the game and print the message we give it. If <code>parse</code> can successfully
convert the string to a number, it will return the <code>Ok</code> variant of <code>Result</code>,
and <code>expect</code> will return the number that we want from the <code>Ok</code> value.</p>
<p>Let’s run the program now!</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 58
Please input your guess.
76
You guessed: 76
Too big!
</code></pre>
<p>Nice! Even though spaces were added before the guess, the program still figured
out that the user guessed 76. Run the program a few times to verify the
different behavior with different kinds of input: guess the number correctly,
guess a number that is too high, and guess a number that is too low.</p>
<p>We have most of the game working now, but the user can make only one guess.
Let’s change that by adding a loop!</p>
<h2>Allowing Multiple Guesses with Looping</h2>
<p>The <code>loop</code> keyword gives us an infinite loop. Add that now to give users more
chances at guessing the number:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
loop {
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
}
}
</code></pre>
<p>As you can see, we’ve moved everything into a loop from the guess input prompt
onward. Be sure to indent those lines another four spaces each, and run the
program again. Notice that there is a new problem because the program is doing
exactly what we told it to do: ask for another guess forever! It doesn’t seem
like the user can quit!</p>
<p>The user could always halt the program by using the keyboard shortcut <code>Ctrl-C</code>.
But there’s another way to escape this insatiable monster that we mentioned in
the <code>parse</code> discussion in “Comparing the Guesses” on page XX: if the user
enters a non-number answer, the program will crash. The user can take advantage
of that in order to quit, as shown here:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 59
Please input your guess.
45
You guessed: 45
Too small!
Please input your guess.
60
You guessed: 60
Too big!
Please input your guess.
59
You guessed: 59
You win!
Please input your guess.
quit
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
</code></pre>
<p>Typing <code>quit</code> actually quits the game, but so will any other non-number input.
However, this is suboptimal to say the least. We want the game to automatically
stop when the correct number is guessed.</p>
<h3>Quitting After a Correct Guess</h3>
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
loop {
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; {
println!(&quot;You win!&quot;);
break;
}
}
}
}
</code></pre>
<p>By adding the <code>break</code> line after <code>You win!</code>, the program will exit the loop
when the user guesses the secret number correctly. Exiting the loop also means
exiting the program, because the loop is the last part of <code>main</code>.</p>
<h3>Handling Invalid Input</h3>
<p>To further refine the game’s behavior, rather than crashing the program when
the user inputs a non-number, let’s make the game ignore a non-number so the
user can continue guessing. We can do that by altering the line where <code>guess</code> is
converted from a <code>String</code> to a <code>u32</code>:</p>
<pre><code class="language-rust,ignore">let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
</code></pre>
<p>Switching from an <code>expect</code> call to a <code>match</code> expression is how you generally
move from crash on error to actually handling the error. Remember that <code>parse</code>
returns a <code>Result</code> type, and <code>Result</code> is an enum that has the variants <code>Ok</code> or
<code>Err</code>. We’re using a <code>match</code> expression here, like we did with the <code>Ordering</code>
result of the <code>cmp</code> method.</p>
<p>If <code>parse</code> is able to successfully turn the string into a number, it will return
an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will match the
first arm’s pattern, and the <code>match</code> expression will just return the <code>num</code> value
that <code>parse</code> produced and put inside the <code>Ok</code> value. That number will end up
right where we want it in the new <code>guess</code> variable we’re creating.</p>
<p>If <code>parse</code> is <em>not</em> able to turn the string into a number, it will return an
<code>Err</code> value that contains more information about the error. The <code>Err</code> value
does not match the <code>Ok(num)</code> pattern in the first <code>match</code> arm, but it does match
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catchall value; in this
example, we’re saying we want to match all <code>Err</code> values, no matter what
information they have inside them. So the program will execute the second arm’s
code, <code>continue</code>, which means to go to the next iteration of the <code>loop</code> and ask
for another guess. So effectively, the program ignores all errors that <code>parse</code>
might encounter!</p>
<p>Now everything in the program should work as expected. Let’s try it by running
<code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/guessing_game`
Guess the number!
The secret number is: 61
Please input your guess.
10
You guessed: 10
Too small!
Please input your guess.
99
You guessed: 99
Too big!
Please input your guess.
foo
Please input your guess.
61
You guessed: 61
You win!
</code></pre>
<p>Awesome! With one tiny final tweak, we will finish the guessing game: recall
that the program is still printing out the secret number. That worked well for
testing, but it ruins the game. Let’s delete the <code>println!</code> that outputs the
secret number. Listing 2-5 shows the final code:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; {
println!(&quot;You win!&quot;);
break;
}
}
}
}
</code></pre>
<figcaption>
<p>Listing 2-5: Complete code of the guessing game</p>
</figcaption>
</figure>
<h2>Summary</h2>
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
<p>This project was a hands-on way to introduce you to many new Rust concepts:
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
In the next few chapters, you’ll learn about these concepts in more detail.
Chapter 3 covers concepts that most programming languages have, such as
variables, data types, and functions, and shows how to use them in Rust.
Chapter 4 explores ownership, which is a Rust feature that is most different
from other languages. Chapter 5 discusses structs and method syntax, and
Chapter 6 endeavors to explain enums.</p>
<h1>Common Programming Concepts</h1>
<p>This chapter covers concepts that appear in almost every programming language
and how they work in Rust. Many programming languages have much in common at
their core. None of the concepts presented in this chapter are unique to Rust,
but we’ll discuss them in the context of Rust and explain their conventions.</p>
<p>Specifically, you’ll learn about variables, basic types, functions, comments,
and control flow. These foundations will be in every Rust program, and learning
them early will give you a strong core to start from.</p>
<!-- PROD: START BOX -->
<blockquote>
<h3>Keywords</h3>
<p>The Rust language has a set of <em>keywords</em> that have been reserved for use by
the language only, much like other languages do. Keep in mind that you cannot
use these words as names of variables or functions. Most of the keywords have
special meanings, and you’ll be using them to do various tasks in your Rust
programs; a few have no current functionality associated with them but have
been reserved for functionality that might be added to Rust in the future. You
can find a list of the keywords in Appendix A.</p>
</blockquote>
<!-- PROD: END BOX -->
<h2>Variables and Mutability</h2>
<p>As mentioned in Chapter 2, by default variables are <em>immutable</em>. This is one of
many nudges in Rust that encourages you to write your code in a way that takes
advantage of the safety and easy concurrency that Rust offers. However, you
still have the option to make your variables mutable. Let’s explore how and why
Rust encourages you to favor immutability, and why you might want to opt out.</p>
<p>When a variable is immutable, that means mean once a value is bound to a name,
you can’t change that value. To illustrate, let’s generate a new project called
<em>variables</em> in your <em>projects</em> directory by using <code>cargo new --bin variables</code>.</p>
<p>Then, in your new <em>variables</em> directory, open <em>src/main.rs</em> and replace its
code with the following:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let 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>Save and run the program using <code>cargo run</code>. You should receive an error
message, as shown in this output:</p>
<pre><code class="language-text">$ cargo run
Compiling variables v0.0.1 (file:///projects/variables)
error[E0384]: re-assignment of immutable variable `x`
--&gt; src/main.rs:4:5
|
2 | let x = 5;
| - first assignment to `x`
3 | println!(&quot;The value of x is: {}&quot;, x);
4 | x = 6;
| ^^^^^ re-assignment of immutable variable
</code></pre>
<p>This example shows how the compiler helps you find errors in your programs.
Even though compiler errors can be frustrating, they only mean your program
isn’t safely doing what you want it to do yet; they do <em>not</em> mean that you’re
not a good programmer! Experienced Rustaceans still get compiler errors. The
error indicates that the cause of the error is <code>re-assignment of immutable variable</code>, because we tried to assign a second value to the immutable <code>x</code>
variable.</p>
<p>It’s important that we get compile-time errors when we attempt to change a
value that we previously designated as immutable because this very situation
can lead to bugs. If one part of our code operates on the assumption that a
value will never change and another part of our code changes that value, it’s
possible that the first part of the code won’t do what it was designed to do.
This cause of bugs can be difficult to track down after the fact, especially
when the second piece of code changes the value only <em>sometimes</em>.</p>
<p>In Rust the compiler guarantees that when we state that a value won’t change,
it really won’t change. That means that when you’re reading and writing code,
you don’t have to keep track of how and where a value might change, which can
make code easier to reason about.</p>
<p>But mutability can be very useful. Variables are immutable only by default; we
can make them mutable by adding <code>mut</code> in front of the variable name. In
addition to allowing this value to change, it conveys intent to future readers
of the code by indicating that other parts of the code will be changing this
variable value.</p>
<p>For example, change <em>src/main.rs</em> to the following:</p>
<p><span class="filename">Filename: src/main.rs</span></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>When we run this program, we get the following:</p>
<pre><code class="language-text">$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
</code></pre>
<p>Using <code>mut</code>, we’re allowed to change the value that <code>x</code> binds to from <code>5</code> to
<code>6</code>. In some cases, you’ll want to make a variable mutable because it makes the
code more convenient to write than an implementation that only uses immutable
variables.</p>
<p>There are multiple trade-offs to consider, in addition to the prevention of
bugs. For example, in cases where you’re using large data structures, mutating
an instance in place may be faster than copying and returning newly allocated
instances. With smaller data structures, always creating new instances and
writing in a more functional programming style may be easier to reason about,
so the lower performance penalty might be worth it to gain that clarity.</p>
<h3>Differences Between Variables and Constants</h3>
<p>Not being able to change the value of a variable might have reminded you of
another programming concept that most languages have: <em>constants</em>. Constants
are also values bound to a name that are not allowed to change, but there are a
few differences between constants and variables. First, using <code>mut</code> with
constants is not allowed: constants aren't only immutable by default, they're
always immutable. Constants are declared using the <code>const</code> keyword instead of
the <code>let</code> keyword, and the type of the value <em>must</em> be annotated. We're about
to cover types and type annotations in the next section, “Data Types,” so don't
worry about the details right now. Constants can be declared in any scope,
including the global scope, which makes them useful for a value that many parts
of your code need to know about. The last difference is that constants may only
be set to a constant expression, not the result of a function call or any other
value that could only be used at runtime.</p>
<p>Here's an example of a constant declaration where the constant's name is
<code>MAX_POINTS</code> and its value is set to 100,000. Rust constant naming convention
is to use all upper case with underscores between words:</p>
<pre><code>const MAX_POINTS: u32 = 100_000;
</code></pre>
<p>Constants are valid for the entire lifetime of a program, within the scope they
were declared in. That makes constants useful for values in your application
domain that multiple part of the program might need to know about, such as the
maximum number of points any player of a game is allowed to earn or the number
of seconds in a year.</p>
<p>Documenting hardcoded values used throughout your program by naming them as
constants is useful to convey the meaning of that value to future maintainers
of the code. It also helps to have only one place in your code that you would
need to change if the hardcoded value needed to be updated in the future.</p>
<h3>Shadowing</h3>
<p>As we saw in the guessing game tutorial in Chapter 2, we can declare new
variables with the same name as a previous variables, and the new variable
<em>shadows</em> the previous variable. Rustaceans say that the first variable is
<em>shadowed</em> by the second, which means that the second variable’s value is what
we’ll see when we use the variable. We can shadow a variable by using the same
variable’s name and repeating the use of the <code>let</code> keyword as follows:</p>
<p><span class="filename">Filename: src/main.rs</span></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 program first binds <code>x</code> to a value of <code>5</code>. Then it shadows <code>x</code> by
repeating <code>let x =</code>, taking the original value and adding <code>1</code> so the value of
<code>x</code> is then <code>6</code>. The third <code>let</code> statement also shadows <code>x</code>, taking the
previous value and multiplying it by <code>2</code> to give <code>x</code> a final value of <code>12</code>.
When you run this program, it will output the following:</p>
<pre><code class="language-text">$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Running `target/debug/variables`
The value of x is: 12
</code></pre>
<p>This is different than marking a variable as <code>mut</code>, because unless we use the
<code>let</code> keyword again, we’ll get a compile-time error if we accidentally try to
reassign to this variable. We can perform a few transformations on a value but
have the variable be immutable after those transformations have been completed.</p>
<p>The other difference between <code>mut</code> and shadowing is that because we’re
effectively creating a new variable when we use the <code>let</code> keyword again, we can
change the type of the value, but reuse the same name. For example, say our
program asks a user to show how many spaces they want between some text by
inputting space characters, but we really want to store that input as a number:</p>
<pre><code class="language-rust">let spaces = &quot; &quot;;
let spaces = spaces.len();
</code></pre>
<p>This construct is allowed because the first <code>spaces</code> variable is a string type,
and the second <code>spaces</code> variable, which is a brand-new variable that happens to
have the same name as the first one, is a number type. Shadowing thus spares us
from having to come up with different names, like <code>spaces_str</code> and
<code>spaces_num</code>; instead, we can reuse the simpler <code>spaces</code> name. However, if we
try to use <code>mut</code> for this, as shown here:</p>
<pre><code class="language-rust,ignore">let mut spaces = &quot; &quot;;
spaces = spaces.len();
</code></pre>
<p>we’ll get a compile-time error because we’re not allowed to mutate a variable’s
type:</p>
<pre><code class="language-text">error[E0308]: mismatched types
--&gt; src/main.rs:3:14
|
3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected &amp;str, found usize
|
= note: expected type `&amp;str`
= note: found type `usize`
</code></pre>
<p>Now that we’ve explored how variables work, let’s look at more data types they
can have.</p>
<h2>Data Types</h2>
<p>Every value in Rust is of a certain <em>type</em>, which tells Rust what kind of data
is being specified so it knows how to work with that data. In this section,
we’ll look at a number of types that are built into the language. We split the
types into two subsets: scalar and compound.</p>
<p>Throughout this section, keep in mind that Rust is a <em>statically typed</em>
language, which means that it must know the types of all variables at compile
time. The compiler can usually infer what type we want to use based on the
value and how we use it. In cases when many types are possible, such as when we
converted a <code>String</code> to a numeric type using <code>parse</code> in Chapter 2, we must add
a type annotation, like this:</p>
<pre><code class="language-rust">let guess: u32 = &quot;42&quot;.parse().unwrap();
</code></pre>
<p>If we don’t add the type annotation here, Rust will display the following
error, which means the compiler needs more information from us to know which
possible type we want to use:</p>
<pre><code class="language-text">error[E0282]: unable to infer enough type information about `_`
--&gt; src/main.rs:2:5
|
2 | let guess = &quot;42&quot;.parse().unwrap();
| ^^^^^ cannot infer type for `_`
|
= note: type annotations or generic parameter binding required
</code></pre>
<p>You’ll see different type annotations as we discuss the various data types.</p>
<h3>Scalar Types</h3>
<p>A <em>scalar</em> type represents a single value. Rust has four primary scalar types:
integers, floating-point numbers, booleans, and characters. You’ll likely
recognize these from other programming languages, but let’s jump into how they
work in Rust.</p>
<h4>Integer Types</h4>
<p>An <em>integer</em> is a number without a fractional component. We used one integer
type earlier in this chapter, the <code>i32</code> type. This type declaration indicates
that the value it’s associated with should be a signed integer (hence the <code>i</code>,
as opposed to a <code>u</code> for unsigned) for a 32-bit system. Table 3-1 shows the
built-in integer types in Rust. Each variant in the Signed and Unsigned columns
(for example, <em>i32</em>) can be used to declare the type of an integer value.</p>
<figure>
<figcaption>
<p>Table 3-1: Integer Types in Rust</p>
</figcaption>
<table><thead><tr><td> Length </td><td> Signed </td><td> Unsigned </td></tr></thead>
<tr><td> 8-bit </td><td> i8 </td><td> u8 </td></tr>
<tr><td> 16-bit </td><td> i16 </td><td> u16 </td></tr>
<tr><td> 32-bit </td><td> i32 </td><td> u32 </td></tr>
<tr><td> 64-bit </td><td> i64 </td><td> u64 </td></tr>
<tr><td> arch </td><td> isize </td><td> usize </td></tr>
</table>
</figure>
<p>Each variant can be either signed or unsigned and has an explicit size.
Signed and unsigned refers to whether it’s possible for the number to be
negative or positive; in other words, whether the number needs to have a sign
with it (signed) or whether it will only ever be positive and can therefore be
represented without a sign (unsigned). It’s like writing numbers on paper: when
the sign matters, a number is shown with a plus sign or a minus sign; however,
when it’s safe to assume the number is positive, it’s shown with no sign.
Signed numbers are stored using two’s complement representation (if you’re
unsure what this is, you can search for it online; an explanation is outside
the scope of this book).</p>
<p>Each signed variant can store numbers from -(2<sup>n - 1</sup>) to 2<sup>n -
1</sup> - 1 inclusive, where <code>n</code> is the number of bits that variant uses. So an
<code>i8</code> can store numbers from -(2<sup>7</sup>) to 2<sup>7</sup>, which equals
-128 to 127. Unsigned variants can store numbers from 0 to 2<sup>n</sup> - 1,
so a <code>u8</code> can store numbers from 0 to 2<sup>8</sup> - 1, which equals 0 to 255.</p>
<p>Additionally, the <code>isize</code> and <code>usize</code> types depend on the kind of computer your
program is running on: 64-bits if you’re on a 64-bit architecture and 32-bits
if you’re on a 32-bit architecture.</p>
<p>You can write integer literals in any of the forms shown in Table 3-2. Note
that all number literals except the byte literal allow a type suffix, such as
<code>57u8</code>, and <code>_</code> as a visual separator, such as <code>1_000</code>.</p>
<figure>
<figcaption>
<p>Table 3-2: Integer Literals in Rust</p>
</figcaption>
<table><thead><tr><td> Number literals </td><td> Example </td></tr></thead>
<tr><td> Decimal </td><td> <code>98_222</code> </td></tr>
<tr><td> Hex </td><td> <code>0xff</code> </td></tr>
<tr><td> Octal </td><td> <code>0o77</code> </td></tr>
<tr><td> Binary </td><td> <code>0b1111_0000</code> </td></tr>
<tr><td> Byte (<code>u8</code> only) </td><td> <code>b'A'</code> </td></tr>
</table>
</figure>
<p>So how do you know which type of integer to use? If you’re unsure, Rust’s
defaults are generally good choices, and integer types default to <code>i32</code>: it’s
generally the fastest, even on 64-bit systems. The primary situation in which
you’d use <code>isize</code> or <code>usize</code> is when indexing some sort of collection.</p>
<h4>Floating-Point Types</h4>
<p>Rust also has two primitive types for <em>floating-point numbers</em>, which are
numbers with decimal points. Rust’s floating-point types are <code>f32</code> and <code>f64</code>,
which are 32 bits and 64 bits in size, respectively. The default type is <code>f64</code>
because it’s roughly the same speed as <code>f32</code> but is capable of more precision.
It’s possible to use an <code>f64</code> type on 32-bit systems, but it will be slower
than using an <code>f32</code> type on those systems. Most of the time, trading potential
worse performance for better precision is a reasonable initial choice, and you
should benchmark your code if you suspect floating-point size is a problem in
your situation.</p>
<p>Here’s an example that shows floating-point numbers in action:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
</code></pre>
<p>Floating-point numbers are represented according to the IEEE-754 standard. The
<code>f32</code> type is a single-precision float, and <code>f64</code> has double precision.</p>
<h4>Numeric Operations</h4>
<p>Rust supports the usual basic mathematic operations you’d expect for all of the
number types: addition, subtraction, multiplication, division, and remainder.
The following code shows how you’d use each one in a <code>let</code> statement:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
// addition
let sum = 5 + 10;
// subtraction
let difference = 95.5 - 4.3;
// multiplication
let product = 4 * 30;
// division
let quotient = 56.7 / 32.2;
// remainder
let remainder = 43 % 5;
}
</code></pre>
<p>Each expression in these statements uses a mathematical operator and evaluates
to a single value, which is then bound to a variable. Appendix B contains a
list of all operators that Rust provides.</p>
<h4>The Boolean Type</h4>
<p>As in most other programming languages, a boolean type in Rust has two possible
values: <code>true</code> and <code>false</code>. The boolean type in Rust is specified using <code>bool</code>.
For example:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let t = true;
let f: bool = false; // with explicit type annotation
}
</code></pre>
<p>The main way to consume boolean values is through conditionals, such as an <code>if</code>
statement. We’ll cover how <code>if</code> statements work in Rust in the “Control Flow”
section.</p>
<h4>The Character Type</h4>
<p>So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
<code>char</code> type is the language’s most primitive alphabetic type, and the following
code shows one way to use it:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let c = 'z';
let z = 'ℤ';
let heart_eyed_cat = '😻';
}
</code></pre>
<p>Rust’s <code>char</code> type represents a Unicode Scalar Value, which means it can
represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
ideographs, emoji, and zero width spaces are all valid <code>char</code> types in Rust.
Unicode Scalar Values range from <code>U+0000</code> to <code>U+D7FF</code> and <code>U+E000</code> to
<code>U+10FFFF</code> inclusive. However, a “character” isn’t really a concept in Unicode,
so your human intuition for what a “character” is may not match up with what a
<code>char</code> is in Rust. We’ll discuss this topic in detail in the “Strings” section
in Chapter 8.</p>
<h3>Compound Types</h3>
<p><em>Compound types</em> can group multiple values of other types into one type. Rust
has two primitive compound types: tuples and arrays.</p>
<h4>Grouping Values into Tuples</h4>
<p>A tuple is a general way of grouping together some number of other values with
a variety of types into one compound type.</p>
<p>We create a tuple by writing a comma-separated list of values inside
parentheses. Each position in the tuple has a type, and the types of the
different values in the tuple don’t have to be the same. We’ve added optional
type annotations in this example:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
</code></pre>
<p>The variable <code>tup</code> binds to the entire tuple, since a tuple is considered a
single compound element. To get the individual values out of a tuple, we can
use pattern matching to destructure a tuple value, like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>This program first creates a tuple and binds it to the variable <code>tup</code>. It then
uses a pattern with <code>let</code> to take <code>tup</code> and turn it into three separate
variables, <code>x</code>, <code>y</code>, and <code>z</code>. This is called <em>destructuring</em>, because it breaks
the single tuple into three parts. Finally, the program prints the value of
<code>y</code>, which is <code>6.4</code>.</p>
<p>In addition to destructuring through pattern matching, we can also access a
tuple element directly by using a period (<code>.</code>) followed by the index of the
value we want to access. For example:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;
}
</code></pre>
<p>This program creates a tuple, <code>x</code>, and then makes new variables for each
element by using their index. As with most programming languages, the first
index in a tuple is 0.</p>
<h4>Arrays</h4>
<p>Another way to have a collection of multiple values is with an <em>array</em>. Unlike
a tuple, every element of an array must have the same type. Arrays in Rust are
different than arrays in some other languages because arrays in Rust have a
fixed length: once declared, they cannot grow or shrink in size.</p>
<p>In Rust, the values going into an array are written as a comma-separated list
inside square brackets:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
}
</code></pre>
<p>Arrays are useful when you want your data allocated on the stack rather than
the heap (we will discuss the stack and the heap more in Chapter 4), or when
you want to ensure you always have a fixed number of elements. They aren’t as
flexible as the vector type, though. The vector type is a similar collection
type provided by the standard library that <em>is</em> allowed to grow or shrink in
size. If you’re unsure whether to use an array or a vector, you should probably
use a vector: Chapter 8 discusses vectors in more detail.</p>
<p>An example of when you might want to use an array rather than a vector is in a
program that needs to know the names of the months of the year. It’s very
unlikely that such a program will need to add or remove months, so you can use
an array because you know it will always contain 12 items:</p>
<pre><code class="language-rust">let months = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;,
&quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;];
</code></pre>
<h5>Accessing Array Elements</h5>
<p>An array is a single chunk of memory allocated on the stack. We can access
elements of an array using indexing, like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}
</code></pre>
<p>In this example, the variable named <code>first</code> will get the value <code>1</code>, because
that is the value at index <code>[0]</code> in the array. The variable named <code>second</code> will
get the value <code>2</code> from index <code>[1]</code> in the array.</p>
<h5>Invalid Array Element Access</h5>
<p>What happens if we try to access an element of an array that is past the end of
the array? Say we change the example to the following:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let a = [1, 2, 3, 4, 5];
let element = a[10];
println!(&quot;The value of element is: {}&quot;, element);
}
</code></pre>
<p>Running this code using <code>cargo run</code> produces the following result:</p>
<pre><code class="language-text">$ cargo run
Compiling arrays v0.1.0 (file:///projects/arrays)
Running `target/debug/arrays`
thread '&lt;main&gt;' panicked at 'index out of bounds: the len is 5 but the index is
10', src/main.rs:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
</code></pre>
<p>The compilation didn’t produce any errors, but the program results in a
<em>runtime</em> error and didn’t exit successfully. When you attempt to access an
element using indexing, Rust will check that the index you’ve specified is less
than the array length. If the index is greater than the length, Rust will
<em>panic</em>, which is the term Rust uses when a program exits with an error.</p>
<p>This is the first example of Rust’s safety principles in action. In many
low-level languages, this kind of check is not done, and when you provide an
incorrect index, invalid memory can be accessed. Rust protects you against this
kind of error by immediately exiting instead of allowing the memory access and
continuing. Chapter 9 discusses more of Rust’s error handling.</p>
<h2>How Functions Work</h2>
<p>Functions are pervasive in Rust code. You’ve already seen one of the most
important functions in the language: the <code>main</code> function, which is the entry
point of many programs. You’ve also seen the <code>fn</code> keyword, which allows you to
declare new functions.</p>
<p>Rust code uses <em>snake case</em> as the conventional style for function and variable
names. In snake case, all letters are lowercase and underscores separate words.
Here’s a program that contains an example function definition:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
another_function();
}
fn another_function() {
println!(&quot;Another function.&quot;);
}
</code></pre>
<p>Function definitions in Rust start with <code>fn</code> and have a set of parentheses
after the function name. The curly braces tell the compiler where the function
body begins and ends.</p>
<p>We can call any function we’ve defined by entering its name followed by a set
of parentheses. Because <code>another_function</code> is defined in the program, it can be
called from inside the <code>main</code> function. Note that we defined <code>another_function</code>
<em>after</em> the <code>main</code> function in the source code; we could have defined it before
as well. Rust doesn’t care where you define your functions, only that they’re
defined somewhere.</p>
<p>Let’s start a new binary project named <em>functions</em> to explore functions
further. Place the <code>another_function</code> example in <em>src/main.rs</em> and run it. You
should see the following output:</p>
<pre><code class="language-text">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
Hello, world!
Another function.
</code></pre>
<p>The lines execute in the order in which they appear in the <code>main</code> function.
First, the “Hello, world!” message prints, and then <code>another_function</code> is
called and its message is printed.</p>
<h3>Function Arguments</h3>
<p>Functions can also take arguments. The following rewritten version of
<code>another_function</code> shows what arguments look like in Rust:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Try running this program; you should get the following output:</p>
<pre><code class="language-text">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p>The declaration of <code>another_function</code> has one argument named <code>x</code>. The type of
<code>x</code> is specified as <code>i32</code>. When <code>5</code> is passed to <code>another_function</code>, the
<code>println!</code> macro puts <code>5</code> where the pair of curly braces were in the format
string.</p>
<p>In function signatures, you <em>must</em> declare the type. This is a deliberate
decision in Rust’s design: requiring type annotations in function definitions
means the compiler almost never needs you to use them elsewhere in the code to
figure out what you mean.</p>
<p>When you want a function to have multiple arguments, separate them inside the
function signature with commas, like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
another_function(5, 6);
}
fn another_function(x: i32, y: i32) {
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>This example creates a function with two arguments, both of which are <code>i32</code>
types. If your function has multiple arguments, the arguments don’t need to be
the same type, but they just happen to be in this example. The function then
prints out the values of both of its arguments.</p>
<p>Let’s try running this code. Replace the program currently in your <em>function</em>
project’s <em>src/main.rs</em> file with the preceding example, and run it using
<code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of x is: 5
The value of y is: 6
</code></pre>
<p>Because <code>5</code> is passed as the <code>x</code> argument and <code>6</code> is passed as the <code>y</code>
argument, the two strings are printed with these values.</p>
<h3>Function Bodies</h3>
<p>Function bodies are made up of a series of statements optionally ending in an
expression. So far, we’ve only covered functions without an ending expression,
but we have seen expressions as parts of statements. Because Rust is an
expression-based language, this is an important distinction to understand.
Other languages don’t have the same distinctions, so let’s look at what
statements and expressions are and how their differences affect the bodies of
functions.</p>
<h3>Statements and Expressions</h3>
<p>We’ve actually already used statements and expressions. <em>Statements</em> are
instructions that perform some action and do not return a value. <em>Expressions</em>
evaluate to a resulting value. Let’s look at some examples.</p>
<p>Creating a variable and assigning a value to it with the <code>let</code> keyword is a
statement. In Listing 3-3, <code>let y = 6;</code> is a statement:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let y = 6;
}
</code></pre>
<figcaption>
<p>Listing 3-3: A <code>main</code> function declaration containing one statement.</p>
</figcaption>
</figure>
<p>Function definitions are also statements; the entire preceding example is a
statement in itself.</p>
<p>Statements do not return values. Therefore, you can’t assign a <code>let</code> statement
to another variable, as the following code tries to do:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let x = (let y = 6);
}
</code></pre>
<p>When you run this program, you’ll get an error like this:</p>
<pre><code class="language-text">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found statement (`let`)
--&gt; src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^
|
= note: variable declaration using `let` is a statement
</code></pre>
<p>The <code>let y = 6</code> statement does not return a value, so there isn’t anything for
<code>x</code> to bind to. This is different than in other languages, such as C and Ruby,
where the assignment returns the value of the assignment. In those languages,
you can write <code>x = y = 6</code> and have both <code>x</code> and <code>y</code> have the value <code>6</code>; that is
not the case in Rust.</p>
<p>Expressions evaluate to something and make up most of the rest of the code that
you’ll write in Rust. Consider a simple math operation, such as <code>5 + 6</code>, which
is an expression that evaluates to the value <code>11</code>. Expressions can be part of
statements: in Listing 3-3 that had the statement <code>let y = 6;</code>, <code>6</code> is an
expression that evaluates to the value <code>6</code>. Calling a function is an
expression. Calling a macro is an expression. The block that we use to create
new scopes, <code>{}</code>, is an expression, for example:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = {
let x = 3;
x + 1
};
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>This expression:</p>
<pre><code class="language-rust,ignore">{
let x = 3;
x + 1
}
</code></pre>
<p>is a block that, in this case, evaluates to <code>4</code>. That value gets bound to <code>y</code>
as part of the <code>let</code> statement. Note the line without a semicolon at the end,
unlike most of the lines you’ve seen so far. Expressions do not include ending
semicolons. If you add a semicolon to the end of an expression, you turn it
into a statement, which will then not return a value. Keep this in mind as you
explore function return values and expressions next.</p>
<h3>Functions with Return Values</h3>
<p>Functions can return values to the code that calls them. We don’t name return
values, but we do declare their type after an arrow (<code>-&gt;</code>). In Rust, the return
value of the function is synonymous with the value of the final expression in
the block of the body of a function. Here’s an example of a function that
returns a value:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn five() -&gt; i32 {
5
}
fn main() {
let x = five();
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>There are no function calls, macros, or even <code>let</code> statements in the <code>five</code>
function—just the number <code>5</code> by itself. That’s a perfectly valid function in
Rust. Note that the function’s return type is specified, too, as <code>-&gt; i32</code>. Try
running this code; the output should look like this:</p>
<pre><code class="language-text">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p>The <code>5</code> in <code>five</code> is the function’s return value, which is why the return type
is <code>i32</code>. Let’s examine this in more detail. There are two important bits:
first, the line <code>let x = five();</code> shows that we’re using the return value of a
function to initialize a variable. Because the function <code>five</code> returns a <code>5</code>,
that line is the same as the following:</p>
<pre><code class="language-rust">let x = 5;
</code></pre>
<p>Second, the <code>five</code> function requires no arguments and defines the type of the
return value, but the body of the function is a lonely <code>5</code> with no semicolon
because it’s an expression whose value we want to return. Let’s look at another
example:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let x = plus_one(5);
println!(&quot;The value of x is: {}&quot;, x);
}
fn plus_one(x: i32) -&gt; i32 {
x + 1
}
</code></pre>
<p>Running this code will print <code>The value of x is: 6</code>. What happens if we place a
semicolon at the end of the line containing <code>x + 1</code>, changing it from an
expression to a statement?</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let x = plus_one(5);
println!(&quot;The value of x is: {}&quot;, x);
}
fn plus_one(x: i32) -&gt; i32 {
x + 1;
}
</code></pre>
<p>Running this code produces an error, as follows:</p>
<pre><code class="language-text">error[E0269]: not all control paths return a value
--&gt; src/main.rs:7:1
|
7 | fn plus_one(x: i32) -&gt; i32 {
| ^
|
help: consider removing this semicolon:
--&gt; src/main.rs:8:10
|
8 | x + 1;
| ^
</code></pre>
<p>The main error message, “not all control paths return a value,” reveals the
core issue with this code. The definition of the function <code>plus_one</code> says that
it will return an <code>i32</code>, but statements don’t evaluate to a value. Therefore,
nothing is returned, which contradicts the function definition and results in
an error. In this output, Rust provides a message to possibly help rectify this
issue: it suggests removing the semicolon, which would fix the error.</p>
<h2>Comments</h2>
<p>All programmers strive to make their code easy to understand, but sometimes
extra explanation is warranted. In these cases, programmers leave notes, or
<em>comments</em>, in their source code that the compiler will ignore but people
reading the source code may find useful.</p>
<p>Here’s a simple comment:</p>
<pre><code class="language-rust">// Hello, world.
</code></pre>
<p>In Rust, comments must start with two slashes and continue until the end of the
line. For comments that extend beyond a single line, you’ll need to include
<code>//</code> on each line, like this:</p>
<pre><code class="language-rust">// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.
</code></pre>
<p>Comments can also be placed at the end of lines containing code:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let lucky_number = 7; // I’m feeling lucky today.
}
</code></pre>
<p>But you’ll more often see them used in this format, with the comment on a
separate line above the code it's annotating:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
// I’m feeling lucky today.
let lucky_number = 7;
}
</code></pre>
<p>That’s all there is to comments. They’re not particularly complicated.</p>
<h2>Control Flow</h2>
<p>Deciding whether or not to run some code depending on if a condition is true or
deciding to run some code repeatedly while a condition is true are basic
building blocks in most programming languages. The most common constructs that
let you control the flow of execution of Rust code are <code>if</code> expressions and
loops.</p>
<h3><code>if</code> Expressions</h3>
<p>An <code>if</code> expression allows us to branch our code depending on conditions. We
provide a condition and then state, “If this condition is met, run this block
of code. If the condition is not met, do not run this block of code.”</p>
<p>Create a new project called <em>branches</em> in your <em>projects</em> directory to explore
the <code>if</code> expression. In the <em>src/main.rs</em> file, input the following:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let number = 3;
if number &lt; 5 {
println!(&quot;condition was true&quot;);
} else {
println!(&quot;condition was false&quot;);
}
}
</code></pre>
<p>All <code>if</code> expressions start with the keyword <code>if</code>, which is followed by a
condition. In this case, the condition checks whether or not the variable
<code>number</code> has a value less than 5. The block of code we want to execute if the
condition is true is placed immediately after the condition inside curly
braces. Blocks of code associated with the conditions in <code>if</code> expressions are
sometimes called <em>arms</em>, just like the arms in <code>match</code> expressions that we
discussed in the “Comparing the Guess to the Secret Number” section of Chapter</p>
<ol start="2">
<li>Optionally, we can also include an <code>else</code> expression, which we chose to do
here, to give the program an alternative block of code to execute should the
condition evaluate to false. If you don’t provide an <code>else</code> expression and the
condition is false, the program will just skip the <code>if</code> block and move on to
the next bit of code.</li>
</ol>
<p>Try running this code; you should see the following output:</p>
<pre><code class="language-text">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was true
</code></pre>
<p>Let’s try changing the value of <code>number</code> to a value that makes the condition
<code>false</code> to see what happens:</p>
<pre><code class="language-rust,ignore">let number = 7;
</code></pre>
<p>Run the program again, and look at the output:</p>
<pre><code class="language-text">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was false
</code></pre>
<p>It’s also worth noting that the condition in this code <em>must</em> be a <code>bool</code>. To
see what happens if the condition isn’t a <code>bool</code>, try running the following
code:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let number = 3;
if number {
println!(&quot;number was three&quot;);
}
}
</code></pre>
<p>The <code>if</code> condition evaluates to a value of <code>3</code> this time, and Rust throws an
error:</p>
<pre><code class="language-text"> Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: mismatched types
--&gt; src/main.rs:4:8
|
4 | if number {
| ^^^^^^ expected bool, found integral variable
|
= note: expected type `bool`
= note: found type `{integer}`
error: aborting due to previous error
Could not compile `branches`.
</code></pre>
<p>The error indicates that Rust expected a <code>bool</code> but got an integer. Rust will
not automatically try to convert non-boolean types to a boolean, unlike
languages such as Ruby and JavaScript. You must be explicit and always provide
<code>if</code> with a <code>boolean</code> as its condition. If we want the <code>if</code> code block to run
only when a number is not equal to <code>0</code>, for example, we can change the <code>if</code>
expression to the following:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let number = 3;
if number != 0 {
println!(&quot;number was something other than zero&quot;);
}
}
</code></pre>
<p>Running this code will print <code>number was something other than zero</code>.</p>
<h4>Multiple Conditions with <code>else if</code></h4>
<p>We can have multiple conditions by combining <code>if</code> and <code>else</code> in an <code>else if</code>
expression. For example:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let number = 6;
if number % 4 == 0 {
println!(&quot;number is divisible by 4&quot;);
} else if number % 3 == 0 {
println!(&quot;number is divisible by 3&quot;);
} else if number % 2 == 0 {
println!(&quot;number is divisible by 2&quot;);
} else {
println!(&quot;number is not divisible by 4, 3, or 2&quot;);
}
}
</code></pre>
<p>This program has four possible paths it can take. After running it, you should
see the following output:</p>
<pre><code class="language-text">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
number is divisible by 3
</code></pre>
<p>When this program executes, it checks each <code>if</code> expression in turn and executes
the first body for which the condition holds true. Note that even though 6 is
divisible by 2, we don’t see the output <code>number is divisible by 2</code>, nor do we
see the <code>number is not divisible by 4, 3, or 2</code> text from the <code>else</code> block. The
reason is that Rust will only execute the block for the first true condition,
and once it finds one, it won’t even check the rest.</p>
<p>Using too many <code>else if</code> expressions can clutter your code, so if you have more
than one, you might want to refactor your code. Chapter 6 describes a powerful
Rust branching construct called <code>match</code> for these cases.</p>
<h4>Using <code>if</code> in a <code>let</code> statement</h4>
<p>Because <code>if</code> is an expression, we can use it on the right side of a <code>let</code>
statement, for instance in Listing 3-4:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!(&quot;The value of number is: {}&quot;, number);
}
</code></pre>
<figcaption>
<p>Listing 3-4: Assigning the result of an <code>if</code> expression to a variable</p>
</figcaption>
</figure>
<p>The <code>number</code> variable will be bound to a value based on the outcome of the <code>if</code>
expression. Run this code to see what happens:</p>
<pre><code class="language-text">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
The value of number is: 5
</code></pre>
<p>Remember that blocks of code evaluate to the last expression in them, and
numbers by themselves are also expressions. In this case, the value of the
whole <code>if</code> expression depends on which block of code executes. This means the
values that have the potential to be results from each arm of the <code>if</code> must be
the same type; in Listing 3-4, the results of both the <code>if</code> arm and the <code>else</code>
arm were <code>i32</code> integers. But what happens if the types are mismatched, as in
the following example?</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let condition = true;
let number = if condition {
5
} else {
&quot;six&quot;
};
println!(&quot;The value of number is: {}&quot;, number);
}
</code></pre>
<p>When we run this code, we’ll get an error. The <code>if</code> and <code>else</code> arms have value
types that are incompatible, and Rust indicates exactly where to find the
problem in the program:</p>
<pre><code class="language-text"> Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: if and else have incompatible types
--&gt; src/main.rs:4:18
|
4 | let number = if condition {
| ^ expected integral variable, found reference
|
= note: expected type `{integer}`
= note: found type `&amp;’static str`
</code></pre>
<p>The expression in the <code>if</code> block evaluates to an integer, and the expression in
the <code>else</code> block evaluates to a string. This won’t work because variables must
have a single type. Rust needs to know at compile time what type the <code>number</code>
variable is, definitively, so it can verify at compile time that its type is
valid everywhere we use <code>number</code>. Rust wouldn’t be able to do that if the type
of <code>number</code> was only determined at runtime; the compiler would be more complex
and would make fewer guarantees about the code if it had to keep track of
multiple hypothetical types for any variable.</p>
<h3>Repetition with Loops</h3>
<p>It’s often useful to execute a block of code more than once. For this task,
Rust provides several <em>loops</em>. A loop runs through the code inside the loop
body to the end and then starts immediately back at the beginning. To
experiment with loops, let’s make a new project called <em>loops</em>.</p>
<p>Rust has three kinds of loops: <code>loop</code>, <code>while</code>, and <code>for</code>. Let’s try each one.</p>
<h4>Repeating Code with <code>loop</code></h4>
<p>The <code>loop</code> keyword tells Rust to execute a block of code over and over again
forever or until you explicitly tell it to stop.</p>
<p>As an example, change the <em>src/main.rs</em> file in your <em>loops</em> directory to look
like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
loop {
println!(&quot;again!&quot;);
}
}
</code></pre>
<p>When we run this program, we’ll see <code>again!</code> printed over and over continuously
until we stop the program manually. Most terminals support a keyboard shortcut,
ctrl-C, to halt a program that is stuck in a continual loop. Give it a try:</p>
<pre><code class="language-text">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!
</code></pre>
<p>The symbol <code>^C</code> represents where you pressed ctrl-C. You may or may not see the
word <code>again!</code> printed after the <code>^C</code>, depending on where the code was in the
loop when it received the halt signal.</p>
<p>Fortunately, Rust provides another, more reliable way to break out of a loop.
You can place the <code>break</code> keyword within the loop to tell the program when to
stop executing the loop. Recall that we did this in the guessing game in the
“Quitting After a Correct Guess” section of Chapter 2 to exit the
program when the user won the game by guessing the correct number.</p>
<h4>Conditional Loops with <code>while</code></h4>
<p>It’s often useful for a program to evaluate a condition within a loop. While
the condition is true, the loop runs. When the condition ceases to be true, you
call <code>break</code>, stopping the loop. This loop type could be implemented using a
combination of <code>loop</code>, <code>if</code>, <code>else</code>, and <code>break</code>; you could try that now in a
program, if you’d like.</p>
<p>However, this pattern is so common that Rust has a built-in language construct
for it, and it’s called a <code>while</code> loop. The following example uses <code>while</code>: the
program loops three times, counting down each time. Then, after the loop, it
prints another message and exits:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let mut number = 3;
while number != 0 {
println!(&quot;{}!&quot;, number);
number = number - 1;
}
println!(&quot;LIFTOFF!!!&quot;);
}
</code></pre>
<p>This construct eliminates a lot of nesting that would be necessary if you used
<code>loop</code>, <code>if</code>, <code>else</code>, and <code>break</code>, and it’s clearer. While a condition holds
true, the code runs; otherwise, it exits the loop.</p>
<h4>Looping Through a Collection with <code>for</code></h4>
<p>You could use the <code>while</code> construct to loop over the elements of a collection,
such as an array. For example:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index &lt; 5 {
println!(&quot;the value is: {}&quot;, a[index]);
index = index + 1;
}
}
</code></pre>
<figcaption>
<p>Listing 3-5: Looping through each element of a collection using a <code>while</code> loop</p>
</figcaption>
</figure>
<p>Here, the code counts up through the elements in the array. It starts at index
<code>0</code>, and then loops until it reaches the final index in the array (that is,
when <code>index &lt; 5</code> is no longer true). Running this code will print out every
element in the array:</p>
<pre><code class="language-text">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
</code></pre>
<p>All five array values appear in the terminal, as expected. Even though <code>index</code>
will reach a value of <code>6</code> at some point, the loop stops executing before trying
to fetch a sixth value from the array.</p>
<p>But this approach is error prone; we could cause the program to panic if the
index length is incorrect. It’s also slow, because the compiler needs to
perform the conditional check on every element on every iteration through the
loop.</p>
<p>As a more efficient alternative, you can use a <code>for</code> loop and execute some code
for each item in a collection. A <code>for</code> loop looks like this:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!(&quot;the value is: {}&quot;, element);
}
}
</code></pre>
<figcaption>
<p>Listing 3-6: Looping through each element of a collection using a <code>for</code> loop</p>
</figcaption>
</figure>
<p>When we run this code, we’ll see the same output as in Listing 3-5. More
importantly, we’ve now increased the safety of the code and eliminated the
chance of bugs that might result from going beyond the end of the array or not
going far enough and missing some items.</p>
<p>For example, in the code in Listing 3-5, if you removed an item from the <code>a</code>
array but forgot to update the condition to <code>while index &lt; 4</code>, the code would
panic. Using the <code>for</code> loop, you don’t need to remember to change any other
code if you changed the number of values in the array.</p>
<p>The safety and conciseness of <code>for</code> loops make them the most commonly used loop
construct in Rust. Even in situations in which you want to run some code a
certain number of times, as in the countdown example that used a <code>while</code> loop
in Listing 3-5, most Rustaceans would use a <code>for</code> loop. The way to do that
would be to use a <code>Range</code>, which is a type provided by the standard library
that generates all numbers in sequence starting from one number and ending
before another number.</p>
<p>Here’s what the countdown would look like using a <code>for</code> loop and another method
we’ve not yet talked about, <code>rev</code>, to reverse the range:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
for number in (1..4).rev() {
println!(&quot;{}!&quot;, number);
}
println!(&quot;LIFTOFF!!!&quot;);
}
</code></pre>
<p>This code is a bit nicer, isn’t it?</p>
<h2>Summary</h2>
<p>You made it! That was a sizable chapter: you learned about variables, scalar
and<code>if</code> expressions, and loops! If you want to practice with the concepts
discussed in this chapter, try building programs to do the following:</p>
<ul>
<li>Convert temperatures between Fahrenheit and Celsius.</li>
<li>Generate the nth Fibonacci number.</li>
<li>Print the lyrics to the Christmas carol “The Twelve Days of Christmas,”
taking advantage of the repetition in the song.</li>
</ul>
<p>When you’re ready to move on, we’ll talk about a concept in Rust that <em>doesn’t</em>
commonly exist in other programming languages: ownership.</p>
<h1>Understanding Ownership</h1>
<p>Ownership is Rust’s most unique feature, and enables Rust to make memory safety
guarantees without needing a garbage collector. It’s therefore important to
understand how ownership works in Rust. In this chapter we’ll talk about
ownership as well as several related features: borrowing, slices, and how Rust
lays things out in memory.</p>
<h2>What is Ownership?</h2>
<p>Rust’s central feature is <em>ownership</em>. It is a feature that is straightforward
to explain, but has deep implications for the rest of the language.</p>
<p>All programs have to manage the way they use a computer’s memory while running.
Some languages have garbage collection that’s constantly looking for no longer
used memory as the program runs, while in others, the programmer has to
explicitly allocate and free the memory. Rust takes a third approach: memory is
managed through a system of ownership with a set of rules that the compiler
checks at compile-time. You do not pay any run-time cost for any of these
features.</p>
<p>Since ownership is a new concept for many programmers, it does take some time
to get used to. There is good news, though: the more experienced you become
with Rust and the rules of the ownership system, the more you’ll be able to
naturally develop code that is both safe and efficient. Keep at it!</p>
<p>Once you understand ownership, you have a good foundation for understanding the
features that make Rust unique. In this chapter, we’ll learn ownership by going
through some examples, focusing on a very common data structure: strings.</p>
<!-- PROD: START BOX -->
<blockquote>
<h3>The Stack and the Heap</h3>
<p>In many programming languages, we don’t have to think about the stack and the
heap very often. But in a systems programming language like Rust, whether a
value is on the stack or the heap has more of an effect on how the language
behaves and why we have to make certain decisions. We’re going to be
describing parts of ownership in relation to the stack and the heap, so here
is a brief explanation.</p>
<p>Both the stack and the heap are parts of memory that is available to your code
to use at runtime, but they are structured in different ways. The stack stores
values in the order it gets them and removes the values in the opposite order.
This is referred to as <em>last in, first out</em>. Think of a stack of plates: when
you add more plates, you put them on top of the pile, and when you need a
plate, you take one off the top. Adding or removing plates from the middle or
bottom wouldn’t work as well! Adding data is called <em>pushing onto the stack</em>
and removing data is called <em>popping off the stack</em>.</p>
<p>The stack is fast because of the way it accesses the data: it never has to
look around for a place to put new data or a place to get data from; that
place is always the top. Another property that makes the stack fast is that
all data on the stack must take up a known, fixed size.</p>
<p>For data with a size unknown to us at compile time, or a size that might
change, we can store data on the heap instead. The heap is less organized:
when we put data on the heap, we ask for some amount of space. The operating
system finds an empty spot somewhere in the heap that is big enough, marks it
as being in use, and returns to us a pointer to that location. This process
is called <em>allocating on the heap</em>, and sometimes we just say “allocating”
for short. Pushing values onto the stack is not considered allocating. Since
the pointer is a known, fixed size, we can store the pointer on the stack,
but when we want the actual data, we have to follow the pointer.</p>
<p>Think of being seated at a restaurant. When you enter, you say how many people
are in your group, and the staff finds an empty table that would fit everyone
and leads you there. If someone in your group comes late, they can ask where
you have been seated to find you.</p>
<p>Accessing data in the heap is slower because we have to follow a pointer to
get there. Contemporary processors are faster if they jump around less in
memory. Continuing the analogy, consider a server at a restaurant who is
taking orders from many tables. It's most efficient to get all of the orders
at one table before moving on to the next table. Taking an order from table
A, then an order from table B, then one from A again, then one from B again
would be much slower. By the same token, a processor can do its job better if
it works on data that's close to other data (as it is on the stack), rather
than farther away (as it can be on the heap). Allocating a large amount of
space on the heap can also take time.</p>
<p>When our code calls a function, the values passed into the function
(including, potentially, pointers to data on the heap) and the function’s
local variables get pushed onto the stack. When the function is over, those
values get popped off the stack.</p>
<p>Keeping track of what parts of code are using what data on the heap,
minimizing the amount of duplicate data on the heap, and cleaning up unused
data on the heap so that we don’t run out of space—these are all problems
that ownership addresses. Once you understand ownership, you won’t need to
think about the stack and the heap very often, but knowing that managing heap
data is why ownership exists can help explain why it works the way it does.</p>
</blockquote>
<!-- PROD: END BOX -->
<h3>Ownership Rules</h3>
<p>First, let’s take a look at the rules. Keep these in mind as we go through the
examples that will illustrate the rules:</p>
<blockquote>
<ol>
<li>Each value in Rust has a variable that’s called its <em>owner</em>.</li>
<li>There can only be one owner at a time.</li>
<li>When the owner goes out of scope, the value will be dropped.</li>
</ol>
</blockquote>
<h3>Variable Scope</h3>
<p>We’ve walked through an example of a Rust program already in the tutorial
chapter. Now that we’re past basic syntax, we won’t include all of the <code>fn main() {</code> stuff in examples, so if you’re following along, you will have to put
the following examples inside of a <code>main</code> function yourself. This lets our
examples be a bit more concise, letting us focus on the actual details rather
than boilerplate.</p>
<p>As a first example of ownership, we’ll look at the <em>scope</em> of some variables. A
scope is the range within a program for which an item is valid. Let’s say we
have a variable that looks like this:</p>
<pre><code class="language-rust">let s = &quot;hello&quot;;
</code></pre>
<p>The variable <code>s</code> refers to a string literal, where the value of the string is
hard coded into the text of our program. The variable is valid from the point
at which it’s declared until the end of the current <em>scope</em>. That is:</p>
<pre><code class="language-rust">{ // s is not valid here, it’s not yet declared
let s = &quot;hello&quot;; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>In other words, there are two important points in time here:</p>
<ul>
<li>When <code>s</code> comes <em>into scope</em>, it is valid.</li>
<li>It remains so until it <em>goes out of scope</em>.</li>
</ul>
<p>At this point, things are similar to other programming languages. Now let’s
build on top of this understanding by introducing the <code>String</code> type.</p>
<h3>The <code>String</code> Type</h3>
<p>In order to illustrate the rules of ownership, we need a data type that is more
complex than the ones we covered in Chapter 3. All of the data types we’ve
looked at previously are stored on the stack and popped off the stack when
their scope is over, but we want to look at data that is stored on the heap and
explore how Rust knows when to clean that data up.</p>
<p>We’re going to use <code>String</code> as the example here and concentrate on the parts of
<code>String</code> that relate to ownership. These aspects also apply to other complex
data types provided by the standard library and that you create. We’ll go into
more depth about <code>String</code> specifically in Chapter 8.</p>
<p>We’ve already seen string literals, where a string value is hard-coded into our
program. String literals are convenient, but they aren’t always suitable for
every situation you want to use text. For one thing, they’re immutable. For
another, not every string value can be known when we write our code: what if we
want to take user input and store it?</p>
<p>For things like this, Rust has a second string type, <code>String</code>. This type is
allocated on the heap, and as such, is able to store an amount of text that is
unknown to us at compile time. You can create a <code>String</code> from a string literal
using the <code>from</code> function, like so:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
</code></pre>
<p>The double colon (<code>::</code>) is an operator that allows us to namespace this
particular <code>from</code> function under the <code>String</code> type itself, rather than using
some sort of name like <code>string_from</code>. We’ll discuss this syntax more in the
“Method Syntax” and “Modules” chapters.</p>
<p>This kind of string <em>can</em> be mutated:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
s.push_str(&quot;, world!&quot;); // push_str() appends a literal to a String
println!(&quot;{}&quot;, s); // This will print `hello, world!`
</code></pre>
<p>So, what’s the difference here? Why can <code>String</code> be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.</p>
<h3>Memory and Allocation</h3>
<p>In the case of a string literal, because we know the contents at compile time,
the text is hard-coded directly into the final executable. This makes string
literals quite fast and efficient. But these properties only come from its
immutability. Unfortunately, we can’t put a blob of memory into the binary for
each piece of text whose size is unknown at compile time and whose size might
change over the course of running the program.</p>
<p>With the <code>String</code> type, in order to support a mutable, growable piece of text,
we need to allocate an amount of memory on the heap, unknown at compile time,
to hold the contents. This means two things:</p>
<ol>
<li>The memory must be requested from the operating system at runtime.</li>
<li>We need a way of giving this memory back to the operating system when we’re
done with our <code>String</code>.</li>
</ol>
<p>That first part is done by us: when we call <code>String::from</code>, its implementation
requests the memory it needs. This is pretty much universal in programming
languages.</p>
<p>The second case, however, is different. In languages with a <em>garbage collector</em>
(GC), the GC will keep track and clean up memory that isn’t being used anymore,
and we, as the programmer, don’t need to think about it. Without GC, it’s the
programmer’s responsibility to identify when memory is no longer being used and
call code to explicitly return it, just as we did to request it. Doing this
correctly has historically been a difficult problem in programming. If we
forget, we will waste memory. If we do it too early, we will have an invalid
variable. If we do it twice, that’s a bug too. We need to pair exactly one
<code>allocate</code> with exactly one <code>free</code>.</p>
<p>Rust takes a different path: the memory is automatically returned once the
variable that owns it goes out of scope. Here’s a version of our scope example
from earlier using <code>String</code>:</p>
<pre><code class="language-rust">{
let s = String::from(&quot;hello&quot;); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>There is a natural point at which we can return the memory our <code>String</code> needs
back to the operating system: when <code>s</code> goes out of scope. When a variable goes
out of scope, Rust calls a special function for us. This function is called
<code>drop</code>, and it is where the author of <code>String</code> can put the code to return the
memory. Rust calls <code>drop</code> automatically at the closing <code>}</code>.</p>
<blockquote>
<p>Note: This pattern is sometimes called *Resource Acquisition Is
Initialization* in C++, or RAII for short. The <code>drop</code> function in Rust will be
familiar to you if you have used RAII patterns.</p>
</blockquote>
<p>This pattern has a profound impact on the way that Rust code is written. It may
seem simple right now, but things can get tricky in more advanced situations
when we want to have multiple variables use the data that we have allocated on
the heap. Let’s go over some of those situations now.</p>
<h4>Ways Variables and Data Interact: Move</h4>
<p>There are different ways that multiple variables can interact with the same data
in Rust. Let’s take an example using an integer:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
</code></pre>
<p>We can probably guess what this is doing based on our experience with other
languages: “Bind the value <code>5</code> to <code>x</code>, then make a copy of the value in <code>x</code> and
bind it to <code>y</code>.” We now have two variables, <code>x</code> and <code>y</code>, and both equal <code>5</code>.
This is indeed what is happening since integers are simple values with a known,
fixed size, and these two <code>5</code> values are pushed onto the stack.</p>
<p>Now let’s look at the <code>String</code> version:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
</code></pre>
<p>This looks very similar to the previous code, so we might assume that the way
it works would be the same: that the second line would make a copy of the value
in <code>s1</code> and bind it to <code>s2</code>. This isn’t quite what happens.</p>
<p>To explain this more thoroughly, let’s take a look at what <code>String</code> looks like
under the covers in Figure 4-1. A <code>String</code> is made up of three parts, shown on
the left: a pointer to the memory that holds the contents of the string, a
length, and a capacity. This group of data is stored on the stack. On the right
is the memory that holds the contents, and this is on the heap.</p>
<figure>
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-1: Representation in memory of a <code>String</code> holding the value <code>&quot;hello&quot;</code>
bound to <code>s1</code></p>
</figcaption>
</figure>
<p>The length is how much memory, in bytes, the contents of the <code>String</code> is
currently using. The capacity is the total amount of memory, in bytes, that the
<code>String</code> has gotten from the operating system. The difference between length
and capacity matters but not in this context, so for now, it’s fine to ignore
the capacity.</p>
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> data itself is copied, meaning we
copy the pointer, the length, and the capacity that are on the stack. We do not
copy the data on the heap that the <code>String</code>’s pointer refers to. In other
words, it looks like figure 4-2.</p>
<figure>
<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-2: Representation in memory of the variable <code>s2</code> that has a copy of
<code>s1</code>’s pointer, length and capacity</p>
</figcaption>
</figure>
<p>And <em>not</em> Figure 4-3, which is what memory would look like if Rust instead
copied the heap data as well. If Rust did this, the operation <code>s2 = s1</code> could
potentially be very expensive if the data on the heap was large.</p>
<figure>
<img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-3: Another possibility for what <code>s2 = s1</code> might do, if Rust chose to
copy heap data as well.</p>
</figcaption>
</figure>
<p>Earlier, we said that when a variable goes out of scope, Rust will
automatically call the <code>drop</code> function and clean up the heap memory for that
variable. But in figure 4-2, we see both data pointers pointing to the same
location. This is a problem: when <code>s2</code> and <code>s1</code> go out of scope, they will both
try to free the same memory. This is known as a <em>double free</em> error and is one
of the memory safety bugs we mentioned before. Freeing memory twice can lead to
memory corruption, which can potentially lead to security vulnerabilities.</p>
<p>In order to ensure memory safety, there’s one more detail to what happens in
this situation in Rust. Instead of trying to copy the allocated memory, Rust
says that <code>s1</code> is no longer valid and, therefore, doesn’t need to free anything
when it goes out of scope. Check out what happens when you try to use <code>s1</code>
after <code>s2</code> is created:</p>
<pre><code class="language-rust,ignore">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
println!(&quot;{}&quot;, s1);
</code></pre>
<p>You’ll get an error like this:</p>
<pre><code class="language-text">5:22 error: use of moved value: `s1` [E0382]
println!(&quot;{}&quot;, s1);
^~
5:24 note: in this expansion of println! (defined in &lt;std macros&gt;)
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default
let s2 = s1;
^~
</code></pre>
<p>If you have heard the terms “shallow copy” and “deep copy” while working with
other languages, the concept of copying the pointer, length, and capacity
without copying the data probably sounds like a shallow copy. But because Rust
also invalidates the first variable, instead of calling this a shallow copy,
it’s known as a <em>move</em>. Here we would read this by saying that <code>s1</code> was <em>moved</em>
into <code>s2</code>. So what actually happens looks like Figure 4-4.</p>
<figure>
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-4: Representation in memory after <code>s1</code> has been invalidated</p>
</figcaption>
</figure>
<p>That solves our problem! With only <code>s2</code> valid, when it goes out of scope, it
alone will free the memory, and we’re done.</p>
<p>Furthermore, there’s a design choice that’s implied by this: Rust will never
automatically create “deep” copies of your data. Therefore, any <em>automatic</em>
copying can be assumed to be inexpensive.</p>
<h4>Ways Variables and Data Interact: Clone</h4>
<p>If we <em>do</em> want to deeply copy the <code>String</code>’s data and not just the <code>String</code>
itself, there’s a common method for that: <code>clone</code>. We will discuss methods in
the section on <a href="ch05-01-structs.html"><code>structs</code> in Chapter 5</a><!-- ignore -->, but they’re a
common enough feature in many programming languages that you have probably seen
them before.</p>
<p>Here’s an example of the <code>clone</code> method in action:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1.clone();
println!(&quot;s1 = {}, s2 = {}&quot;, s1, s2);
</code></pre>
<p>This will work just fine, and this is how you can explicitly get the behavior
we showed in Figure 4-3, where the heap data <em>does</em> get copied.</p>
<p>When you see a call to <code>clone</code>, you know that some arbitrary code is being
executed, and that code may be expensive. It’s a visual indicator that
something different is going on here.</p>
<h4>Stack-only Data: Copy</h4>
<p>There’s another wrinkle we haven’t talked about yet. This code, that we showed
earlier, works and is valid:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!(&quot;x = {}, y = {}&quot;, x, y);
</code></pre>
<p>This seems to contradict what we just learned: we don’t have a call to <code>clone</code>,
but <code>x</code> is still valid, and wasn’t moved into <code>y</code>.</p>
<p>This is because types like integers that have a known size at compile time are
stored entirely on the stack, so copies of the actual values are quick to make.
That means there’s no reason we would want to prevent <code>x</code> from being valid
after we create the variable <code>y</code>. In other words, there’s no difference between
deep and shallow copying here, so calling <code>clone</code> wouldn’t do anything
differently from the usual shallow copying and we can leave it out.</p>
<p>Rust has a special annotation called the <code>Copy</code> trait that we can place on
types like these (we’ll talk more about traits in Chapter 10). If a type has
the <code>Copy</code> trait, an older variable is still usable after assignment. Rust will
not let us annotate a type with the <code>Copy</code> trait if the type, or any of its
parts, has implemented the <code>Drop</code> trait. If the type needs something special
to happen when the value goes out of scope and we add the <code>Copy</code> annotation to
that type, we will get a compile-time error.</p>
<p>So what types are <code>Copy</code>? You can check the documentation for the given type to
be sure, but as a rule of thumb, any group of simple scalar values can be Copy,
and nothing that requires allocation or is some form of resource is <code>Copy</code>.
Here’s some of the types that are <code>Copy</code>:</p>
<ul>
<li>All of the integer types, like <code>u32</code>.</li>
<li>The boolean type, <code>bool</code>, with values <code>true</code> and <code>false</code>.</li>
<li>All of the floating point types, like <code>f64</code>.</li>
<li>Tuples, but only if they contain types which are also <code>Copy</code>. <code>(i32, i32)</code> is
<code>Copy</code>, but <code>(i32, String)</code> is not.</li>
</ul>
<h3>Ownership and Functions</h3>
<p>The semantics for passing a value to a function are similar to assigning a
value to a variable. Passing a variable to a function will move or copy, just
like assignment. Here’s an example, with some annotations showing where
variables go into and out of scope:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;); // s comes into scope.
takes_ownership(s); // s’s value moves into the function...
// ... and so is no longer valid here.
let x = 5; // x comes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so it’s okay to still
// use x afterward.
} // Here, x goes out of scope, then s. But since s’s value was moved, nothing
// special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope.
println!(&quot;{}&quot;, some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope.
println!(&quot;{}&quot;, some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
</code></pre>
<p>If we tried to use <code>s</code> after the call to <code>takes_ownership</code>, Rust would throw a
compile-time error. These static checks protect us from mistakes. Try adding
code to <code>main</code> that uses <code>s</code> and <code>x</code> to see where you can use them and where
the ownership rules prevent you from doing so.</p>
<h3>Return Values and Scope</h3>
<p>Returning values can also transfer ownership. Here’s an example with similar
annotations:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1.
let s2 = String::from(&quot;hello&quot;); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3.
} // Here, s3 goes out of scope, and is dropped. s2 goes out of scope, but was
// moved, so nothing happens. s1 goes out of scope, and is dropped.
fn gives_ownership() -&gt; String { // gives_ownership will move its
// return value into the function
// that calls it.
let some_string = String::from(&quot;hello&quot;); // some_string comes into scope.
some_string // some_string is returned, and
// moves out to the calling
// function.
}
// takes_and_gives_back will both take a String and return one
fn takes_and_gives_back(a_string: String) -&gt; String { // a_string comes into scope
a_string // a_string is returned, and moves out to the calling function
}
</code></pre>
<p>It’s the same pattern, every time: assigning a value to another variable moves
it, and when heap data values’ variables go out of scope, if the data hasn’t
been moved to be owned by another variable, the value will be cleaned up by
<code>drop</code>.</p>
<p>Taking ownership then returning ownership with every function is a bit tedious.
What if we want to let a function use a value but not take ownership? It’s
quite annoying that anything we pass in also needs to be passed back if we want
to use it again, in addition to any data resulting from the body of the
function that we might want to return as well.</p>
<p>It is possible to return multiple values using a tuple, like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let (s2, len) = calculate_length(s1);
println!(&quot;The length of '{}' is {}.&quot;, s2, len);
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
</code></pre>
<p>But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for this concept: references.</p>
<h2>References and Borrowing</h2>
<p>The issue with the tuple code at the end of the last section is that we have to
return the <code>String</code> back to the calling function so that we can still use the
<code>String</code> after the call to <code>calculate_length</code>, since the <code>String</code> was moved
into <code>calculate_length</code>.</p>
<p>Here is how you would define and use a <code>calculate_length</code> function that takes a
<em>reference</em> to an object as an argument instead of taking ownership of the
argument:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let len = calculate_length(&amp;s1);
println!(&quot;The length of '{}' is {}.&quot;, s1, len);
}
fn calculate_length(s: &amp;String) -&gt; usize {
s.len()
}
</code></pre>
<p>First, you’ll notice all of the tuple stuff in the variable declaration and the
function return value is gone. Next, note that we pass <code>&amp;s1</code> into
<code>calculate_length</code>, and in its definition, we take <code>&amp;String</code> rather than
<code>String</code>.</p>
<p>These <code>&amp;</code>s are <em>references</em>, and they allow you to refer to some value without
taking ownership of it. Figure 4-5 shows a diagram of this.</p>
<figure>
<img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" />
<figcaption>
<p>Figure 4-5: <code>&amp;String s</code> pointing at <code>String s1</code></p>
</figcaption>
</figure>
<p>Let’s take a closer look at the function call here:</p>
<pre><code class="language-rust"># fn calculate_length(s: &amp;String) -&gt; usize {
# s.len()
# }
let s1 = String::from(&quot;hello&quot;);
let len = calculate_length(&amp;s1);
</code></pre>
<p>The <code>&amp;s1</code> syntax lets us create a reference which <em>refers</em> to the value of <code>s1</code>
but does not own it. Because it does not own it, the value it points to will
not be dropped when the reference goes out of scope.</p>
<p>Likewise, the signature of the function uses <code>&amp;</code> to indicate that it takes a
reference as an argument. Let’s add some explanatory annotations:</p>
<pre><code class="language-rust">fn calculate_length(s: &amp;String) -&gt; usize { // s is a reference to a String
s.len()
} // Here, s goes out of scope. But since it does not have ownership of what
// it refers to, nothing happens.
</code></pre>
<p>It’s the same process as before, but we don’t drop what the reference points to
when it goes out of scope because we don’t have ownership. This lets us write
functions which take references as arguments instead of the values themselves,
so that we won’t need to return them to give back ownership.</p>
<p>We call this process <em>borrowing</em>. Just like with real life, if a person owns
something, you can borrow it from them, and when you’re done, you have to give
it back.</p>
<p>So what happens if we try to modify something we’re borrowing? Try this code
out. Spoiler alert: it doesn’t work!</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let s = String::from(&quot;hello&quot;);
change(&amp;s);
}
fn change(some_string: &amp;String) {
some_string.push_str(&quot;, world&quot;);
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error: cannot borrow immutable borrowed content `*some_string` as mutable
--&gt; error.rs:8:5
|
8 | some_string.push_str(&quot;, world&quot;);
| ^^^^^^^^^^^
</code></pre>
<p>Just as variables are immutable by default, so are references. We’re not allowed
to modify something we have a reference to.</p>
<h3>Mutable References</h3>
<p>We can fix this error with just a small tweak:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let mut s = String::from(&quot;hello&quot;);
change(&amp;mut s);
}
fn change(some_string: &amp;mut String) {
some_string.push_str(&quot;, world&quot;);
}
</code></pre>
<p>First, we had to change <code>s</code> to be <code>mut</code>. Then we had to create a mutable
reference with <code>&amp;mut s</code> and accept a mutable reference with <code>some_string: &amp;mut String</code>.</p>
<p>Mutable references have one big restriction, though: you can only have one
mutable reference to a particular piece of data in a particular scope. This
code will fail:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">let mut s = String::from(&quot;hello&quot;);
let r1 = &amp;mut s;
let r2 = &amp;mut s;
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error[E0499]: cannot borrow `s` as mutable more than once at a time
--&gt; borrow_twice.rs:5:19
|
4 | let r1 = &amp;mut s;
| - first mutable borrow occurs here
5 | let r2 = &amp;mut s;
| ^ second mutable borrow occurs here
6 | }
| - first borrow ends here
</code></pre>
<p>This restriction allows for mutation but in a very controlled fashion. It is
something that new Rustaceans struggle with, because most languages let you
mutate whenever you’d like. The benefit of having this restriction is that Rust
can prevent data races at compile time.</p>
<p>A <em>data race</em> is a particular type of race condition where these three things
occur:</p>
<ol>
<li>Two or more pointers access the same data at the same time</li>
<li>At least one of the pointers is being used to write to the data</li>
<li>There’s no mechanism being used to synchronize access to the data</li>
</ol>
<p>Data races cause undefined behavior and can be difficult to diagnose and fix
when trying to track them down at runtime; Rust prevents this problem from
happening since it won’t even compile code with data races!</p>
<p>As always, we can use <code>{}</code>s to create a new scope, allowing for multiple
mutable references, just not <em>simultaneous</em> ones:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
{
let r1 = &amp;mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &amp;mut s;
</code></pre>
<p>There is a similar rule for combining mutable and immutable references. This
code errors:</p>
<pre><code class="language-rust,ignore">let mut s = String::from(&quot;hello&quot;);
let r1 = &amp;s; // no problem
let r2 = &amp;s; // no problem
let r3 = &amp;mut s; // BIG PROBLEM
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--&gt; borrow_thrice.rs:6:19
|
4 | let r1 = &amp;s; // no problem
| - immutable borrow occurs here
5 | let r2 = &amp;s; // no problem
6 | let r3 = &amp;mut s; // BIG PROBLEM
| ^ mutable borrow occurs here
7 | }
| - immutable borrow ends here
</code></pre>
<p>Whew! We <em>also</em> cannot have a mutable reference while we have an immutable one.
Users of an immutable reference don’t expect the values to suddenly change out
from under them! Multiple immutable references are okay, however, since no one
who is just reading the data has the ability to affect anyone else’s reading of
the data.</p>
<p>Even though these errors may be frustrating at times, remember that it’s the
Rust compiler pointing out a potential bug earlier (at compile time rather than
at runtime) and showing you exactly where the problem is instead of you having
to track down why sometimes your data isn’t what you thought it should be.</p>
<h3>Dangling References</h3>
<p>In languages with pointers, it’s easy to make the error of creating a <em>dangling
pointer</em>, a pointer referencing a location in memory that may have been given
to someone else, by freeing some memory while keeping around a pointer to that
memory. In Rust, by contrast, the compiler guarantees that references will
never be dangling: if we have a reference to some data, the compiler will
ensure that the data will not go out of scope before the reference to the data
does.</p>
<p>Let’s try to create a dangling reference:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -&gt; &amp;String {
let s = String::from(&quot;hello&quot;);
&amp;s
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error[E0106]: missing lifetime specifier
--&gt; dangle.rs:5:16
|
5 | fn dangle() -&gt; &amp;String {
| ^^^^^^^
|
= help: this function's return type contains a borrowed value, but there is no
value for it to be borrowed from
= help: consider giving it a 'static lifetime
error: aborting due to previous error
</code></pre>
<p>This error message refers to a feature we haven’t learned about yet:
<em>lifetimes</em>. We’ll discuss lifetimes in detail in Chapter 10, but, disregarding
the parts about lifetimes, the message does contain the key to why this code is
a problem:</p>
<pre><code class="language-text">this function's return type contains a borrowed value, but there is no value
for it to be borrowed from.
</code></pre>
<p>Let’s have a closer look at exactly what’s happening at each stage of our
<code>dangle</code> code:</p>
<pre><code class="language-rust,ignore">fn dangle() -&gt; &amp;String { // dangle returns a reference to a String
let s = String::from(&quot;hello&quot;); // s is a new String
&amp;s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
// Danger!
</code></pre>
<p>Because <code>s</code> is created inside of <code>dangle</code>, when the code of <code>dangle</code> is
finished, it will be deallocated. But we tried to return a reference to it.
That means this reference would be pointing to an invalid <code>String</code>! That’s no
good. Rust won’t let us do this.</p>
<p>The correct code here is to return the <code>String</code> directly:</p>
<pre><code class="language-rust">fn no_dangle() -&gt; String {
let s = String::from(&quot;hello&quot;);
s
}
</code></pre>
<p>This works, no problem. Ownership is moved out, nothing is deallocated.</p>
<h3>The Rules of References</h3>
<p>Here’s a recap of what we’ve talked about:</p>
<ol>
<li>At any given time, you may have <em>either</em>, but not both of:
<ol>
<li>One mutable reference.</li>
<li>Any number of immutable references.</li>
</ol>
</li>
<li>References must always be valid.</li>
</ol>
<p>Next, let’s look at a different kind of reference: slices.</p>
<h2>Slices</h2>
<p>There is another data type which does not have ownership: slices. Slices let
you reference a contiguous sequence of elements in a collection rather than the
whole collection itself.</p>
<p>Here’s a small programming problem: write a function which takes a string and
returns the first word it finds in that string. If it doesn’t find a space in
the string, it means the whole string is one word, so the whole thing should be
returned.</p>
<p>Let’s think about the signature of this function:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; ?
</code></pre>
<p>This function, <code>first_word</code>, takes a <code>&amp;String</code> as an argument. We don’t want
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about <em>part</em> of a string. We could return the index of the end of
the word, though. Let’s try that:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; usize {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
</code></pre>
<p>Let’s break that down a bit:</p>
<pre><code class="language-rust,ignore">let bytes = s.as_bytes();
</code></pre>
<p>Since we need to go through the String element by element and check if a value
is a space, we will convert our String to an array of bytes using the
<code>as_bytes</code> method.</p>
<pre><code class="language-rust,ignore">for (i, &amp;item) in bytes.iter().enumerate() {
</code></pre>
<p>We will be discussing iterators in more detail in Chapter 16, but for now, know
that <code>iter</code> is a method that returns each element in a collection, and
<code>enumerate</code> wraps the result of <code>iter</code> and returns each element as part of a
tuple instead, where the first element of the tuple is the index, and the
second element is a reference to the element itself. This is a bit nicer than
calculating the index ourselves.</p>
<p>Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we
match against the tuple with <code>i</code> for the index and <code>&amp;item</code> for a single byte.
Since we get a reference from <code>.iter().enumerate()</code>, we use <code>&amp;</code> in the pattern.</p>
<pre><code class="language-rust,ignore"> if item == b' ' {
return i;
}
}
s.len()
</code></pre>
<p>We search for the byte that represents the space, using the byte literal
syntax. If we find a space, we return the position. Otherwise, we return the
length of the string, using <code>s.len()</code>.</p>
<p>We now have a way to find out the index of the end of the first word in the
string, but there’s a problem. We’re returning a <code>usize</code> on its own, but it’s
only a meaningful number in the context of the <code>&amp;String</code>. In other words,
because it’s a separate value from the <code>String</code>, there’s no guarantee that it
will still be valid in the future. Consider this program that uses this
<code>first_word</code> function:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust"># fn first_word(s: &amp;String) -&gt; usize {
# let bytes = s.as_bytes();
#
# for (i, &amp;item) in bytes.iter().enumerate() {
# if item == b' ' {
# return i;
# }
# }
#
# s.len()
# }
#
fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s); // word will get the value 5.
s.clear(); // This empties the String, making it equal to &quot;&quot;.
// word still has the value 5 here, but there’s no more string that
// we could meaningfully use the value 5 with. word is now totally invalid!
}
</code></pre>
<p>This program compiles without any errors, and also would if we used <code>word</code>
after calling <code>s.clear()</code>. <code>word</code> isn’t connected to the state of <code>s</code> at all,
so <code>word</code> still contains the value <code>5</code>. We could use that value <code>5</code> with the
variable <code>s</code> to try to extract the first word out, but this would be a bug
since the contents of <code>s</code> have changed since we saved <code>5</code> in <code>word</code>.</p>
<p>This is bad! It’s even worse if we wanted to write a <code>second_word</code> function.
Its signature would have to look like this:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; (usize, usize) {
</code></pre>
<p>Now we’re tracking both a start <em>and</em> an ending index, and we have even more
values that were calculated from data in a particular state but aren’t tied to
that state at all. We now have three unrelated variables floating around which
need to be kept in sync.</p>
<p>Luckily, Rust has a solution to this problem: string slices.</p>
<h3>String Slices</h3>
<p>A string slice is a reference to part of a <code>String</code>, and looks like this:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello world&quot;);
let hello = &amp;s[0..5];
let world = &amp;s[6..11];
</code></pre>
<p>This is similar to taking a reference to the whole <code>String</code>, but with the extra
<code>[0..5]</code> bit. Rather than a reference to the entire <code>String</code>, it’s a reference
to an internal position in the <code>String</code> and the number of elements that it
refers to.</p>
<p>We create slices with a range of <code>[starting_index..ending_index]</code>, but the
slice data structure actually stores the starting position and the length of
the slice. So in the case of <code>let world = &amp;s[6..11];</code>, <code>world</code> would be a slice
that contains a pointer to the 6th byte of <code>s</code> and a length value of 5.</p>
<p>Figure 4-6 shows this in a diagram:</p>
<figure>
<img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-6: String slice referring to part of a <code>String</code></p>
</figcaption>
</figure>
<p>With Rust’s <code>..</code> range syntax, if you want to start at the first index (zero),
you can drop the value before the <code>..</code>. In other words, these are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let slice = &amp;s[0..2];
let slice = &amp;s[..2];
</code></pre>
<p>By the same token, if your slice should include the last byte of the <code>String</code>,
you can drop the trailing number. That means these are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let len = s.len();
let slice = &amp;s[3..len];
let slice = &amp;s[3..];
</code></pre>
<p>You can also drop both values to take a slice of the entire string. So these
are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let len = s.len();
let slice = &amp;s[0..len];
let slice = &amp;s[..];
</code></pre>
<p>With this in mind, let’s re-write <code>first_word</code> to return a slice. The type that
signifies “string slice” is written as <code>&amp;str</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return &amp;s[0..i];
}
}
&amp;s[..]
}
</code></pre>
<p>We get the index for the end of the word in the same way as before, by looking
for the first occurrence of a space. When we find a space, we return a string
slice using the start of the string and the index of the space as the starting
and ending indices.</p>
<p>Now when we call <code>first_word</code>, we get back a single value that is tied to the
underlying data. The value is made up of a reference to the starting point of
the slice and the number of elements in the slice.</p>
<p>Returning a slice would also work for a <code>second_word</code> function:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>We now have a straightforward API that’s much harder to mess up. Remember our
bug from before, when we got the first word but then cleared the string so that
our first word was invalid? That code was logically incorrect but didn’t show
any immediate errors. The problems would show up later, if we kept trying to
use the first word index with an emptied string. Slices make this bug
impossible, and let us know we have a problem with our code much sooner. Using
the slice version of <code>first_word</code> will throw a compile time error:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s);
s.clear(); // Error!
}
</code></pre>
<p>Here’s the compiler error:</p>
<pre><code class="language-text">17:6 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
s.clear(); // Error!
^
15:29 note: previous borrow of `s` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `s` until the borrow ends
let word = first_word(&amp;s);
^
18:2 note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>Remember from the borrowing rules that if we have an immutable reference to
something, we cannot also take a mutable reference. Since <code>clear</code> needs to
truncate the <code>String</code>, it tries to take a mutable reference, which fails. Not
only has Rust made our API easier to use, but it’s also eliminated an entire
class of errors at compile time!</p>
<h4>String Literals are Slices</h4>
<p>Remember how we talked about string literals being stored inside of the binary
itself? Now that we know about slices, we can now properly understand string
literals.</p>
<pre><code class="language-rust">let s = &quot;Hello, world!&quot;;
</code></pre>
<p>The type of <code>s</code> here is <code>&amp;str</code>: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; <code>&amp;str</code> is an
immutable reference.</p>
<h4>String Slices as Arguments</h4>
<p>Knowing that you can take slices of both literals and <code>String</code>s leads us to one
more improvement on <code>first_word</code>, and that’s its signature:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>A more experienced Rustacean would write this one instead because it allows us
to use the same function on both <code>String</code>s and <code>&amp;str</code>s:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>If we have a string slice, we can pass that as the argument directly. If we
have a <code>String</code>, we can pass a slice of the entire <code>String</code>. This makes our API
more general and useful without losing any functionality:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust"># fn first_word(s: &amp;str) -&gt; &amp;str {
# let bytes = s.as_bytes();
#
# for (i, &amp;item) in bytes.iter().enumerate() {
# if item == b' ' {
# return &amp;s[0..i];
# }
# }
#
# &amp;s[..]
# }
fn main() {
let my_string = String::from(&quot;hello world&quot;);
// first_word works on slices of `String`s
let word = first_word(&amp;my_string[..]);
let my_string_literal = &quot;hello world&quot;;
// first_word works on slices of string literals
let word = first_word(&amp;my_string_literal[..]);
// since string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
}
</code></pre>
<h3>Other Slices</h3>
<p>String slices, as you might imagine, are specific to strings. But there’s a
more general slice type, too. Consider this array:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
</code></pre>
<p>Just like we may want to refer to a part of a string, we may want to refer to
part of an array, and would do so like this:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
let slice = &amp;a[1..3];
</code></pre>
<p>This slice has the type <code>&amp;[i32]</code>. It works the exact same way as string slices
do, by storing a reference to the first element and a length. You’ll use this
kind of slice for all sorts of other collections. We’ll discuss these in detail
when we talk about vectors in Chapter 8.</p>
<h2>Summary</h2>
<p>The concepts of ownership, borrowing, and slices are what ensure memory safety
in Rust programs at compile time. Rust is a language that gives you control
over your memory usage like other systems programming languages, but having the
owner of data automatically clean up that data when the owner goes out of scope
means you don’t have to write and debug extra code to get this control.</p>
<p>Ownership affects how lots of other parts of Rust work, so we will be talking
about these concepts further throughout the rest of the book. Let’s move on to
the next chapter where we’ll look at grouping pieces of data together in a
<code>struct</code>.</p>
<h1>Structs</h1>
<p>A <code>struct</code>, short for <em>structure</em>, is a custom data type that lets us name and
package together multiple related values that make up a meaningful group. If
you come from an object-oriented language, a <code>struct</code> is like an object’s data
attributes. In the next section of this chapter, we’ll talk about how to define
methods on our structs; methods are how you specify the <em>behavior</em> that goes
along with a struct’s data. The <code>struct</code> and <code>enum</code> (that we will talk about in
Chapter 6) concepts are the building blocks for creating new types in your
program’s domain in order to take full advantage of Rust’s compile-time type
checking.</p>
<p>One way of thinking about structs is that they are similar to tuples, which we
talked about in Chapter 3. Like tuples, the pieces of a struct can be different
types. Unlike tuples, we name each piece of data so that it’s clearer what the
values mean. Structs are more flexible as a result of these names: we don’t
have to rely on the order of the data to specify or access the values of an
instance.</p>
<p>To define a struct, we enter the keyword <code>struct</code> and give the whole struct a
name. A struct’s name should describe what the significance is of these pieces
of data being grouped together. Then, inside curly braces, we define the names
of the pieces of data, which we call <em>fields</em>, and specify each field’s type.
For example, Listing 5-1 shows a struct to store information about a user
account:</p>
<figure>
<pre><code class="language-rust">struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
</code></pre>
<figcaption>
<p>Listing 5-1: A <code>User</code> struct definition</p>
</figcaption>
</figure>
<p>To use a struct once we've defined it, we create an <em>instance</em> of that struct
by specifying concrete values for each of the fields. Creating an instance is
done by stating the name of the struct, then curly braces with <code>key: value</code>
pairs inside it where the keys are the names of the fields and the values are
the data we want to store in those fields. The fields don’t have to be
specified in the same order in which the struct declared them. In other words,
the struct definition is like a general template for the type, and instances
fill in that template with particular data to create values of the type. For
example, we can declare a particular user like this:</p>
<pre><code class="language-rust"># struct User {
# username: String,
# email: String,
# sign_in_count: u64,
# active: bool,
# }
#
let user1 = User {
email: String::from(&quot;someone@example.com&quot;),
username: String::from(&quot;someusername123&quot;),
active: true,
sign_in_count: 1,
};
</code></pre>
<p>To get a particular value out of a struct, we can use dot notation. If we
wanted just this user’s email address, we can say <code>user1.email</code>.</p>
<h2>Ownership of Struct Data</h2>
<p>In the <code>User</code> struct definition in Listing 5-1, we used the owned <code>String</code> type
rather than the <code>&amp;str</code> string slice type. This is a deliberate choice because
we want instances of this struct to own all of its data, and for that data to
be valid for as long as the entire struct is valid.</p>
<p>It is possible for structs to store references to data owned by something else,
but to do so requires the use of <em>lifetimes</em>, a feature of Rust that we'll
discuss in Chapter 10. Lifetimes ensure that the data a struct references is
valid for as long as the struct is. If you try to store a reference in a struct
without specifying lifetimes, like this:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">struct User {
username: &amp;str,
email: &amp;str,
sign_in_count: u64,
active: bool,
}
fn main() {
let user1 = User {
email: &quot;someone@example.com&quot;,
username: &quot;someusername123&quot;,
active: true,
sign_in_count: 1,
};
}
</code></pre>
<p>The compiler will complain that it needs lifetime specifiers:</p>
<pre><code class="language-text">error[E0106]: missing lifetime specifier
--&gt;
|
2 | username: &amp;str,
| ^ expected lifetime parameter
error[E0106]: missing lifetime specifier
--&gt;
|
3 | email: &amp;str,
| ^ expected lifetime parameter
</code></pre>
<p>We will talk about how to fix these errors in order to store references in
structs in Chapter 10, but for now, fix errors like these by switching to owned
types like <code>String</code> instead of references like <code>&amp;str</code>.</p>
<h2>An Example Program</h2>
<p>To understand when we might want to use structs, let’s write a program that
calculates the area of a rectangle. We’ll start off with single variables, then
refactor our program until we’re using structs instead.</p>
<p>Let’s make a new binary project with Cargo called <em>rectangles</em> that will take
the length and width of a rectangle specified in pixels and will calculate the
area of the rectangle. Listing 5-2 has a short program with one way of doing
just that in our project’s <em>src/main.rs</em>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let length1 = 50;
let width1 = 30;
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(length1, width1)
);
}
fn area(length: u32, width: u32) -&gt; u32 {
length * width
}
</code></pre>
<figcaption>
<p>Listing 5-2: Calculating the area of a rectangle specified by its length and
width in separate variables</p>
</figcaption>
</figure>
<p>Let’s try running this program with <code>cargo run</code>:</p>
<pre><code class="language-text">The area of the rectangle is 1500 square pixels.
</code></pre>
<h3>Refactoring with Tuples</h3>
<p>Our little program works okay; it figures out the area of the rectangle by
calling the <code>area</code> function with each dimension. But we can do better. The
length and the width are related to each other since together they describe one
rectangle.</p>
<p>The issue with this method is evident in the signature of <code>area</code>:</p>
<pre><code class="language-rust,ignore">fn area(length: u32, width: u32) -&gt; u32 {
</code></pre>
<p>The <code>area</code> function is supposed to calculate the area of one rectangle, but our
function takes two arguments. The arguments are related, but that’s not
expressed anywhere in our program itself. It would be more readable and more
manageable to group length and width together.</p>
<p>We’ve already discussed one way we might do that in Chapter 3: tuples. Listing
5-3 has a version of our program which uses tuples:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let rect1 = (50, 30);
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(rect1)
);
}
fn area(dimensions: (u32, u32)) -&gt; u32 {
dimensions.0 * dimensions.1
}
</code></pre>
<figcaption>
<p>Listing 5-3: Specifying the length and width of the rectangle with a tuple</p>
</figcaption>
</figure>
<!-- I will add ghosting & wingdings once we're in libreoffice /Carol -->
<p>In one way, this is a little better. Tuples let us add a bit of structure, and
we’re now passing just one argument. But in another way this method less clear:
tuples don’t give names to their elements, so our calculation has gotten more
confusing because we have to index into the parts of the tuple:</p>
<!-- I will change this to use wingdings instead of repeating this code once
we're in libreoffice /Carol -->
<pre><code class="language-rust,ignore">dimensions.0 * dimensions.1
</code></pre>
<p>It doesn’t matter if we mix up length and width for the area calculation, but
if we were to draw the rectangle on the screen it would matter! We would have
to remember that <code>length</code> was the tuple index <code>0</code> and <code>width</code> was the tuple
index <code>1</code>. If someone else was to work on this code, they would have to figure
this out and remember it as well. It would be easy to forget or mix these
values up and cause errors, since we haven’t conveyed the meaning of our data
in our code.</p>
<h3>Refactoring with Structs: Adding More Meaning</h3>
<p>Here is where we bring in structs. We can transform our tuple into a data type
with a name for the whole as well as names for the parts, as shown in Listing
5-4:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(&amp;rect1)
);
}
fn area(rectangle: &amp;Rectangle) -&gt; u32 {
rectangle.length * rectangle.width
}
</code></pre>
<figcaption>
<p>Listing 5-4: Defining a <code>Rectangle</code> struct</p>
</figcaption>
</figure>
<!-- Will add ghosting & wingdings once we're in libreoffice /Carol -->
<p>Here we’ve defined a struct and given it the name <code>Rectangle</code>. Inside the <code>{}</code>
we defined the fields to be <code>length</code> and <code>width</code>, both of which have type
<code>u32</code>. Then in <code>main</code>, we create a particular instance of a <code>Rectangle</code> that
has a length of 50 and a width of 30.</p>
<p>Our <code>area</code> function now takes one argument that we’ve named <code>rectangle</code> whose
type is an immutable borrow of a struct <code>Rectangle</code> instance. As we covered in
Chapter 4, we want to borrow the struct rather than take ownership of it so
that <code>main</code> keeps its ownership and can continue using <code>rect1</code>, so that’s why
we have the <code>&amp;</code> in the function signature and at the call site.</p>
<p>The <code>area</code> function accesses the <code>length</code> and <code>width</code> fields of the <code>Rectangle</code>
instance it got as an argument. Our function signature for <code>area</code> now says
exactly what we mean: calculate the area of a <code>Rectangle</code>, using its <code>length</code>
and <code>width</code> fields. This conveys that the length and width are related to each
other, and gives descriptive names to the values rather than using the tuple
index values of <code>0</code> and <code>1</code>. This is a win for clarity.</p>
<h3>Adding Useful Functionality with Derived Traits</h3>
<p>It’d be nice to be able to print out an instance of our <code>Rectangle</code> while we’re
debugging our program and see the values for all its fields. Listing 5-5 tries
using the <code>println!</code> macro as we have been:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(&quot;rect1 is {}&quot;, rect1);
}
</code></pre>
<figcaption>
<p>Listing 5-5: Attempting to print a <code>Rectangle</code> instance</p>
</figcaption>
</figure>
<p>If we run this, we get an error with this core message:</p>
<pre><code class="language-text">error[E0277]: the trait bound `Rectangle: std::fmt::Display` is not satisfied
</code></pre>
<p>The <code>println!</code> macro can do many kinds of formatting, and by default, <code>{}</code>
tells <code>println!</code> to use formatting known as <code>Display</code>: output intended for
direct end-user consumption. The primitive types we’ve seen so far implement
<code>Display</code> by default, as there’s only one way you’d want to show a <code>1</code> or any
other primitive type to a user. But with structs, the way <code>println!</code> should
format the output is less clear as there are more display possibilities: Do you
want commas or not? Do you want to print the struct <code>{}</code>s? Should all the
fields be shown? Because of this ambiguity, Rust doesn’t try to guess what we
want and structs do not have a provided implementation of <code>Display</code>.</p>
<p>If we keep reading the errors, though, we’ll find this helpful note:</p>
<pre><code class="language-text">note: `Rectangle` cannot be formatted with the default formatter; try using
`:?` instead if you are using a format string
</code></pre>
<p>Let’s try it! The <code>println!</code> will now look like
<code>println!(&quot;rect1 is {:?}&quot;, rect1);</code>. Putting the specifier <code>:?</code> inside
the <code>{}</code> tells <code>println!</code> we want to use an output format called <code>Debug</code>.
<code>Debug</code> is a trait that enables us to print out our struct in a way that is
useful for developers so that we can see its value while we are debugging our
code.</p>
<p>Let’s try running with this change and… drat. We still get an error:</p>
<pre><code class="language-text">error: the trait bound `Rectangle: std::fmt::Debug` is not satisfied
</code></pre>
<p>Again, though, the compiler has given us a helpful note!</p>
<pre><code class="language-text">note: `Rectangle` cannot be formatted using `:?`; if it is defined in your
crate, add `#[derive(Debug)]` or manually implement it
</code></pre>
<p>Rust <em>does</em> include functionality to print out debugging information, but we
have to explicitly opt-in to having that functionality be available for our
struct. To do that, we add the annotation <code>#[derive(Debug)]</code> just before our
struct definition, as shown in Listing 5-6:</p>
<figure>
<pre><code class="language-rust">#[derive(Debug)]
struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(&quot;rect1 is {:?}&quot;, rect1);
}
</code></pre>
<figcaption>
<p>Listing 5-6: Adding the annotation to derive the <code>Debug</code> trait and printing the
<code>Rectangle</code> instance using debug formatting</p>
</figcaption>
</figure>
<p>At this point, if we run this program, we won’t get any errors and we’ll see
the following output:</p>
<pre><code class="language-text">rect1 is Rectangle { length: 50, width: 30 }
</code></pre>
<p>Nice! It’s not the prettiest output, but it shows the values of all the fields
for this instance, which would definitely help during debugging. If we want
output that is a bit prettier and easier to read, which can be helpful with
larger structs, we can use <code>{:#?}</code> in place of <code>{:?}</code> in the <code>println!</code> string.
If we use the pretty debug style in this example, the output will look like:</p>
<pre><code class="language-text">rect1 is Rectangle {
length: 50,
width: 30
}
</code></pre>
<p>There are a number of traits Rust has provided for us to use with the <code>derive</code>
annotation that can add useful behavior to our custom types. Those traits and
their behaviors are listed in Appendix C. We’ll be covering how to implement
these traits with custom behavior, as well as creating your own traits, in
Chapter 10.</p>
<p>Our <code>area</code> function is pretty specific—it only computes the area of rectangles.
It would be nice to tie this behavior together more closely with our
<code>Rectangle</code> struct, since it’s behavior that our <code>Rectangle</code> type has
specifically. Let’s now look at how we can continue to refactor this code by
turning the <code>area</code> function into an <code>area</code> <em>method</em> defined on our <code>Rectangle</code>
type.</p>
<h2>Method Syntax</h2>
<p><em>Methods</em> are similar to functions: they’re declared with the <code>fn</code> keyword and
their name, they can take arguments and return values, and they contain some
code that gets run when they’re called from somewhere else. Methods are
different from functions, however, because they’re defined within the context
of a struct (or an enum or a trait object, which we will cover in Chapters 6
and 13, respectively), and their first argument is always <code>self</code>, which
represents the instance of the struct that the method is being called on.</p>
<h3>Defining Methods</h3>
<p>Let’s change our <code>area</code> function that takes a <code>Rectangle</code> instance as an
argument and instead make an <code>area</code> method defined on the <code>Rectangle</code> struct,
as shown in Listing 5-7:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">#[derive(Debug)]
struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.length * self.width
}
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
rect1.area()
);
}
</code></pre>
<figcaption>
<p>Listing 5-7: Defining an <code>area</code> method on the <code>Rectangle</code> struct</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings here in libreoffice /Carol -->
<p>In order to make the function be defined within the context of <code>Rectangle</code>, we
start an <code>impl</code> block (<code>impl</code> is short for <em>implementation</em>). Then we move the
function within the <code>impl</code> curly braces, and change the first (and in this
case, only) argument to be <code>self</code> in the signature and everywhere within the
body. Then in <code>main</code> where we called the <code>area</code> function and passed <code>rect1</code> as
an argument, we can instead use <em>method syntax</em> to call the <code>area</code> method on
our <code>Rectangle</code> instance. Method syntax is taking an instance and adding a dot
followed by the method name, parentheses, and any arguments.</p>
<p>In the signature for <code>area</code>, we get to use <code>&amp;self</code> instead of <code>rectangle: &amp;Rectangle</code> because Rust knows the type of <code>self</code> is <code>Rectangle</code> due to this
method being inside the <code>impl Rectangle</code> context. Note we still need to have
the <code>&amp;</code> before <code>self</code>, just like we had <code>&amp;Rectangle</code>. Methods can choose to
take ownership of <code>self</code>, borrow <code>self</code> immutably as we’ve done here, or borrow
<code>self</code> mutably, just like any other argument.</p>
<p>We’ve chosen <code>&amp;self</code> here for the same reason we used <code>&amp;Rectangle</code> in the
function version: we don’t want to take ownership, and we just want to be able
to read the data in the struct, not write to it. If we wanted to be able to
change the instance that we’ve called the method on as part of what the method
does, we’d put <code>&amp;mut self</code> as the first argument instead. Having a method that
takes ownership of the instance by having just <code>self</code> as the first argument is
rarer; this is usually used when the method transforms <code>self</code> into something
else and we want to prevent the caller from using the original instance after
the transformation.</p>
<p>The main benefit of using methods over functions, in addition to getting to use
method syntax and not having to repeat the type of <code>self</code> in every method’s
signature, is for organization. We’ve put all the things we can do with an
instance of a type together in one <code>impl</code> block, rather than make future users
of our code search for capabilities of <code>Rectangle</code> all over the place.</p>
<!-- PROD: START BOX -->
<blockquote>
<h3>Where’s the <code>-&gt;</code> operator?</h3>
<p>In languages like C++, there are two different operators for calling methods:
<code>.</code> if you’re calling a method on the object directly, and <code>-&gt;</code> if you’re
calling the method on a pointer to the object and thus need to dereference the
pointer first. In other words, if <code>object</code> is a pointer, <code>object-&gt;something()</code>
is like <code>(*object).something()</code>.</p>
<p>Rust doesn’t have an equivalent to the <code>-&gt;</code> operator; instead, Rust has a
feature called <em>automatic referencing and dereferencing</em>. Calling methods is
one of the few places in Rust that has behavior like this.</p>
<p>Here’s how it works: when you call a method with <code>object.something()</code>, Rust
will automatically add in <code>&amp;</code>, <code>&amp;mut</code>, or <code>*</code> so that <code>object</code> matches the
signature of the method. In other words, these are the same:</p>
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
# struct Point {
# x: f64,
# y: f64,
# }
#
# impl Point {
# fn distance(&amp;self, other: &amp;Point) -&gt; f64 {
# let x_squared = f64::powi(other.x - self.x, 2);
# let y_squared = f64::powi(other.y - self.y, 2);
#
# f64::sqrt(x_squared + y_squared)
# }
# }
# let p1 = Point { x: 0.0, y: 0.0 };
# let p2 = Point { x: 5.0, y: 6.5 };
p1.distance(&amp;p2);
(&amp;p1).distance(&amp;p2);
</code></pre>
<p>The first one looks much, much cleaner. This automatic referencing behavior
works because methods have a clear receiver — the type of <code>self</code>. Given the
receiver and name of a method, Rust can figure out definitively whether the
method is just reading (so needs <code>&amp;self</code>), mutating (so <code>&amp;mut self</code>), or
consuming (so <code>self</code>). The fact that Rust makes borrowing implicit for method
receivers is a big part of making ownership ergonomic in practice.</p>
</blockquote>
<!-- PROD: END BOX -->
<h3>Methods with More Arguments</h3>
<p>Let’s practice some more with methods by implementing a second method on our
<code>Rectangle</code> struct. This time, we’d like for an instance of <code>Rectangle</code> to take
another instance of <code>Rectangle</code> and return <code>true</code> if the second rectangle could
fit completely within <code>self</code> and <code>false</code> if it would not. That is, if we run
the code in Listing 5-8, once we've defined the <code>can_hold</code> method:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
let rect2 = Rectangle { length: 40, width: 10 };
let rect3 = Rectangle { length: 45, width: 60 };
println!(&quot;Can rect1 hold rect2? {}&quot;, rect1.can_hold(&amp;rect2));
println!(&quot;Can rect1 hold rect3? {}&quot;, rect1.can_hold(&amp;rect3));
}
</code></pre>
<figcaption>
<p>Listing 5-8: Demonstration of using the as-yet-unwritten <code>can_hold</code> method</p>
</figcaption>
</figure>
<p>We want to see this output, since both of <code>rect2</code>’s dimensions are smaller than
<code>rect1</code>’s, but <code>rect3</code> is wider than <code>rect1</code>:</p>
<pre><code class="language-text">Can rect1 hold rect2? true
Can rect1 hold rect3? false
</code></pre>
<p>We know we want to define a method, so it will be within the <code>impl Rectangle</code>
block. The method name will be <code>can_hold</code>, and it will take an immutable borrow
of another <code>Rectangle</code> as an argument. We can tell what the type of the
argument will be by looking at a call site: <code>rect1.can_hold(&amp;rect2)</code> passes in
<code>&amp;rect2</code>, which is an immutable borrow to <code>rect2</code>, an instance of <code>Rectangle</code>.
This makes sense, since we only need to read <code>rect2</code> (rather than write, which
would mean we’d need a mutable borrow) and we want <code>main</code> to keep ownership of
<code>rect2</code> so that we could use it again after calling this method. The return
value of <code>can_hold</code> will be a boolean, and the implementation will check to see
if <code>self</code>’s length and width are both greater than the length and width of the
other <code>Rectangle</code>, respectively. Let’s add this new method to the <code>impl</code> block
from Listing 5-7:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust"># #[derive(Debug)]
# struct Rectangle {
# length: u32,
# width: u32,
# }
#
impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.length * self.width
}
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.length &gt; other.length &amp;&amp; self.width &gt; other.width
}
}
</code></pre>
<!-- Will add ghosting here in libreoffice /Carol -->
<p>If we run this with the <code>main</code> from Listing 5-8, we will get our desired output!
Methods can take multiple arguments that we add to the signature after the
<code>self</code> parameter, and those arguments work just like arguments in functions do.</p>
<h3>Associated Functions</h3>
<p>One more useful feature of <code>impl</code> blocks: we’re allowed to define functions
within <code>impl</code> blocks that <em>don’t</em> take <code>self</code> as a parameter. These are called
<em>associated functions</em>, since they’re associated with the struct. They’re still
functions though, not methods, since they don’t have an instance of the struct
to work with. You’ve already used an associated function: <code>String::from</code>.</p>
<p>Associated functions are often used for constructors that will return a new
instance of the struct. For example, we could provide an associated function
that would take one dimension argument and use that as both length and width,
thus making it easier to create a square <code>Rectangle</code> rather than having to
specify the same value twice:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust"># #[derive(Debug)]
# struct Rectangle {
# length: u32,
# width: u32,
# }
#
impl Rectangle {
fn square(size: u32) -&gt; Rectangle {
Rectangle { length: size, width: size }
}
}
</code></pre>
<p>To call this associated function, we use the <code>::</code> syntax with the struct name:
<code>let sq = Rectange::square(3);</code>, for example. This function is namespaced by
the struct: the <code>::</code> syntax is used for both associated functions and
namespaces created by modules, which we’ll learn about in Chapter 7.</p>
<h2>Summary</h2>
<p>Structs let us create custom types that are meaningful for our domain. By using
structs, we can keep associated pieces of data connected to each other and name
each piece to make our code clear. Methods let us specify the behavior that
instances of our structs have, and associated functions let us namespace
functionality that is particular to our struct without having an instance
available.</p>
<p>Structs aren’t the only way we can create custom types, though; let’s turn to
the <code>enum</code> feature of Rust and add another tool to our toolbox.</p>
<!-- Hi Steve, Carol. I like this chapter, we're getting into some powerful
tools here! I saw that the copyeditor has suggested listing numbers, which I
think is a good idea. If you agree, could you suggest captions and add
numbering to those listings we reference again in the chapter? Also, if we are
going to include any of these in the source files can you add file names?
Thanks! /Liz -->
<!-- I added some listing numbers where the code examples were lengthy or
referred to again. I haven't added any file names-- the code in this chapter is
little snippets that would be useful in larger programs, but they could appear
anywhere and don't have to be in any particular file. /Carol -->
<h1>Enums</h1>
<p>In this chapter we'll look at <em>enumerations</em>, also referred to as <em>enums</em>.
Enums allow you to define a type by enumerating its possible values. First
we'll define and use an enum to show how an enum can encode meaning along with
data. Then we'll explore a particularly useful enum, <code>Option</code>, which expresses
that a value can be either something or nothing. Next we'll look at how pattern
matching in the <code>match</code> statement makes it easy to run different code for
different values of an enum. Finally, we'll cover how the <code>if let</code> construct is
another convenient and concise idiom you have available to handle enums in your
code.</p>
<p>Enums are a feature in many languages, but their capabilities differ
per-language. Rust’s enums are most similar to &quot;algebraic data types&quot; in
functional languages like F#, OCaml, or Haskell.</p>
<h2>Defining an Enum</h2>
<!-- I'm not sure what you meant by "looking inside it" when you said "I wasn't
clear throughout this section whether we were defining the IpAddrKind enum or
looking inside it", but I've tried to clarify. Please elaborate on what you
meant by that and why it's confusing if I haven't resolved the issue. /Carol -->
<p>Let's look at a situation we might want to express in code and see why enums
are useful and more appropriate than structs in this case. Say we need to work
with IP addresses. There are two major standards used for IP addresses today:
version four and version six. These are the only possibilities for an IP
address that our program will come across: we can <em>enumerate</em> all possible
values, which is where <em>enumeration</em> gets its name.</p>
<p>Any IP address can be either a version four or a version six address, but not
both at the same time. That property of IP addresses makes the enum data
structure appropriate for this case, since enum values can only be one of the
variants. Both version four and version six addresses are still fundamentally
IP addresses, though, so they should be treated as the same type when the code
is handling situations that apply to any kind of IP address.</p>
<p>We can express this concept in code by defining an <code>IpAddrKind</code> enumeration and
listing the possible kinds an IP address can be, <code>V4</code> and <code>V6</code>. These are known
as the <em>variants</em> of the enum:</p>
<pre><code class="language-rust">enum IpAddrKind {
V4,
V6,
}
</code></pre>
<p>This is now a custom data type that we can use elsewhere in our code.</p>
<h3>Enum Values</h3>
<!-- Liz: You seemed confused at this point about the differences between an
enum's definition, which includes its valid variants, and using the values of
the enum. You had changed this text to be:
<p>&quot;Enum variants can optionally have associated values. We can create values of
<code>IpAddrKind</code> like this:&quot;</p>
<p>While it's strictly true that enum values are &quot;optional&quot;, there wouldn't be any
point in defining the enum unless you were going to use values of that type.
Also, &quot;associated&quot; has other meanings in Rust that we don't want to conflate
with.</p>
<p>We've tried to clear up the confusion here by relating enum definition and
instantiation to struct definition and instantiation, assuming the reader
understands structs at this point. We're having trouble figuring out just the
right wording here, though, so we have two options for you. Please let us
know which is clearest, or a combination of the two, or if you have any
suggestions in a totally different direction! /Carol --&gt;</p>
<!-- Option 1: -->
An `enum` definition is similar to a `struct` definition: it defines a new type
and a template of what instances of that new type will be like. When you want to
use a struct, you create an instance of the struct. When you want to use an
enum, you use an instance of the enum that is one of the variants the enum
allows.
<!-- Option 2: -->
When you want to use a struct, you create an instance of the *struct* itself.
When you want to use an enum, you create an instance of one of its *variants*.
Each variant is defined like a struct, and you instantiate both using the same
syntax.
<!-- end options -->
<p>We can create instances of each of the two variants of <code>IpAddrKind</code> like this:</p>
<pre><code class="language-rust"># enum IpAddrKind {
# V4,
# V6,
# }
#
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;
</code></pre>
<p>Note that the variants of the enum are namespaced under its identifier, and we
use the double colon to separate the two. The reason this is useful is that now
both values <code>IpAddrKind::V4</code> and <code>IpAddrKind::V6</code> are of the same type:
<code>IpAddrKind</code>. We can then, for instance, define a function that takes any
<code>IpAddrKind</code> as an argument:</p>
<pre><code class="language-rust"># enum IpAddrKind {
# V4,
# V6,
# }
#
fn route(ip_type: IpAddrKind) { }
</code></pre>
<p>And we can call this function with either variant:</p>
<pre><code class="language-rust"># enum IpAddrKind {
# V4,
# V6,
# }
#
# fn route(ip_type: IpAddrKind) { }
#
route(IpAddrKind::V4);
route(IpAddrKind::V6);
</code></pre>
<p>Enums have more tricks up their sleeves, too. Thinking more about our IP
address type, at the moment we don’t have a way to store the actual <em>data</em> of
the IP address; we only know what <em>kind</em> it is. Given that you just learned
about structs, you might tackle this problem as in Listing 6-1:</p>
<figure>
<pre><code class="language-rust">enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from(&quot;127.0.0.1&quot;),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from(&quot;::1&quot;),
};
</code></pre>
<figcaption>
<p>Listing 6-1: Storing the data and type of an IP address using a <code>struct</code></p>
</figcaption>
</figure>
<!-- I will add wingdings here in libreoffice /Carol -->
<p>Here, we've defined a struct <code>IpAddr</code> that has two fields: a <code>kind</code> field that
is of type <code>IpAddrKind</code> (the enum we defined previously), and an <code>address</code>
field of type <code>String</code>. We have two instances of this struct. The first,
<code>home</code>, has the value <code>IpAddrKind::V4</code> as its <code>kind</code>, with associated address
data of <code>127.0.0.1</code>. The second instance, <code>loopback</code>, has the other variant of
<code>IpAddrKind</code> as its <code>kind</code> value, <code>V6</code>, and has address <code>::1</code> associated with
it. We’ve used a struct to bundle the <code>kind</code> and <code>address</code> values together, so
that now the kind is associated with the value itself.</p>
<p>We can represent the same concept in a more concise way using just an enum
rather than an enum as part of a struct by putting data directly into each enum
variant. This new definition of the <code>IpAddr</code> enum says that both <code>V4</code> and <code>V6</code>
variants will have associated <code>String</code> values:</p>
<pre><code class="language-rust">enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from(&quot;127.0.0.1&quot;));
let loopback = IpAddr::V6(String::from(&quot;::1&quot;));
</code></pre>
<p>We attach data to each variant of the enum directly, no need for an extra
struct.</p>
<p>There's another advantage to using an enum over a struct: each variant can
store <em>different kinds</em> of data. Version four type IP addresses will always
have four numeric components that will have values between 0 and 255. If we
wanted to store <code>V4</code> addresses as four <code>u8</code>s but still express <code>V6</code> addresses
as <code>String</code>s, we wouldn't be able to with a <code>struct</code>. Enums handle this case
with ease:</p>
<pre><code class="language-rust">enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from(&quot;::1&quot;));
</code></pre>
<p>We've been showing a bunch of different possibilities that we could define in
our code for storing IP addresses of the two different kinds using an enum. It
turns out, though, that wanting to store IP addresses and encode which kind
they are is so common that <a href="../std/net/enum.IpAddr.html">the standard library has a definition we can
use!</a><!-- ignore --> Let's look at how the standard libary defines
<code>IpAddr</code>: it has the exact enum and variants that we've defined and used, but
it chose to embed the address data inside the variants in the form of two
different structs, which are defined differently for each variant:</p>
<pre><code class="language-rust">struct Ipv4Addr {
// details elided
}
struct Ipv6Addr {
// details elided
}
enum IpAddr {
V4(Ipv4Addr),
V6(Ipv6Addr),
}
</code></pre>
<p>This illustrates you can put any kind of data inside of an enum variant:
strings, numeric types, structs, and you could even include another enum! Also,
standard library types are often not much more complicated than what you might
come up with.</p>
<p>Note that even though the standard library contains a definition for <code>IpAddr</code>,
we can still choose to create and use our own definition without conflict since
we haven't brought the standard library's definition into our scope. We'll talk
more about importing types in Chapter 7.</p>
<p>Let's look at another example: here’s an enum with a wide variety of types
embedded in its variants:</p>
<pre><code class="language-rust">enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
</code></pre>
<p>This enum has four variants with different types:</p>
<ul>
<li><code>Quit</code> has no data associated with it at all.</li>
<li><code>Move</code> includes an anonymous struct inside of it.</li>
<li><code>Write</code> includes a single <code>String</code>.</li>
<li><code>ChangeColor</code> includes three <code>i32</code>s.</li>
</ul>
<p>This is similar to different kinds of struct definitions, except without the
<code>struct</code> keyword and all grouped together under the <code>Message</code> type. The
following structs could hold the same data that the enum variants above hold:</p>
<pre><code class="language-rust">struct QuitMessage; // unit struct
struct MoveMessage {
x: i32,
y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple struct
</code></pre>
<p>But if we used the different structs, we wouldn't be able to as easily define a
function that could take any of these kinds of messages as we could with the
<code>Message</code> enum defined above.</p>
<p>One more similarity between enums and structs: just as we are able to define
methods on structs using <code>impl</code>, we are also able to define methods on enums.
Here's a method, <code>call</code>, that we could define on our <code>Message</code> enum:</p>
<pre><code class="language-rust"># enum Message {
# Quit,
# Move { x: i32, y: i32 },
# Write(String),
# ChangeColor(i32, i32, i32),
# }
#
impl Message {
fn call(&amp;self) {
// body would be defined here
}
}
let m = Message::Write(String::from(&quot;hello&quot;));
m.call();
</code></pre>
<!-- I will add wingdings here /Carol -->
<p>The body of the method would use <code>self</code> to get the value that we called the
method on. In this example, we've created a variable <code>m</code> that has the value
<code>Message::Write(&quot;hello&quot;)</code>, and that is what <code>self</code> will be in the body of
the <code>call</code> method when <code>m.call()</code> runs.</p>
<p>Let's look at another enum in the standard library that is very common and
useful: <code>Option</code>.</p>
<h2>The <code>Option</code> Enum and its Advantages Over Null Values</h2>
<p>In the previous section, we looked at how the <code>IpAddr</code> enum let us use Rust's
type system to encode more information than just the data into our program.
This section is a case study of <code>Option</code>, which is another enum defined by the
standard library. The <code>Option</code> type is used in many places because it encodes
the very common scenario in which a value could be <em>something</em> or it could be
<em>nothing</em>. Expressing this concept in terms of the type system means the
compiler can check that you've handled all the cases you should be handling,
which can prevent bugs that are extremely common in other programming languages.</p>
<p>Programming language design is often thought of in terms of which features you
include, but the features you leave out are important too. Rust does not have
the <em>null</em> feature that many other languages have. Null is a value that means
there is no value there. In languages with null, variables can always be in one
of two states: null or not-null.</p>
<p>The inventor of null has this to say:</p>
<blockquote>
<p>I call it my billion-dollar mistake. At that time, I was designing the first
comprehensive type system for references in an object-oriented language. My
goal was to ensure that all use of references should be absolutely safe, with
checking performed automatically by the compiler. But I couldn't resist the
temptation to put in a null reference, simply because it was so easy to
implement. This has led to innumerable errors, vulnerabilities, and system
crashes, which have probably caused a billion dollars of pain and damage in
the last forty years.</p>
<ul>
<li>Tony Hoare &quot;Null References: The Billion Dollar Mistake&quot;</li>
</ul>
</blockquote>
<p>The problem with null values is that if you try to actually use a value that's
null as if it is a not-null value, you'll get an error of some kind. Because
this null or not-null property is pervasive, it's extremely easy to make this
kind of error.</p>
<p>The concept that null is trying to express is still a useful one, however: a
null is a value which is currently invalid or absent for some reason.</p>
<p>The problem isn't with the concept itself, but with the particular
implementation. As such, Rust does not have nulls, but it does have an enum
that can encode the concept of a value being present or absent. This enum is
<code>Option&lt;T&gt;</code>, and it is <a href="../std/option/enum.Option.html">defined by the standard library</a><!-- ignore -->
as follows:</p>
<pre><code class="language-rust">enum Option&lt;T&gt; {
Some(T),
None,
}
</code></pre>
<p>The <code>Option&lt;T&gt;</code> enum is so useful that it's even included in the prelude; you
don't need to import it explicitly. Furthermore, so are its variants: you can
use <code>Some</code> and <code>None</code> directly, without prefixing them with <code>Option::</code>. This is
still just a regular enum, however, <code>Some(T)</code> and <code>None</code> are still values of
type <code>Option&lt;T&gt;</code>.</p>
<!-- We haven't spoken about the prelude so far in the book, I think I made a
note of that in a previous chapter---we should tell the reader what it is
before mentioning it so they know what significance it has here -->
<!-- We did speak about the prelude previously, in chapter 2, the Processing a
Guess section. I don't have any comments from you about it there... /Carol -->
<p>The <code>&lt;T&gt;</code> syntax is a feature of Rust we haven't talked about yet. It's a
generic type parameter, and we'll cover generics in more detail in Chapter 10.
For now, all you need to know is that this means the <code>Some</code> variant of the
<code>Option</code> enum can hold one piece of data of any type. Here are some examples of
using <code>Option</code> values to hold number types and string types:</p>
<pre><code class="language-rust">let some_number = Some(5);
let some_string = Some(&quot;a string&quot;);
let absent_number: Option&lt;i32&gt; = None;
</code></pre>
<p>If we use <code>None</code> rather than <code>Some</code>, we need to tell Rust what type of
<code>Option&lt;T&gt;</code> we have.</p>
<p>When we have a <code>Some</code> value, we know that there is a value present, and the
value is held within the <code>Some</code>. When we have a <code>None</code> value, in some sense,
that means the same thing that null does: we do not have a valid value. So why
is this any better than null?</p>
<p>In short, because <code>Option&lt;T&gt;</code> and <code>T</code> (where <code>T</code> can be any type) are different
types from each other, so the compiler won't let us use an <code>Option</code> value as if
it was definitely a valid value. For example, this code won't compile because
it's trying to compare an <code>Option&lt;i8&gt;</code> to an <code>i8</code>:</p>
<pre><code class="language-rust,ignore">let x: i8 = 5;
let y: Option&lt;i8&gt; = Some(5);
let sum = x + y;
</code></pre>
<p>If we run this code, we get an error message like this:</p>
<pre><code class="language-text">error[E0277]: the trait bound `i8: std::ops::Add&lt;std::option::Option&lt;i8&gt;&gt;` is not satisfied
--&gt;
|
7 | let sum = x + y;
| ^^^^^
|
</code></pre>
<p>Intense! What this error message is trying to say is that Rust does not
understand how to add an <code>Option&lt;i8&gt;</code> and an <code>i8</code>, since they're different
types. When we have a value of a type like <code>i8</code> in Rust, the compiler will
ensure that we always have a valid value. We can proceed confidently without
having to check for null before using that value. Only when we have an
<code>Option&lt;i8&gt;</code> (or whatever type of value we're working with) do we have to
worry about possibly not having a value, and the compiler will make sure we
handle that case before using the value.</p>
<p>In other words, you have to convert an <code>Option&lt;T&gt;</code> to a <code>T</code> before you can do
<code>T</code> stuff with it. This helps catch one of the most common issues with null,
generally: assuming that something isn't null when it actually is.</p>
<p>This is pretty powerful: in order to have a value that can possibly be null,
you have to explicitly opt in by making the type of that value <code>Option&lt;T&gt;</code>.
Then, when you use that value, you are required to explicitly handle the case
when the value is null. Everywhere that a value has a type that isn't an
<code>Option&lt;T&gt;</code>, you <em>can</em> safely assume that the value isn't null. This was a
deliberate design decision for Rust to limit null's pervasiveness and increase
the safety of Rust code.</p>
<!-- So does None count as an option<T>? I lost the None thread a bit here -->
<!-- Yes, since `Option<T>` is an enum and `None` is a variant of this enum,
`None`'s type is `Option<T>`. I hope with the clarifications I added in the
previous section that this will be clear by this point. /Carol -->
<p>So, how <em>do</em> you get the <code>T</code> value out of a <code>Some</code> variant when you have a
value of type <code>Option&lt;T&gt;</code> so that you can use that value? The <code>Option&lt;T&gt;</code> enum
has a large number of methods useful in a variety of situations that you can
check out in <a href="../std/option/enum.Option.html">its documentation</a><!-- ignore -->, and becoming familiar
with them will be extremely useful in your journey with Rust.</p>
<p>What we generally want to do in order to use an <code>Option&lt;T&gt;</code> value is to have
code that will handle each variant. We want some code that will run only in the
case that we have a <code>Some(T)</code> value, and this code <em>is</em> allowed to use the
inner <code>T</code>. We want some <em>other</em> code to run if we have a <code>None</code> value, and that
code doesn't have a <code>T</code> value available. The <code>match</code> expression is a control
flow construct that does just this, when used with enums: it will run different
code depending on which variant of the enum it has, and that code can use the
data inside the matching value.</p>
<!-- I'm not sure about this connecting paragraph, it doesn't seem like match
and option are actually that much connected, at least not at first. That's
fine, this is all under the enum heading, but it might confuse if we imply
otherwise --- unless I'm just missing the connection -->
<!-- I've tried to make the connection more explicit, is this better? /Carol -->
<h2>Match</h2>
<p>Rust has an extremely powerful control-flow operator, <code>match</code>, that allows us to
compare a value against a series of patterns and then execute code based on
which pattern matches. The power comes from the expressiveness of the patterns
and the compiler checks that make sure all possible cases are handled.</p>
<p>Think of a <code>match</code> expression kind of like a coin sorting machine: coins slide
down a track with variously sized holes along it, and each coin falls
through the first hole it encounters that it fits into. In the same way, values
go through each pattern in a <code>match</code>, and at the first pattern the value
&quot;fits&quot;, the value will fall into the associated code block to be used during
execution.</p>
<p>Since we're already talking about coins, let's use them for an example using
<code>match</code>! We can write a function that can take an unknown American coin and, in
a similar way as the counting machine, determine which coin it is and
return its value in cents, shown here in Listing 6-2:</p>
<figure>
<pre><code class="language-rust">enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -&gt; i32 {
match coin {
Coin::Penny =&gt; 1,
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter =&gt; 25,
}
}
</code></pre>
<figcaption>
<p>Listing 6-2: An enum and a <code>match</code> expression that has the variants of the enum
as its patterns.</p>
</figcaption>
</figure>
<!--- Flagging as a place to possibly put wingding numbers -- would it work to
put two arms in this example? I think that would illustrate the control flow
well -->
<!-- I think we're moving away from using generic examples like this and talking
about concrete examples instead. I've changed the text to reflect that, and I'm
happy to add wingdings once we're in libreoffice. /Carol -->
<p>Let's break down the <code>match</code> in the <code>value_in_cents</code> function. First, we list
the <code>match</code> keyword followed by an expression, which in this case is the value
<code>coin</code>. This feels very similar to an expression used with <code>if</code>, but there's a
big difference: with <code>if</code>, the expression needs to return a boolean value.
Here, it can be any type. The type of <code>coin</code> in this example is the <code>Coin</code> enum
that we have defined above.</p>
<p>Next, we have the <em>match arms</em>. An arm has two parts: a pattern and some code.
The first arm here has a pattern that is the value <code>Coin::Penny</code>, then the <code>=&gt;</code>
operator that separates the pattern and the code to run. The code in this case
is just the value <code>1</code>. Each arm is separated from the next with a comma.</p>
<p>When the <code>match</code> expression executes, it compares the resulting value against
the pattern of each arm, in order. If a pattern matches the value, the code
associated with that pattern is executed. If that pattern doesn't match the
value, execution continues to the next arm, much like a coin sorting machine.
We can have as many arms as we need: our <code>match</code> above has four arms.</p>
<p>The code associated with each arm is an expression, and the resulting value of
the expression in the matching arm is the value that gets returned for the
entire <code>match</code> expression.</p>
<p>Curly braces typically aren't used if the match arm code is short, as it is in
the above example where each arm just returns a value. If you wanted to run
multiple lines of code in a match arm, you can use curly braces. For example,
this code would print out &quot;Lucky penny!&quot; every time the method was called with
a <code>Coin::Penny</code>, but would still return the last value of the block, <code>1</code>:</p>
<pre><code class="language-rust"># enum Coin {
# Penny,
# Nickel,
# Dime,
# Quarter,
# }
#
fn value_in_cents(coin: Coin) -&gt; i32 {
match coin {
Coin::Penny =&gt; {
println!(&quot;Lucky penny!&quot;);
1
},
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter =&gt; 25,
}
}
</code></pre>
<h3>Patterns that Bind to Values</h3>
<p>Another useful feature of match arms is that they can bind to parts of the
values that match the pattern. This is how we can extract values out of enum
variants.</p>
<p>As an example, let's change one of our enum variants to hold data inside it.
From 1999 through 2008, the U.S. printed quarters with different designs for
each of the 50 states on one side. No other coins got state designs, so only
quarters have this extra value. We can add this information to our <code>enum</code>
by changing the <code>Quarter</code> variant to include a <code>State</code> value stored inside it
as we've done here in Listing 6-3:</p>
<figure>
<pre><code class="language-rust">#[derive(Debug)] // So we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// ... etc
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(UsState),
}
</code></pre>
<figcaption>
<p>Listing 6-3: A <code>Coin</code> enum where the <code>Quarter</code> variant also holds a <code>UsState</code>
value</p>
</figcaption>
</figure>
<p>Let's imagine that a friend of ours is trying to collect all 50 state quarters.
While we sort our loose change by coin type, we're also going to call out the
name of the state associated with each quarter so that if it's one our friend
doesn't have they can add it to their collection.</p>
<p>In the match expression for this, we add a variable, <code>state</code>, to the pattern
that matches values of the variant <code>Coin::Quarter</code>. When a <code>Coin::Quarter</code>
matches, the <code>state</code> variable will bind to the value of that quarter's state.
Then we can use <code>state</code> in the code for that arm like so:</p>
<pre><code class="language-rust"># #[derive(Debug)]
# enum UsState {
# Alabama,
# Alaska,
# }
#
# enum Coin {
# Penny,
# Nickel,
# Dime,
# Quarter(UsState),
# }
#
fn value_in_cents(coin: Coin) -&gt; i32 {
match coin {
Coin::Penny =&gt; 1,
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter(state) =&gt; {
println!(&quot;State quarter from {:?}!&quot;, state);
25
},
}
}
</code></pre>
<p>If we were to call <code>value_in_cents(Coin::Quarter(UsState::Alaska))</code>, <code>coin</code>
would be <code>Coin::Quarter(UsState::Alaska)</code>. When we compare that value with each
of the match arms, none of them match until we reach <code>Coin::Quarter(state)</code>. At
that point, the binding for <code>state</code> will be the value <code>UsState::Alaska</code>. We can
then use that binding in the <code>println!</code> expression, thus getting the inner
state value out of the <code>Coin</code> enum variant for <code>Quarter</code>.</p>
<h3>Matching with Option<T></h3>
<p>In the previous section we wanted to get the inner <code>T</code> value out of the <code>Some</code>
case when using <code>Option&lt;T&gt;</code>; we can do this in a very similar way! Instead of
comparing coins we will be comparing the variants of <code>Option&lt;T&gt;</code>, but the way
that the <code>match</code> expression works remains the same.</p>
<p>Let's say we want to write a function that takes an <code>Option&lt;i32&gt;</code> and if
there's a value inside, adds one to that value. If there isn't a value inside,
the function should return the <code>None</code> value and not attempt to perform any
operations.</p>
<p>This function is very easy to write, thanks to <code>match</code>, and will look like
Listing 6-4:</p>
<figure>
<pre><code class="language-rust">fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
match x {
None =&gt; None,
Some(i) =&gt; Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
</code></pre>
<figcaption>
<p>Listing 6-4: A function that uses a <code>match</code> expression on an <code>Option&lt;i32&gt;</code></p>
</figcaption>
</figure>
<!-- Flagging for wingding numbers -->
<h4>Matching <code>Some(T)</code></h4>
<p>Let's examine the first execution of <code>plus_one</code> in more detail. In the above
example when we call <code>plus_one(five)</code>, the variable <code>x</code> in the body of
<code>plus_one</code> will have the value <code>Some(5)</code>. We compare that against each match
arm:</p>
<pre><code class="language-rust,ignore">None =&gt; None,
</code></pre>
<p>The <code>Some(5)</code> value doesn't match the pattern <code>None</code>, so we continue.</p>
<pre><code class="language-rust,ignore">Some(i) =&gt; Some(i + 1),
</code></pre>
<p>Does <code>Some(5)</code> match <code>Some(i)</code>? Why yes it does! We have the same variant. The
<code>i</code> binds to the value contained in <code>Some</code>, so <code>i</code> takes the value <code>5</code>. The
code in the match arm is then executed, so we add one to the value of <code>i</code>
and create a new <code>Some</code> value with our total <code>6</code> inside.</p>
<h4>Matching <code>None</code></h4>
<p>Now let's consider the second call of <code>plus_one</code> where <code>x</code> is <code>None</code>. We
enter the <code>match</code>, and compare to the first arm:</p>
<pre><code class="language-rust,ignore">None =&gt; None,
</code></pre>
<p>It matches! There's no value to add to, so the program stops and returns the
<code>None</code> value on the right side of <code>=&gt;</code>. Since the first arm matched, no other
arms are compared.</p>
<p>Combining <code>match</code> and enums together is extremely powerful. You'll see this
pattern a lot in Rust code: <code>match</code> against an enum, bind a variable to the
data inside, then execute code based on it. It's a bit tricky at first, but
once you get used to it, you'll wish you had it in all languages. It's
consistently a user favorite.</p>
<h3>Matches are Exhaustive</h3>
<p>There's one other aspect of <code>match</code> we haven't discussed. Consider this version
of our <code>plus_one</code> function:</p>
<pre><code class="language-rust,ignore">fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
match x {
Some(i) =&gt; Some(i + 1),
}
}
</code></pre>
<p>We didn't handle the <code>None</code> case, so this will cause a bug. Luckily, it's a bug
Rust knows how to catch. If we try to compile this code, we'll get this error:</p>
<pre><code class="language-text">error[E0004]: non-exhaustive patterns: `None` not covered
--&gt;
|
6 | match x {
| ^ pattern `None` not covered
</code></pre>
<p>Rust knows that we did not cover every possible option, and even knows which
pattern we forgot! Enums in Rust are <em>exhaustive</em>: we must exhaust every last
option possible in order to be valid. Especially in the case of <code>Option&lt;T&gt;</code>,
when Rust prevents us from forgetting to explicitly handle the <code>None</code> case, it
protects us from assuming that we have a value when we might have null and thus
making the billion-dollar mistake discussed earlier.</p>
<h3>The _ Placeholder</h3>
<p>Rust also has a pattern we can use in situations when we don't want to list all
possible values. For example, a <code>u8</code> can have valid values of zero through 255.
If we only care about the values 1, 3, 5, and 7, we don't want to have to list
out 0, 2, 4, 6, 8, 9 all the way up to 255. Thankfully, we don't have to: we
can use the special pattern <code>_</code> instead.</p>
<pre><code class="language-rust">let some_u8_value = 0u8;
match some_u8_value {
1 =&gt; println!(&quot;one&quot;),
3 =&gt; println!(&quot;three&quot;),
5 =&gt; println!(&quot;five&quot;),
7 =&gt; println!(&quot;seven&quot;),
_ =&gt; (),
}
</code></pre>
<p>The <code>_</code> pattern will match any value. By putting it after our other arms, the
<code>_</code> will match all the possible cases that aren't specified before it. The <code>()</code>
is just the unit value, so nothing will happen in the <code>_</code> case. This way, we
can say that we want to do nothing for all of the possible values that we don't
list before the <code>_</code> placeholder.</p>
<p>The <code>match</code> expression can be a little wordy for the case where we only care
about <em>one</em> of the cases, though. For that case, Rust provides <code>if let</code>.</p>
<h2>Concise control flow with <code>if let</code></h2>
<p>The <code>if let</code> syntax lets you combine <code>if</code> and <code>let</code> into a less verbose way to
handle values that match one pattern and ignoring the rest. Take the following
program:</p>
<pre><code class="language-rust"># let some_option = Some(5);
match some_option {
Some(x) =&gt; {
// do something with x
},
None =&gt; (),
}
</code></pre>
<p>We want to do something with the <code>Some</code> match, but do nothing with the <code>None</code>
case. We can do this with an <code>Option</code>, but with a more complex enum,
adding <code>_ =&gt; ()</code> after processing just one variant is a lot of boilerplate code
that we have to add to satisfy the <code>match</code> expression.</p>
<p>Instead, we could write this in a shorter way with <code>if let</code>. This code behaves
exactly the same as the <code>match</code> above:</p>
<pre><code class="language-rust"># let some_option = Some(5);
if let Some(x) = some_option {
// do something with x
}
</code></pre>
<p><code>if let</code> takes a pattern and an expression separated by an <code>=</code>. It works
just like a <code>match</code>, where the expression is given to the <code>match</code> and the
pattern is its first arm.</p>
<p>Using <code>if let</code> means you have less to type, less indentation, and less
boilerplate. However, we've lost the exhaustiveness checking that <code>match</code>
enforces. Choosing between <code>match</code> and <code>if let</code> depends on what you're doing in
your particular case, and if gaining conciseness is an appropriate tradeoff for
losing exhaustiveness checking.</p>
<p>In other words, you can think of <code>if let</code> as syntax sugar for a <code>match</code> that
runs code when the value matches one pattern and then ignores all other values.</p>
<p>We can include an <code>else</code> that goes with an <code>if let</code>. The block of code that
goes with the <code>else</code> is the same as the block of code that would go with the
<code>_</code> case in the <code>match</code> expression that is equivalent to the <code>if let</code> and
<code>else</code>. Recall the <code>Coin</code> enum definition in Listing 6-3, where the <code>Quarter</code>
variant also held a <code>UsState</code> value. If we wanted to count all non-quarter
coins we see while also announcing the state of the quarters, we could do that
with a <code>match</code> expression like this:</p>
<pre><code class="language-rust"># #[derive(Debug)]
# enum UsState {
# Alabama,
# Alaska,
# }
#
# enum Coin {
# Penny,
# Nickel,
# Dime,
# Quarter(UsState),
# }
# let coin = Coin::Penny;
let mut count = 0;
match coin {
Coin::Quarter(state) =&gt; println!(&quot;State quarter from {:?}!&quot;, state),
_ =&gt; count += 1,
}
</code></pre>
<p>Or we could choose to use an <code>if let</code> and <code>else</code> expression like this:</p>
<pre><code class="language-rust"># #[derive(Debug)]
# enum UsState {
# Alabama,
# Alaska,
# }
#
# enum Coin {
# Penny,
# Nickel,
# Dime,
# Quarter(UsState),
# }
# let coin = Coin::Penny;
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!(&quot;State quarter from {:?}!&quot;, state);
} else {
count += 1;
}
</code></pre>
<p>If you find yourself in a situation where your program has logic that is
verbose to express using a <code>match</code>, remember that <code>if let</code> is in your Rust
toolbox as well.</p>
<h2>Summary</h2>
<p>We've now covered how to use enums to create custom types that can be one of a
set of enumerated values. We've shown how the standard library's <code>Option&lt;T&gt;</code>
type helps you use the type system to prevent errors. When enum values have data
inside them, you can use <code>match</code> or <code>if let</code> to extract and use those values,
depending on how many cases you need to handle.</p>
<p>Your Rust programs can now express concepts in your domain using structs and
enums. Creating custom types to use in your API ensures type safety: the
compiler will make certain your functions only get values of the type each
function expects.</p>
<p>In order to provide a well-organized API to your users that is straightforward
to use and only exposes exactly what your users will need, let's now turn to
Rust's <em>modules</em>.</p>
<h1>Modules</h1>
<p>When you start writing programs in Rust, your code might live solely in the
<code>main</code> function. As your code grows, you’ll eventually move functionality out
into other functions, both for re-use and for better organization. By splitting
your code up into smaller chunks, each chunk is easier to understand on its
own. But what happens if find yourself with too many functions? Rust has a
module system that handles the problem of wanting to to re-use code while
keeping your code organized.</p>
<p>In the same way that you extract lines of code into a function, you can extract
functions (and other code like structs and enums too) into different modules. A
<em>module</em> is a namespace that contains definitions of functions or types, and
you can choose whether those definitions are visible outside their module
(public) or not (private). Here’s an overview of how modules work:</p>
<ul>
<li>You declare a new module with the keyword <code>mod</code></li>
<li>By default, everything is set as private, but you can use the <code>pub</code> keyword
to make the module public, and therefore visible outside of the namespace.</li>
<li>The <code>use</code> keyword allows you to bring modules, or the definitions inside
modules, into scope so that it’s easier to refer to them.</li>
</ul>
<p>We’ll take a look at each of these parts and see how they fit into the whole.</p>
<h2><code>mod</code> and the Filesystem</h2>
<p>We’ll start our module example by making a new project with Cargo, but instead
of creating a binary crate, we’re going to make a library crate: a project that
other people can pull into their projects as a dependency. We saw this with the
<code>rand</code> crate in Chapter 2.</p>
<p>We’ll create a skeleton of a library that provides some general networking
functionality; we’re going to concentrate on the organization of the modules
and functions, but not worry about what code goes in the function bodies. We’ll
call our library <code>communicator</code>. By default, cargo will create a library unless
another type of project is specified, so if we leave off the <code>--bin</code> option
that we’ve been using so far our project will be a library:</p>
<pre><code class="language-text">$ cargo new communicator
$ cd communicator
</code></pre>
<p>Notice that Cargo generated <em>src/lib.rs</em> instead of <em>src/main.rs</em>. Inside
<em>src/lib.rs</em> we’ll find this:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
</code></pre>
<p>Cargo creates an empty test to help us get our library started, rather
than the “Hello, world!” binary that we get with the <code>--bin</code> option. We’ll look
at the <code>#[]</code> and <code>mod tests</code> syntax a little later, but for now just make sure
to leave it in your <em>src/lib.rs</em>.</p>
<p>Since we don’t have a <em>src/main.rs</em>, there’s nothing for Cargo to execute with
the <code>cargo run</code> command. Therefore, we will be using the <code>cargo build</code> command
to only compile our library crate’s code.</p>
<p>We’re going to look at different options for organizing your library’s code
which will be suitable in a variety of situations, depending on the intentions
you have for your code.</p>
<h3>Module Definitions</h3>
<p>For our <code>communicator</code> networking library, we’re first going to define a module
named <code>network</code> that contains the definition of a function called <code>connect</code>.
Every module definition in Rust starts with the <code>mod</code> keyword. Add this code to
the beginning of the <em>lib.rs</em> file, above the test code:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">mod network {
fn connect() {
}
}
</code></pre>
<p>After the <code>mod</code> keyword, we put the name of the module, <code>network</code>, then a block
of code in curly braces. Everything inside this block is inside the namespace
<code>network</code>. In this case, we have a single function, <code>connect</code>. If we wanted to
call this function from a script outside the <code>network</code> module, we would need to
specify the module and use the namespace syntax <code>::</code>, like so:
<code>network::connect()</code>, rather than just <code>connect()</code>.</p>
<p>We can also have multiple modules, side-by-side, in the same <em>src/lib.rs</em> file.
For example, to have a <code>client</code> module too, that also has a function named
<code>connect</code>, we can add:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">mod network {
fn connect() {
}
}
mod client {
fn connect() {
}
}
</code></pre>
<figcaption>
<p>Listing 7-1: The <code>network</code> module and the <code>client</code> module defined side-by-side
in <em>src/lib.rs</em></p>
</figcaption>
</figure>
<p>Now we have a <code>network::connect</code> function and a <code>client::connect</code> function.
These can have completely different functionality, and the function names do
not conflict with each other since they’re in different modules.</p>
<p>While in this case, we’re building a library, there's nothing special about
<em>lib.rs</em>. We could also make use of submodules in a <em>main.rs</em> as well. In fact,
we can also put modules inside of modules. This can be useful as your modules
grow to keep related functionality organized together and separate
functionality apart. The choice of how you organize your code depends on how
you think about the relationship between the parts of your code. For instance,
the <code>client</code> code and its <code>connect</code> function might make more sense to users of
our library if it was inside the <code>network</code> namespace instead, like so:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">mod network {
fn connect() {
}
mod client {
fn connect() {
}
}
}
</code></pre>
<figcaption>
<p>Listing 7-2: Moving the <code>client</code> module inside of the <code>network</code> module</p>
</figcaption>
</figure>
<p>In your <em>src/lib.rs</em> file, replace the existing <code>mod network</code> and <code>mod client</code>
definitions with this one that has the <code>client</code> module as an inner module of
<code>network</code>. Now we have the functions <code>network::connect</code> and
<code>network::client::connect</code>: again, the two functions named <code>connect</code> don’t
conflict with each other since they’re in different namespaces.</p>
<p>In this way, modules form a hierarchy. The contents of <em>src/lib.rs</em> are at the
topmost level, and the submodules are at lower levels. Here’s what the
organization of our example from Listing 7-1 looks like when thought of this
way:</p>
<pre><code class="language-text">communicator
├── network
└── client
</code></pre>
<p>And here’s the example from Listing 7-2:</p>
<pre><code class="language-text">communicator
└── network
└── client
</code></pre>
<p>You can see that in Listing 7-2, <code>client</code> is a child of the <code>network</code> module,
rather than a sibling. More complicated projects can have a lot of modules, and
they’ll need to be organized logically in order to keep track of them. What
“logically” means in your project is up to you and depends on how you and users
of your library think about your project’s domain. Use the techniques we’ve
shown here to create side-by-side modules and nested modules in whatever
structure you would like.</p>
<h3>Moving Modules to Other Files</h3>
<p>Modules form a hierarchical structure, much like another structure in computing
that you’re used to: file systems! We can use Rust’s module system along with
multiple files to split Rust projects up so that not everything lives in
<em>src/lib.rs</em>. For this example, we will start with this code in <em>src/lib.rs</em>:</p>
<figure>
<span class="filename">File: src/lib.rs</span>
<pre><code class="language-rust">mod client {
fn connect() {
}
}
mod network {
fn connect() {
}
mod server {
fn connect() {
}
}
}
</code></pre>
<figcaption>
<p>Listing 7-3: Three modules, <code>client</code>, <code>network</code>, and <code>network::server</code> all
defined in <em>src/lib.rs</em></p>
</figcaption>
</figure>
<p>which has this module hierarchy:</p>
<pre><code class="language-text">communicator
├── client
└── network
└── server
</code></pre>
<p>If these modules had many functions, and each function was getting long, we
would have to scroll through this file to find the code we wanted to work with.
This would be a good reason to pull each of the <code>client</code>, <code>network</code>, and
<code>server</code> modules out of <em>src/lib.rs</em> and into their own files. Let’s start by
extracting the <code>client</code> module into another file. First, replace the <code>client</code>
module code in <em>src/lib.rs</em> with the following:</p>
<p><span class="filename">File: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">mod client;
mod network {
fn connect() {
}
mod server {
fn connect() {
}
}
}
</code></pre>
<!-- I will add wingdings/ghosting in libreoffice /Carol -->
<p>We’re still <em>defining</em> the <code>client</code> module here, but by removing the curly
braces and definitions inside the <code>client</code> module and replacing them with a
semicolon, we’re letting Rust know to look in another location for the code
defined inside that module.</p>
<p>So now we need to create the external file with that module name. Create a
<em>client.rs</em> file in your <em>src/</em> directory, then open it up and enter the
following, which is the <code>connect</code> function in the <code>client</code> module that we
removed in the previous step:</p>
<p><span class="filename">File: src/client.rs</span></p>
<pre><code class="language-rust">fn connect() {
}
</code></pre>
<p>Note that we don’t need a <code>mod</code> declaration in this file; that’s because we
already declared the <code>client</code> module with <code>mod</code> in <em>src/lib.rs</em>. This file just
provides the <em>contents</em> of the <code>client</code> module. If we put a <code>mod client</code> here,
we’d be giving the <code>client</code> module its own submodule named <code>client</code>!</p>
<p>Rust only knows to look in <em>src/lib.rs</em> by default. If we want to add more
files to our project, we need to tell Rust in <em>src/lib.rs</em> to look in other
files; this is why <code>mod client</code> needs to be defined in <em>src/lib.rs</em> and can’t
be defined in <em>src/client.rs</em>.</p>
<p>Now, everything should compile successfully, though you’ll get a few warnings.
Remember to use <code>cargo build</code> instead of <code>cargo run</code> since we have a library
crate rather than a binary crate:</p>
<pre><code class="language-text">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/client.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/lib.rs:4:5
|
4 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/lib.rs:8:9
|
8 | fn connect() {
| ^
</code></pre>
<p>These warnings tell us that we have functions that are never used. Don’t worry
about those warnings for now; we’ll address them later in the chapter. The good
news is that they’re just warnings; our project was built successfully!</p>
<p>Let’s extract the <code>network</code> module into its own file next, using the same
pattern. In <em>src/lib.rs</em>, delete the body of the <code>network</code> module and add a
semicolon to the declaration, like so:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">mod client;
mod network;
</code></pre>
<p>Then create a new <em>src/network.rs</em> file and enter the following:</p>
<p><span class="filename">Filename: src/network.rs</span></p>
<pre><code class="language-rust">fn connect() {
}
mod server {
fn connect() {
}
}
</code></pre>
<p>Notice that we still have a <code>mod</code> declaration within this module file;
this is because we still want <code>server</code> to be a sub-module of <code>network</code>.</p>
<p>Now run <code>cargo build</code> again. Success! We have one more module to extract:
<code>server</code>. Because it’s a sub-module—that is, a module within a module—our
current tactic of extracting a module into a file named after that module won’t
work. We’re going to try anyway so that we can see the error. First change
<em>src/network.rs</em> to have <code>mod server;</code> instead of the <code>server</code> module’s
contents:</p>
<p><span class="filename">Filename: src/network.rs</span></p>
<pre><code class="language-rust,ignore">fn connect() {
}
mod server;
</code></pre>
<p>Then create a <em>src/server.rs</em> file and enter the contents of the <code>server</code>
module that we extracted:</p>
<p><span class="filename">Filename: src/server.rs</span></p>
<pre><code class="language-rust">fn connect() {
}
</code></pre>
<p>When we try to <code>cargo build</code>, we’ll get this error:</p>
<figure>
<pre><code class="language-text">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
error: cannot declare a new module at this location
--&gt; src/network.rs:4:5
|
4 | mod server;
| ^^^^^^
|
note: maybe move this module `network` to its own directory via `network/mod.rs`
--&gt; src/network.rs:4:5
|
4 | mod server;
| ^^^^^^
note: ... or maybe `use` the module `server` instead of possibly redeclaring it
--&gt; src/network.rs:4:5
|
4 | mod server;
| ^^^^^^
</code></pre>
<figcaption>
<p>Listing 7-4: Error when trying to extract the <code>server</code> submodule into
<em>src/server.rs</em></p>
</figcaption>
</figure>
<p>The error says we <code>cannot declare a new module at this location</code> and is
pointing to the <code>mod server;</code> line in <em>src/network.rs</em>. So <em>src/network.rs</em> is
different than <em>src/lib.rs</em> somehow; let’s keep reading to understand why.</p>
<p>The note in the middle of Listing 7-4 is actually pretty helpful, as it points
out something we haven’t yet talked about doing:</p>
<blockquote>
<p>note: maybe move this module <code>network</code> to its own directory via
<code>network/mod.rs</code></p>
</blockquote>
<p>Instead of continuing to follow the same file naming pattern we used
previously, we can do what the note suggests:</p>
<ol>
<li>Make a new <em>directory</em> named <em>network</em>, the parent module’s name</li>
<li>Move the <em>src/network.rs</em> file into the new <em>network</em> directory and rename
it so that it is now <em>src/network/mod.rs</em></li>
<li>Move the submodule file <em>src/server.rs</em> into the <em>network</em> directory</li>
</ol>
<p>Here are commands to carry out these steps:</p>
<pre><code class="language-text">$ mkdir src/network
$ mv src/network.rs src/network/mod.rs
$ mv src/server.rs src/network
</code></pre>
<p>Now if we try to <code>cargo build</code>, compilation will work (we’ll still have
warnings though). Our module layout still looks like this, which is exactly the
same as it did when we had all the code in <em>src/lib.rs</em> in Listing 7-3:</p>
<pre><code class="language-text">communicator
├── client
└── network
└── server
</code></pre>
<p>The corresponding file layout now looks like this:</p>
<pre><code class="language-text">├── src
│   ├── client.rs
│   ├── lib.rs
│   └── network
│   ├── mod.rs
│   └── server.rs
</code></pre>
<p>So when we wanted to extract the <code>network::server</code> module, why did we have to
also change the <em>src/network.rs</em> file into the <em>src/network/mod.rs</em> file, and
also put the code for <code>network::server</code> in the <code>network</code> directory in
<em>src/network/server.rs</em>, instead of just being able to extract the
<code>network::server</code> into <em>src/server.rs</em>? The reason is that Rust wouldn’t be
able to tell that <code>server</code> was supposed to be a submodule of <code>network</code> if the
<em>server.rs</em> file was in the <em>src</em> directory. To make it clearer why Rust can’t
tell, let’s consider a different example where we have this module hierarchy
with all the definitions in <em>src/lib.rs</em>:</p>
<pre><code class="language-text">communicator
├── client
└── network
└── client
</code></pre>
<p>In this example, we have three modules again, <code>client</code>, <code>network</code>, and
<code>network::client</code>. If we follow the same steps we originally did above for
extracting modules into files, for the <code>client</code> module we would create
<em>src/client.rs</em>. For the <code>network</code> module, we would create <em>src/network.rs</em>.
Then we wouldn’t be able to extract the <code>network::client</code> module into a
<em>src/client.rs</em> file, because that already exists for the top-level <code>client</code>
module! If we put the code in both the <code>client</code> and <code>network::client</code> modules
in the <em>src/client.rs</em> file, Rust would not have any way to know whether the
code was for <code>client</code> or for <code>network::client</code>.</p>
<p>Therefore, once we wanted to extract a file for the <code>network::client</code> submodule
of the <code>network</code> module, we needed to create a directory for the <code>network</code>
module instead of a <em>src/network.rs</em> file. The code that is in the <code>network</code>
module then goes into the <em>src/network/mod.rs</em> file, and the submodule
<code>network::client</code> can have its own <em>src/network/client.rs</em> file. Now the
top-level <em>src/client.rs</em> is unambiguously the code that belongs to the
<code>client</code> module.</p>
<h3>Rules of Module File Systems</h3>
<p>In summary, these are the rules of modules with regards to files:</p>
<ul>
<li>
<p>If a module named <code>foo</code> has no submodules, you should put the declarations
for <code>foo</code> in a file named <em>foo.rs</em>.</p>
</li>
<li>
<p>If a module named <code>foo</code> does have submodules, you should put the declarations
for <code>foo</code> in a file named <em>foo/mod.rs</em>.</p>
</li>
<li>
<p>The first two rules apply recursively, so that if a module named <code>foo</code> has a
submodule named <code>bar</code> and <code>bar</code> does not have submodules, you should have the
following files in your <em>src</em> directory:</p>
<pre><code class="language-text">├── foo
│   ├── bar.rs (contains the declarations in `foo::bar`)
│   └── mod.rs (contains the declarations in `foo`, including `mod bar`)
</code></pre>
</li>
<li>
<p>The modules themselves should be declared in their parent module’s file using
the <code>mod</code> keyword.</p>
</li>
</ul>
<p>Next, we’ll talk about the <code>pub</code> keyword, and get rid of those warnings!</p>
<h2>Controlling Visibility with <code>pub</code></h2>
<p>We resolved the error messages shown in Listing 7-4 by moving the <code>network</code> and
<code>network::server</code> code into the <em>src/network/mod.rs</em> and
<em>src/network/server.rs</em> files, respectively. At that point, <code>cargo build</code> was
able to build our project, but we still get some warning messages about the
<code>client::connect</code>, <code>network::connect</code>, and <code>network::server::connect</code> functions
not being used:</p>
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
src/client.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/mod.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>So why are we receiving these warnings? After all, we’re building a library
with functions that are intended to be used by our <em>users</em>, and not necessarily
by us within our own project, so it shouldn’t matter that these <code>connect</code>
functions go unused. The point of creating them is that they will be used by
another project and not our own.</p>
<p>To understand why this program invokes these warnings, let’s try using the
<code>connect</code> library as if we were another project, calling it externally. We can
do that by creating a binary crate in the same directory as our library crate,
by making a <em>src/main.rs</em> file containing this code:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">extern crate communicator;
fn main() {
communicator::client::connect();
}
</code></pre>
<p>We use the <code>extern crate</code> command to bring the <code>communicator</code> library crate
into scope, because our package actually now contains <em>two</em> crates. Cargo
treats <em>src/main.rs</em> as the root file of a binary crate, which is separate from
the existing library crate whose root file is <em>src/lib.rs</em>. This pattern is
quite common for executable projects: most functionality is in a library crate,
and the binary crate uses that library crate. This way, other programs can also
use the library crate, and it’s a nice separation of concerns.</p>
<p>Our binary crate right now just calls our library’s <code>connect</code> function from the
<code>client</code> module. However, invoking <code>cargo build</code> will now give us an error
after the warnings:</p>
<pre><code class="language-text">error: module `client` is private
--&gt; src/main.rs:4:5
|
4 | communicator::client::connect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>Ah ha! This tells us that the <code>client</code> module is private, and this is the crux
of the warnings. It’s also the first time we’ve run into the concepts of
<em>public</em> and <em>private</em> in the context of Rust. The default state of all code in
Rust is private: no one else is allowed to use the code. If you don’t use a
private function within your own program, since your own program is the only
code allowed to use that function, Rust will warn you that the function has
gone unused.</p>
<p>Once we specify that a function like <code>client::connect</code> is public, not only will
our call to that function from our binary crate be allowed, the warning that
the function is unused will go away. Marking something public lets Rust know
that we intend for the function to be used by code outside of our program. Rust
considers the theoretical external usage that’s now possible as the function
“being used.” Thus, when something is marked as public, Rust will not require
that it’s used in our own program and will stop warning that the item is
unused.</p>
<h3>Making a Function Public</h3>
<p>To tell Rust to make something public, we add the <code>pub</code> keyword to the start of
the declaration of the item we want to make public. We’ll focus on fixing the
warning that tells us that <code>client::connect</code> has gone unused for now, as well
as the “module <code>client</code> is private” error from our binary crate. Modify
<em>src/lib.rs</em> to make the <code>client</code> module public, like so:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">pub mod client;
mod network;
</code></pre>
<p>The <code>pub</code> goes right before <code>mod</code>. Let’s try building again:</p>
<pre><code class="language-text">&lt;warnings&gt;
error: function `connect` is private
--&gt; src/main.rs:4:5
|
4 | communicator::client::connect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>Hooray! We have a different error! Yes, different error messages are a cause
for celebration. The new error says “function <code>connect</code> is private”, so let’s
edit <code>src/client.rs</code> to make <code>client::connect</code> public too:</p>
<p><span class="filename">Filename: src/client.rs</span></p>
<pre><code class="language-rust">pub fn connect() {
}
</code></pre>
<p>And run <code>cargo build</code> again:</p>
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/mod.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>It compiled, and the warning about <code>client::connect</code> not being used is gone!</p>
<p>Unused code warnings don’t always indicate that something needs to be made
public: if you <em>didn’t</em> want these functions to be part of your public API,
unused code warnings could be alerting you to code you no longer needed and can
safely delete. They could also be alerting you to a bug, if you had just
accidentally removed all places within your library where this function is
called.</p>
<p>In our case though, we <em>do</em> want the other two functions to be part of our
crate’s public API, so let’s mark them as <code>pub</code> as well to try to get rid of
the remaining warnings. Modify <em>src/network/mod.rs</em> to be:</p>
<p><span class="filename">Filename: src/network/mod.rs</span></p>
<pre><code class="language-rust,ignore">pub fn connect() {
}
mod server;
</code></pre>
<p>And compile:</p>
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/mod.rs:1:1
|
1 | pub fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>Hmmm, we’re still getting an unused function warning even though
<code>network::connect</code> is set to <code>pub</code>. This is because the function is public
within the module, but the <code>network</code> module that the function resides in is not
public. We’re working from the interior of the library out this time, where
with <code>client::connect</code> we worked from the outside in. We need to change
<code>src/lib.rs</code> to make <code>network</code> public too:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">pub mod client;
pub mod network;
</code></pre>
<p>Now if we compile, that warning is gone:</p>
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>Only one warning left! Try to fix this one on your own!</p>
<h3>Privacy Rules</h3>
<p>Overall, these are the rules for item visibility:</p>
<ol>
<li>If an item is public, it can be accessed through any of its
parent modules.</li>
<li>If an item is private, it may be accessed only by the current module and its
child modules.</li>
</ol>
<h3>Privacy Examples</h3>
<p>Let’s look at a few more examples to get some practice. Create a new libary
project and enter the code in Listing 7-5 into your new project’s <em>src/lib.rs</em>:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust,ignore">mod outermost {
pub fn middle_function() {}
fn middle_secret_function() {}
mod inside {
pub fn inner_function() {}
fn secret_function() {}
}
}
fn try_me() {
outermost::middle_function();
outermost::middle_secret_function();
outermost::inside::inner_function();
outermost::inside::secret_function();
}
</code></pre>
<figcaption>
<p>Listing 7-5: Examples of private and public functions, some of which are
incorrect</p>
</figcaption>
</figure>
<p>Before you try to compile this code, make a guess about which lines in <code>try_me</code>
function will have errors. Then try compiling to see if you were right, and read
on for discussion of the errors!</p>
<h4>Looking at the Errors</h4>
<p>The <code>try_me</code> function is in the root module of our project. The module named
<code>outermost</code> is private, but the second privacy rule says the <code>try_me</code> function
is allowed to access the <code>outermost</code> module since <code>outermost</code> is in the current
(root) module, as is <code>try_me</code>.</p>
<p>The call to <code>outermost::middle_function</code> will work. This is because
<code>middle_function</code> is public, and <code>try_me</code> is accessing <code>middle_function</code>
through its parent module, <code>outermost</code> We determined in the previous paragraph
that this module is accessible.</p>
<p>The call to <code>outermost::middle_secret_function</code> will cause a compilation error.
<code>middle_secret_function</code> is private, so the second rule applies. The root
module is neither the current module of <code>middle_secret_function</code> (<code>outermost</code>
is), nor is it a child module of the current module of <code>middle_secret_function</code>.</p>
<p>The module named <code>inside</code> is private and has no child modules, so it can only
be accessed by its current module, <code>outermost</code>. That means the <code>try_me</code>
function is not allowed to call <code>outermost::inside::inner_function</code> or
<code>outermost::inside::secret_function</code> either.</p>
<h4>Fixing the Errors</h4>
<p>Here are some suggestions for changing the code in an attempt to fix the
errors. Before you try each one, make a guess as to whether it will fix the
errors, then compile to see if you’re right and use the privacy rules to
understand why.</p>
<ul>
<li>What if the <code>inside</code> module was public?</li>
<li>What if <code>outermost</code> was public and <code>inside</code> was private?</li>
<li>What if, in the body of <code>inner_function</code>, you called
<code>::outermost::middle_secret_function()</code>? (The two colons at the beginning
mean that we want to refer to the namespaces starting from the root
namespace.)</li>
</ul>
<p>Feel free to design more experiments and try them out!</p>
<p>Next, let’s talk about bringing items into a scope with the <code>use</code> keyword.</p>
<h2>Importing Names</h2>
<p>We’ve covered how to call functions defined within a module using the module
name as part of the call, as in the call to the <code>namespaces</code> function shown
here in Listing 7-6.</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">pub mod a {
pub mod series {
pub mod of {
pub fn namespaces() {}
}
}
}
fn main() {
a::series::of::namespaces();
}
</code></pre>
<figcaption>
<p>Listing 7-6: Calling a function by fully specifying its enclosing module’s
namespaces</p>
</figcaption>
</figure>
<p>As you can see, referring to the fully qualified name can get quite lengthy.
Luckily, Rust has a keyword to make these calls more concise.</p>
<h3>Concise Imports with <code>use</code></h3>
<p>Rust’s <code>use</code> keyword works to shorten lengthy function calls by bringing the
modules of the function you want to call into a scope. Here’s an example of
bringing the <code>a::series::of</code> namespace into a binary crate’s root scope:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">pub mod a {
pub mod series {
pub mod of {
pub fn namespaces() {}
}
}
}
use a::series::of;
fn main() {
of::namespaces();
}
</code></pre>
<p>The line <code>use a::series::of;</code> has made it so that anywhere in this scope that
we would want to refer to the <code>of</code> namespace, instead of having to say
<code>a::series::of</code>, we can replace that with <code>of</code>.</p>
<p>The <code>use</code> keyword brings only what we have specified into scope; it does not
bring children of modules into scope. That’s why we still have to say
<code>of::namespaces</code> when we want to call the <code>namespaces</code> function.</p>
<p>We could have chosen to bring the function itself into scope, by instead
specifying the function in the <code>use</code> as follows:</p>
<pre><code class="language-rust">pub mod a {
pub mod series {
pub mod of {
pub fn namespaces() {}
}
}
}
use a::series::of::namespaces;
fn main() {
namespaces();
}
</code></pre>
<p>This allows us to exclude any of the modules and just reference the function at
the callsite.</p>
<p>Since enums also form this kind of namespace, we can import an enum’s variants
with <code>use</code> as well. For any kind of <code>use</code> statement, if you’re importing
multiple items from one namespace, you can list them using curly braces and
commas in the last position, like so:</p>
<pre><code class="language-rust">enum TrafficLight {
Red,
Yellow,
Green,
}
use TrafficLight::{Red, Yellow};
fn main() {
let red = Red;
let yellow = Yellow;
let green = TrafficLight::Green; // because we didn’t `use` TrafficLight::Green
}
</code></pre>
<h3>Glob Imports with <code>*</code></h3>
<p>To import all the items in a namespace at once, we can use the <code>*</code> syntax. For
example:</p>
<pre><code class="language-rust">enum TrafficLight {
Red,
Yellow,
Green,
}
use TrafficLight::*;
fn main() {
let red = Red;
let yellow = Yellow;
let green = Green;
}
</code></pre>
<p>The <code>*</code> is called a <em>glob</em>, and it will import everything that’s visible inside
of the namespace. Globs should be used sparingly: they are convenient, but you
might also pull in more things than you expected and cause naming conflicts.</p>
<h3>Using <code>super</code> to Access a Parent Module</h3>
<p>As you now know, when you create a library crate, Cargo makes a <code>tests</code> module
for you. Let’s go into more detail about that now. In your <code>communicator</code>
project, open <em>src/lib.rs</em>.</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">pub mod client;
pub mod network;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
</code></pre>
<p>We’ll explain more about testing in Chapter 12, but parts of this should make
sense now: we have a module named <code>tests</code> that lives next to our other modules
and contains one function named <code>it_works</code>. Even though there are special
annotations, the <code>tests</code> module is just another module! So our module hierarchy
looks like this:</p>
<pre><code class="language-text">communicator
├── client
├── network
| └── client
└── tests
</code></pre>
<p>Tests are for exercising the code within our library, so let’s try to call
our <code>client::connect</code> function from this <code>it_works</code> function, even though
we’re not going to be checking any functionality right now:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn it_works() {
client::connect();
}
}
</code></pre>
<p>Run the tests by invoking the <code>cargo test</code> command:</p>
<pre><code class="language-text">$ cargo test
Compiling communicator v0.1.0 (file:///projects/communicator)
error[E0433]: failed to resolve. Use of undeclared type or module `client`
--&gt; src/lib.rs:9:9
|
9 | client::connect();
| ^^^^^^^^^^^^^^^ Use of undeclared type or module `client`
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>The compilation failed, but why? We don’t need to place <code>communicator::</code> in
front of the function like we did in <code>src/main.rs</code> because we are definitely
within the <code>communicator</code> library crate here. The reason is that paths are
always relative to the current module, which here is <code>tests</code>. The only
exception is in a <code>use</code> statement, where paths are relative to the crate root
by default. Our <code>tests</code> module needs the <code>client</code> module in its scope!</p>
<p>So how do we get back up one module in the module hierarchy to be able to call
the <code>client::connect</code> function in the <code>tests</code> module? In the <code>tests</code> module, we
can either use leading colons to let Rust know that we want to start from the
root and list the whole path:</p>
<pre><code class="language-rust,ignore">::client::connect();
</code></pre>
<p>Or we can use <code>super</code> to move up one module in the hierarchy from our current
module:</p>
<pre><code class="language-rust,ignore">super::client::connect();
</code></pre>
<p>These two options don’t look all that different in this example, but if you’re
deeper in a module hierarchy, starting from the root every time would get long.
In those cases, using <code>super</code> to get from the current module to sibling modules
is a good shortcut. Plus, if you’ve specified the path from the root in many
places in your code and then you rearrange your modules by moving a subtree to
another place, you’d end up needing to update the path in a lot of places,
which would be tedious.</p>
<p>It would also be annoying to have to type <code>super::</code> all the time in each test,
but you’ve already seen the tool for that solution: <code>use</code>! The <code>super::</code>
functionality changes the path you give to <code>use</code> so that it is relative to the
parent module instead of to the root module.</p>
<p>For these reasons, in the <code>tests</code> module especially, <code>use super::something</code> is
usually the way to go. So now our test looks like this:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
use super::client;
#[test]
fn it_works() {
client::connect();
}
}
</code></pre>
<p>If we run <code>cargo test</code> again, the test will pass and the first part of the test
result output will be:</p>
<pre><code class="language-text">$ cargo test
Compiling communicator v0.1.0 (file:///projects/communicator)
Running target/debug/communicator-92007ddb5330fa5a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<h2>Summary</h2>
<p>Now you know techniques for organizing your code! Use these to group related
functionality together, keep files from getting too long, and present a tidy
public API to users of your library.</p>
<p>Next, let’s look at some collection data structures in the standard library
that you can make use of in your nice, neat code!</p>
<h1>Fundamental Collections</h1>
<p>Rust's standard library includes a number of really useful data structures
called <em>collections</em>. Most other data types represent one specific value, but
collections can contain multiple values. Unlike the built-in array and tuple
types, the data these collections point to is stored on the heap, which means
the amount of data does not need to be known at compile time and can grow or
shrink as the program runs. Each kind of collection has different capabilities
and costs, and choosing an appropriate one for the situation you're in is a
skill you'll develop over time. In this chapter, we'll go over three
collections which are used very often in Rust programs:</p>
<ul>
<li>A <em>vector</em> allows us to store a variable number of values next to each other.</li>
<li>A <em>string</em> is a collection of characters. We've seen the <code>String</code> type
before, but we'll talk about it in depth now.</li>
<li>A <em>hash map</em> allows us to associate a value with a particular key.</li>
</ul>
<p>There are more specialized variants of each of these data structures for
particular situations, but these are the most fundamental and common. We're
going to discuss how to create and update each of the collections, as well as
what makes each special.</p>
<h2>Vectors</h2>
<p>The first type we'll look at is <code>Vec&lt;T&gt;</code>, also known as a <em>vector</em>. Vectors
allow us to store more than one value in a single data structure that puts all
the values next to each other in memory. Vectors can only store values of the
same type. They are useful in situations where you have a list of items, such
as the lines of text in a file or the prices of items in a shopping cart.</p>
<h3>Creating a New Vector</h3>
<p>To create a new, empty vector, we can call the <code>Vec::new</code> function:</p>
<pre><code class="language-rust">let v: Vec&lt;i32&gt; = Vec::new();
</code></pre>
<p>Note that we added a type annotation here. Since we aren't inserting any values
into this vector, Rust doesn't know what kind of elements we intend to store.
This is an important point. Vectors are homogenous: they may store many values,
but those values must all be the same type. Vectors are implemented using
generics, which Chapter 10 will cover how to use in your own types. For now,
all you need to know is that the <code>Vec</code> type provided by the standard library
can hold any type, and when a specific <code>Vec</code> holds a specific type, the type
goes within angle brackets. We've told Rust that the <code>Vec</code> in <code>v</code> will hold
elements of the <code>i32</code> type.</p>
<p>In real code, Rust can infer the type of value we want to store once we insert
values, so you rarely need to do this type annotation. It's more common to
create a <code>Vec</code> that has initial values, and Rust provides the <code>vec!</code> macro for
convenience. The macro will create a new <code>Vec</code> that holds the values we give
it. This will create a new <code>Vec&lt;i32&gt;</code> that holds the values <code>1</code>, <code>2</code>, and <code>3</code>:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3];
</code></pre>
<p>Because we've given initial <code>i32</code> values, Rust can infer that the type of <code>v</code>
is <code>Vec&lt;i32&gt;</code>, and the type annotation isn't necessary. Let's look at how to
modify a vector next.</p>
<h3>Updating a Vector</h3>
<p>To create a vector then add elements to it, we can use the <code>push</code> method:</p>
<pre><code class="language-rust">let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
</code></pre>
<p>As with any variable as we discussed in Chapter 3, if we want to be able to
change its value, we need to make it mutable with the <code>mut</code> keyword. The
numbers we place inside are all <code>i32</code>s, and Rust infers this from the data, so
we don't need the <code>Vec&lt;i32&gt;</code> annotation.</p>
<h3>Dropping a Vector Drops its Elements</h3>
<p>Like any other <code>struct</code>, a vector will be freed when it goes out of scope:</p>
<pre><code class="language-rust">{
let v = vec![1, 2, 3, 4];
// do stuff with v
} // &lt;- v goes out of scope and is freed here
</code></pre>
<p>When the vector gets dropped, all of its contents will also be dropped, meaning
those integers it holds will be cleaned up. This may seem like a
straightforward point, but can get a little more complicated once we start to
introduce references to the elements of the vector. Let's tackle that next!</p>
<h3>Reading Elements of Vectors</h3>
<p>Now that you know how to create, update, and destroy vectors, knowing how to
read their contents is a good next step. There are two ways to reference a
value stored in a vector. In the examples, we've annotated the types of the
values that are returned from these functions for extra clarity.</p>
<p>This example shows both methods of accessing a value in a vector either with
indexing syntax or the <code>get</code> method:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3, 4, 5];
let third: &amp;i32 = &amp;v[2];
let third: Option&lt;&amp;i32&gt; = v.get(2);
</code></pre>
<p>There are a few things to note here. First, that we use the index value of <code>2</code>
to get the third element: vectors are indexed by number, starting at zero.
Second, the two different ways to get the third element are: using <code>&amp;</code> and
<code>[]</code>s, which gives us a reference, or using the <code>get</code> method with the index
passed as an argument, which gives us an <code>Option&lt;&amp;T&gt;</code>.</p>
<p>The reason Rust has two ways to reference an element is so that you can choose
how the program behaves when you try to use an index value that the vector
doesn't have an element for. As an example, what should a program do if it has
a vector that holds five elements then tries to access an element at index 100
like this:</p>
<pre><code class="language-rust,should_panic">let v = vec![1, 2, 3, 4, 5];
let does_not_exist = &amp;v[100];
let does_not_exist = v.get(100);
</code></pre>
<p>When you run this, you will find that with the first <code>[]</code> method, Rust will
cause a <code>panic!</code> when a non-existent element is referenced. This method would
be preferable if you want your program to consider an attempt to access an
element past the end of the vector to be a fatal error that should crash the
program.</p>
<p>When the <code>get</code> method is passed an index that is outside the array, it will
return <code>None</code> without <code>panic!</code>ing. You would use this if accessing an element
beyond the range of the vector will happen occasionally under normal
circumstances. Your code can then have logic to handle having either
<code>Some(&amp;element)</code> or <code>None</code>, as we discussed in Chapter 6. For example, the
index could be coming from a person entering a number. If they accidentally
enter a number that's too large and your program gets a <code>None</code> value, you could
tell the user how many items are in the current <code>Vec</code> and give them another
chance to enter a valid value. That would be more user-friendly than crashing
the program for a typo!</p>
<h4>Invalid References</h4>
<p>Once the program has a valid reference, the borrow checker will enforce the
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
any other references to the contents of the vector stay valid. Recall the rule
that says we can't have mutable and immutable references in the same scope.
That rule applies in this example, where we hold an immutable reference to the
first element in a vector and try to add an element to the end:</p>
<pre><code class="language-rust,ignore">let mut v = vec![1, 2, 3, 4, 5];
let first = &amp;v[0];
v.push(6);
</code></pre>
<p>Compiling this will give us this error:</p>
<pre><code class="language-text">error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
|
4 | let first = &amp;v[0];
| - immutable borrow occurs here
5 |
6 | v.push(6);
| ^ mutable borrow occurs here
7 | }
| - immutable borrow ends here
</code></pre>
<p>This code might look like it should work: why should a reference to the first
element care about what changes about the end of the vector? The reason why
this code isn't allowed is due to the way vectors work. Adding a new element
onto the end of the vector might require allocating new memory and copying the
old elements over to the new space, in the circumstance that there isn't enough
room to put all the elements next to each other where the vector was. In that
case, the reference to the first element would be pointing to deallocated
memory. The borrowing rules prevent programs from ending up in that situation.</p>
<blockquote>
<p>Note: For more on this, see <a href="https://doc.rust-lang.org/stable/nomicon/vec.html">The Nomicon</a>.</p>
</blockquote>
<h3>Using an Enum to Store Multiple Types</h3>
<p>At the beginning of this chapter, we said that vectors can only store values
that are all the same type. This can be inconvenient; there are definitely use
cases for needing to store a list of things of different types. Luckily, the
variants of an enum are all defined under the same enum type. When we need to
store elements of a different type in a vector this scenario, we can define and
use an enum!</p>
<p>For example, let's say we want to get values from a row in a spreadsheet, where
some of the columns in the row contain integers, some floating point numbers,
and some strings. We can define an enum whose variants will hold the different
value types, and then all of the enum variants will be considered the same
type, that of the enum. Then we can create a vector that holds that enum and
so, ultimately, holds different types:</p>
<pre><code class="language-rust">enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from(&quot;blue&quot;)),
SpreadsheetCell::Float(10.12),
];
</code></pre>
<p>The reason Rust needs to know exactly what types will be in the vector at
compile time is so that it knows exactly how much memory on the heap will be
needed to store each element. A secondary advantage to this is that we can be
explicit about what types are allowed in this vector. If Rust allowed a vector
to hold any type, there would be a chance that one or more of the types would
cause errors with the operations performed on the elements of the vector. Using
an enum plus a <code>match</code> means that Rust will ensure at compile time that we
always handle every possible case, as we discussed in Chapter 6.</p>
<!-- Can you briefly explain what the match is doing here, as a recap? How does
it mean we always handle every possible case? I'm not sure it's totally clear.
-->
<!-- Because this is a focus of chapter 6 rather than this chapter's focus, we
don't think we should repeat it here as well, but we added a reference. /Carol
-->
<p>If you don't know at the time that you're writing a program the exhaustive set
of types the program will get at runtime to store in a vector, the enum
technique won't work. Insetad, you can use a trait object, which we'll cover in
Chapter 13.</p>
<p>Now that we've gone over some of the most common ways to use vectors, be sure
to take a look at the API documentation for all of the many useful methods
defined on <code>Vec</code> by the standard library. For example, in addition to <code>push</code>
there's a <code>pop</code> method that will remove and return the last element. Let's move
on to the next collection type: <code>String</code>!</p>
<!-- Do you mean the Rust online documentation here? Are you not including it
in the book for space reasons? We might want to justify sending them out of the
book if we don't want to cover it here -->
<!-- Yes, there are many, many methods on Vec: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
Also there are occcasionally new methods available with new versions of the
language, so there's no way we can be comprehensive here. We want the reader to
use the API documentation in these situations since the purpose of the online
docs is to be comprehensive and up to date. I personally wouldn't expect a book
like this to duplicate the info that's in the API docs, so I don't think a
justification is necessary here. /Carol -->
<h2>Strings</h2>
<p>We've already talked about strings a bunch in Chapter 4, but let's take a more
in-depth look at them now. Strings are an area that new Rustaceans commonly get
stuck on. This is due to a combination of three things: Rust's propensity for
making sure to expose possible errors, strings being a more complicated data
structure than many programmers give them credit for, and UTF-8. These things
combine in a way that can seem difficult when coming from other languages.</p>
<p>The reason Strings are in the collections chapter is that strings are
implemented as a collection of bytes plus some methods to provide useful
functionality when those bytes are interpreted as text. In this section, we'll
talk about the operations on <code>String</code> that every collection type has, like
creating, updating, and reading. We'll also discuss the ways in which <code>String</code>
is different than the other collections, namely how indexing into a <code>String</code> is
complicated by the differences in which people and computers interpret <code>String</code>
data.</p>
<h3>What is a String?</h3>
<p>Before we can dig into those aspects, we need to talk about what exactly we
mean by the term 'string'. Rust actually only has one string type in the core
language itself: <code>str</code>, the string slice, which is usually seen in its borrowed
form, <code>&amp;str</code>. We talked about <em>string slices</em> in Chapter 4: these are a
reference to some UTF-8 encoded string data stored elsewhere. String literals,
for example, are stored in the binary output of the program, and are therefore
string slices.</p>
<p>The type called <code>String</code> is provided in Rust's standard library rather than
coded into the core language, and is a growable, mutable, owned, UTF-8 encoded
string type. When Rustaceans talk about 'strings' in Rust, they usually mean
both the <code>String</code> and the string slice <code>&amp;str</code> types, not just one of those.
This section is largely about <code>String</code>, but both these types are used heavily
in Rust's standard library. Both <code>String</code> and string slices are UTF-8 encoded.</p>
<p>Rust's standard library also includes a number of other string types, such as
<code>OsString</code>, <code>OsStr</code>, <code>CString</code>, and <code>CStr</code>. Library crates may provide even
more options for storing string data. Similar to the <code>*String</code>/<code>*Str</code> naming,
they often provide an owned and borrowed variant, just like <code>String</code>/<code>&amp;str</code>.
These string types may store different encodings or be represented in memory in
a different way, for example. We won't be talking about these other string
types in this chapter; see their API documentation for more about how to use
them and when each is appropriate.</p>
<h3>Creating a New String</h3>
<p>Many of the same operations available with <code>Vec</code> are available with <code>String</code> as
well, starting with the <code>new</code> function to create a string, like so:</p>
<pre><code class="language-rust">let s = String::new();
</code></pre>
<p>This creates a new empty string called <code>s</code> that we can then load data into.</p>
<p>Often, we'll have some initial data that we'd like to start the string off
with. For that, we use the <code>to_string</code> method, which is available on any type
that implements the <code>Display</code> trait, which string literals do:</p>
<pre><code class="language-rust">let data = &quot;initial contents&quot;;
let s = data.to_string();
// the method also works on a literal directly:
let s = &quot;initial contents&quot;.to_string();
</code></pre>
<p>This creates a string containing <code>initial contents</code>.</p>
<p>We can also use the function <code>String::from</code> to create a <code>String</code> from a string
literal. This is equivalent to using <code>to_string</code>:</p>
<pre><code class="language-rust">let s = String::from(&quot;initial contents&quot;);
</code></pre>
<p>Because strings are used for so many things, there are many different generic
APIs that can be used for strings, so there are a lot of options. Some of them
can feel redundant, but they all have their place! In this case, <code>String::from</code>
and <code>.to_string</code> end up doing the exact same thing, so which you choose is a
matter of style.</p>
<p>Remember that strings are UTF-8 encoded, so we can include any properly encoded
data in them:</p>
<pre><code class="language-rust">let hello = &quot;السلام عليكم&quot;;
let hello = &quot;Dobrý den&quot;;
let hello = &quot;Hello&quot;;
let hello = &quot;שָׁלוֹם&quot;;
let hello = &quot;नमस्ते&quot;;
let hello = &quot;こんにちは&quot;;
let hello = &quot;안녕하세요&quot;;
let hello = &quot;你好&quot;;
let hello = &quot;Olá&quot;;
let hello = &quot;Здравствуйте&quot;;
let hello = &quot;Hola&quot;;
</code></pre>
<h3>Updating a String</h3>
<p>A <code>String</code> can can grow in size and its contents can change just like the
contents of a <code>Vec</code>, by pushing more data into it. In addition, <code>String</code> has
concatenation operations implemented with the <code>+</code> operator for convenience.</p>
<h4>Appending to a String with Push</h4>
<p>We can grow a <code>String</code> by using the <code>push_str</code> method to append a string slice:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;foo&quot;);
s.push_str(&quot;bar&quot;);
</code></pre>
<p><code>s</code> will contain &quot;foobar&quot; after these two lines. The <code>push_str</code> method takes a
string slice because we don't necessarily want to take ownership of the
argument. For example, it would be unfortunate if we weren't able to use <code>s2</code>
after appending its contents to <code>s1</code>:</p>
<pre><code class="language-rust">let mut s1 = String::from(&quot;foo&quot;);
let s2 = String::from(&quot;bar&quot;);
s1.push_str(&amp;s2);
</code></pre>
<p>The <code>push</code> method is defined to take a single character as an argument and add
it to the <code>String</code>:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;lo&quot;);
s.push('l');
</code></pre>
<p>After this, <code>s</code> will contain &quot;lol&quot;.</p>
<h4>Concatenation with the + Operator or the <code>format!</code> Macro</h4>
<p>Often, we'll want to combine two existing strings together. One way is to use
the <code>+</code> operator like this:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;Hello, &quot;);
let s2 = String::from(&quot;world!&quot;);
let s3 = s1 + &amp;s2; // Note that s1 has been moved here and can no longer be used
</code></pre>
<p>After this code the String <code>s3</code> will contain <code>Hello, world!</code>. The reason that
<code>s1</code> is no longer valid after the addition and the reason that we used a
reference to <code>s2</code> has to do with the signature of the method that gets called
when we use the <code>+</code> operator. The <code>+</code> operator uses the <code>add</code> method, whose
signature looks something like this:</p>
<pre><code class="language-rust,ignore">fn add(self, s: &amp;str) -&gt; String {
</code></pre>
<p>This isn't the exact signature that's in the standard library; there <code>add</code> is
defined using generics. Here, we're looking at the signature of <code>add</code> with
concrete types substituted for the generic ones, which is what happens when we
call this method with <code>String</code> values. This signature gives us the clues we
need to understand the tricky bits of the <code>+</code> operator.</p>
<p>First of all, <code>s2</code> has an <code>&amp;</code>, meaning that we are adding a <em>reference</em> of the
second string to the first string. This is because of the <code>s</code> argument in the
<code>add</code> function: we can only add a <code>&amp;str</code> to a <code>String</code>, we can't add two
<code>String</code>s together. Remember back in Chapter 4 when we talked about how
<code>&amp;String</code> will coerce to <code>&amp;str</code>: we write <code>&amp;s2</code> so that the <code>String</code> will
coerce to the proper type, <code>&amp;str</code>. Because this method does not take ownership
of the argument, <code>s2</code> will still be valid after this operation.</p>
<p>Second, we can see in the signature that <code>add</code> takes ownership of <code>self</code>,
because <code>self</code> does <em>not</em> have an <code>&amp;</code>. This means <code>s1</code> in the above example
will be moved into the <code>add</code> call and no longer be valid after that. So while
<code>let s3 = s1 + &amp;s2;</code> looks like it will copy both strings and create a new one,
this statement actually takes ownership of <code>s1</code>, appends a copy of <code>s2</code>'s
contents, then returns ownership of the result. In other words, it looks like
it's making a lot of copies, but isn't: the implementation is more efficient
than copying.</p>
<p>If we need to concatenate multiple strings, the behavior of <code>+</code> gets unwieldy:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;tic&quot;);
let s2 = String::from(&quot;tac&quot;);
let s3 = String::from(&quot;toe&quot;);
let s = s1 + &quot;-&quot; + &amp;s2 + &quot;-&quot; + &amp;s3;
</code></pre>
<p><code>s</code> will be &quot;tic-tac-toe&quot; at this point. With all of the <code>+</code> and <code>&quot;</code>
characters, it gets hard to see what's going on. For more complicated string
combining, we can use the <code>format!</code> macro:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;tic&quot;);
let s2 = String::from(&quot;tac&quot;);
let s3 = String::from(&quot;toe&quot;);
let s = format!(&quot;{}-{}-{}&quot;, s1, s2, s3);
</code></pre>
<!-- Are we going to discuss the format macro elsewhere at all? If not, some
more info here might be good, this seems like a really useful tool. Is it only
used on strings? -->
<!-- No, we weren't planning on it. We thought it would be sufficient to
mention that it works the same way as `println!` since we've covered how
`println!` works in Ch 2, "Printing Values with `println!` Placeholders" and Ch
5, Ch 5, "Adding Useful Functionality with Derived Traits". `format!` can be
used on anything that `println!` can; using `{}` in the format string works
with anything that implements the `Display` trait and `{:?}` works with
anything that implements the `Debug` trait. Do you have any thoughts on how we
could make the similarities with `format!` and `println!` clearer than what we
have in the next paragraph without repeating the `println!` content too much?
/Carol -->
<p>This code will also set <code>s</code> to &quot;tic-tac-toe&quot;. The <code>format!</code> macro works in the
same way as <code>println!</code>, but instead of printing the output to the screen, it
returns a <code>String</code> with the contents. This version is much easier to read, and
also does not take ownership of any of its arguments.</p>
<h3>Indexing into Strings</h3>
<p>In many other languages, accessing individual characters in a string by
referencing them by index is a valid and common operation. In Rust, however, if
we try to access parts of a <code>String</code> using indexing syntax, we'll get an error.
That is, this code:</p>
<pre><code class="language-rust,ignore">let s1 = String::from(&quot;hello&quot;);
let h = s1[0];
</code></pre>
<p>will result in this error:</p>
<pre><code class="language-text">error: the trait bound `std::string::String: std::ops::Index&lt;_&gt;` is not
satisfied [--explain E0277]
|&gt;
|&gt; let h = s1[0];
|&gt; ^^^^^
note: the type `std::string::String` cannot be indexed by `_`
</code></pre>
<p>The error and the note tell the story: Rust strings don't support indexing. So
the follow-up question is, why not? In order to answer that, we have to talk a
bit about how Rust stores strings in memory.</p>
<h4>Internal Representation</h4>
<p>A <code>String</code> is a wrapper over a <code>Vec&lt;u8&gt;</code>. Let's take a look at some of our
properly-encoded UTF-8 example strings from before. First, this one:</p>
<pre><code class="language-rust">let len = &quot;Hola&quot;.len();
</code></pre>
<p>In this case, <code>len</code> will be four, which means the <code>Vec</code> storing the string
&quot;Hola&quot; is four bytes long: each of these letters takes one byte when encoded in
UTF-8. What about this example, though?</p>
<pre><code class="language-rust">let len = &quot;Здравствуйте&quot;.len();
</code></pre>
<p>A person asked how long the string is might say 12. However, Rust's answer
is 24. This is the number of bytes that it takes to encode &quot;Здравствуйте&quot; in
UTF-8, since each character takes two bytes of storage. Therefore, an index
into the string's bytes will not always correlate to a valid character.</p>
<p>To demonstrate, consider this invalid Rust code:</p>
<pre><code class="language-rust,ignore">let hello = &quot;Здравствуйте&quot;;
let answer = &amp;hello[0];
</code></pre>
<p>What should the value of <code>answer</code> be? Should it be <code>З</code>, the first letter? When
encoded in UTF-8, the first byte of <code>З</code> is <code>208</code>, and the second is <code>151</code>, so
<code>answer</code> should in fact be <code>208</code>, but <code>208</code> is not a valid character on its
own. Returning <code>208</code> is likely not what a person would want if they asked for
the first letter of this string, but that's the only data that Rust has at byte
index 0. Returning the byte value is probably not what people want, even with
only latin letters: <code>&amp;&quot;hello&quot;[0]</code> would return <code>104</code>, not <code>h</code>. To avoid
returning an unexpected value and causing bugs that might not be discovered
immediately, Rust chooses to not compile this code at all and prevent
misunderstandings earlier.</p>
<h4>Bytes and Scalar Values and Grapheme Clusters! Oh my!</h4>
<p>This leads to another point about UTF-8: there are really three relevant ways
to look at strings, from Rust's perspective: as bytes, scalar values, and
grapheme clusters (the closest thing to what people would call 'letters').</p>
<p>If we look at the Hindi word &quot;नमस्ते&quot; written in the Devanagari script, it is
ultimately stored as a <code>Vec</code> of <code>u8</code> values that looks like this:</p>
<pre><code class="language-text">[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135]
</code></pre>
<p>That's 18 bytes, and is how computers ultimately store this data. If we look at
them as Unicode scalar values, which are what Rust's <code>char</code> type is, those
bytes look like this:</p>
<pre><code class="language-text">['न', 'म', 'स', '्', 'त', 'े']
</code></pre>
<p>There are six <code>char</code> values here, but the fourth and sixth are not letters,
they're diacritics that don't make sense on their own. Finally, if we look at
them as grapheme clusters, we'd get what a person would call the four letters
that make up this word:</p>
<pre><code class="language-text">[&quot;न&quot;, &quot;म&quot;, &quot;स्&quot;, &quot;ते&quot;]
</code></pre>
<p>Rust provides different ways of interpreting the raw string data that computers
store so that each program can choose the interpretation it needs, no matter
what human language the data is in.</p>
<p>A final reason Rust does not allow you to index into a <code>String</code> to get a
character is that indexing operations are expected to always take constant time
(O(1)). It isn't possible to guarantee that performance with a <code>String</code>,
though, since Rust would have to walk through the contents from the beginning
to the index to determine how many valid characters there were.</p>
<p>All of these problems mean that Rust does not implement <code>[]</code> for <code>String</code>, so
we cannot directly do this.</p>
<h3>Slicing Strings</h3>
<p>However, indexing the <em>bytes</em> of a string is very useful, and is not expected
to be fast. While we can't use <code>[]</code> with a single number, we <em>can</em> use <code>[]</code>
with a range to create a string slice containing particular bytes:</p>
<pre><code class="language-rust">let hello = &quot;Здравствуйте&quot;;
let s = &amp;hello[0..4];
</code></pre>
<p>Here, <code>s</code> will be a <code>&amp;str</code> that contains the first four bytes of the string.
Earlier, we mentioned that each of these characters was two bytes, so that
means that <code>s</code> will be &quot;Зд&quot;.</p>
<p>What would happen if we did <code>&amp;hello[0..1]</code>? The answer: it will panic at
runtime, in the same way that accessing an invalid index in a vector does:</p>
<pre><code class="language-text">thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not lie on
character boundary', ../src/libcore/str/mod.rs:1694
</code></pre>
<p>You should use this with caution, since it can cause your program to crash.</p>
<h3>Methods for Iterating Over Strings</h3>
<p>Luckily, there are other ways we can access elements in a String.</p>
<p>If we need to perform operations on individual characters, the best way to do
so is to use the <code>chars</code> method. Calling <code>chars</code> on &quot;नमस्ते&quot; separates out and
returns six values of type <code>char</code>, and you can iterate over the result in order
to access each element:</p>
<pre><code class="language-rust">for c in &quot;नमस्ते&quot;.chars() {
println!(&quot;{}&quot;, c);
}
</code></pre>
<p>This code will print:</p>
<pre><code class="language-text">न
म
स
्
त
े
</code></pre>
<p>The <code>bytes</code> method returns each raw byte, which might be appropriate for your
domain:</p>
<pre><code class="language-rust">for b in &quot;नमस्ते&quot;.bytes() {
println!(&quot;{}&quot;, b);
}
</code></pre>
<p>This code will print the 18 bytes that make up this <code>String</code>, starting with:</p>
<pre><code class="language-text">224
164
168
224
// ... etc
</code></pre>
<p>But make sure to remember that valid UTF-8 characters may be made up of more
than one byte.</p>
<p>Getting grapheme clusters from <code>String</code>s is complex, so this functionality is
not provided by the standard library. There are crates available on crates.io
if this is the functionality you need.</p>
<!-- Can you recommend some, or maybe just say why we aren't outlining the
method here, ie it's complicated and therefore best to use a crate? -->
<!-- We're trying not to mention too many crates in the book. Most crates are
provided by the community, so we don't want to mention some and not others and
seem biased towards certain crates, plus crates can change more quickly (and
new crates can be created) than the language and this book will. /Carol -->
<h3>Strings are Not so Simple</h3>
<p>To summarize, strings are complicated. Different programming languages make
different choices about how to present this complexity to the programmer. Rust
has chosen to make the correct handling of <code>String</code> data the default behavior
for all Rust programs, which does mean programmers have to put more thought
into handling UTF-8 data upfront. This tradeoff exposes more of the complexity
of strings than other programming languages do, but this will prevent you from
having to handle errors involving non-ASCII characters later in your
development lifecycle.</p>
<p>Let's switch to something a bit less complex: Hash Map!</p>
<h2>Hash Maps</h2>
<p>The last of our fundamental collections is the <em>hash map</em>. The type <code>HashMap&lt;K, V&gt;</code> stores a mapping of keys of type <code>K</code> to values of type <code>V</code>. It does this
via a <em>hashing function</em>, which determines how it places these keys and values
into memory. Many different programming languages support this kind of data
structure, but often with a different name: hash, map, object, hash table, or
associative array, just to name a few.</p>
<p>Hash maps are useful for when you want to be able to look up data not by an
index, as you can with vectors, but by using a key that can be of any type. For
example, in a game, you could keep track of each team's score in a hash map
where each key is a team's name and the values are each team's score. Given a
team name, you can retrieve their score.</p>
<p>We'll go over the basic API of hash maps in this chapter, but there are many
more goodies hiding in the functions defined on <code>HashMap</code> by the standard
library. As always, check the standard library documentation for more
information.</p>
<h3>Creating a New Hash Map</h3>
<p>We can create an empty <code>HashMap</code> with <code>new</code>, and add elements with <code>insert</code>.
Here we're keeping track of the scores of two teams whose names are Blue and
Yellow. The Blue team will start with 10 points and the Yellow team starts with
50:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from(&quot;Blue&quot;), 10);
scores.insert(String::from(&quot;Yellow&quot;), 50);
</code></pre>
<p>Note that we need to first <code>use</code> the <code>HashMap</code> from the collections portion of
the standard library. Of our three fundamental collections, this one is the
least often used, so it's not included in the features imported automatically
in the prelude. Hash maps also have less support from the standard library;
there's no built-in macro to construct them, for example.</p>
<p>Just like vectors, hash maps store their data on the heap. This <code>HashMap</code> has
keys of type <code>i32</code> and values of type <code>&amp;str</code>. Like vectors, hash maps are
homogenous: all of the keys must have the same type, and all of the values must
have the same type.</p>
<p>Another way of constructing a hash map is by using the <code>collect</code> method on a
vector of tuples, where each tuple consists of a key and its value. The
<code>collect</code> method gathers up data into a number of collection types, including
<code>HashMap</code>. For example, if we had the team names and initial scores in two
separate vectors, we can use the <code>zip</code> method to create a vector of tuples
where &quot;Blue&quot; is paired with 10, and so forth. Then we can use the <code>collect</code>
method to turn that vector of tuples into a <code>HashMap</code>:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let teams = vec![String::from(&quot;Blue&quot;), String::from(&quot;Yellow&quot;)];
let initial_scores = vec![10, 50];
let scores: HashMap&lt;_, _&gt; = teams.iter().zip(initial_scores.iter()).collect();
</code></pre>
<p>The type annotation <code>HashMap&lt;_, _&gt;</code> is needed here because it's possible to
<code>collect</code> into many different data structures, and Rust doesn't know which you
want unless you specify. For the type parameters for the key and value types,
however, we use underscores and Rust can infer the types that the hash map
contains based on the types of the data in the vector.</p>
<h3>Hashmaps and Ownership</h3>
<p>For types that implement the <code>Copy</code> trait, like <code>i32</code>, the values are copied
into the hash map. For owned values like <code>String</code>, the values will be moved and
the hash map will be the owner of those values:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let field_name = String::from(&quot;Favorite color&quot;);
let field_value = String::from(&quot;Blue&quot;);
let mut map = HashMap::new();
map.insert(field_name, field_value);
// field_name and field_value are invalid at this point
</code></pre>
<p>We would not be able to use the bindings <code>field_name</code> and <code>field_value</code> after
they have been moved into the hash map with the call to <code>insert</code>.</p>
<p>If we insert references to values into the hash map, the values themselves will
not be moved into the hash map. The values that the references point to must be
valid for at least as long as the hash map is valid, though. We will talk more
about these issues in the Lifetimes section of Chapter 10.</p>
<h3>Accessing Values in a Hash Map</h3>
<p>We can get a value out of the hash map by providing its key to the <code>get</code> method:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from(&quot;Blue&quot;), 10);
scores.insert(String::from(&quot;Yellow&quot;), 50);
let team_name = String::from(&quot;Blue&quot;);
let score = scores.get(&amp;team_name);
</code></pre>
<p>Here, <code>score</code> will have the value that's associated with the Blue team, and the
result will be <code>Some(10)</code>. The result is wrapped in <code>Some</code> because <code>get</code>
returns an <code>Option&lt;V&gt;</code>; if there's no value for that key in the hash map, <code>get</code>
will return <code>None</code>. The program will need to handle the <code>Option</code> in one of
the ways that we covered in Chapter 6.</p>
<p>We can iterate over each key/value pair in a hash map in a similar manner as we
do with vectors, using a <code>for</code> loop:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from(&quot;Blue&quot;), 10);
scores.insert(String::from(&quot;Yellow&quot;), 50);
for (key, value) in &amp;scores {
println!(&quot;{}: {}&quot;, key, value);
}
</code></pre>
<p>This will print each pair, in an arbitrary order:</p>
<pre><code class="language-text">Yellow: 50
Blue: 10
</code></pre>
<h3>Updating a Hash Map</h3>
<!-- So the quantity of keys must be defined up front, that's not growable?
That could be worthy saying -->
<!-- No, the number of keys is growable, it's just that for EACH individual
key, there can only be one value. I've tried to clarify. /Carol -->
<p>While the number of keys and values is growable, each individual key can only
have one value associated with it at a time. When we want to change the data in
a hash map, we have to decide how to handle the case when a key already has a
value assigned. We could choose to replace the old value with the new value,
completely disregarding the old value. We could choose to keep the old value
and ignore the new value, and only add the new value if the key <em>doesn't</em>
already have a value. Or we could combine the old value and the new value.
Let's look at how to do each of these!</p>
<h4>Overwriting a Value</h4>
<p>If we insert a key and a value into a hashmap, then insert that same key with a
different value, the value associated with that key will be replaced. Even
though this following code calls <code>insert</code> twice, the hash map will only contain
one key/value pair because we're inserting the value for the Blue team's key
both times:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from(&quot;Blue&quot;), 10);
scores.insert(String::from(&quot;Blue&quot;), 25);
println!(&quot;{:?}&quot;, scores);
</code></pre>
<p>This will print <code>{&quot;Blue&quot;: 25}</code>. The original value of 25 has been overwritten.</p>
<h4>Only Insert If the Key Has No Value</h4>
<p>It's common to want to check if a particular key has a value and, if it does
not, insert a value for it. Hash maps have a special API for this, called
<code>entry</code>, that takes the key we want to check as an argument. The return value
of the <code>entry</code> function is an enum, <code>Entry</code>, that represents a value that might
or might not exist. Let's say that we want to check if the key for the Yellow
team has a value associated with it. If it doesn't, we want to insert the value
50, and the same for the Blue team. With the entry API, the code for this
looks like:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert(String::from(&quot;Blue&quot;), 10);
scores.entry(String::from(&quot;Yellow&quot;)).or_insert(50);
scores.entry(String::from(&quot;Blue&quot;)).or_insert(50);
println!(&quot;{:?}&quot;, scores);
</code></pre>
<p>The <code>or_insert</code> method on <code>Entry</code> returns the value for the <code>Entry</code>'s key if it
exists, and if not, inserts its argument as the new value for the <code>Entry</code>'s key
and returns that. This is much cleaner than writing the logic ourselves, and in
addition, plays more nicely with the borrow checker.</p>
<p>This code will print <code>{&quot;Yellow&quot;: 50, &quot;Blue&quot;: 10}</code>. The first call to <code>entry</code>
will insert the key for the Yellow team with the value 50, since the Yellow
team doesn't have a value already. The second call to <code>entry</code> will not change
the hash map since the Blue team already has the value 10.</p>
<h4>Update a Value Based on the Old Value</h4>
<p>Another common use case for hash maps is to look up a key's value then update
it, based on the old value. For instance, if we wanted to count how many times
each word appeared in some text, we could use a hash map with the words as keys
and increment the value to keep track of how many times we've seen that word.
If this is the first time we've seen a word, we'll first insert the value <code>0</code>.</p>
<pre><code class="language-rust">use std::collections::HashMap;
let text = &quot;hello world wonderful world&quot;;
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!(&quot;{:?}&quot;, map);
</code></pre>
<p>This will print <code>{&quot;world&quot;: 2, &quot;hello&quot;: 1, &quot;wonderful&quot;: 1}</code>. The <code>or_insert</code>
method actually returns a mutable reference (<code>&amp;mut V</code>) to the value for this
key. Here we store that mutable reference in the <code>count</code> variable, so in order
to assign to that value we must first dereference <code>count</code> using the asterisk
(<code>*</code>). The mutable reference goes out of scope at the end of the <code>for</code> loop, so
all of these changes are safe and allowed by the borrowing rules.</p>
<h3>Hashing Function</h3>
<p>By default, <code>HashMap</code> uses a cryptographically secure hashing function that can
provide resistance to Denial of Service (DoS) attacks. This is not the fastest
hashing algorithm out there, but the tradeoff for better security that comes
with the drop in performance is worth it. If you profile your code and find
that the default hash function is too slow for your purposes, you can switch to
another function by specifying a different <em>hasher</em>. A hasher is a type that
implements the <code>BuildHasher</code> trait. We'll be talking about traits and how to
implement them in Chapter 10.</p>
<h2>Summary</h2>
<p>Vectors, strings, and hash maps will take you far in programs where you need to
store, access, and modify data. Here are some exercises you should now be
equipped to solve:</p>
<ol>
<li>Given a list of integers, use a vector and return the mean (average), median
(when sorted, the value in the middle position), and mode (the value that
occurs most often; a hash map will be helpful here) of the list.</li>
<li>Convert strings to Pig Latin, where the first consonant of each word is
moved to the end of the word with an added &quot;ay&quot;, so &quot;first&quot; becomes
&quot;irst-fay&quot;. Words that start with a vowel get &quot;hay&quot; added to the end instead
(&quot;apple&quot; becomes &quot;apple-hay&quot;). Remember about UTF-8 encoding!</li>
<li>Using a hash map and vectors, create a text interface to allow a user to add
employee names to a department in the company. For example, &quot;Add Sally to
Engineering&quot; or &quot;Add Amir to Sales&quot;. Then let the user retrieve a list of all
people in a department or all people in the company by department, sorted
alphabetically.</li>
</ol>
<p>The standard library API documentation describes methods these types have that
will be helpful for these exercises!</p>
<p>We're getting into more complex programs where operations can fail, which means
it's a perfect time to go over error handling next!</p>
<h1>Error Handling</h1>
<p>Rust's focus on reliability extends to the area of error handling. Errors are a
fact of life in software, so Rust has a number of features that you can use to
handle situations in which something bad happens. In many cases, Rust requires
you to acknowledge the possibility of an error occurring and take some action
in that situation. This makes your program more robust by eliminating the
possibility of unexpected errors only being discovered after you've deployed
your code to production.</p>
<p>Rust groups errors into two major kinds: errors that are <em>recoverable</em>, and
errors that are <em>unrecoverable</em>. Recoverable errors are problems like a file not
being found, where it's usually reasonable to report that problem to the user
and retry the operation. Unrecoverable errors are problems like trying to
access a location beyond the end of an array, and these are always symptoms of
bugs.</p>
<p>Most languages do not distinguish between the two kinds of errors, so they
handle both kinds in the same way using mechanisms like exceptions. Rust
doesn't have exceptions. Instead, it has the value <code>Result&lt;T, E&gt;</code> to return in
the case of recoverable errors and the <code>panic!</code> macro that stops execution when
it encounters unrecoverable errors. This chapter will cover the more
straightforward case of calling <code>panic!</code> first. Then, we'll talk about
returning <code>Result&lt;T, E&gt;</code> values and calling functions that return <code>Result&lt;T, E&gt;</code>. Finally, we'll discuss considerations to take into account when deciding
whether to try to recover from an error or to stop execution.</p>
<h2>Unrecoverable Errors with <code>panic!</code></h2>
<p>Sometimes, bad things happen, and there's nothing that you can do about it. For
these cases, Rust has a macro, <code>panic!</code>. When this macro executes, your program
will print a failure message, unwind and clean up the stack, and then quit. The
most common reason for this is when a bug of some kind has been detected, and
it's not clear how to handle the error.</p>
<!-- PROD: START BOX -->
<blockquote>
<h4>Unwinding</h4>
<p>By default, when a <code>panic!</code> happens in Rust, the program starts
<em>unwinding</em>, which means Rust walks back up the stack and cleans up the data
from each function it encounters. Doing that walking and cleanup is a lot of
work. The alternative is to immediately <code>abort</code>, which ends the program
without cleaning up. Memory that the program was using will need to be cleaned
up by the operating system. If you're in a situation where you need to make
the resulting binary as small as possible, you can switch from unwinding on
panic to aborting on panic by adding <code>panic = 'abort'</code> to the appropriate
<code>[profile]</code> sections in your <em>Cargo.toml</em>.</p>
</blockquote>
<!-- PROD: END BOX -->
<p>Let's try out calling <code>panic!()</code> with a simple program:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,should_panic">fn main() {
panic!(&quot;crash and burn&quot;);
}
</code></pre>
<p>If you run it, you'll see something like this:</p>
<pre><code class="language-text">$ cargo run
Compiling panic v0.1.0 (file:///projects/panic)
Finished debug [unoptimized + debuginfo] target(s) in 0.25 secs
Running `target/debug/panic`
thread 'main' panicked at 'crash and burn', src/main.rs:2
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
</code></pre>
<p>There are three lines of error message here. The first line shows our panic
message and the place in our source code where the panic occurred:
<em>src/main.rs</em>, line two.</p>
<p>But that only shows us the exact line that called <code>panic!</code>. That's not always
useful. Let's look at another example to see what it's like when a <code>panic!</code>
call comes from code we call instead of from our code directly:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,should_panic">fn main() {
let v = vec![1, 2, 3];
v[100];
}
</code></pre>
<p>We're attempting to access the hundredth element of our vector, but it only has
three elements. In this situation, Rust will panic. Using <code>[]</code> is supposed to
return an element. If you pass <code>[]</code> an invalid index, though, there's no
element that Rust could return here that would be correct.</p>
<p>Other languages like C will attempt to give you exactly what you asked for in
this situation, even though it isn't what you want: you'll get whatever is at
the location in memory that would correspond to that element in the vector,
even though the memory doesn't belong to the vector. This is called a <em>buffer
overread</em>, and can lead to security vulnerabilities if an attacker can
manipulate the index in such a way as to read data they shouldn't be allowed to
that is stored after the array.</p>
<p>In order to protect your program from this sort of vulnerability, if you try to
read an element at an index that doesn't exist, Rust will stop execution and
refuse to continue with an invalid value. Let's try it and see:</p>
<pre><code class="language-text">$ cargo run
Compiling panic v0.1.0 (file:///projects/panic)
Finished debug [unoptimized + debuginfo] target(s) in 0.27 secs
Running `target/debug/panic`
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is
100', ../src/libcollections/vec.rs:1265
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
</code></pre>
<p>This points at a file we didn't write, <em>../src/libcollections/vec.rs</em>. That's
the implementation of <code>Vec&lt;T&gt;</code> in the standard library. While it's easy to see
in this short program where the error was, it would be nicer if we could have
Rust tell us what line in our program caused the error.</p>
<p>That's what the next line, the <code>note</code> is about. If we set the <code>RUST_BACKTRACE</code>
environment variable, we'll get a backtrace of exactly how the error happend.
Let's try that. Listing 9-1 shows the output:</p>
<figure>
<pre><code class="language-text">$ RUST_BACKTRACE=1 cargo run
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/panic`
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is
100', ../src/libcollections/vec.rs:1265
stack backtrace:
1: 0x560956150ae9 -
std::sys::backtrace::tracing::imp::write::h482d45d91246faa2
2: 0x56095615345c -
std::panicking::default_hook::_{{closure}}::h89158f66286b674e
3: 0x56095615291e - std::panicking::default_hook::h9e30d428ee3b0c43
4: 0x560956152f88 -
std::panicking::rust_panic_with_hook::h2224f33fb7bf2f4c
5: 0x560956152e22 - std::panicking::begin_panic::hcb11a4dc6d779ae5
6: 0x560956152d50 - std::panicking::begin_panic_fmt::h310416c62f3935b3
7: 0x560956152cd1 - rust_begin_unwind
8: 0x560956188a2f - core::panicking::panic_fmt::hc5789f4e80194729
9: 0x5609561889d3 -
core::panicking::panic_bounds_check::hb2d969c3cc11ed08
10: 0x56095614c075 - _&lt;collections..vec..Vec&lt;T&gt; as
core..ops..Index&lt;usize&gt;&gt;::index::hb9f10d3dadbe8101
at ../src/libcollections/vec.rs:1265
11: 0x56095614c134 - panic::main::h2d7d3751fb8705e2
at /projects/panic/src/main.rs:4
12: 0x56095615af46 - __rust_maybe_catch_panic
13: 0x560956152082 - std::rt::lang_start::h352a66f5026f54bd
14: 0x56095614c1b3 - main
15: 0x7f75b88ed72f - __libc_start_main
16: 0x56095614b3c8 - _start
17: 0x0 - &lt;unknown&gt;
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
</code></pre>
<figcaption>
<p>Listing 9-1: The backtrace generated by a call to <code>panic!</code> displayed when
the environment variable <code>RUST_BACKTRACE</code> is set</p>
</figcaption>
</figure>
<p>That's a lot of output! Line 11 of the backtrace points to the line in our
project causing the problem: <em>src/main.rs</em> line four. The key to reading the
backtrace is to start from the top and read until we see files that we wrote:
that's where the problem originated. If we didn't want our program to panic
here, this line is where we would start investigating in order to figure out
how we got to this location with values that caused the panic.</p>
<p>Now that we've covered how to <code>panic!</code> to stop our code's execution and how to
debug a <code>panic!</code>, let's look at how to instead return and use recoverable
errors with <code>Result</code>.</p>
<h2>Recoverable Errors with <code>Result</code></h2>
<p>Most errors aren't so dire. Sometimes, when a function fails, it's for a reason
that we can easily interpret and respond to. As an example, maybe we are making
a request to a website, but it's down for maintenance. In this situation, we'd
like to wait and then try again. Terminating our process isn't the right thing
to do here.</p>
<p>In these cases, Rust's standard library provides an <code>enum</code> to use as the return
type of the function:</p>
<pre><code class="language-rust">enum Result&lt;T, E&gt; {
Ok(T),
Err(E),
}
</code></pre>
<p>The <code>Ok</code> variant indicates a successful result, and <code>Err</code> indicates an
unsuccessful result. These two variants each contain one thing: in <code>Ok</code>'s case,
it's the successful return value. With <code>Err</code>, it's some value that represents
the error. The <code>T</code> and <code>E</code> are generic type parameters; we'll go into generics
in more detail in Chapter 10. What you need to know for right now is that the
<code>Result</code> type is defined such that it can have the same behavior for any type
<code>T</code> that is what we want to return in the success case, and any type <code>E</code> that
is what we want to return in the error case.</p>
<p>Listing 9-2 shows an example of something that might fail: opening a file.</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">use std::fs::File;
fn main() {
let f = File::open(&quot;hello.txt&quot;);
}
</code></pre>
<figcaption>
<p>Listing 9-2: Opening a file</p>
</figcaption>
</figure>
<p>The type of <code>f</code> in this example is a <code>Result</code>, because there are many ways in
which opening a file can fail. For example, unless we created <code>hello.txt</code>, this
file does not yet exist. Before we can do anything with our <code>File</code>, we need to
extract it out of the result. Listing 9-3 shows one way to handle the <code>Result</code>
with a basic tool: the <code>match</code> expression that we learned about in Chapter 6.</p>
<!-- I'll ghost everything except the match statement lines in the libreoffice file /Carol -->
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,should_panic">use std::fs::File;
fn main() {
let f = File::open(&quot;hello.txt&quot;);
let f = match f {
Ok(file) =&gt; file,
Err(error) =&gt; panic!(&quot;There was a problem opening the file: {:?}&quot;,
error),
};
}
</code></pre>
<figcaption>
<p>Listing 9-3: Using a <code>match</code> expression to handle the <code>Result</code> variants we
might have</p>
</figcaption>
</figure>
<p>If we see an <code>Ok</code>, we can return the inner <code>file</code> out of the <code>Ok</code> variant. If
we see <code>Err</code>, we have to decide what to do with it. The simplest thing is to
turn our error into a <code>panic!</code> instead, by calling the macro. And since we
haven't created that file yet, we'll see a message indicating as such when we
print the error value:</p>
<pre><code class="language-text">thread 'main' panicked at 'There was a problem opening the file: Error { repr:
Os { code: 2, message: &quot;No such file or directory&quot; } }', src/main.rs:8
</code></pre>
<h3>Matching on Different Errors</h3>
<p>There are many reasons why opening a file might fail, and we may not want to
take the same actions to try to recover for all of them. For example, if the
file we're trying to open does not exist, we could choose to create it. If the
file exists but we don't have permission to read it, or any other error, we
still want to <code>panic!</code> in the same way as above and not create the file.</p>
<p>The <code>Err</code> type <code>File::open</code> returns is <a href="../std/io/struct.Error.html"><code>io::Error</code></a><!-- ignore -->,
which is a struct provided by the standard library. This struct has a method
<code>kind</code> that we can call to get an <a href="../std/io/enum.ErrorKind.html"><code>io::ErrorKind</code></a><!-- ignore -->
value that we can use to handle different causes of an <code>Err</code> returned from
<code>File::open</code> differently as in Listing 9-4:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">use std::fs::File;
use std::io::ErrorKind;
fn main() {
let f = File::open(&quot;hello.txt&quot;);
let f = match f {
Ok(file) =&gt; file,
Err(ref error) if error.kind() == ErrorKind::NotFound =&gt; {
match File::create(&quot;hello.txt&quot;) {
Ok(fc) =&gt; fc,
Err(e) =&gt; panic!(&quot;Tried to create file but there was a problem: {:?}&quot;, e),
}
},
Err(error) =&gt; panic!(&quot;There was a problem opening the file: {:?}&quot;,
error),
};
}
</code></pre>
<figcaption>
<p>Listing 9-4: Handling different kinds of errors in different ways</p>
</figcaption>
</figure>
<!-- I will add ghosting and wingdings here in libreoffice /Carol -->
<p>This example uses a <em>match guard</em> with the second arm's pattern to add a
condition that further refines the pattern. The <code>ref</code> in the pattern is needed
so that the <code>error</code> is not moved into the guard condition. The condition we
want to check is that the value <code>error.kind()</code> returns is the <code>NotFound</code>
variant of the <code>ErrorKind</code> enum. Note that <code>File::create</code> could also fail, so
we need to add an inner <code>match</code> statement as well! The last arm of the outer
<code>match</code> stays the same to panic on any error besides the file not being found.</p>
<h3>Shortcuts for Panic on Error: <code>unwrap</code> and <code>expect</code></h3>
<p>Using <code>match</code> works okay but can be a bit verbose, and it doesn't always
communicate intent well. The <code>Result&lt;T, E&gt;</code> type has many helper methods
defined on it to do various things. &quot;Panic on an error result&quot; is one of those
methods, and it's called <code>unwrap()</code>:</p>
<!-- I'll ghost everything except `unwrap()` in the libreoffice file /Carol -->
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,should_panic">use std::fs::File;
fn main() {
let f = File::open(&quot;hello.txt&quot;).unwrap();
}
</code></pre>
<p>This has similar behavior as the example using <code>match</code> in Listing 9-3: If the
call to <code>open()</code> returns <code>Ok</code>, return the value inside. If it's an <code>Err</code>, panic.</p>
<p>There's also another method that is similar to <code>unwrap()</code>, but lets us choose
the error message: <code>expect()</code>. Using <code>expect()</code> instead of <code>unwrap()</code> and
providing good error messages can convey your intent and make tracking down the
source of a panic easier. <code>expect()</code> looks like this:</p>
<!-- I'll ghost everything except `expect()` in the libreoffice file /Carol -->
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,should_panic">use std::fs::File;
fn main() {
let f = File::open(&quot;hello.txt&quot;).expect(&quot;Failed to open hello.txt.&quot;);
}
</code></pre>
<p>This isn't the only way to deal with errors, however. This entire section is
supposed to be about recovering from errors, but we've gone back to panic. This
observation gets at an underlying truth: you can easily turn a recoverable
error into an unrecoverable one with <code>unwrap()</code> or <code>expect()</code>, but you can't
turn an unrecoverable <code>panic!</code> into a recoverable one. This is why good Rust
code chooses to make errors recoverable: you give your caller choices.</p>
<p>The Rust community has a love/hate relationship with <code>unwrap()</code> and <code>expect()</code>.
They're very handy when prototyping, before you're ready to decide how to
handle errors, and in that case they leave clear markers to look for when you
are ready to make your program more robust. They're useful in tests since they
will cause the test to fail if there's an error any place you call them. In
examples, you might not want to muddy the code with proper error handling. But
if you use them in a library, mis-using your library can cause other people's
programs to halt unexpectedly, and that's not very user-friendly.</p>
<p>Another time it's appropriate to call <code>unwrap</code> is when we have some other logic
that ensures the <code>Result</code> will have an <code>Ok</code> value, but the logic isn't
something the compiler understands. If you can ensure by manually inspecting
the code that you'll never have an <code>Err</code> variant, it is perfectly acceptable to
call <code>unwrap</code>. Here's an example:</p>
<pre><code class="language-rust">use std::net::IpAddr;
let home = &quot;127.0.0.1&quot;.parse::&lt;IpAddr&gt;().unwrap();
</code></pre>
<p>We're creating an <code>IpAddr</code> instance by parsing a hardcoded string. We can see
that <code>&quot;127.0.0.1&quot;</code> is a valid IP address, so it's acceptable to use <code>unwrap</code>
here. If we got the IP address string from a user of our program instead of
hardcoding this value, we'd definitely want to handle the <code>Result</code> in a more
robust way instead.</p>
<h3>Propagating errors with <code>try!</code> or <code>?</code></h3>
<p>When writing a function, if you don't want to handle the error where you are,
you can return the error to the calling function. For example, Listing 9-5
shows a function that reads a username from a file. If the file doesn't exist
or can't be read, this function will return those errors to the code that
called this function:</p>
<figure>
<pre><code class="language-rust"># use std::fs::File;
# use std::io;
# use std::io::Read;
#
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let f = File::open(&quot;hello.txt&quot;);
let mut f = match f {
Ok(file) =&gt; file,
Err(e) =&gt; return Err(e),
};
let mut s = String::new();
match f.read_to_string(&amp;mut s) {
Ok(_) =&gt; Ok(s),
Err(e) =&gt; Err(e),
}
}
</code></pre>
<figcaption>
<p>Listing 9-5: A function that returns errors to the calling code using <code>match</code></p>
</figcaption>
</figure>
<p>Since the <code>Result</code> type has two type parameters, we need to include them both
in our function signature. In this case, <code>File::open</code> and <code>read_to_string</code>
return <code>std::io::Error</code> as the value inside the <code>Err</code> variant, so we will also
use it as our error type. If this function succeeds, we want to return the
username as a <code>String</code> inside the <code>Ok</code> variant, so that is our success type.</p>
<p>This is a very common way of handling errors: propagate them upward until
you're ready to deal with them. This pattern is so common in Rust that there is
a macro for it, <code>try!</code>, and as of Rust 1.14 <!-- 1.14 has not been released as
a stable version yet, but that's the version the question mark operator will be
released in /Carol -->, dedicated syntax for it: the question mark
operator. We could have written the code in Listing 9-5 using the <code>try!</code> macro,
as in Listing 9-6, and it would have the same functionality as the <code>match</code>
expressions:</p>
<!-- I'll ghost everything except the calls to `try!` in the libreoffice file
/Carol -->
<figure>
<pre><code class="language-rust"># use std::fs::File;
# use std::io;
# use std::io::Read;
#
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let mut f = try!(File::open(&quot;hello.txt&quot;));
let mut s = String::new();
try!(f.read_to_string(&amp;mut s));
Ok(s)
}
</code></pre>
<figcaption>
<p>Listing 9-6: A function that returns errors to the calling code using <code>try!</code></p>
</figcaption>
</figure>
<p>Or as in Listing 9-7, which uses the question mark operator:</p>
<figure>
<pre><code class="language-rust"># fn main() {}
# use std::fs::File;
# use std::io;
# use std::io::Read;
#
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let mut f = File::open(&quot;hello.txt&quot;)?;
let mut s = String::new();
f.read_to_string(&amp;mut s)?;
Ok(s)
}
</code></pre>
<figcaption>
<p>Listing 9-7: A function that returns errors to the calling code using <code>?</code></p>
</figcaption>
</figure>
<p>The <code>?</code> operator at the end of the <code>open</code> call does the same thing as the
example that uses <code>match</code> and the example that uses the <code>try!</code> macro: It will
return the value inside an <code>Ok</code> to the binding <code>f</code>, but will return early out
of the whole function and give any <code>Err</code> value we get to our caller. The same
thing applies to the <code>?</code> at the end of the <code>read_to_string</code> call.</p>
<p>The advantage of using the question mark operator over the <code>try!</code> macro is the
question mark operator permits chaining. We could further shorten this code
by instead doing:</p>
<pre><code class="language-rust"># fn main() {}
# use std::fs::File;
# use std::io;
# use std::io::Read;
#
fn read_username_from_file() -&gt; Result&lt;String, io::Error&gt; {
let mut s = String::new();
File::open(&quot;hello.txt&quot;)?.read_to_string(&amp;mut s)?;
Ok(s)
}
</code></pre>
<p>Much nicer, right? The <code>try!</code> macro and the <code>?</code> operator make propagating
errors upwards much more ergonomic. There's one catch though: they can only be
used in functions that return a <code>Result</code>, since they expand to the same <code>match</code>
expression we saw above that had a potential early return of an <code>Err</code> value.
Let's look at what happens if we try to use <code>try!</code> in the <code>main</code> function,
which you'll recall has a return type of <code>()</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore"># use std::fs::File;
fn main() {
let f = try!(File::open(&quot;hello.txt&quot;));
}
</code></pre>
<!-- NOTE: as of 2016-10-12, the error message when calling `?` in a function
that doesn't return a result is confusing. `try!` isn't as bad, so I'm using
that. When https://github.com/rust-lang/rust/issues/35946 is fixed, we can
switch this example to use `?`. /Carol -->
<p>When we compile this, we get the following error message:</p>
<pre><code class="language-text">error[E0308]: mismatched types
--&gt;
|
3 | let f = try!(File::open(&quot;hello.txt&quot;));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
|
= note: expected type `()`
= note: found type `std::result::Result&lt;_, _&gt;`
</code></pre>
<p>The mismatched types that this error is pointing out says the <code>main()</code> function
has a return type of <code>()</code>, but the <code>try!</code> macro might return a <code>Result</code>. So in
functions that don't return <code>Result</code>, when you call other functions that return
<code>Result</code>, you'll need to use a <code>match</code> or one of the methods on <code>Result</code> to
handle it instead of using <code>try!</code> or <code>?</code>.</p>
<p>Now that we've discussed the details of calling <code>panic!</code> or returning <code>Result</code>,
let's return to the topic of how to decide which is appropriate in which cases.</p>
<h2>To <code>panic!</code> or Not To <code>panic!</code></h2>
<p>So how do you decide when you should call <code>panic!</code> and when you should return
<code>Result</code>? A good default for a function that might fail is to return <code>Result</code>
since that gives the caller of your function the most flexibility.</p>
<p>But that answer is simplistic. There are cases where you might want to call
<code>panic!</code> in library code that have to do with Rust's quest for safety. Let's
look at some more nuanced guidelines.</p>
<h3>Guidelines for Error Handling</h3>
<p><code>panic!</code> when your code is in a situation where it's possible to be in a bad
state and:</p>
<ul>
<li>The bad state is not something that's <em>expected</em> to happen occasionally</li>
<li>Your code after this point needs to rely on not being in this bad state</li>
<li>There's not a good way to encode this information in the types you use</li>
</ul>
<p>By <em>bad state</em>, we mean some assumption, guarantee, contract, or invariant has
been broken. Some examples are invalid values, contradictory values, or
nothing when you expect to have something. If someone calls your code and
passes in values that don't make sense, the best thing might be to <code>panic!</code> and
alert the person using your library to the bug in their code so that they can
fix it during development. Similarly, <code>panic!</code> is often appropriate if you call
someone else's code that is out of your control, and it returns an invalid
state that you have no way of fixing.</p>
<p>Taking each point in turn:</p>
<p>Some bad states are expected to happen sometimes, and will happen no matter how
well you write your code. Examples of this include a parser being given
malformed data to parse, or an HTTP request returning a status that indicates
you have hit a rate limit. In these cases, you should indicate that failure is
an expected possibility by returning a <code>Result</code> and propagate these bad states
upwards so that the caller can decide how they would like to handle the
problem. <code>panic!</code> would not be the best way to handle these cases.</p>
<p>When your code performs operations on values, your code should verify the
values are valid first, then proceed confidently with the operations. This is
mostly for safety reasons: attempting to operate on invalid data can expose
your code to vulnerabilities. This is the main reason that the standard library
will <code>panic!</code> if you attempt an out-of-bounds array access: trying to access
memory that doesn't belong to the current data structure is a common security
problem. Functions often have <em>contracts</em>: their behavior is only guaranteed if
the inputs meet particular requirements. Panicking when the contract is
violated makes sense because a contract violation always indicates a
caller-side bug, and it is not a kind of error you want callers to have to
explicitly handle. In fact, there's no reasonable way for calling code to
recover: the calling <em>programmers</em> need to fix the code. Contracts for a
function, especially when a violation will cause a <code>panic</code>, should be explained
in the API documentation for the function.</p>
<p>Having lots of error checks in all of your functions would be verbose and
annoying, though. Luckily, our last guideline has a tip for this situation: use
Rust's type system (and thus the type checking the compiler does) to do a lot
of the checks for you. If your function takes a particular type as an argument,
you can proceed with your code's logic knowing that the compiler has already
ensured you have a valid value. For example, if you have a type rather than an
<code>Option</code>, you know that you will have something rather than nothing and you
don't have to have an explicit check to make sure. Another example is using an
unsigned integer type like <code>u32</code>, which ensures the argument value is never
negative.</p>
<h3>Creating Custom Types for Validation</h3>
<p>Going a step further with the idea of using Rust's type system to ensure we
have a valid value, let's look at an example of creating a custom type for
validation. Recall the guessing game in Chapter 2, where our code asked the user
to guess a number between 1 and 100. We actually never validated that the
user's guess was between those numbers before checking it against our secret
number, only that it was positive. In this case, the consequences were not very
dire: our output of &quot;Too high&quot; or &quot;Too low&quot; would still be correct. It would be
a nice enhancement to guide the user towards valid guesses, though. We could
add a check after we parse the guess:</p>
<pre><code class="language-rust,ignore">loop {
// snip
let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
if guess &lt; 1 || guess &gt; 100 {
println!(&quot;The secret number will be between 1 and 100.&quot;);
continue;
}
match guess.cmp(&amp;secret_number) {
// snip
}
</code></pre>
<!-- I'll add wingding numbers in the libreoffice file /Carol -->
<p>The <code>if</code> expression checks to see if our value is out of range, tells the user
about the problem, and calls <code>continue</code> to start the next iteration of the loop
and ask for another guess. After the <code>if</code> expression, we can proceed with the
comparisons between <code>guess</code> and the secret number knowing that guess is between
1 and 100.</p>
<p>If we had a situation where it was absolutely critical we had a value between 1
and 100, and we had many functions that had this requirement, it would be
tedious (and potentially impact performance) to have a check like this in every
function. Instead, we can make a new type and put the validations in one place,
in the type's constructor. Then our functions can use the type with the
confidence that we have values that meet our requirements. Listing 9-8 shows
one way to define a <code>Guess</code> type that will only create an instance of <code>Guess</code>
if the <code>new</code> function gets a value between 1 and 100:</p>
<figure>
<pre><code class="language-rust">struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -&gt; Guess {
if value &lt; 1 || value &gt; 100 {
panic!(&quot;Guess value must be between 1 and 100, got {}.&quot;, value);
}
Guess {
value: value,
}
}
pub fn value(&amp;self) -&gt; u32 {
self.value
}
}
</code></pre>
<figcaption>
<p>Listing 9-8: A <code>Guess</code> type that will only hold values between 1 and 100</p>
</figcaption>
</figure>
<p>If code calling <code>Guess::new</code> passed in a value that was not between 1 and 100,
that would be a violation of the contract that <code>Guess::new</code> is relying on. This
function needs to signal to the calling code that it has a bug somewhere
leading to the contract violation. The conditions in which <code>Guess::new</code> might
panic should be discussed in its public-facing API documentation, which we will
cover in Chapter 14.</p>
<p>Important to note is the <code>value</code> field of the <code>Guess</code> struct is private, so
code using this struct may not set that value directly. Callers <em>must</em> use the
<code>Guess::new</code> constructor function to create an instance of <code>Guess</code>, and they
may read the value using the public <code>value</code> function, but they may not access
the field directly. This means any created instance of <code>Guess</code> that does not
cause a <code>panic!</code> when <code>new</code> is called is guaranteed to return numbers between 1
and 100 from its <code>value</code> function.</p>
<p>A function that takes as an argument or returns only numbers between 1 and 100
could then declare in its signature to take a <code>Guess</code> rather than a <code>u32</code>, and
would not need to do any additional checks in its body.</p>
<h2>Summary</h2>
<p>Rust's error handling features are designed to help you write more robust code.
The <code>panic!</code> macro signals that your program is in a state it can't handle, and
lets you tell the process to stop instead of trying to proceed with invalid or
incorrect values. The <code>Result</code> enum uses Rust's type system as a sign that
operations you call might fail in a way that your code could recover from. You
can use <code>Result</code> to tell code that calls yours that it needs to handle
potential success or failure as well. Using <code>panic!</code> and <code>Result</code> in the
appropriate situations will help your code be more reliable in the face of
inevitable problems.</p>
<p>Now that we've seen useful ways that the standard library uses generics with
the <code>Option</code> and <code>Result</code> enums, let's talk about how generics work and how you
can make use of them in your code.</p>
<h1>Generics</h1>
<p>One of the core tools a programming language gives you is the ability to deal
effectively with duplication of code. It's important to minimize the amount of
code that is duplicated throughout a program to make maintenace easier and
minimize logic errors. Maintenance will be easier if there's only one place
that you need to change the code if you change your mind about how the program
should work, rather than multiple places in the code. If your program's logic
is duplicated in different places and those places don't match, you'll get
errors or unexpected and undesired behavior from your program that could be
hard to track down. Rust has the concept of <em>generics</em> as one way to eliminate
duplicate code. Generics come in the form of generic types, traits that those
generic types have, and generic lifetimes. We'll cover how to use all of these
in this chapter.</p>
<h2>Removing Duplication by Extracting a Function</h2>
<p>Let's first go through a technique for dealing with duplication that you're
probably familiar with: extracting a function. Consider a small program that
finds the largest number in a list, shown in Listing 10-1:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let mut largest = numbers[0];
for number in numbers {
if number &gt; largest {
largest = number;
}
}
println!(&quot;The largest number is {}&quot;, largest);
}
</code></pre>
<figcaption>
<p>Listing 10-1: Code to find the largest number in a list of numbers</p>
</figcaption>
</figure>
<p>If we needed to find the largest number in two different lists of numbers, we
could duplicate the code in Listing 10-1 and have the same logic exist in two
places in the program:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let mut largest = numbers[0];
for number in numbers {
if number &gt; largest {
largest = number;
}
}
println!(&quot;The largest number is {}&quot;, largest);
let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let mut largest = numbers[0];
for number in numbers {
if number &gt; largest {
largest = number;
}
}
println!(&quot;The largest number is {}&quot;, largest);
}
</code></pre>
<p>Copying code is tedious and error-prone, plus now we have two places to update
the logic if we need it to change. Rust, like many languages, gives us a way to
deal with this duplication by creating an abstraction, and in this case the
abstraction we'll use is a function. Here's a program where we've extracted the
code in Listing 10-1 that finds the largest number into a function named
<code>largest</code>. This program can find the largest number in two different lists of
numbers, but the code from Listing 10-1 only exists in one spot:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn largest(numbers: Vec&lt;i32&gt;) {
let mut largest = numbers[0];
for number in numbers {
if number &gt; largest {
largest = number;
}
}
println!(&quot;The largest number is {}&quot;, largest);
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
largest(numbers);
let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];
largest(numbers);
}
</code></pre>
<p>The function takes an argument, <code>numbers</code>, which represents any concrete
<code>Vec&lt;i32&gt;</code> that we might pass into the function. The code in the function
definition operates on the <code>numbers</code> representation of any <code>Vec&lt;i32&gt;</code>. When
we call the <code>largest</code> function, the code actually runs on the specific values
that we pass in.</p>
<p>Functions aren't the only way to eliminate duplication. For example, our
<code>largest</code> function only works for vectors of <code>i32</code>. What if we wanted to find
the largest number in a list of floats? Or the largest value in some sort of
custom <code>struct</code> or <code>enum</code>? We can't solve those kinds of duplication with
regular functions.</p>
<p>To solve these kinds of problems, Rust provides a feature called <em>generics</em>. In
the same way that functions allow us to abstract over common code, generics
allow us to abstract over types. This ability gives us tremendous power to
write code that works in a large number of situations. First, we'll examine the
syntax of generics. Then, we'll talk about another feature that's used to
augment generics: traits. Finally, we'll discuss one of Rust's most unique uses
of generics: lifetimes.</p>
<h2>Generics Syntax</h2>
<p>We've already hinted at the idea of generics in previous chapters, but we
never dug into what exactly they are or how to use them. In places where we
specify a type, like function signatures or structs, instead we can use
<em>generics</em>. Generics are stand-ins that represent an abstract set instead of something concrete. In this section, we're going to cover generic <em>data types</em>.</p>
<p>You can recognize when any kind of generics are used by the way that they fit
into Rust's syntax: any time you see angle brackets, <code>&lt;&gt;</code>, you're dealing with
generics. Types we've seen before, like in Chapter 8 where we discussed vectors
with types like <code>Vec&lt;i32&gt;</code>, employ generics. The type that the standard library
defines for vectors is <code>Vec&lt;T&gt;</code>. That <code>T</code> is called a <em>type parameter</em>, and it
serves a similar function as parameters to functions: you fill in the parameter
with a concrete type, and that determines how the overall type works. In the
same way that a function like <code>foo(x: i32)</code> can be called with a specific value
such as <code>foo(5)</code>, a <code>Vec&lt;T&gt;</code> can be created with a specific type, like
<code>Vec&lt;i32&gt;</code>.</p>
<h3>Duplicated Enum Definitions</h3>
<p>Let's dive into generic data types in more detail. We learned about how to use
the <code>Option&lt;T&gt;</code> enum in Chapter 6, but we never examined its definition. Let's
try to imagine how we'd write it! We'll start from duplicated code like we did
in the &quot;Removing Duplication by Extracting a Function&quot; section. This time,
we'll remove the duplication by extracting a generic data type instead of
extracting a function, but the mechanics of doing the extraction will be
similar. First, let's consider an <code>Option</code> enum with a <code>Some</code> variant that can
only hold an <code>i32</code>. We'll call this enum <code>OptionalNumber</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">enum OptionalNumber {
Some(i32),
None,
}
fn main() {
let number = OptionalNumber::Some(5);
let no_number = OptionalNumber::None;
}
</code></pre>
<p>This works just fine for <code>i32</code>s. But what if we also wanted to store <code>f64</code>s? We
would have to duplicate code to define a separate <code>Option</code> enum type for each
type we wanted to be able to hold in the <code>Some</code> variants. For example, here is
how we could define and use <code>OptionalFloatingPointNumber</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">enum OptionalFloatingPointNumber {
Some(f64),
None,
}
fn main() {
let number = OptionalFloatingPointNumber::Some(5.0);
let no_number = OptionalFloatingPointNumber::None;
}
</code></pre>
<p>We've made the enum's name a bit long in order to drive the point home. With
what we currently know how to do in Rust, we would have to write a unique type
for every single kind of value we wanted to have either <code>Some</code> or <code>None</code> of. In
other words, the idea of &quot;an optional value&quot; is a more abstract concept than one
specific type. We want it to work for any type at all.</p>
<h3>Removing Duplication by Extracting a Generic Data Type</h3>
<p>Let's see how to get from duplicated types to the generic type. Here are the
definitions of our two enums side-by-side:</p>
<pre><code class="language-text">enum OptionalNumber { enum OptionalFloatingPointNumber {
Some(i32), Some(f64),
None, None,
} }
</code></pre>
<p>Aside from the names, we have one line where the two definitions are very
close, but still different: the line with the <code>Some</code> definitions. The only
difference is the type of the data in that variant, <code>i32</code> and <code>f64</code>.</p>
<p>Just like we can parameterize arguments to a function by choosing a name, we
can parameterize the type by choosing a name. In this case, we've chosen the
name <code>T</code>. We could choose any identifier here, but Rust style has type
parameters follow the same style as types themselves: CamelCase. In addition,
they tend to be short, often one letter. <code>T</code> is the traditional default choice,
short for 'type'. Let's use that name in our <code>Some</code> variant definitions where
the <code>i32</code> and <code>f64</code> types were:</p>
<pre><code class="language-text">enum OptionalNumber { enum OptionalFloatingPointNumber {
Some(T), Some(T),
None, None,
} }
</code></pre>
<p>There's one problem, though: we've <em>used</em> <code>T</code>, but not defined it. This would
be similar to using an argument to a function in the body without declaring it
in the signature. We need to tell Rust that we've introduced a generic
parameter. The syntax to do that is the angle brackets, like this:</p>
<pre><code class="language-text">enum OptionalNumber&lt;T&gt; { enum OptionalFloatingPointNumber&lt;T&gt; {
Some(T), Some(T),
None, None,
} }
</code></pre>
<p>The <code>&lt;&gt;</code>s after the enum name indicate a list of type parameters, just like
<code>()</code> after a function name indicates a list of value parameters. Now the only
difference between our two <code>enum</code>s is the name. Since we've made them generic,
they're not specific to integers or floating point numbers anymore, so they can
have the same name:</p>
<pre><code class="language-text">enum Option&lt;T&gt; { enum Option&lt;T&gt; {
Some(T), Some(T),
None, None,
} }
</code></pre>
<p>Now they're identical! We've made our type fully generic. This definition is
also how <code>Option</code> is defined in the standard library. If we were to read this
definition aloud, we'd say, &quot;<code>Option</code> is an <code>enum</code> with one type parameter,
<code>T</code>. It has two variants: <code>Some</code>, which has a value with type <code>T</code>, and <code>None</code>,
which has no value.&quot; We can now use the same <code>Option</code> type whether we're holding an <code>i32</code> or an <code>f64</code>:</p>
<pre><code class="language-rust">let integer = Option::Some(5);
let float = Option::Some(5.0);
</code></pre>
<p>We've left in the <code>Option::</code> namespace for consistency with the previous
examples, but since <code>use Option::*</code> is in the prelude, it's not needed. Usually
using <code>Option</code> looks like this:</p>
<pre><code class="language-rust">let integer = Some(5);
let float = Some(5.0);
</code></pre>
<p>When you recognize situations with almost-duplicate types like this in your
code, you can follow this process to reduce duplication using generics.</p>
<h3>Monomorphization at Compile Time</h3>
<p>Understanding this refactoring process is also useful in understanding how
generics work behind the scenes: the compiler does the exact opposite of this
process when compiling your code. <em>Monomorphization</em> means taking code that
uses generic type parameters and generating code that is specific for each
concrete type that is used with the generic code. Monomorphization is why
Rust's generics are extremely efficient at runtime. Consider this code that
uses the standard library's <code>Option</code>:</p>
<pre><code class="language-rust">let integer = Some(5);
let float = Some(5.0);
</code></pre>
<p>When Rust compiles this code, it will perform monomorphization. What this means
is the compiler will see that we've used two kinds of <code>Option&lt;T&gt;</code>: one where
<code>T</code> is <code>i32</code>, and one where <code>T</code> is <code>f64</code>. As such, it will expand the generic
definition of <code>Option&lt;T&gt;</code> into <code>Option_i32</code> and <code>Option_f64</code>, thereby replacing
the generic definition with the specific ones. The more specific version looks
like the duplicated code we started with at the beginning of this section:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">enum Option_i32 {
Some(i32),
None,
}
enum Option_f64 {
Some(f64),
None,
}
fn main() {
let integer = Option_i32::Some(5);
let float = Option_f64::Some(5.0);
}
</code></pre>
<p>In other words, we can write the non-duplicated form that uses generics in our
code, but Rust will compile that into code that acts as though we wrote the
specific type out in each instance. This means we pay no runtime cost for using
generics; it's just like we duplicated each particular definition.</p>
<h3>Generic Structs</h3>
<p>In a similar fashion as we did with enums, we can use <code>&lt;&gt;</code>s with structs as
well in order to define structs that have a generic type parameter in one or
more of their fields. Generic structs also get monomorphized into specialized
types at compile time. Listing 10-2 shows the definition and use of a <code>Point</code>
struct that could hold <code>x</code> and <code>y</code> coordinate values that are any type:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Point&lt;T&gt; {
x: T,
y: T,
}
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
}
</code></pre>
<figcaption>
<p>Listing 10-2: A <code>Point</code> struct that holds <code>x</code> and <code>y</code> values of type <code>T</code></p>
</figcaption>
</figure>
<p>The syntax is the same with structs: add a <code>&lt;T&gt;</code> after the name of the struct,
then use <code>T</code> in the definition where you want to use that generic type instead
of a specific type.</p>
<h3>Multiple Type Parameters</h3>
<p>Note that in the <code>Point</code> definition in Listing 10-2, we've used the same <code>T</code>
parameter for both fields. This means <code>x</code> and <code>y</code> must always be values of the
same type. Trying to instantiate a <code>Point</code> that uses an <code>i32</code> for <code>x</code> and an
<code>f64</code> for <code>y</code>, like this:</p>
<pre><code class="language-rust,ignore">let p = Point { x: 5, y: 20.0 };
</code></pre>
<p>results in a compile-time error that indicates the type of <code>y</code> must match the
type of <code>x</code>:</p>
<pre><code class="language-text">error[E0308]: mismatched types
|
7 | let p = Point { x: 5, y: 20.0 };
| ^^^^ expected integral variable, found floating-point variable
|
= note: expected type `{integer}`
= note: found type `{float}`
</code></pre>
<p>If we need to be able to have fields with generic but different types, we can
declare multiple type parameters within the angle brackets, separated by a
comma. Listing 10-3 shows how to define a <code>Point</code> that can have different types
for <code>x</code> and <code>y</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Point&lt;X, Y&gt; {
x: X,
y: Y,
}
fn main() {
let integer = Point { x: 5, y: 10 };
let float = Point { x: 1.0, y: 4.0 };
let p = Point { x: 5, y: 20.0 };
}
</code></pre>
<figcaption>
<p>Listing 10-3: A <code>Point</code> struct that holds an <code>x</code> value of type <code>X</code> and a <code>y</code>
value of type <code>Y</code></p>
</figcaption>
</figure>
<p>Now <code>x</code> will have the type of <code>X</code>, and <code>y</code> will have the type of <code>Y</code>, and we
can instantiate a <code>Point</code> with an <code>i32</code> for <code>x</code> and an <code>f64</code> for <code>y</code>.</p>
<p>We can make <code>enum</code>s with multiple type parameters as well. Recall the enum
<code>Result&lt;T, E&gt;</code> from Chapter 9 that we used for recoverable errors. Here's its
definition:</p>
<pre><code class="language-rust">enum Result&lt;T, E&gt; {
Ok(T),
Err(E),
}
</code></pre>
<p>Each variant stores a different kind of information, and they're both generic.</p>
<p>You can have as many type parameters as you'd like. Similarly to parameters of
values in function signatures, if you have a lot of parameters, the code can
get quite confusing, so try to keep the number of parameters defined in any one
type small if you can.</p>
<h3>Generic Functions and Methods</h3>
<p>In a similar way to data structures, we can use the <code>&lt;&gt;</code> syntax in function or
method definitions. The angle brackets for type parameters go after the
function or method name and before the argument list in parentheses:</p>
<pre><code class="language-rust">fn generic_function&lt;T&gt;(value: T) {
// code goes here
}
</code></pre>
<p>We can use the same process that we used to refactor duplicated type
definitions using generics to refactor duplicated function definitions using
generics. Consider these two side-by-side function signatures that differ in
the type of <code>value</code>:</p>
<pre><code class="language-text">fn takes_integer(value: i32) { fn takes_float(value: f64) {
// code goes here // code goes here
} }
</code></pre>
<p>We can add a type parameter list that declares the generic type <code>T</code> after the
function names, then use <code>T</code> where the specific <code>i32</code> and <code>f64</code> types were:</p>
<pre><code class="language-text">fn takes_integer&lt;T&gt;(value: T) { fn takes_float&lt;T&gt;(value: T) {
// code goes here // code goes here
} }
</code></pre>
<p>At this point, only the names differ, so we could unify the two functions into
one:</p>
<pre><code class="language-rust,ignore">fn takes&lt;T&gt;(value: T) {
// code goes here
}
</code></pre>
<p>There's one problem though. We've got some function <em>definitions</em> that work,
but if we try to use <code>value</code> in code in the function body, we'll get an
error. For example, the function definition in Listing 10-4 tries to print out
<code>value</code> in its body:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust,ignore">fn show_anything&lt;T&gt;(value: T) {
println!(&quot;I have something to show you!&quot;);
println!(&quot;It's: {}&quot;, value);
}
</code></pre>
<figcaption>
<p>Listing 10-4: A <code>show_anything</code> function definition that does not yet compile</p>
</figcaption>
</figure>
<p>Compiling this definition results in an error:</p>
<pre><code class="language-text"> error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
--&gt; &lt;anon&gt;:3:37
|
3 | println!(&quot;It's: {}&quot;, value);
| ^^^^^ trait `T: std::fmt::Display` not satisfied
|
= help: consider adding a `where T: std::fmt::Display` bound
= note: required by `std::fmt::Display::fmt`
error: aborting due to previous error(s)
</code></pre>
<p>This error mentions something we haven't learned about yet: traits. In the next
section, we'll learn how to make this compile.</p>
<h2>Traits</h2>
<p><em>Traits</em> are similar to a feature often called 'interfaces' in other languages,
but are also different. Traits let us do another kind of abstraction: they let
us abstract over <em>behavior</em> that types can have in common.</p>
<p>When we use a generic type parameter, we are telling Rust that any type is
valid in that location. When other code <em>uses</em> a value that could be of any
type, we need to also tell Rust that the type has the functionality that we
need. Traits let us specify that, for example, we need any type <code>T</code> that has
methods defined on it that allow us to print a value of that type. This is
powerful because we can still leave our definitions generic to allow use of
many different types, but we can constrain the type at compile-time to types
that have the behavior we need to be able to use.</p>
<p>Listing 10-5 has an example definition of a trait named <code>Printable</code> with a
method named <code>print</code>:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">trait Printable {
fn print(&amp;self);
}
</code></pre>
<figcaption>
<p>Listing 10-5: A <code>Printable</code> trait definition with one method, <code>print</code></p>
</figcaption>
</figure>
<p>We declare a trait with the <code>trait</code> keyword, then the trait's name. In this
case, our trait will describe types which can be printed. Inside of curly
braces, we declare a method signature, but instead of providing an
implementation inside curly braces, we put a semicolon after the signature. A
trait can have multiple methods in its body, with the method signatures listend one per line and each line ending in a semicolon.</p>
<p>Implementing a trait for a particular type looks similar to implementing
methods on a type since it's also done with the <code>impl</code> keyword, but we specify
the trait name as well. Inside the <code>impl</code> block, we specify definitions for the
trait's methods in the context of the specific type. Listing 10-6 has an
example of implementing the <code>Printable</code> trait from Listing 10-5 (that only has
the <code>print</code> method) for a <code>Temperature</code> enum:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust"># trait Printable {
# fn print(&amp;self);
# }
#
enum Temperature {
Celsius(i32),
Fahrenheit(i32),
}
impl Printable for Temperature {
fn print(&amp;self) {
match *self {
Temperature::Celsius(val) =&gt; println!(&quot;{}°C&quot;, val),
Temperature::Fahrenheit(val) =&gt; println!(&quot;{}°F&quot;, val),
}
}
}
</code></pre>
<figcaption>
<p>Listing 10-6: Implementing the <code>Printable</code> trait on a <code>Temperature</code> enum</p>
</figcaption>
</figure>
<p>In the same way <code>impl</code> lets us define methods, we've used it to define methods
that pertain to our trait. We can call methods that our trait has defined just
like we can call other methods:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust"># trait Printable {
# fn print(&amp;self);
# }
#
# enum Temperature {
# Celsius(i32),
# Fahrenheit(i32),
# }
#
# impl Printable for Temperature {
# fn print(&amp;self) {
# match *self {
# Temperature::Celsius(val) =&gt; println!(&quot;{}°C&quot;, val),
# Temperature::Fahrenheit(val) =&gt; println!(&quot;{}°F&quot;, val),
# }
# }
# }
#
fn main() {
let t = Temperature::Celsius(37);
t.print();
}
</code></pre>
<p>Note that in order to use a trait's methods, the trait itself must be in scope.
If the definition of <code>Printable</code> was in a module, the definition would need to
be defined as <code>pub</code> and we would need to <code>use</code> the trait in the scope where we
wanted to call the <code>print</code> method. This is because it's possible to have two
traits that both define a method named <code>print</code>, and our <code>Temperature</code> enum might
implement both. Rust wouldn't know which <code>print</code> method we wanted unless we
brought the trait we wanted into our current scope with <code>use</code>.</p>
<h3>Trait Bounds</h3>
<p>Defining traits with methods and implementing the trait methods on a particular
type gives Rust more information than just defining methods on a type directly.
The information Rust gets is that the type that implements the trait can be
used in places where the code specifies that it needs some type that implements
a trait. To illustrate this, Listing 10-7 has a <code>print_anything</code> function
definition. This is similar to the <code>show_anything</code> function from Listing 10-4,
but this function has a <em>trait bound</em> on the generic type <code>T</code> and uses the
<code>print</code> function from the trait. A trait bound constrains the generic type to
be any type that implements the trait specified, instead of any type at all.
With the trait bound, we're then allowed to use the trait method <code>print</code> in the
function body:</p>
<figure>
<span class="filename">Filename: src/lib.rs</figure>
<pre><code class="language-rust"># trait Printable {
# fn print(&amp;self);
# }
#
fn print_anything&lt;T: Printable&gt;(value: T) {
println!(&quot;I have something to print for you!&quot;);
value.print();
}
</code></pre>
<figcaption>
<p>Listing 10-7: A <code>print_anything</code> function that uses the trait bound <code>Printable</code>
on type <code>T</code></p>
</figcaption>
</figure>
<p>Trait bounds are specified in the type name declarations within the angle
brackets. After the name of the type that you want to apply the bound to, add a
colon (<code>:</code>) and then specify the name of the trait. This function now specifies
that it takes a <code>value</code> parameter that can be of any type, as long as that type
implements the trait <code>Printable</code>. We need to specify the <code>Printable</code> trait in
the type name declarations because we want to be able to call the <code>print</code>
method that is part of the <code>Printable</code> trait.</p>
<p>Now we are able to call the <code>print_anything</code> function from Listing 10-7 and
pass it a <code>Temperature</code> instance as the <code>value</code> parameter, since we implemented
the trait <code>Printable</code> on <code>Temperature</code> in Listing 10-6:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust"># trait Printable {
# fn print(&amp;self);
# }
#
# enum Temperature {
# Celsius(i32),
# Fahrenheit(i32),
# }
#
# impl Printable for Temperature {
# fn print(&amp;self) {
# match *self {
# Temperature::Celsius(val) =&gt; println!(&quot;{}°C&quot;, val),
# Temperature::Fahrenheit(val) =&gt; println!(&quot;{}°F&quot;, val),
# }
# }
# }
#
# fn print_anything&lt;T: Printable&gt;(value: T) {
# println!(&quot;I have something to print for you!&quot;);
# value.print();
# }
#
fn main() {
let temperature = Temperature::Fahrenheit(98);
print_anything(temperature);
}
</code></pre>
<p>If we implement the <code>Printable</code> trait on other types, we can use them with the
<code>print_anything</code> method too. If we try to call <code>print_anything</code> with an <code>i32</code>,
which does <em>not</em> implement the <code>Printable</code> trait, we get a compile-time error
that looks like this:</p>
<pre><code class="language-text">error[E0277]: the trait bound `{integer}: Printable` is not satisfied
|
29 | print_anything(3);
| ^^^^^^^^^^^^^^ trait `{integer}: Printable` not satisfied
|
= help: the following implementations were found:
= help: &lt;Point as Printable&gt;
= note: required by `print_anything`
</code></pre>
<p>Traits are an extremely useful feature of Rust. You'll almost never see generic
functions without an accompanying trait bound. There are many traits in the
standard library, and they're used for many, many different things. For
example, our <code>Printable</code> trait is similar to one of those traits, <code>Display</code>.
And in fact, that's how <code>println!</code> decides how to format things with <code>{}</code>. The
<code>Display</code> trait has a <code>fmt</code> method that determines how to format something.</p>
<p>Listing 10-8 shows our original example from Listing 10-3, but this time using
the standard library's <code>Display</code> trait in the trait bound on the generic type
in the <code>show_anything</code> function:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">use std::fmt::Display;
fn show_anything&lt;T: Display&gt;(value: T) {
println!(&quot;I have something to show you!&quot;);
println!(&quot;It's: {}&quot;, value);
}
</code></pre>
<figcaption>
<p>Listing 10-8: The <code>show_anything</code> function with trait bounds</p>
</figcaption>
</figure>
<p>Now that this function specifies that <code>T</code> can be any type as long as that type
implements the <code>Display</code> trait, this code will compile.</p>
<h3>Multiple Trait Bounds and <code>where</code> Syntax</h3>
<p>Each generic type can have its own trait bounds. The signature for a function
that takes a type <code>T</code> that implements <code>Display</code> and a type <code>U</code> that implements
<code>Printable</code> looks like:</p>
<pre><code class="language-rust,ignore">fn some_function&lt;T: Display, U: Printable&gt;(value: T, other_value: U) {
</code></pre>
<p>To specify multiple trait bounds on one type, list the trait bounds in a list
with a <code>+</code> between each trait. For example, here's the signature of a function
that takes a type <code>T</code> that implements <code>Display</code> and <code>Clone</code> (which is another
standard library trait we have mentioned):</p>
<pre><code class="language-rust,ignore">fn some_function&lt;T: Display + Clone&gt;(value: T) {
</code></pre>
<p>When trait bounds start getting complicated, there is another syntax that's a
bit cleaner: <code>where</code>. And in fact, the error we got when we ran the code from
Listing 10-3 referred to it:</p>
<pre><code class="language-text">help: consider adding a `where T: std::fmt::Display` bound
</code></pre>
<p>The <code>where</code> syntax moves the trait bounds after the function arguments list.
This definition of <code>show_anything</code> means the exact same thing as the definition
in Listing 10-8, just said a different way:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">use std::fmt::Display;
fn show_anything&lt;T&gt;(value: T) where T: Display {
println!(&quot;I have something to show you!&quot;);
println!(&quot;It's: {}&quot;, value);
}
</code></pre>
<p>Instead of <code>T: Display</code> going inside the angle brackets, they go after the
<code>where</code> keyword at the end of the function signature. This can make complex
signatures easier to read. The <code>where</code> clause and its parts can also go on new
lines. Here's the signature of a function that takes three generic type
parameters that each have multiple trait bounds:</p>
<pre><code class="language-rust,ignore">fn some_function&lt;T, U, V&gt;(t: T, u: U, v: V)
where T: Display + Clone,
U: Printable + Debug,
V: Clone + Printable
{
</code></pre>
<p>Generic type parameters and trait bounds are part of Rust's rich type system.
Another important kind of generic in Rust interacts with Rust's ownership and
references features, and they're called <em>lifetimes</em>.</p>
<h2>Lifetime Syntax</h2>
<p>Generic type parameters let us abstract over types, and traits let us abstract
over behavior. There's one more way that Rust allows us to do something
similar: <em>lifetimes</em> allow us to be generic over scopes of code.</p>
<p>Scopes of code? Yes, it's a bit unusual. Lifetimes are, in some ways, Rust's
most distinctive feature. They are a bit different than the tools you have used
in other programming languages. Lifetimes are a big topic, so we're not going
to cover everything about them in this chapter. What we <em>are</em> going to do is
talk about the very basics of lifetimes, so that when you see the syntax in
documentation or other places, you'll be familiar with the concepts. Chapter 20
will contain more advanced information about everything lifetimes can do.</p>
<h3>Core Syntax</h3>
<p>We talked about references in Chapter 4, but we left out an important detail.
As it turns out, every reference in Rust has a <em>lifetime</em>, which is the scope
for which that reference is valid. Most of the time, lifetimes are implicit,
but just like we can choose to annotate types everywhere, we can choose to
annotate lifetimes.</p>
<p>Lifetimes have a slightly unusual syntax:</p>
<pre><code class="language-rust,ignore">&amp;i32 // a reference
&amp;'a i32 // a reference with an explicit lifetime
</code></pre>
<p>The <code>'a</code> there is a <em>lifetime</em> with the name <code>a</code>. A single apostrophe indicates
that this name is for a lifetime. Lifetime names need to be declared before
they're used. Here's a function signature with lifetime declarations and
annotations:</p>
<pre><code class="language-rust,ignore">fn some_function&lt;'a&gt;(argument: &amp;'a i32) {
</code></pre>
<p>Notice anything? In the same way that generic type declarations go inside angle
brackets after the function name, lifetime declarations also go inside those
same angle brackets. We can even write functions that take both a lifetime
declaration and a generic type declaration:</p>
<pre><code class="language-rust,ignore">fn some_function&lt;'a, T&gt;(argument: &amp;'a T) {
</code></pre>
<p>This function takes one argument, a reference to some type, <code>T</code>, and the
reference has the lifetime <code>'a</code>. In the same way that we parameterize functions
that take generic types, we parameterize references with lifetimes.</p>
<p>So, that's the syntax, but <em>why</em>? What does a lifetime do, anyway?</p>
<h3>Lifetimes Prevent Dangling References</h3>
<p>Consider the program in listing 10-8. There's an outer scope and an inner
scope. The outer scope declares a variable named <code>r</code> with no initial value, and
the inner scope declares a variable named <code>x</code> with the initial value of 5.
Inside the inner scope, we attempt to set the value of <code>r</code> to a reference to
<code>x</code>. Then the inner scope ends and we attempt to print out the value in <code>r</code>:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust,ignore">{
let r;
{
let x = 5;
r = &amp;x;
}
println!(&quot;r: {}&quot;, r);
}
</code></pre>
<figcaption>
<p>Listing 10-8: An attempt to use a reference whose value has gone out of scope</p>
</figcaption>
</figure>
<p>If we compile this code, we get an error:</p>
<pre><code class="language-text"> error: `x` does not live long enough
--&gt; &lt;anon&gt;:6:10
|
6 | r = &amp;x;
| ^ does not live long enough
7 | }
| - borrowed value only lives until here
...
10 | }
| - borrowed value needs to live until here
</code></pre>
<p>The variable <code>x</code> doesn't &quot;live long enough.&quot; Why not? Well, <code>x</code> is going to go
out of scope when we hit the closing curly brace on line 7, ending the inner
scope. But <code>r</code> is valid for the outer scope; its scope is larger and we say
that it &quot;lives longer.&quot; If Rust allowed this code to work, <code>r</code> would be
referencing memory that was deallocated when <code>x</code> went out of scope. That'd be
bad! Once it's deallocated, it's meaningless.</p>
<p>So how does Rust determine that this code should not be allowed? Part of the
compiler called the <em>borrow checker</em> compares scopes to determine that all
borrows are valid. Here's the same example from Listing 10-8 with some
annotations:</p>
<pre><code class="language-rust,ignore">{
let r; // -------+-- 'a
// |
{ // |
let x = 5; // -+-----+-- 'b
r = &amp;x; // | |
} // -+ |
// |
println!(&quot;r: {}&quot;, r); // |
// |
// -------+
}
</code></pre>
<p>Here, we've annotated the lifetime of <code>r</code> with <code>'a</code> and the lifetime of <code>x</code>
with <code>'b</code>. Rust looks at these lifetimes and sees that <code>r</code> has a lifetime of
<code>'a</code>, but that it refers to something with a lifetime of <code>'b</code>. It rejects the
program because the lifetime <code>'b</code> is shorter than the lifetime of <code>'a</code>-- the
value that the reference is referring to does not live as long as the reference
does.</p>
<p>Let's look at a different example that compiles because it does not try to make
a dangling reference, and see what the lifetimes look like:</p>
<pre><code class="language-rust">{
let x = 5; // -----+-- 'b
// |
let r = &amp;x; // --+--+-- 'a
// | |
println!(&quot;r: {}&quot;, r); // | |
// --+ |
// -----+
}
</code></pre>
<p>Here, <code>x</code> lives for <code>'b</code>, which in this case is larger than <code>'a</code>. This is
allowed: Rust knows that the reference in <code>r</code> will always be valid, as it has a
smaller scope than <code>x</code>, the value it refers to.</p>
<p>Note that we didn't have to name any lifetimes in the code itself; Rust figured
it out for us. One situation in which Rust can't figure out the lifetimes is
for a function or method when one of the arguments or return values is a
reference, except for a few scenarios we'll discuss in the lifetime elision
section.</p>
<h3>Lifetime Annotations in Struct Definitions</h3>
<p>Another time that Rust can't figure out the lifetimes is when structs have a
field that holds a reference. In that case, naming the lifetimes looks like
this:</p>
<pre><code class="language-rust">struct Ref&lt;'a&gt; {
x: &amp;'a i32,
}
</code></pre>
<p>Again, the lifetime names are declared in the angle brackets where generic type
parameters are declared, and this is because lifetimes are a form of generics.
In the examples above, <code>'a</code> and <code>'b</code> were concrete lifetimes: we knew about <code>r</code>
and <code>x</code> and how long they would live exactly. However, when we write a
function, we can't know beforehand exactly all of the arguments that it could
be called with and how long they will be valid for. We have to explain to Rust
what we expect the lifetime of the argument to be (we'll learn about how
to know what you expect the lifetime to be in a bit). This is similar to
writing a function that has an argument of a generic type: we don't know what
type the arguments will actually end up being when the function gets called.
Lifetimes are the same idea, but they are generic over the scope of a
reference, rather than a type.</p>
<h3>Lifetime Annotations in Function Signatures</h3>
<p>Lifetime annotations for functions go on the function signature, but we don't
have to annotate any of the code in the function body with lifetimes. That's
because Rust can analyze the specific code inside the function without any
help. When a function interacts with references that come from or go to code
outside that function, however, the lifetimes of those arguments or return
values will potentially be different each time that function gets called. Rust
would have to analyze every place the function is called to determine that
there were no dangling references. That would be impossible because a library
that you provide to someone else might be called in code that hasn't been
written yet, at the time that you're compiling your library.</p>
<p>Lifetime parameters specify generic lifetimes that will apply to any specific
lifetimes the function gets called with. The annotation of lifetime parameters
tell Rust what it needs to know in order to be able to analyze a function
without knowing about all possible calling code. Lifetime annotations do not
change how long any of the references involved live. In the same way that
functions can accept any type when the signature specifies a generic type
parameter, functions can accept references with any lifetime when the signature
specifies a generic lifetime parameter.</p>
<p>To understand lifetime annotations in context, let's write a function that will
return the longest of two string slices. The way we want to be able to call
this function is by passing two string slices, and we want to get back a string
slice. The code in Listing 10-9 should print <code>The longest string is abcd</code> once
we've implemented the <code>longest</code> function:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
# if x.len() &gt; y.len() {
# x
# } else {
# y
# }
# }
#
fn main() {
let a = String::from(&quot;abcd&quot;);
let b = &quot;xyz&quot;;
let c = longest(a.as_str(), b);
println!(&quot;The longest string is {}&quot;, c);
}
</code></pre>
<figcaption>
<p>Listing 10-9: A <code>main</code> function that demonstrates how we'd like to use the
<code>longest</code> function</p>
</figcaption>
</figure>
<p>Note that we want the function to take string slices because we don't want the
<code>longest</code> function to take ownership of its arguments, and we want the function
to be able to accept slices of a <code>String</code> (like <code>a</code>) is as well as string
literals (<code>b</code>). Refer back to the &quot;String Slices as Arguments&quot; section of
Chapter 4 for more discussion about why these are the arguments we want.</p>
<p>Here's the start of an implementation of the <code>longest</code> function that won't
compile yet:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
if x.len() &gt; y.len() {
x
} else {
y
}
}
</code></pre>
<p>If we try to compile this, we get an error that talks about lifetimes:</p>
<pre><code class="language-text">error[E0106]: missing lifetime specifier
|
1 | fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
</code></pre>
<p>The help text is telling us that the return type needs a generic lifetime
parameter on it because this function is returning a reference and Rust can't
tell if the reference being returned refers to <code>x</code> or <code>y</code>. Actually, we don't
know either, since in the <code>if</code> block in the body of this function returns a
reference to <code>x</code> and the <code>else</code> block returns a reference to <code>y</code>! The way to
specify the lifetime parameters in this case is to have the same lifetime for
all of the input parameters and the return type:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;'a str) -&gt; &amp;'a str {
if x.len() &gt; y.len() {
x
} else {
y
}
}
</code></pre>
<p>This will compile and will produce the result we want with the <code>main</code> function
in Listing 10-9. This function signature is now saying that for some lifetime
named <code>'a</code>, it will get two arguments, both which are string slices that live
at least as long as the lifetime <code>'a</code>. The function will return a string slice
that also will last at least as long as the lifetime <code>'a</code>. This is the contract
we are telling Rust we want it to enforce. By specifying the lifetime
parameters in this function signature, we are not changing the lifetimes of any
values passed in or returned, but we are saying that any values that do not
adhere to this contract should be rejected by the borrow checker. This function
does not know (or need to know) exactly how long <code>x</code> and <code>y</code> will live since it
knows that there is some scope that can be substituted for <code>'a</code> that will
satisfy this signature.</p>
<p>The exact way to specify lifetime parameters depends on what your function is
doing. If the function didn't actually return the longest string slice but
instead always returned the first argument, we wouldn't need to specify a
lifetime on <code>y</code>. This code compiles:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn longest&lt;'a&gt;(x: &amp;'a str, y: &amp;str) -&gt; &amp;'a str {
x
}
</code></pre>
<p>The lifetime parameter for the return type needs to be specified and needs to
match one of the arguments' lifetime parameters. If the reference returned does
<em>not</em> refer to one of the arguments, the only other possibility is that it
refers to a value created within this function, and that would be a dangling
reference since the value will go out of scope at the end of the function.
Consider this attempted implementation of <code>longest</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn longest&lt;'a&gt;(x: &amp;str, y: &amp;str) -&gt; &amp;'a str {
let result = String::from(&quot;really long string&quot;);
result.as_str()
}
</code></pre>
<p>Even though we've specified a lifetime for the return type, this function fails
to compile with the following error message:</p>
<pre><code class="language-text">error: `result` does not live long enough
|
3 | result.as_str()
| ^^^^^^ does not live long enough
4 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the block at 1:44...
|
1 | fn longest&lt;'a&gt;(x: &amp;str, y: &amp;str) -&gt; &amp;'a str {
| ^
</code></pre>
<p>The problem is that <code>result</code> will go out of scope and get cleaned up at the end
of the <code>longest</code> function, and we're trying to return a reference to <code>result</code>
from the function. There's no way we can specify lifetime parameters that would
change the dangling reference, and Rust won't let us create a dangling
reference. In this case, the best fix would be to return an owned data type
rather than a reference so that the calling function is then responsible for
cleaning up the value.</p>
<p>Ultimately, lifetime syntax is about connecting the lifetimes of various
arguments and return values of functions. Once they're connected, Rust has
enough information to allow memory-safe operations and disallow operations that
would create dangling pointers or otherwise violate memory safety.</p>
<h3>Lifetime Elision</h3>
<p>If every reference has a lifetime, and we need to provide them for functions
that use references as arguments or return values, then why did this function
from the &quot;String Slices&quot; section of Chapter 4 compile? We haven't annotated any
lifetimes here, yet Rust happily compiles this function:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">fn first_word(s: &amp;str) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return &amp;s[0..i];
}
}
&amp;s[..]
}
</code></pre>
<p>The answer is historical: in early versions of pre-1.0 Rust, this would not
have compiled. Every reference needed an explicit lifetime. At that time, the
function signature would have been written like this:</p>
<pre><code class="language-rust,ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {
</code></pre>
<p>After writing a lot of Rust code, some patterns developed. The Rust team
noticed that the vast majority of code followed the pattern, and being forced
to use explicit lifetime syntax on every reference wasn't a very great
developer experience.</p>
<p>To make it so that lifetime annotations weren't needed as often, they added
<em>lifetime elision rules</em> to Rust's analysis of references. This feature isn't
full inference: Rust doesn't try to guess what you meant in places where there
could be ambiguity. The rules are a very basic set of particular cases, and if
your code fits one of those cases, you don't need to write the lifetimes
explicitly. Here are the rules:</p>
<p>Lifetimes on function arguments are called <em>input lifetimes</em>, and lifetimes on
return values are called <em>output lifetimes</em>. There's one rule related to how
Rust infers input lifetimes in the absence of explicit annotations:</p>
<ol>
<li>Each argument that is a reference and therefore needs a lifetime parameter
gets its own. In other words, a function with one argument gets one lifetime
parameter: <code>fn foo&lt;'a&gt;(x: &amp;'a i32)</code>, a function with two arguments gets two
separate lifetime parameters: <code>fn foo&lt;'a, 'b&gt;(x: &amp;'a i32, y: &amp;'b i32)</code>, and
so on.</li>
</ol>
<p>And two rules related to output lifetimes:</p>
<ol start="2">
<li>If there is exactly one input lifetime parameter, that lifetime is assigned
to all output lifetime parameters: <code>fn foo&lt;'a&gt;(x: &amp;'a i32) -&gt; &amp;'a i32</code>.</li>
<li>If there are multiple input lifetime parameters, but one of them is <code>&amp;self</code>
or <code>&amp;mut self</code>, then the lifetime of <code>self</code> is the lifetime assigned to all
output lifetime parameters. This makes writing methods much nicer.</li>
</ol>
<p>If none of these three rules apply, then you must explicitly annotate input and
output lifetimes. These rules do apply in the <code>first_word</code> function, which is
why we didn't have to specify any lifetimes.</p>
<p>These rules cover the vast majority of cases, allowing you to write a lot of
code without needing to specify explicit lifetimes. However, Rust is always
checking these rules and the lifetimes in your program, and cases in which the
lifetime elision rules do not apply are cases where you'll need to add lifetime
parameters to help Rust understand the contracts of your code.</p>
<h3>Lifetime Annotations in Method Definitions</h3>
<p>Now that we've gone over the lifetime elision rules, defining methods on
structs that hold references will make more sense. The lifetime name needs to
be declared after the <code>impl</code> keyword and then used after the struct's name,
since the lifetime is part of the struct's type. The lifetimes can be elided in
any methods where the output type's lifetime is the same as that of the
struct's because of the third elision rule. Here's a struct called <code>App</code> that
holds a reference to another struct, <code>Config</code>, defined elsewhere. The
<code>append_to_name</code> method does not need lifetime annotations even though the
method has a reference as an argument and is returning a reference; the
lifetime of the return value will be the lifetime of <code>self</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust"># struct Config {}
#
struct App&lt;'a&gt; {
name: String,
config: &amp;'a Config,
}
impl&lt;'a&gt; App&lt;'a&gt; {
fn append_to_name(&amp;mut self, suffix: &amp;str) -&gt; &amp;str {
self.name.push_str(suffix);
self.name.as_str()
}
}
</code></pre>
<h3>The Static Lifetime</h3>
<p>There is <em>one</em> special lifetime that Rust knows about: <code>'static</code>. The <code>'static</code>
lifetime is the entire duration of the program. All string literals have the
<code>'static</code> lifetime:</p>
<pre><code class="language-rust">let s: &amp;'static str = &quot;I have a static lifetime.&quot;;
</code></pre>
<p>The text of this string is stored directly in the binary of your program and
the binary of your program is always available. Therefore, the lifetime of all
string literals is <code>'static</code>. You may see suggestions to use the <code>'static</code>
lifetime in error message help text, but before adding it, think about whether
the reference you have is one that actually lives the entire lifetime of your
program or not (or even if you want it to live that long, if it could). Most of
the time, the problem in the code is an attempt to create a dangling reference
or a mismatch of the available lifetimes, and the solution is fixing those
problems, not specifying the <code>'static</code> lifetime.</p>
<h2>Summary</h2>
<p>We've covered the basics of Rust's system of generics. Generics are the core to
building good abstractions, and can be used in a number of ways. There's more
to learn about them, particularly lifetimes, but we'll cover those in later
chapters. Let's move on to testing.</p>
<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>Rust is a programming language that cares a lot about correctness, but
correctness is a complex topic and isn't easy to prove. Rust places a lot of
weight on its type system to help ensure that our programs do what we intend,
but it cannot help with everything. As such, Rust also includes support for
writing software tests in the language itself.</p>
<p>For example, we can write a function called <code>add_two</code> with a signature that
accepts an integer as an argument and returns an integer as a result. We can
implement and compile that function, and Rust can do all the type checking and
borrow checking that we've seen it's capable of doing. What Rust <em>can't</em> check
for us is that we've implemented this function to return the argument plus two
and not the argument plus 10 or the argument minus 50! That's where tests come
in. We can write tests that, for example, pass <code>3</code> to the <code>add_two</code> function
and check that we get <code>5</code> back. We can run the tests whenever we make changes
to our code to make sure we didn't change any existing behavior from what the
tests specify it should be.</p>
<p>Testing is a skill, and we cannot hope to cover everything about how to write
good tests in one chapter of a book. What we can discuss, however, are the
mechanics of Rust's testing facilities. We'll talk about the annotations and
macros available to you when writing your tests, the default behavior and
options provided for running your tests, and how to organize tests into unit
tests and integration tests.</p>
<h2>Writing Tests</h2>
<p>Tests are Rust functions that use particular features and are written in such a
way as to verify that non-test code is functioning in the expected manner.
Everything we've discussed about Rust code applies to Rust tests as well! Let's
look at the features Rust provides specifically for writing tests: the <code>test</code>
attribute, a few macros, and the <code>should_panic</code> attribute.</p>
<h3>The <code>test</code> attribute</h3>
<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 library project with Cargo called <code>adder</code>:</p>
<pre><code class="language-text">$ cargo new adder
Created library `adder` project
$ cd adder
</code></pre>
<p>Cargo will automatically generate a simple test when you make a new library
project. Here's the contents of <code>src/lib.rs</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
</code></pre>
<p>For now, let's ignore the <code>tests</code> module and the <code>#[cfg(test)]</code> annotation in
order to focus on just the function. Note the <code>#[test]</code> before it: this
attribute indicates this is a test function. The function 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-text">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 0.22 secs
Running target/debug/deps/adder-ce99bcc2479f4607
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; we're
going to focus on the first set in this chapter. The second set of output is
for documentation tests, which we'll talk about in Chapter 14. For now, note
this line:</p>
<pre><code class="language-text">test it_works ... ok
</code></pre>
<p>The <code>it_works</code> text comes from the name of our function.</p>
<p>We also get a summary line that tells us the aggregate results of all the
tests that we have:</p>
<pre><code class="language-text">test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<h3>The <code>assert!</code> macro</h3>
<p>The empty test function passes because any test which doesn't <code>panic!</code> passes,
and any test that does <code>panic!</code> fails. Let's make the test fail by using the
<code>assert!</code> macro:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert!(false);
}
</code></pre>
<p>The <code>assert!</code> macro is provided by the standard library, and it takes one
argument. If the argument is <code>true</code>, nothing happens. If the argument is
<code>false</code>, the macro will <code>panic!</code>. Let's run our tests again:</p>
<pre><code class="language-text">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 0.22 secs
Running target/debug/deps/adder-ce99bcc2479f4607
running 1 test
test it_works ... FAILED
failures:
---- it_works stdout ----
thread 'it_works' panicked at 'assertion failed: false', src/lib.rs:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.
failures:
it_works
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
error: test failed
</code></pre>
<p>Rust indicates that our test failed:</p>
<pre><code class="language-text">test it_works ... FAILED
</code></pre>
<p>And shows that the test failed because the <code>assert!</code> macro in <code>src/lib.rs</code> on
line 5 got a <code>false</code> value:</p>
<pre><code class="language-text">thread 'it_works' panicked at 'assertion failed: false', src/lib.rs:5
</code></pre>
<p>The test failure is also reflected in the summary line:</p>
<pre><code class="language-text">test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
</code></pre>
<h3>Testing equality with the <code>assert_eq!</code> and <code>assert_ne!</code> macros</h3>
<p>A common way to test functionality is to compare the result of the code under
test to the value you expect it to be, and check that they're equal. You can do
this using the <code>assert!</code> macro by passing it an expression using the <code>==</code>
macro. This is so common, though, that the standard library provides a pair of
macros to do this for convenience: <code>assert_eq!</code> and <code>assert_ne!</code>. These macros
compare two arguments for equality or inequality, respectively. The other
advantage of using these macros is they will print out what the two values
actually are if the assertion fails so that it's easier to see <em>why</em> the test
failed, whereas the <code>assert!</code> macro would just print out that it got a <code>false</code>
value for the <code>==</code> expression.</p>
<p>Here's an example test that uses each of these macros and will pass:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert_eq!(&quot;Hello&quot;, &quot;Hello&quot;);
assert_ne!(&quot;Hello&quot;, &quot;world&quot;);
}
</code></pre>
<p>You can also specify an optional third argument to each of these macros, which
is a custom message that you'd like to be added to the failure message. The
macros expand to logic similar to this:</p>
<pre><code class="language-rust,ignore">// assert_eq! - panic if the values aren't equal
if left_val != right_val {
panic!(
&quot;assertion failed: `(left == right)` (left: `{:?}`, right: `{:?}`): {}&quot;
left_val,
right_val,
optional_custom_message
)
}
// assert_ne! - panic if the values are equal
if left_val == right_val {
panic!(
&quot;assertion failed: `(left != right)` (left: `{:?}`, right: `{:?}`): {}&quot;
left_val,
right_val,
optional_custom_message
)
}
</code></pre>
<p>Let's take a look at a test that will fail becasue <code>hello</code> is not equal to
<code>world</code>. We've also added a custom error message, <code>greeting operation failed</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[test]
fn a_simple_case() {
let result = &quot;hello&quot;; // this value would come from running your code
assert_eq!(result, &quot;world&quot;, &quot;greeting operation failed&quot;);
}
</code></pre>
<p>Running this indeed fails, and the output we get explains why the test failed
and includes the custom error message we specified:</p>
<pre><code class="language-text">---- a_simple_case stdout ----
thread 'a_simple_case' panicked at 'assertion failed: `(left == right)`
(left: `&quot;hello&quot;`, right: `&quot;world&quot;`): greeting operation failed',
src/main.rs:4
</code></pre>
<p>The two arguments to <code>assert_eq!</code> are named &quot;left&quot; and &quot;right&quot; rather than
&quot;expected&quot; and &quot;actual&quot;; the order of the value that comes from your code and
the value hardcoded into your test isn't important.</p>
<p>Since these macros use the operators <code>==</code> and <code>!=</code> and print the values using
debug formatting, the values being compared must implement the <code>PartialEq</code> and
<code>Debug</code> traits. Types provided by Rust implement these traits, but for structs
and enums that you define, you'll need to add <code>PartialEq</code> in order to be able
to assert that values of those types are equal or not equal and <code>Debug</code> in
order to be able to print out the values in the case that the assertion fails.
Because both of these traits are derivable traits that we mentioned in Chapter
5, usually this is as straightforward as adding the <code>#[derive(PartialEq, Debug)]</code> annotation to your struct or enum definition. See Appendix C for more
details about these and other derivable traits.</p>
<h2>Test for failure with <code>should_panic</code></h2>
<p>We can invert our test's failure with another attribute: <code>should_panic</code>. This
is useful when we want to test that calling a particular function will cause an
error. For example, let's test something that we know will panic from Chapter
8: attempting to create a slice using range syntax with byte indices that
aren't on character boundaries. Add the <code>#[should_panic]</code> attribute before the
function like the <code>#[test]</code> attribute, as shown in Listing 11-1:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">#[test]
#[should_panic]
fn slice_not_on_char_boundaries() {
let s = &quot;Здравствуйте&quot;;
&amp;s[0..1];
}
</code></pre>
<figcaption>
<p>Listing 11-1: A test expecting a <code>panic!</code></p>
</figcaption>
</figure>
<p>This test will succeed, since the code panics and we said that it should. If
this code happened to run and did not cause a <code>panic!</code>, this test would fail.</p>
<p><code>should_panic</code> tests can be fragile, as it's hard to guarantee that the test
didn't fail for a different reason than the one you were expecting. 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 more robust version of Listing 11-1 would be the
following, in Listing 11-2:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">#[test]
#[should_panic(expected = &quot;do not lie on character boundary&quot;)]
fn slice_not_on_char_boundaries() {
let s = &quot;Здравствуйте&quot;;
&amp;s[0..1];
}
</code></pre>
<!-- I will add ghosting in libreoffice /Carol -->
<figcaption>
<p>Listing 11-2: A test expecting a <code>panic!</code> with a particular message</p>
</figcaption>
</figure>
<p>Try on your own to see what happens when a <code>should_panic</code> test panics but
doesn't match the expected message: cause a <code>panic!</code> that happens for a
different reason in this test, or change the expected panic message to
something that doesn't match the character boundary panic message.</p>
<h2>Running tests</h2>
<p>Just like <code>cargo run</code> compiles your code and then runs the resulting binary,
<code>cargo test</code> compiles your code in test mode and runs the resulting test
binary. The default behavior of the binary that <code>cargo test</code> produces is to run
all the tests in parallel and to capture output generated during test runs so
that it's easier to read the output about the test results.</p>
<p>The default behavior of running tests can be changed by specifying command line
options. Some of these options can be passed to <code>cargo test</code>, and some need to
be passed instead to the resulting test binary. The way to separate these
arguments is with <code>--</code>: after <code>cargo test</code>, list the arguments that go to
<code>cargo test</code>, then the separator <code>--</code>, and then the arguments that go to the
test binary.</p>
<h3>Tests Run in Parallel</h3>
<p>Tests are run in parallel using threads. For this reason, you should take care
that your tests are written in such a way as to not depend on each other or on
any shared state. Shared state can also include the environment, such as the
current working directory or environment variables.</p>
<p>If you don't want this behavior, or if you want more fine-grained control over
the number of threads used, you can send the <code>--test-threads</code> flag and the
number of threads to the test binary. Setting the number of test threads to 1
means to not use any parallelism:</p>
<pre><code class="language-text">$ cargo test -- --test-threads=1
</code></pre>
<h3>Tests Capture Output</h3>
<p>By default, Rust's test library captures and discards output to standard out
and standard error, unless the test fails. For example, if you call <code>println!</code>
in a test and the test passes, you won't see the <code>println!</code> output in your
terminal. This behavior can be disabled by sending the <code>--nocapture</code> flag to
the test binary:</p>
<pre><code class="language-text">$ cargo test -- --nocapture
</code></pre>
<h3>Running a Subset of Tests by Name</h3>
<p>Sometimes, running a full test suite can take a long time. If you're only
working on code in a particular area, you might want to only run the tests
having to do with that code. <code>cargo test</code> takes an argument that allows you to
only run certain tests, specified by name.</p>
<p>Let's create three tests with the following names as shown in Listing 11-3:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">#[test]
fn add_two_and_two() {
assert_eq!(4, 2 + 2);
}
#[test]
fn add_three_and_two() {
assert_eq!(5, 3 + 2);
}
#[test]
fn one_hundred() {
assert_eq!(102, 100 + 2);
}
</code></pre>
<figcaption>
<p>Listing 11-3: Three tests with a variety of names</p>
</figcaption>
</figure>
<p>Running with different arguments will run different subsets of the tests. No
arguments, as we've already seen, runs all the tests:</p>
<pre><code class="language-text">$ cargo test
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/adder-06a75b4a1f2515e9
running 3 tests
test add_three_and_two ... ok
test one_hundred ... ok
test add_two_and_two ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>We can pass the name of any test function to run only that test:</p>
<pre><code class="language-text">$ cargo test one_hundred
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/adder-06a75b4a1f2515e9
running 1 test
test one_hundred ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>We can also pass part of a name, and <code>cargo test</code> will run all tests that match:</p>
<pre><code class="language-text">$ cargo test add
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/adder-06a75b4a1f2515e9
running 2 tests
test add_three_and_two ... ok
test add_two_and_two ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Module names become part of the test name, so module names can be used in a
similar way to run just the tests for a particular module. For example, if our
code was organized into a module named <code>adding</code> and a module named
<code>subtracting</code> with tests in each, as in Listing 11-4:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">mod adding {
#[test]
fn add_two_and_two() {
assert_eq!(4, 2 + 2);
}
#[test]
fn add_three_and_two() {
assert_eq!(5, 3 + 2);
}
#[test]
fn one_hundred() {
assert_eq!(102, 100 + 2);
}
}
mod subtracting {
#[test]
fn subtract_three_and_two() {
assert_eq!(1, 3 - 2);
}
}
</code></pre>
<figcaption>
<p>Listing 11-4: Tests in two modules named <code>adding</code> and <code>subtracting</code></p>
</figcaption>
</figure>
<p>Running <code>cargo test</code> will run all of the tests, and the module names will
appear in the test names in the output:</p>
<pre><code class="language-text">$ cargo test
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/adder-d84f1c6cb24adeb4
running 4 tests
test adding::add_two_and_two ... ok
test adding::add_three_and_two ... ok
test subtracting::subtract_three_and_two ... ok
test adding::one_hundred ... ok
</code></pre>
<p>Running <code>cargo test adding</code> would run just the tests in that module and not any
of the tests in the subtracting module:</p>
<pre><code class="language-text">$ cargo test adding
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/adder-d84f1c6cb24adeb4
running 3 tests
test adding::add_three_and_two ... ok
test adding::one_hundred ... ok
test adding::add_two_and_two ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<h3>Ignore Some Tests Unless Specifically Requested</h3>
<p>Sometimes a few specific tests can be very time-consuming to execute, so during
most runs of <code>cargo test</code>, we'd like to exclude them. Instead of having to
construct an argument to <code>cargo test</code> to run all tests except these and
remember to use that argument every time, we can annotate these tests with the
<code>ignore</code> attribute:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[test]
fn it_works() {
assert!(true);
}
#[test]
#[ignore]
fn expensive_test() {
// code that takes an hour to run
}
</code></pre>
<p>Now if we run our tests, we'll see <code>it_works</code> is run, but <code>expensive_test</code> is
not:</p>
<pre><code class="language-text">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 0.24 secs
Running target/debug/deps/adder-ce99bcc2479f4607
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>We can run only the expensive tests by explicitly asking to run them using
<code>cargo test -- --ignored</code>:</p>
<pre><code class="language-text">$ cargo test -- --ignored
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/adder-ce99bcc2479f4607
running 1 test
test expensive_test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>This way, most of the time that you run <code>cargo test</code> the results would be fast.
When you're at a point that it makes sense to check the results of the
<code>ignored</code> tests and you have time to wait for the results, you can choose to
run <code>cargo test -- --ignored</code> instead.</p>
<h2>Test Organization</h2>
<p>As mentioned before, testing is a large discipline, and different people
sometimes use different terminology and organization. The Rust community tends
to think about tests in terms of two main categories: <em>unit tests</em> and
<em>integration tests</em>. Unit tests tend to be smaller and more focused, testing
one module in isolation at a time. They can also test private interfaces.
Integration tests are entirely external to your library. They use your code in
the same way any other code would, using only the public interface and
exercising multiple modules per test. Both kinds of tests are important to
ensure that the pieces of your library are doing what you expect them to
separately and together.</p>
<h3>Unit Tests</h3>
<p>The purpose of unit tests is to test each unit of code in isolation from the
rest of the code, in order to be able to quickly pinpoint where code is working
as expected or not. Unit tests live in the <em>src</em> directory, in the same files
as the code they are testing. They are separated into their own <code>tests</code> module
in each file.</p>
<h4>The Tests Module and <code>cfg(test)</code></h4>
<p>By placing tests in their own module and using the <code>cfg</code> annotation on the
module, we can tell Rust to only compile and run the test code when we run
<code>cargo test</code>. This saves compile time when we only want to build the library
code with <code>cargo build</code>, and saves space in the resulting compiled artifact
since the tests are not included.</p>
<p>Remember when we generated the new <code>adder</code> project in the last section? Cargo
generated this code for us:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
</code></pre>
<p>We ignored the module stuff so we could concentrate on the mechanics of the
test code inside the module, but now let's focus on the code surrounding our
tests.</p>
<p>First of all, there's a new attribute, <code>cfg</code>. The <code>cfg</code> attribute lets us
declare that something should only be included given a certain <em>configuration</em>.
Rust provides the <code>test</code> configuration for compiling and running tests. By
using this attribute, Cargo only compiles our test code if we're currently
trying to run the tests.</p>
<p>Next, the <code>tests</code> module holds all of our test functions, while our code is
outside of the <code>tests</code> module. The name of the <code>tests</code> module is a convention;
otherwise this is a regular module that follows the usual visibility rules we
covered in Chapter 7. Because we're in an inner module, we need to bring the
code under test into scope. This can be annoying if you have a large module, so
this is a common use of globs.</p>
<p>Up until now in this chapter, we've been writing tests in our <code>adder</code> project
that don't actually call any code we've written. Let's change that now! In
<em>src/lib.rs</em>, place this <code>add_two</code> function and <code>tests</code> module that has a test
function to exercise the code, as shown in Listing 11-5:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">pub fn add_two(a: i32) -&gt; i32 {
a + 2
}
#[cfg(test)]
mod tests {
use add_two;
#[test]
fn it_works() {
assert_eq!(4, add_two(2));
}
}
</code></pre>
<figcaption>
<p>Listing 11-5: Testing the function <code>add_two</code> in a child <code>tests</code> module</p>
</figcaption>
</figure>
<p>Notice in addition to the test function, we also added <code>use add_two;</code> within
the <code>tests</code> module. This brings the code we want to test into the scope of the
inner <code>tests</code> module, just like we'd need to do for any inner module. If we run
this test now with <code>cargo test</code>, it will pass:</p>
<pre><code class="language-text">running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>If we had forgotten to bring the <code>add_two</code> function into scope, we would get an
unresolved name error since the <code>tests</code> module wouldn't know anything about the
<code>add_two</code> function:</p>
<pre><code class="language-text">error[E0425]: unresolved name `add_two`
--&gt; src/lib.rs:9:23
|
9 | assert_eq!(4, add_two(2));
| ^^^^^^^ unresolved name
</code></pre>
<p>If this module contained lots of code we wanted to test, it would be annoying
to list everything in the <code>use</code> statement in the tests. It's common instead to
put <code>use super::*;</code> within a module's <code>test</code> submodule in order to bring
everything into the <code>test</code> module scope at once.</p>
<h4>Testing Private Functions</h4>
<p>There's controversy within the testing community about whether you should write
unit tests for private functions or not. Regardless of which testing ideology
you adhere to, Rust does allow you to test private functions due to the way
that the privacy rules work. Consider the code in Listing 11-6 with the private
function <code>internal_adder</code>:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">pub fn add_two(a: i32) -&gt; i32 {
internal_adder(a, 2)
}
fn internal_adder(a: i32, b: i32) -&gt; i32 {
a + b
}
#[cfg(test)]
mod tests {
use internal_adder;
#[test]
fn internal() {
assert_eq!(4, internal_adder(2, 2));
}
}
</code></pre>
<figcaption>
<p>Listing 11-6: Testing a private function</p>
</figcaption>
</figure>
<p>Because tests are just Rust code and the <code>tests</code> module is just another module,
we can import and call <code>internal_adder</code> in a test just fine. If you don't think
private functions should be tested, there's nothing in Rust that will compel
you to do so.</p>
<h3>Integration Tests</h3>
<p>In Rust, integration tests are tests that are entirely external to your
library. They use your library in the same way any other code would. Their
purpose is to test that many parts of your library work correctly together.
Units of code that work correctly by themselves could have problems when
integrated, so test coverage of the integrated code is important as well.</p>
<h4>The <em>tests</em> Directory</h4>
<p>Cargo has support for integration tests in the <em>tests</em> directory. If you make
one and put Rust files inside, Cargo will compile each of the files as an
individual crate. Let's give it a try!</p>
<p>First, make a <em>tests</em> directory at the top level of your project directory,
next to <em>src</em>. Then, make a new file, <em>tests/integration_test.rs</em>, and put the
code in Listing 11-7 inside:</p>
<figure>
<span class="filename">Filename: tests/integration_test.rs</span>
<pre><code class="language-rust,ignore">extern crate adder;
#[test]
fn it_adds_two() {
assert_eq!(4, adder::add_two(2));
}
</code></pre>
<figcaption>
<p>Listing 11-7: An integration test of a function in the <code>adder</code> crate</p>
</figcaption>
</figure>
<p>We now have <code>extern crate adder</code> at the top, which we didn't need in the unit
tests. Each test in the <code>tests</code> directory is an entirely separate crate, so we
need to import our library into each of them. 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, by importing the crate and using only the public
API.</p>
<p>We also don't need a <code>tests</code> module in this file. The whole directory won't be
compiled unless we're running the tests, so we don't need to annotate any part
of it with <code>#[cfg(test)]</code>. Also, each test file is already isolated into its
own crate, so we don't need to separate the test code further.</p>
<p>Let's run the integration tests, which also get run when we run <code>cargo test</code>:</p>
<pre><code class="language-text">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Running target/debug/deps/adder-91b3e234d4ed382a
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Running target/debug/integration_test-952a27e0126bb565
running 1 test
test it_adds_two ... 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 of output: the unit tests, the integration test, and
the doc tests. Note that adding more unit tests in any <em>src</em> file will add more
lines to the unit tests section. Adding more test functions to the integration
test file we created will add more lines to that section. If we add more
integration test <em>files</em> in the <em>tests</em> directory, there will be more
integration test sections: one for each file.</p>
<p>Specifying a test function name argument with <code>cargo test</code> will also match
against test function names in any integration test file. To run all of the
tests in only one particular integration test file, use the <code>--test</code> argument
of <code>cargo test</code>:</p>
<pre><code class="language-text">$ cargo test --test integration_test
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/integration_test-952a27e0126bb565
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<h4>Submodules in Integration Tests</h4>
<p>As you add more integration tests, you may want to make more than one file in
the <code>tests</code> directory in order to group the test functions by the functionality
they're testing, for example. As we mentioned before, that will work fine,
given that Cargo treats every file as its own crate.</p>
<p>Eventually, you may have a set of helper functions that are common to all
integration tests, for example, functions that set up common scenarios. If you
extract these into a file in the <em>tests</em> directory, like <em>tests/common.rs</em> for
example, this file will be compiled into a separate crate just like the Rust
files in this directory that contain test functions are. There will be a
separate section in the test output for this file. Since this is probably not
what you want, it's recommended to instead use a <em>mod.rs</em> file in a
subdirectory, like <em>tests/common/mod.rs</em>, for helper functions. Files in
subdirectories of the <em>tests</em> directory do not get compiled as separate crates
or have sections in the test output.</p>
<h4>Integration Tests for Binary Crates</h4>
<p>If your project is a binary crate that only contains a <em>src/main.rs</em> and does
not have a <em>src/lib.rs</em>, it is not possible to create integration tests in the
<em>tests</em> directory and use <code>extern crate</code> to import the functions in
<em>src/main.rs</em>. This is one of the reasons Rust projects that provide a binary
have a straightforward <em>src/main.rs</em> that calls logic that lives in
<em>src/lib.rs</em>. With that structure, integration tests <em>can</em> test the library
crate by using <code>extern crate</code> to cover the important functionality, and if that
works, the small amount of code in <em>src/main.rs</em> will work as well and does not
need to be tested.</p>
<h2>Summary</h2>
<p>Rust's testing features provide a way to specify how code should function to
ensure the code continues to work in the specified ways even as we make
changes. Unit tests exercise different parts of a library separately and can
test private implementation details. Integration tests cover the use of many
parts of the library working together, and use the library's public API to test
the code in the same way other code will use it. Rust's type system and
ownership rules help prevent some kinds of bugs, but tests are an important
part of reducing logic bugs having to do with how your code is expected to
behave.</p>
<p>Let's put together the knowledge from this chapter and other previous chapters
and work on a project in the next chapter!</p>
<h2>Organizing your Public API</h2>
<p>Here, we will describe the properties that a good public API in Rust has in
order to be pleasant for others to use.</p>
<h3>Re-exports with <code>pub use</code></h3>
<p>If your internal code organization doesn't match your desired public API
organization, you can re-export items in the way you want them to be organized.</p>
<p>To re-export a name, combine the <code>pub</code> keyword with <code>use</code>:</p>
<pre><code class="language-rust"># fn main() {} // this ex needs to be outside main
mod a {
pub mod namespace {
pub fn function() {}
}
}
pub use a::namespace::function;
</code></pre>
<p>Here, the <code>a</code> module is not public to users of our library, so neither are its
children, even though <code>namespace</code> and <code>function</code> are public <em>within</em> our
library. So users of our library couldn't call <code>a::namespace::function()</code>
themselves. However, since we've re-exported <code>function</code> with <code>pub use</code>,
<code>function</code> will be public. Users can just call <code>function</code> themselves,
directly. This allows us to organize our code internally however we'd like,
while presenting a different external interface.</p>
<h2>Documentation</h2>
<!-- Insert why documentation is important here, who your audience is for documentation -->
<h3>Documentation comments</h3>
<p>Rust has another kind of comment: a documentation comment. These
comments don’t affect the way that the code works, but they do work with Rust’s
tools. More specifically, the <code>rustdoc</code> tool that comes with Rust reads
documentation comments and produces HTML documentation from them.</p>
<p>Documentation comments use an extra slash:</p>
<pre><code class="language-rust">/// The foo function doesn’t really do much.
fn foo() {
}
/// We also can use
/// multiple comments here too,
/// like we did before
fn bar() {
}
</code></pre>
<p>This comment would then be interpreted by <code>rustdoc</code> as documenting the thing
that follows it: <code>foo</code> and <code>bar</code>.</p>
<p>Because documentation comments have semantic meaning to <code>rustdoc</code>, the compiler
will pay attention to the placement of your documentation comments. For
example, a program with only this:</p>
<pre><code class="language-rust,ignore">/// What am I documenting?
</code></pre>
<p>Will give a compiler error:</p>
<pre><code class="language-text">src/main.rs:1:1: 1:27 error: expected item after doc comment
src/main.rs:1 /// What am I documenting?
^~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<h3>Generating HTML documentation</h3>
<h3>Documentation examples</h3>
<p>Another special part about documentation comments is that code examples in
documentation comments are run as part of your tests, so that they're less
likely to go out of date! To use this feature:</p>
<ul>
<li>TODO: insert a documentation example, preferably one that demonstrates a
<code>use</code> statement including parts of the current crate, not just stdlib.</li>
</ul>
<h2>Workspaces and Multiple Related Crates</h2>
<p>Projects can define a <em>workspace</em>, which is a set of crates that will all share
the same <em>Cargo.lock</em> and output directory.</p>
<p>We weren't technically precise about the difference between a <em>package</em> and a
<em>crate</em> until now, and casually people will use the words <em>package</em> and <em>crate</em>
interchangeably and everyone will understand.</p>
<p>But there are cases when it makes sense to have multiple crates in one project
because (insert reasons here). For example, (insert examples here, maybe
log/env_log in rust-lang-nursery?)</p>
<p>So let's get more precise now. Earlier, we said:</p>
<blockquote>
<p>A <em>crate</em> is what we call a package of Rust code.</p>
</blockquote>
<p>This definition is problematic because &quot;package&quot; does mean something specific
in terms of Cargo, but we used it in a general sense in that previous
definition.</p>
<p>Historically speaking, a &quot;compilation unit&quot; is the definition we use in Rust.
This comes from C and C++, which has three phases of going from &quot;here's my
source&quot; to &quot;here's something I run&quot;:</p>
<ol>
<li><strong>Preprocessing</strong>: this is where <code>cpp</code> (the c preprocessor, not &quot;c plus
plus&quot;) does <code>#include</code> and all that jazz</li>
<li><strong>Compiling</strong>: taking the output of preprocessing and turning it into an
object file</li>
<li><strong>Linking</strong>: taking one or many object files, putting them together, and
getting an ELF binary or <code>.exe</code></li>
</ol>
<p>Rust doesn't have a preprocessing step in this sense, and we call out to a
system linker, so <code>rustc</code> only really does step 2. So to be incredibly
technically correct, it's &quot;translation unit&quot;, even though most people say
&quot;compilation unit.&quot;</p>
<p>In some sense, a crate is &quot;that pile of source code you pass the root of to
<code>rustc</code>&quot;, but that feels too circular to be good. &quot;compilation unit&quot; is
technically precise, but is gibberish to a lot of people. And a &quot;package&quot; is
&quot;one or more crates&quot;, which confusingly, gets wrapped up by <code>cargo package</code>
into a file which ends in <code>.crate</code>, but is secretly a tarball.</p>
<p>Whew!</p>
<h1>Concurrency</h1>
<p>This is a really rough sketch of some ideas that this chapter might cover.</p>
<p>From <a href="https://news.ycombinator.com/item?id=13078384">the orange website</a>.</p>
<p>So, with Rust, it's more subtle than that. That is, while threading proper
isn't part of the language itself, Rust's type system is structured in such a
way as to make it possible to build those kinds of libraries. In other words,
Rust's focus on aliasability ends up solving these problems.</p>
<p>So for example, in that paper, 4.1 is about the problem of concurrent
modifiability. And indeed, it says</p>
<blockquote>
<p>Indeed, under the implementation strategy we outlined above, in which the
compiler is unaware of threads, it is allowed to transform code subject only
to sequential cor- rectness constraints and hence could generate the code
con- taining a race.</p>
</blockquote>
<p>However, in Rust, this re-ordering can't happen: Rust won't let you alias x and
y between two threads without some sort of synchronization primitive. But this
isn't because Rust knows about concurrency, it's because Rust knows about
aliasing. In a sense, Rust-the-language makes this program <em>impossible to
write</em>, but a library re-enables you to write this program. You need unsafe to
do this, but it's all wrapped up inside of the implementation of, for example,
Mutex<T>.</p>
<p>From the last part of this section:</p>
<blockquote>
<p>Resolving it essential requires a programming-language-defined and
compiler-respected memory model, simply to ensure that the user and compiler
can agree on when there is a data race.</p>
</blockquote>
<p>We're in agreement here, but the model is built around aliasing, not
concurrency.</p>
<p>4.2 is about speculatively executing store instructions. I know less about
this, but again, it's built on the idea of two threads accessing data at the
same time, unsynchronized. This can't happen in Rust due to the aliasing rules.</p>
<p>4.3 is about register promotion. This cannot happen in Rust, because you don't
call a function to acquire the lock, then do whatever you want. Mutex<T> hides
the value it's locking inside of itself, unable to be accessed from the
outside, and the call to acquire the lock returns a mutable reference to the
inner data. The call to acquire the lock is the only way to get said reference,
and Rust's aliasing rules will forbid any other kind of access through the
returned reference. So this kind of transformation can't happen in Rust either.</p>
<p>Section 5 is about performance. It's true that synchronization primitives are
expensive. Rust can again use unsafe code in a disciplined way to provide safe
concurrent modification, while ruling out data races entirely. For example,
consider a simple map operation. We take an array of integers, and for each
element, add one to it. This is an embarrassingly parallel operation, yet, as
the paper mentions, with a pthreads-style approach to making it safe, one would
need either a single lock around the whole array, which destroys the
concurrency entirely, or some set of more fine-grained locks, which introduce
cost, as well as limiting the amount of concurrency to some degree.</p>
<p>But with a small utility function [1], which performs a small (ie, non-atomic)
check at runtime, we can safety split up our array into as many disjoint chunks
as we'd like, and then pass each one off to its own thread, which is free to do
the modification with no more synchronization needed. In fact, libraries like
Rayon can even determine roughly the correct amount for you, if you don't want
to think about it, and it will near-transparently just handle this for you (you
change a call from iter() to par_iter() and you're done).</p>
<p>1: https://github.com/rust-lang/rust/blob/f8614c397313db00e4b46...</p>
<p>So yeah. I'm in agreement with the paper that the language needs to do <em>some</em>
kind of reasoning, but since aliasing and concurrency are so tightly related, I
would argue that the language could understand only aliasing, not concurrency,
and then library abstractions are sufficient.</p>
<h1>Patterns</h1>
<p>We've actually used patterns a few times so far: they're used in <code>let</code>
statements, in function arguments, and in the <code>match</code> expression. Patterns have
a lot more abilities than we have demonstrated so far, so we'll cover some of
the most commonly used ones in this section. Any of these abilities work in any
place where a pattern is used.</p>
<h2><code>let</code> statements</h2>
<p>A basic <code>let</code> statement has this form:</p>
<pre><code class="language-text">let PATTERN = EXPRESSION;
</code></pre>
<p>We've seen statements like <code>let x = 5;</code> with a variable name in the <code>PATTERN</code>
slot; a variable name is just a particularly humble form of pattern.</p>
<p>Let’s try a more complex pattern. Change our example program to this:</p>
<p><span class="filename">Filename: src/main.rs</span></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 patterns v0.1.0 (file:///projects/patterns)
Running `target/debug/patterns`
The value of x is: 5
The value of y is: 6
</code></pre>
<p>We’ve created two variables 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 the variable <code>x</code>
to the value <code>5</code> and <code>y</code> to <code>6</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 variables 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>Most of the time, Rust uses <em>type inference</em>, meaning that it attempts to infer
the types of your variables rather than you having to declare them explicitly
even though Rust is a statically typed language. Occasionally, Rust won't have
enough information to infer the type of your value, and you will need to add a
type annotation in with the pattern.</p>
<p>Here’s what a <code>let</code> statement with a <em>type annotation</em> looks like:</p>
<pre><code class="language-rust">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 variables:</p>
<pre><code class="language-rust">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>Literals &amp; _</h2>
<p>You can match against literals directly, and <code>_</code> acts as an ‘any’ case:</p>
<pre><code class="language-rust">let x = 1;
match x {
1 =&gt; println!(&quot;one&quot;),
2 =&gt; println!(&quot;two&quot;),
3 =&gt; println!(&quot;three&quot;),
_ =&gt; println!(&quot;anything&quot;),
}
</code></pre>
<p>This prints <code>one</code>.</p>
<h1>Multiple patterns</h1>
<p>You can match multiple patterns with <code>|</code>:</p>
<pre><code class="language-rust">let x = 1;
match x {
1 | 2 =&gt; println!(&quot;one or two&quot;),
3 =&gt; println!(&quot;three&quot;),
_ =&gt; println!(&quot;anything&quot;),
}
</code></pre>
<p>This prints <code>one or two</code>.</p>
<h2>ref and ref mut</h2>
<p>Usually, when you match against a pattern, variables are bound to a value.
This means you'll end up moving the value into the <code>match</code>:</p>
<pre><code class="language-rust,ignore">let name = Some(String::from(&quot;Bors&quot;));
match name {
Some(name) =&gt; println!(&quot;Found a name: {}&quot;, name),
None =&gt; (),
}
// name is moved here. This line will fail to compile:
println!(&quot;name is: {:?}&quot;, name);
</code></pre>
<p>If you'd prefer to bind <code>name</code> to a reference, use the <code>ref</code> keyword:</p>
<pre><code class="language-rust">let name = Some(String::from(&quot;Bors&quot;));
match name {
Some(ref name) =&gt; println!(&quot;Found a name: {}&quot;, name),
None =&gt; (),
}
// name is not moved here; the match only took a reference to its data rather
// than moving it. This will work:
println!(&quot;name is: {:?}&quot;, name);
</code></pre>
<p>And for a mutable reference, <code>ref mut</code>:</p>
<pre><code class="language-rust">let mut name = Some(String::from(&quot;Bors&quot;));
match name {
Some(ref mut name) =&gt; *name = String::from(&quot;Another name&quot;),
None =&gt; (),
}
// name is not moved here; the match only took a reference to its data rather
// than moving it
println!(&quot;name is: {:?}&quot;, name);
</code></pre>
<h2>Destructuring</h2>
<p>Patterns can be used to destructure structs and enums:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };
let Point { x, y } = origin;
</code></pre>
<p>This brings <code>x</code> and <code>y</code> variables into scope, matching the <code>x</code> and <code>y</code> of
<code>origin</code>. While it can be unusual in <code>let</code>, this is the same principle of
patterns in <code>match</code>:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };
match origin {
Point { x, y } =&gt; { }, // variables x and y are created here
}
</code></pre>
<h2>Shadowing</h2>
<p>As with all variables, those declared by a pattern will shadow variables
outside of the <code>match</code> construct:</p>
<pre><code class="language-rust">let x = Some(5);
match x {
Some(x) =&gt; { }, // x is an i32 here, not an Option&lt;i32&gt;
None =&gt; (),
}
</code></pre>
<h2>Ignoring values</h2>
<p>We discussed using <code>_</code> as a whole pattern to ignore it above, but you can
also use <code>_</code> inside of another pattern to ignore just part of it:</p>
<pre><code class="language-rust">let x = Some(5);
match x {
Some(_) =&gt; println!(&quot;got a Some and I don't care what's inside&quot;),
None =&gt; (),
}
</code></pre>
<p>Or like this:</p>
<pre><code class="language-rust">let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) =&gt; println!(&quot;Some numbers: {}, {}, {}&quot;, first, third, fifth),
}
</code></pre>
<p>If you want, you can use <code>..</code> to ignore all of the parts you haven't defined:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
z: i32,
}
let origin = Point { x: 0, y: 0, z: 0 };
match origin {
Point { x, .. } =&gt; { }, // y and z are ignored
}
</code></pre>
<h2>Ranges</h2>
<p>You can match a range of values with <code>...</code>:</p>
<pre><code class="language-rust">let x = 5;
match x {
1 ... 5 =&gt; println!(&quot;one through five&quot;),
_ =&gt; println!(&quot;something else&quot;),
}
</code></pre>
<p>Ranges are usually used with integers or <code>char</code>s:</p>
<pre><code class="language-rust">let x = 'c';
match x {
'a' ... 'j' =&gt; println!(&quot;early ASCII letter&quot;),
'k' ... 'z' =&gt; println!(&quot;late ASCII letter&quot;),
_ =&gt; println!(&quot;something else&quot;),
}
</code></pre>
<h2>Guards</h2>
<p>You can introduce ‘match guards’ with <code>if</code>:</p>
<pre><code class="language-rust">let x = Some(5);
match x {
Some(x) if x &lt; 5 =&gt; println!(&quot;less than five: {}&quot;, x),
Some(x) =&gt; println!(&quot;{}&quot;, x),
None =&gt; (),
}
</code></pre>
<p>If you’re using if with multiple patterns, the if applies to both sides:</p>
<pre><code class="language-rust">let x = 4;
let y = false;
match x {
4 | 5 if y =&gt; println!(&quot;yes&quot;),
_ =&gt; println!(&quot;no&quot;),
}
</code></pre>
<p>This prints <code>no</code>, because the if applies to the whole of <code>4 | 5</code>, and not to only
the <code>5</code>. In other words, the precedence of if behaves like this:</p>
<pre><code class="language-text">(4 | 5) if y =&gt; ...
</code></pre>
<p>not this:</p>
<pre><code class="language-text">4 | (5 if y) =&gt; ...
</code></pre>
<h2>Bindings</h2>
<p>You can bind values to names with <code>@</code>:</p>
<h1>Appendix</h1>
<p>The following sections contain reference material you may find useful in your
Rust journey.</p>
<h2>Keywords</h2>
<p>The following keywords are reserved by the Rust language and may not be used as
names of functions, variables, macros, modules, crates, constants, static
values, attributes, struct fields, or arguments.</p>
<ul>
<li><code>abstract</code></li>
<li><code>alignof</code></li>
<li><code>as</code></li>
<li><code>become</code></li>
<li><code>box</code></li>
<li><code>break</code></li>
<li><code>const</code></li>
<li><code>continue</code></li>
<li><code>crate</code></li>
<li><code>do</code></li>
<li><code>else</code></li>
<li><code>enum</code></li>
<li><code>extern</code></li>
<li><code>false</code></li>
<li><code>final</code></li>
<li><code>fn</code></li>
<li><code>for</code></li>
<li><code>if</code></li>
<li><code>impl</code></li>
<li><code>in</code></li>
<li><code>let</code></li>
<li><code>loop</code></li>
<li><code>macro</code></li>
<li><code>match</code></li>
<li><code>mod</code></li>
<li><code>move</code></li>
<li><code>mut</code></li>
<li><code>offsetof</code></li>
<li><code>override</code></li>
<li><code>priv</code></li>
<li><code>proc</code></li>
<li><code>pub</code></li>
<li><code>pure</code></li>
<li><code>ref</code></li>
<li><code>return</code></li>
<li><code>Self</code></li>
<li><code>self</code></li>
<li><code>sizeof</code></li>
<li><code>static</code></li>
<li><code>struct</code></li>
<li><code>super</code></li>
<li><code>trait</code></li>
<li><code>true</code></li>
<li><code>type</code></li>
<li><code>typeof</code></li>
<li><code>unsafe</code></li>
<li><code>unsized</code></li>
<li><code>use</code></li>
<li><code>virtual</code></li>
<li><code>where</code></li>
<li><code>while</code></li>
<li><code>yield</code></li>
</ul>
<h2>Operators</h2>
<h3>Unary operator expressions</h3>
<p>Rust defines the following unary operators. They are all written as prefix
operators, before the expression they apply to.</p>
<ul>
<li><code>-</code>
: Negation. Signed integer types and floating-point types support negation. It
is an error to apply negation to unsigned types; for example, the compiler
rejects <code>-1u32</code>.</li>
<li><code>*</code>
: Dereference. When applied to a pointer, it denotes the pointed-to location.
For pointers to mutable locations, the resulting value can be assigned to.
On non-pointer types, it calls the <code>deref</code> method of the <code>std::ops::Deref</code>
trait, or the <code>deref_mut</code> method of the <code>std::ops::DerefMut</code> trait (if
implemented by the type and required for an outer expression that will or
could mutate the dereference), and produces the result of dereferencing the
<code>&amp;</code> or <code>&amp;mut</code> borrowed pointer returned from the overload method.</li>
<li><code>!</code>
: Logical negation. On the boolean type, this flips between <code>true</code> and
<code>false</code>. On integer types, this inverts the individual bits in the
two's complement representation of the value.</li>
<li><code>&amp;</code> and <code>&amp;mut</code>
: Borrowing. When applied to a value, these operators produce a
reference (pointer) to that value. The value is also placed into
a borrowed state for the duration of the reference. For a shared
borrow (<code>&amp;</code>), this implies that the value may not be mutated, but
it may be read or shared again. For a mutable borrow (<code>&amp;mut</code>), the
value may not be accessed in any way until the borrow expires.</li>
</ul>
<h3>Binary operator expressions</h3>
<p>Binary operators expressions are given in order of operator precedence.</p>
<h4>Arithmetic operators</h4>
<p>Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
defined in the <code>std::ops</code> module of the <code>std</code> library. This means arithmetic
operators can be overridden for user-defined types. The default meaning of the
operators on standard types is given here.</p>
<ul>
<li><code>+</code>
: Addition and array/string concatenation.
Calls the <code>add</code> method on the <code>std::ops::Add</code> trait.</li>
<li><code>-</code>
: Subtraction.
Calls the <code>sub</code> method on the <code>std::ops::Sub</code> trait.</li>
<li><code>*</code>
: Multiplication.
Calls the <code>mul</code> method on the <code>std::ops::Mul</code> trait.</li>
<li><code>/</code>
: Quotient.
Calls the <code>div</code> method on the <code>std::ops::Div</code> trait.</li>
<li><code>%</code>
: Remainder.
Calls the <code>rem</code> method on the <code>std::ops::Rem</code> trait.</li>
</ul>
<p>Note that Rust does not have a built-in operator for exponential (power)
calculation; see the <code>pow</code> method on the numeric types.</p>
<h4>Bitwise operators</h4>
<p>Like the arithmetic operators, bitwise operators are syntactic sugar for calls
to methods of built-in traits. This means bitwise operators can be overridden
for user-defined types. The default meaning of the operators on standard types
is given here. Bitwise <code>&amp;</code>, <code>|</code> and <code>^</code> applied to boolean arguments are
equivalent to logical <code>&amp;&amp;</code>, <code>||</code> and <code>!=</code> evaluated in non-lazy fashion.</p>
<ul>
<li><code>&amp;</code>
: Bitwise AND.
Calls the <code>bitand</code> method of the <code>std::ops::BitAnd</code> trait.</li>
<li><code>|</code>
: Bitwise inclusive OR.
Calls the <code>bitor</code> method of the <code>std::ops::BitOr</code> trait.</li>
<li><code>^</code>
: Bitwise exclusive OR.
Calls the <code>bitxor</code> method of the <code>std::ops::BitXor</code> trait.</li>
<li><code>&lt;&lt;</code>
: Left shift.
Calls the <code>shl</code> method of the <code>std::ops::Shl</code> trait.</li>
<li><code>&gt;&gt;</code>
: Right shift (arithmetic).
Calls the <code>shr</code> method of the <code>std::ops::Shr</code> trait.</li>
</ul>
<h4>Lazy boolean operators</h4>
<p>The operators <code>||</code> and <code>&amp;&amp;</code> may be applied to operands of boolean type. The
<code>||</code> operator denotes logical 'or', and the <code>&amp;&amp;</code> operator denotes logical
'and'. They differ from <code>|</code> and <code>&amp;</code> in that the right-hand operand is only
evaluated when the left-hand operand does not already determine the result of
the expression. That is, <code>||</code> only evaluates its right-hand operand when the
left-hand operand evaluates to <code>false</code>, and <code>&amp;&amp;</code> only when it evaluates to
<code>true</code>.</p>
<h4>Comparison operators</h4>
<p>Comparison operators are, like the arithmetic operators and bitwise operators,
syntactic sugar for calls to built-in traits. This means that comparison
operators can be overridden for user-defined types. The default meaning of the
operators on standard types is given here.</p>
<ul>
<li><code>==</code>
: Equal to.
Calls the <code>eq</code> method on the <code>std::cmp::PartialEq</code> trait.</li>
<li><code>!=</code>
: Unequal to.
Calls the <code>ne</code> method on the <code>std::cmp::PartialEq</code> trait.</li>
<li><code>&lt;</code>
: Less than.
Calls the <code>lt</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
<li><code>&gt;</code>
: Greater than.
Calls the <code>gt</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
<li><code>&lt;=</code>
: Less than or equal.
Calls the <code>le</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
<li><code>&gt;=</code>
: Greater than or equal.
Calls the <code>ge</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
</ul>
<h4>Type cast expressions</h4>
<p>A type cast expression is denoted with the binary operator <code>as</code>.</p>
<p>Executing an <code>as</code> expression casts the value on the left-hand side to the type
on the right-hand side.</p>
<p>An example of an <code>as</code> expression:</p>
<pre><code class="language-rust"># fn sum(values: &amp;[f64]) -&gt; f64 { 0.0 }
# fn len(values: &amp;[f64]) -&gt; i32 { 0 }
fn average(values: &amp;[f64]) -&gt; f64 {
let sum: f64 = sum(values);
let size: f64 = len(values) as f64;
sum / size
}
</code></pre>
<p>Some of the conversions which can be done through the <code>as</code> operator
can also be done implicitly at various points in the program, such as
argument passing and assignment to a <code>let</code> binding with an explicit
type. Implicit conversions are limited to &quot;harmless&quot; conversions that
do not lose information and which have minimal or no risk of
surprising side-effects on the dynamic execution semantics.</p>
<h4>Assignment expressions</h4>
<p>An <em>assignment expression</em> consists of a pattern followed by an equals
sign (<code>=</code>) and an expression.</p>
<p>Evaluating an assignment expression either copies or
moves its right-hand operand to its left-hand
operand.</p>
<pre><code># let mut x = 0;
# let y = 0;
x = y;
</code></pre>
<h4>Compound assignment expressions</h4>
<p>The <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, and <code>&gt;&gt;</code> operators may be
composed with the <code>=</code> operator. The expression <code>lval OP= val</code> is equivalent to
<code>lval = lval OP val</code>. For example, <code>x = x + 1</code> may be written as <code>x += 1</code>.</p>
<p>Any such expression always has the <code>unit</code> type.</p>
<h4>Operator precedence</h4>
<p>The precedence of Rust binary operators is ordered as follows, going from
strong to weak:</p>
<pre><code class="language-text">as :
* / %
+ -
&lt;&lt; &gt;&gt;
&amp;
^
|
== != &lt; &gt; &lt;= &gt;=
&amp;&amp;
||
.. ...
&lt;-
=
</code></pre>
<p>Operators at the same precedence level are evaluated left-to-right. Unary
operators have the same precedence level and are stronger than any of the
binary operators.</p>
<h2>Derivable Traits</h2>
</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>
<!-- Livereload script (if served using the cli tool) -->
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>