Files
book/print.html
T

13036 lines
685 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>Translations - 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 and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <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-common-collections.html"><strong>8.</strong> Common 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> Generic Types, Traits, and Lifetimes</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Generic Data Types</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits: Defining Shared Behavior</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Validating References with Lifetimes</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><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Concurrency</a></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust OOP?</a></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns</a></li><li><a href="ch19-00-more-lifetimes.html"><strong>19.</strong> More Lifetimes</a></li><li><a href="ch20-00-advanced-types.html"><strong>20.</strong> Advanced Type System Features</a></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>21.3.</strong> Derivable Traits</a></li><li><a href="appendix-04-nightly-rust.html"><strong>21.4.</strong> Nightly Rust</a></li><li><a href="appendix-05-macros.html"><strong>21.5.</strong> Macros</a></li><li><a href="appendix-06-translation.html"><strong>21.6.</strong> Translations</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">
<a class="header" href="#introduction" name="introduction"><h1>Introduction</h1></a>
<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, <a href="https://crates.io/">crates.io</a>! 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>
<a class="header" href="#contributing-to-the-book" name="contributing-to-the-book"><h2>Contributing to the book</h2></a>
<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>
<a class="header" href="#installation" name="installation"><h2>Installation</h2></a>
<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>
<a class="header" href="#installing-on-linux-or-mac" name="installing-on-linux-or-mac"><h3>Installing on Linux or Mac</h3></a>
<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>
<p>Of course, if you disapprove of the <code>curl | sh</code> pattern, you can download, inspect
and run the script however you like.</p>
<a class="header" href="#installing-on-windows" name="installing-on-windows"><h3>Installing on Windows</h3></a>
<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>
<a class="header" href="#custom-installations" name="custom-installations"><h3>Custom installations</h3></a>
<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>
<a class="header" href="#uninstalling" name="uninstalling"><h3>Uninstalling</h3></a>
<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>
<a class="header" href="#troubleshooting" name="troubleshooting"><h3>Troubleshooting</h3></a>
<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>
<a class="header" href="#local-documentation" name="local-documentation"><h3>Local documentation</h3></a>
<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>
<a class="header" href="#hello-world" name="hello-world"><h2>Hello, World!</h2></a>
<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>
<a class="header" href="#creating-a-project-directory" name="creating-a-project-directory"><h3>Creating a Project Directory</h3></a>
<p>First, make a directory 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>
<a class="header" href="#writing-and-running-a-rust-program" name="writing-and-running-a-rust-program"><h3>Writing and Running a Rust Program</h3></a>
<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, run <code>.\main.exe</code> instead of <code>./main</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>
<a class="header" href="#anatomy-of-a-rust-program" name="anatomy-of-a-rust-program"><h3>Anatomy of a Rust Program</h3></a>
<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 has no parameters and returns
nothing.” If there were parameters, their names 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>
<a class="header" href="#compiling-and-running-are-separate-steps" name="compiling-and-running-are-separate-steps"><h3>Compiling and Running Are Separate Steps</h3></a>
<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>
<a class="header" href="#hello-cargo" name="hello-cargo"><h2>Hello, Cargo!</h2></a>
<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>
<a class="header" href="#creating-a-project-with-cargo" name="creating-a-project-with-cargo"><h3>Creating a Project with Cargo</h3></a>
<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>
<a class="header" href="#building-and-running-a-cargo-project" name="building-and-running-a-cargo-project"><h3>Building and Running a Cargo Project</h3></a>
<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>
<a class="header" href="#building-for-release" name="building-for-release"><h3>Building for Release</h3></a>
<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>
<a class="header" href="#cargo-as-convention" name="cargo-as-convention"><h3>Cargo as Convention</h3></a>
<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>
<a class="header" href="#guessing-game" name="guessing-game"><h1>Guessing Game</h1></a>
<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>
<a class="header" href="#setting-up-a-new-project" name="setting-up-a-new-project"><h2>Setting Up a New Project</h2></a>
<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>
<a class="header" href="#processing-a-guess" name="processing-a-guess"><h2>Processing a Guess</h2></a>
<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 bring the
<code>io</code> (input/output) library into scope. The <code>io</code> library comes 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 brings only a few types into the scope of 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 bring that type into scope 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
parameters, 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>
<a class="header" href="#storing-values-with-variables" name="storing-values-with-variables"><h3>Storing Values with Variables</h3></a>
<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>
<a class="header" href="#handling-potential-failure-with-the-result-type" name="handling-potential-failure-with-the-result-type"><h3>Handling Potential Failure with the <code>Result</code> Type</h3></a>
<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>
<a class="header" href="#printing-values-with-println-placeholders" name="printing-values-with-println-placeholders"><h3>Printing Values with <code>println!</code> Placeholders</h3></a>
<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>
<a class="header" href="#testing-the-first-part" name="testing-the-first-part"><h3>Testing the First Part</h3></a>
<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>
<a class="header" href="#generating-a-secret-number" name="generating-a-secret-number"><h2>Generating a Secret Number</h2></a>
<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>
<a class="header" href="#using-a-crate-to-get-more-functionality" name="using-a-crate-to-get-more-functionality"><h3>Using a Crate to Get More Functionality</h3></a>
<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>
<a class="header" href="#the-cargolock-file-ensures-reproducible-builds" name="the-cargolock-file-ensures-reproducible-builds"><h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4></a>
<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>
<a class="header" href="#updating-a-crate-to-get-a-new-version" name="updating-a-crate-to-get-a-new-version"><h4>Updating a Crate to Get a New Version</h4></a>
<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>
<a class="header" href="#generating-a-random-number" name="generating-a-random-number"><h3>Generating a Random Number</h3></a>
<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 use and which functions and methods to call 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>
<a class="header" href="#comparing-the-guess-to-the-secret-number" name="comparing-the-guess-to-the-secret-number"><h2>Comparing the Guess to the Secret Number</h2></a>
<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 brought into scope 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>
<a class="header" href="#allowing-multiple-guesses-with-looping" name="allowing-multiple-guesses-with-looping"><h2>Allowing Multiple Guesses with Looping</h2></a>
<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>
<a class="header" href="#quitting-after-a-correct-guess" name="quitting-after-a-correct-guess"><h3>Quitting After a Correct Guess</h3></a>
<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>
<a class="header" href="#handling-invalid-input" name="handling-invalid-input"><h3>Handling Invalid Input</h3></a>
<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>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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>
<a class="header" href="#common-programming-concepts" name="common-programming-concepts"><h1>Common Programming Concepts</h1></a>
<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>
<a class="header" href="#keywords" name="keywords"><h3>Keywords</h3></a>
<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 -->
<a class="header" href="#variables-and-mutability" name="variables-and-mutability"><h2>Variables and Mutability</h2></a>
<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 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>
<a class="header" href="#differences-between-variables-and-constants" name="differences-between-variables-and-constants"><h3>Differences Between Variables and Constants</h3></a>
<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>
<a class="header" href="#shadowing" name="shadowing"><h3>Shadowing</h3></a>
<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>
<a class="header" href="#data-types" name="data-types"><h2>Data Types</h2></a>
<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().expect(&quot;Not a number!&quot;);
</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().expect(&quot;Not a number!&quot;);
| ^^^^^ 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>
<a class="header" href="#scalar-types" name="scalar-types"><h3>Scalar Types</h3></a>
<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>
<a class="header" href="#integer-types" name="integer-types"><h4>Integer Types</h4></a>
<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> - 1, 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>
<a class="header" href="#floating-point-types" name="floating-point-types"><h4>Floating-Point Types</h4></a>
<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>
<a class="header" href="#numeric-operations" name="numeric-operations"><h4>Numeric Operations</h4></a>
<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>
<a class="header" href="#the-boolean-type" name="the-boolean-type"><h4>The Boolean Type</h4></a>
<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>
<a class="header" href="#the-character-type" name="the-character-type"><h4>The Character Type</h4></a>
<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>
<a class="header" href="#compound-types" name="compound-types"><h3>Compound Types</h3></a>
<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>
<a class="header" href="#grouping-values-into-tuples" name="grouping-values-into-tuples"><h4>Grouping Values into Tuples</h4></a>
<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>
<a class="header" href="#arrays" name="arrays"><h4>Arrays</h4></a>
<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>
<a class="header" href="#accessing-array-elements" name="accessing-array-elements"><h5>Accessing Array Elements</h5></a>
<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>
<a class="header" href="#invalid-array-element-access" name="invalid-array-element-access"><h5>Invalid Array Element Access</h5></a>
<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>
<a class="header" href="#how-functions-work" name="how-functions-work"><h2>How Functions Work</h2></a>
<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>
<a class="header" href="#function-parameters" name="function-parameters"><h3>Function Parameters</h3></a>
<p>Functions can also be defined to have <em>parameters</em>, which are special variables
that are part of a function's signature. When a function has parameters, we can
provide it with concrete values for those parameters. Technically, the concrete
values are called <em>arguments</em>, but in casual conversation people tend to use
the words &quot;parameter&quot; and &quot;argument&quot; interchangeably for either the variables in
a function's definition or the concrete values passed in when you call a
function.</p>
<p>The following rewritten version of <code>another_function</code> shows what parameters
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 parameter 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 of each parameter. 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 parameters, separate the parameter
declarations 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 parameters, both of which are <code>i32</code>
types. The function then prints out the values in both of its parameters. Note
that function parameters don't all need to be the same type - they just happen
to be in this example.</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 we called the function with <code>5</code> as the value for <code>x</code> and <code>6</code> as the
value for <code>y</code>, the two strings are printed using those values.</p>
<a class="header" href="#function-bodies" name="function-bodies"><h3>Function Bodies</h3></a>
<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>
<a class="header" href="#statements-and-expressions" name="statements-and-expressions"><h3>Statements and Expressions</h3></a>
<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>
<a class="header" href="#functions-with-return-values" name="functions-with-return-values"><h3>Functions with Return Values</h3></a>
<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 has no parameters 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>
<a class="header" href="#comments" name="comments"><h2>Comments</h2></a>
<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>
<a class="header" href="#control-flow" name="control-flow"><h2>Control Flow</h2></a>
<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>
<a class="header" href="#if-expressions" name="if-expressions"><h3><code>if</code> Expressions</h3></a>
<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 2. 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.</p>
<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>
<a class="header" href="#multiple-conditions-with-else-if" name="multiple-conditions-with-else-if"><h4>Multiple Conditions with <code>else if</code></h4></a>
<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>
<a class="header" href="#using-if-in-a-let-statement" name="using-if-in-a-let-statement"><h4>Using <code>if</code> in a <code>let</code> statement</h4></a>
<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>
<a class="header" href="#repetition-with-loops" name="repetition-with-loops"><h3>Repetition with Loops</h3></a>
<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>
<a class="header" href="#repeating-code-with-loop" name="repeating-code-with-loop"><h4>Repeating Code with <code>loop</code></h4></a>
<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>
<a class="header" href="#conditional-loops-with-while" name="conditional-loops-with-while"><h4>Conditional Loops with <code>while</code></h4></a>
<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>
<a class="header" href="#looping-through-a-collection-with-for" name="looping-through-a-collection-with-for"><h4>Looping Through a Collection with <code>for</code></h4></a>
<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>5</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 adds
runtime code 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>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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>
<a class="header" href="#understanding-ownership" name="understanding-ownership"><h1>Understanding Ownership</h1></a>
<p>Ownership is Rust’s most unique feature, and it enables Rust to make memory
safety guarantees without needing a garbage collector. Therefore, it’s
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 data out in memory.</p>
<a class="header" href="#what-is-ownership" name="what-is-ownership"><h2>What Is Ownership?</h2></a>
<p>Rust’s central feature is <em>ownership</em>. Although the feature is straightforward
to explain, it 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 constantly looks for no longer used
memory as the program runs; in other languages, the programmer must explicitly
allocate and free the memory. Rust uses a third approach: memory is managed
through a system of ownership with a set of rules that the compiler checks at
compile time. No run-time costs are incurred for any of the ownership features.</p>
<p>Because ownership is a new concept for many programmers, it does take some time
to get used to. The good news is that 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 safe and efficient. Keep at it!</p>
<p>When you understand ownership, you’ll have a solid foundation for understanding
the features that make Rust unique. In this chapter, you’ll learn ownership by
working through some examples that focus on a very common data structure:
strings.</p>
<!-- PROD: START BOX -->
<blockquote>
<a class="header" href="#the-stack-and-the-heap" name="the-stack-and-the-heap"><h3>The Stack and the Heap</h3></a>
<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’ll describe parts of
ownership in relation to the stack and the heap later in this chapter, so here
is a brief explanation in preparation.</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
search for a place to put new data or a place to get data from because 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 abbreviate the phrase as just
“allocating.” Pushing values onto the stack is not considered allocating.
Because 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 state the number of
people in your group, and the staff finds an empty table that fits everyone and
leads you there. If someone in your group comes late, they can ask where you’ve
been seated to find you.</p>
<p>Accessing data in the heap is slower than accessing data on the stack 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 taking orders from many tables. It’s most efficient to get all 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, and then one from B
again would be a much slower process. 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 we don’t run out of space 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 -->
<a class="header" href="#ownership-rules" name="ownership-rules"><h3>Ownership Rules</h3></a>
<p>First, let’s take a look at the ownership rules. Keep these rules in mind as we
work through the examples that 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>
<a class="header" href="#variable-scope" name="variable-scope"><h3>Variable Scope</h3></a>
<p>We’ve walked through an example of a Rust program already in Chapter 2. Now
that we’re past basic syntax, we won’t include all the <code>fn main() {</code> code in
examples, so if you’re following along, you’ll have to put the following
examples inside a <code>main</code> function manually. As a result, our examples will be a
bit more concise, letting us focus on the actual details rather than
boilerplate code.</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
hardcoded 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>. Listing 4-1 has
comments annotating where the variable <code>s</code> is valid:</p>
<figure>
<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>
<figcaption>
<p>Listing 4-1: A variable and the scope in which it is valid</p>
</figcaption>
</figure>
<p>In other words, there are two important points in time here:</p>
<ol>
<li>When <code>s</code> comes <em>into scope</em>, it is valid.</li>
<li>It remains so until it goes <em>out of scope</em>.</li>
</ol>
<p>At this point, the relationship between scopes and when variables are valid is
similar to other programming languages. Now we’ll build on top of this
understanding by introducing the <code>String</code> type.</p>
<a class="header" href="#the-string-type" name="the-string-type"><h3>The <code>String</code> Type</h3></a>
<p>To illustrate the rules of ownership, we need a data type that is more complex
than the ones we covered in Chapter 3. All 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 up that data.</p>
<p>We’ll 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 discuss <code>String</code> in
more depth in Chapter 8.</p>
<p>We’ve already seen string literals, where a string value is hardcoded into our
program. String literals are convenient, but they aren’t always suitable for
every situation in which you want to use text. One reason is that they’re
immutable. Another is that not every string value can be known when we write
our code: for example, what if we want to take user input and store it? For
these situations, 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 rather than using some sort
of name like <code>string_from</code>. We’ll discuss this syntax more in the “Method
Syntax” section of Chapter 5 and when we talk about namespacing with modules in
Chapter 7.</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 is how these two types deal with memory.</p>
<a class="header" href="#memory-and-allocation" name="memory-and-allocation"><h3>Memory and Allocation</h3></a>
<p>In the case of a string literal, we know the contents at compile time so the
text is hardcoded directly into the final executable, making string literals
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 while
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:</p>
<ol>
<li>The memory must be requested from the operating system at runtime.</li>
<li>We need a way of returning this memory 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>However, the second part is different. In languages with a <em>garbage collector
(GC)</em>, the GC keeps track and cleans up memory that isn’t being used anymore,
and we, as the programmer, don’t need to think about it. Without a 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 programming problem. If we forget,
we’ll waste memory. If we do it too early, we’ll 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 Listing 4-1 using a <code>String</code> instead of a string literal:</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
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’s 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: In C++, this pattern of deallocating resources at the end of an item's
lifetime is sometimes called <em>Resource Acquisition Is Initialization (RAII)</em>.
The <code>drop</code> function in Rust will be familiar to you if you’ve used RAII
patterns.</p>
</blockquote>
<p>This pattern has a profound impact on the way Rust code is written. It may seem
simple right now, but the behavior of code can be unexpected in more
complicated situations when we want to have multiple variables use the data
we’ve allocated on the heap. Let’s explore some of those situations now.</p>
<a class="header" href="#ways-variables-and-data-interact-move" name="ways-variables-and-data-interact-move"><h4>Ways Variables and Data Interact: Move</h4></a>
<p>Multiple variables can interact with the same data in different ways in Rust.
Let’s look at an example using an integer in Listing 4-2:</p>
<figure>
<pre><code class="language-rust">let x = 5;
let y = x;
</code></pre>
<figcaption>
<p>Listing 4-2: Assigning the integer value of variable <code>x</code> to <code>y</code></p>
</figcaption>
</figure>
<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 because 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 is, the second line would make a copy of the
value in <code>s1</code> and bind it to <code>s2</code>. But this isn’t quite what happens.</p>
<p>To explain this more thoroughly, let’s look at what <code>String</code> looks like under
the covers in Figure 4-3. 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 on the heap that holds the contents.</p>
<figure>
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-3: 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 received 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 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 pointer refers to. In other words, the data
representation in memory looks like Figure 4-4.</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-4: Representation in memory of the variable <code>s2</code> that has a copy of
the pointer, length, and capacity of <code>s1</code></p>
</figcaption>
</figure>
<p>The representation does <em>not</em> look like Figure 4-5, 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 in terms of runtime
performance 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-5: Another possibility of what <code>s2 = s1</code> might do if Rust copied the
heap data as well</p>
</figcaption>
</figure>
<p>Earlier, we said that when a variable goes out of scope, Rust automatically
calls the <code>drop</code> function and cleans up the heap memory for that variable. But
Figure 4-4 shows 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 previously. Freeing memory twice can lead to memory
corruption, which can potentially lead to security vulnerabilities.</p>
<p>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
considers <code>s1</code> to no longer be valid and therefore, Rust doesn’t need to free
anything when <code>s1</code> 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 because Rust prevents you from using the
invalidated reference:</p>
<pre><code class="language-text">error[E0382]: use of moved value: `s1`
--&gt; src/main.rs:4:27
|
3 | let s2 = s1;
| -- value moved here
4 | println!(&quot;{}, world!&quot;,s1);
| ^^ value used here after move
|
= note: move occurs because `s1` has type `std::string::String`,
which does not implement the `Copy` trait
</code></pre>
<p>If you’ve 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 is shown in Figure 4-6.</p>
<figure>
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
<figcaption>
<p>Figure 4-6: 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>In addition, 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 in terms of runtime performance.</p>
<a class="header" href="#ways-variables-and-data-interact-clone" name="ways-variables-and-data-interact-clone"><h4>Ways Variables and Data Interact: Clone</h4></a>
<p>If we <em>do</em> want to deeply copy the heap data of the <code>String</code>, not just the
stack data, we can use a common method called <code>clone</code>. We’ll discuss method
syntax in Chapter 5, but because methods are a common feature in many
programming languages, you’ve 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 works just fine and is how you can explicitly produce the behavior shown
in Figure 4-5, 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.</p>
<a class="header" href="#stack-only-data-copy" name="stack-only-data-copy"><h4>Stack-Only Data: Copy</h4></a>
<p>There’s another wrinkle we haven’t talked about yet. This code using integers,
part of which was shown earlier in Listing 4-2, 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>But this code 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>The reason is that 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 integers that are stored on the stack (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 won’t 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’ll 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 general rule, any group of simple scalar values can be
<code>Copy</code>, and nothing that requires allocation or is some form of resource is
<code>Copy</code>. Here are some of the types that are <code>Copy</code>:</p>
<ul>
<li>All 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 the floating point types, like <code>f64</code>.</li>
<li>Tuples, but only if they contain types that are also <code>Copy</code>. <code>(i32, i32)</code> is
<code>Copy</code>, but <code>(i32, String)</code> is not.</li>
</ul>
<a class="header" href="#ownership-and-functions" name="ownership-and-functions"><h3>Ownership and Functions</h3></a>
<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. Listing 4-7 has an example with some annotations showing where
variables go into and out of scope:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<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>
<figcaption>
<p>Listing 4-7: Functions with ownership and scope annotated</p>
</figcaption>
</figure>
<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>
<a class="header" href="#return-values-and-scope" name="return-values-and-scope"><h3>Return Values and Scope</h3></a>
<p>Returning values can also transfer ownership. Here’s an example with similar
annotations to those in Listing 4-7:</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 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>The ownership of variables follows 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 and 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’s 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, and it’s called
<em>references</em>.</p>
<a class="header" href="#references-and-borrowing" name="references-and-borrowing"><h2>References and Borrowing</h2></a>
<p>The issue with the tuple code at the end of the preceding section is that we
have to return the <code>String</code> to the calling function so we can still use the
<code>String</code> after the call to <code>calculate_length</code>, because 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 has a
<em>reference</em> to an object as a parameter instead of taking ownership of the
value:</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, notice that all the tuple code in the variable declaration and the
function return value is gone. Second, 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 ampersands are <em>references</em>, and they allow you to refer to some value
without taking ownership of it. Figure 4-8 shows a diagram.</p>
<figure>
<img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" />
<figcaption>
<p>Figure 4-8: <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 that <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 the type of
the parameter <code>s</code> is a reference. 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 because it does not have ownership of what
// it refers to, nothing happens.
</code></pre>
<p>The scope in which the variable <code>s</code> is valid is the same as any function
parameter's scope, but we don’t drop what the reference points to when it goes
out of scope because we don’t have ownership. Functions that have references as
parameters instead of the actual values mean we won’t need to return the values
in order to give back ownership, since we never had ownership.</p>
<p>We call having references as function parameters <em>borrowing</em>. As in real life,
if a person owns something, you can borrow it from them. 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 the code in
Listing 4-9. Spoiler alert: it doesn’t work!</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<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>
<figcaption>
<p>Listing 4-9: Attempting to modify a borrowed value</p>
</figcaption>
</figure>
<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>
<a class="header" href="#mutable-references" name="mutable-references"><h3>Mutable References</h3></a>
<p>We can fix the error in the code from Listing 4-9 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>But mutable references have one big restriction: 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’s
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 in which these three
behaviors 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 you’re trying to track them down at runtime; Rust prevents this problem
from happening because it won’t even compile code with data races!</p>
<p>As always, we can use curly brackets 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>A similar rule exists for combining mutable and immutable references. This code
results in an error:</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! However, multiple immutable references are okay because 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 early (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>
<a class="header" href="#dangling-references" name="dangling-references"><h3>Dangling References</h3></a>
<p>In languages with pointers, it’s easy to erroneously create a <em>dangling
pointer</em>, a pointer that references a location in memory that may have been
given to someone else, by freeing some memory while preserving a pointer to
that memory. In Rust, by contrast, the compiler guarantees that references will
never be dangling references: 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 covered yet: <em>lifetimes</em>.
We’ll discuss lifetimes in detail in Chapter 10. But, if you disregard 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 take 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 <code>dangle</code>, when the code of <code>dangle</code> is finished,
<code>s</code> 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 without any problems. Ownership is moved out, and nothing is
deallocated.</p>
<a class="header" href="#the-rules-of-references" name="the-rules-of-references"><h3>The Rules of References</h3></a>
<p>Let’s recap what we’ve discussed about references:</p>
<ol>
<li>At any given time, you can have <em>either</em> but not both of:</li>
</ol>
<ul>
<li>One mutable reference.</li>
<li>Any number of immutable references.</li>
</ul>
<ol start="2">
<li>References must always be valid.</li>
</ol>
<p>Next, we’ll look at a different kind of reference: slices.</p>
<a class="header" href="#slices" name="slices"><h2>Slices</h2></a>
<p>Another data type that does not have ownership is the <em>slice</em>. Slices let you
reference a contiguous sequence of elements in a collection rather than the
whole collection.</p>
<p>Here’s a small programming problem: write a function that takes a string and
returns the first word it finds in that string. If the function doesn’t find a
space in the string, it means the whole string is one word, so the entire
string 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>, has a <code>&amp;String</code> as a parameter. 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. However, we could return the index of the
end of the word. Let’s try that as shown in Listing 4-10:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<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>
<figcaption>
<p>Listing 4-10: The <code>first_word</code> function that returns a byte index value into
the <code>String</code> parameter</p>
</figcaption>
</figure>
<p>Let’s break down this code a bit. Because we need to go through the <code>String</code>
element by element and check whether a value is a space, we’ll convert our
<code>String</code> to an array of bytes using the <code>as_bytes</code> method:</p>
<pre><code class="language-rust,ignore">let bytes = s.as_bytes();
</code></pre>
<p>Next, we create an iterator over the array of bytes using the <code>iter</code> method :</p>
<pre><code class="language-rust,ignore">for (i, &amp;item) in bytes.iter().enumerate() {
</code></pre>
<p>We’ll discuss iterators in more detail in Chapter 16. 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. The
first element of the returned tuple is the index, and the second element is a
reference to the element. This is a bit more convenient than calculating the
index ourselves.</p>
<p>Because the <code>enumerate</code> method returns a tuple, we can use patterns to
destructure that tuple, just like everywhere else in Rust. So in the <code>for</code>
loop, we specify a pattern that has <code>i</code> for the index in the tuple and <code>&amp;item</code>
for the single byte in the tuple. Because we get a reference to the element
from <code>.iter().enumerate()</code>, we use <code>&amp;</code> in the pattern.</p>
<p>We search for the byte that represents the space by using the byte literal
syntax. If we find a space, we return the position. Otherwise, we return the
length of the string by using <code>s.len()</code>:</p>
<pre><code class="language-rust,ignore"> if item == b' ' {
return i;
}
}
s.len()
</code></pre>
<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 the program in Listing 4-11 that
uses the <code>first_word</code> function from Listing 4-10:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<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>
<figcaption>
<p>Listing 4-11: Storing the result from calling the <code>first_word</code> function then
changing the <code>String</code> contents</p>
</figcaption>
</figure>
<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
because the contents of <code>s</code> have changed since we saved <code>5</code> in <code>word</code>.</p>
<p>Having to worry about the index in <code>word</code> getting out of sync with the data in
<code>s</code> is tedious and error prone! Managing these indices is even more brittle if
we 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 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 that need
to be kept in sync.</p>
<p>Luckily, Rust has a solution to this problem: string slices.</p>
<a class="header" href="#string-slices" name="string-slices"><h3>String Slices</h3></a>
<p>A <em>string slice</em> 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-12 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-12: 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 two periods. 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 includes 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 all this information in mind, let’s rewrite <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 we did in Listing
4-10, 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, since the
compiler will ensure the references into the <code>String</code> remain valid. Remember
the bug in the program in Listing 4-11, when we got the index to the end of the
first word but then cleared the string so our index 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>Recall from the borrowing rules that if we have an immutable reference to
something, we cannot also take a mutable reference. Because <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 has also eliminated an entire
class of errors at compile time!</p>
<a class="header" href="#string-literals-are-slices" name="string-literals-are-slices"><h4>String Literals Are Slices</h4></a>
<p>Recall that we talked about string literals being stored inside the binary. Now
that we know about slices, we can 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>
<a class="header" href="#string-slices-as-parameters" name="string-slices-as-parameters"><h4>String Slices as Parameters</h4></a>
<p>Knowing that you can take slices of 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 the following line 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 directly. If we have a <code>String</code>, we
can pass a slice of the entire <code>String</code>. Defining a function to take a string
slice instead of a reference to a String 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>
<a class="header" href="#other-slices" name="other-slices"><h3>Other Slices</h3></a>
<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 might want to refer to a part of a string, we might 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 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 collections in
detail when we talk about vectors in Chapter 8.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<p>The concepts of ownership, borrowing, and slices are what ensure memory safety
in Rust programs at compile time. The Rust language 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’ll talk about
these concepts further throughout the rest of the book. Let’s move on to the
next chapter and look at grouping pieces of data together in a <code>struct</code>.</p>
<a class="header" href="#structs" name="structs"><h1>Structs</h1></a>
<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>
<a class="header" href="#ownership-of-struct-data" name="ownership-of-struct-data"><h2>Ownership of Struct Data</h2></a>
<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>
<a class="header" href="#an-example-program" name="an-example-program"><h2>An Example Program</h2></a>
<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>
<a class="header" href="#refactoring-with-tuples" name="refactoring-with-tuples"><h3>Refactoring with Tuples</h3></a>
<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 has two parameters. The parameters 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 when we call <code>area</code>. But in another way
this method is 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>
<a class="header" href="#refactoring-with-structs-adding-more-meaning" name="refactoring-with-structs-adding-more-meaning"><h3>Refactoring with Structs: Adding More Meaning</h3></a>
<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 is now defined with one parameter 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>. 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>
<a class="header" href="#adding-useful-functionality-with-derived-traits" name="adding-useful-functionality-with-derived-traits"><h3>Adding Useful Functionality with Derived Traits</h3></a>
<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>
<a class="header" href="#method-syntax" name="method-syntax"><h2>Method Syntax</h2></a>
<p><em>Methods</em> are similar to functions: they’re declared with the <code>fn</code> keyword and
their name, they can have parameters 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 parameter is always <code>self</code>, which
represents the instance of the struct that the method is being called on.</p>
<a class="header" href="#defining-methods" name="defining-methods"><h3>Defining Methods</h3></a>
<p>Let’s change our <code>area</code> function that has a <code>Rectangle</code> instance as a parameter
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) parameter 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 parameter.</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 parameter instead. Having a method that
takes ownership of the instance by having just <code>self</code> as the first parameter 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>
<a class="header" href="#wheres-the---operator" name="wheres-the---operator"><h3>Where’s the <code>-&gt;</code> operator?</h3></a>
<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 -->
<a class="header" href="#methods-with-more-parameters" name="methods-with-more-parameters"><h3>Methods with More Parameters</h3></a>
<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 a parameter. We can tell what the type of the
parameter 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 have multiple parameters that we add to the signature after the
<code>self</code> parameter, and those parameters work just like parameters in functions
do.</p>
<a class="header" href="#associated-functions" name="associated-functions"><h3>Associated Functions</h3></a>
<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 have one dimension parameter 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 = Rectangle::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>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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>
<a class="header" href="#enums-and-pattern-matching" name="enums-and-pattern-matching"><h1>Enums and Pattern Matching</h1></a>
<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. Next, we’ll explore a particularly useful enum, called <code>Option</code>, which
expresses that a value can be either something or nothing. Then we’ll look at
how pattern matching in the <code>match</code> expression 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 available to you to handle
enums in your code.</p>
<p>Enums are a feature in many languages, but their capabilities differ in each
language. Rust’s enums are most similar to <em>algebraic data types</em> in functional
languages like F#, OCaml, and Haskell.</p>
<a class="header" href="#defining-an-enum" name="defining-an-enum"><h2>Defining an Enum</h2></a>
<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. Currently, two major standards are used for IP addresses:
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 enumeration 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, because enum values can only be one of the
variants. Both version four and version six addresses are still fundamentally
IP addresses, 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><code>IpAddrKind</code> is now a custom data type that we can use elsewhere in our code.</p>
<a class="header" href="#enum-values" name="enum-values"><h3>Enum Values</h3></a>
<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 a 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>:</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>Using enums has even more advantages. Thinking more about our IP address type,
at the moment we don’t have a way to store the actual IP address <em>data</em>; we
only know what <em>kind</em> it is. Given that you just learned about structs in
Chapter 5, you might tackle this problem as shown 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 <code>IpAddrKind</code> variant of an IP address using a
<code>struct</code></p>
</figcaption>
</figure>
<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
now the variant is associated with the value.</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, so there is no need for an
extra struct.</p>
<p>There’s another advantage to using an enum rather than a struct: each variant
can have different types and amounts of associated 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> values but
still express <code>V6</code> addresses as one <code>String</code> value, we wouldn’t be able to with
a struct. 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 shown several different possibilities that we could define in our code
for storing IP addresses of the two different varieties using an enum. However,
as it turns out, 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 library defines
<code>IpAddr</code>: it has the exact enum and variants that we’ve defined and used, but
it embeds 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 code illustrates that you can put any kind of data inside an enum variant:
strings, numeric types, or structs, for example. You can 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 create and use our own definition without conflict because 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 of an enum in Listing 6-2: this one has a wide
variety of types embedded in its variants:</p>
<figure>
<pre><code class="language-rust">enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
</code></pre>
<figcaption>
<p>Listing 6-2: A <code>Message</code> enum whose variants each store different amounts and
types of values</p>
</figcaption>
</figure>
<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 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>Defining an enum with variants like the ones in Listing 6-2 is similar to
defining different kinds of struct definitions except the enum doesn’t use the
<code>struct</code> keyword and all the variants are grouped together under the <code>Message</code>
type. The following structs could hold the same data that the preceding enum
variants 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, which each have their own type, 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 in Listing 6-2,
which is a single type.</p>
<p>There is one more similarity between enums and structs: just as we’re able to
define methods on structs using <code>impl</code>, we’re also able to define methods on
enums. Here’s a method named <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) {
// method body would be defined here
}
}
let m = Message::Write(String::from(&quot;hello&quot;));
m.call();
</code></pre>
<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>
<a class="header" href="#the-option-enum-and-its-advantages-over-null-values" name="the-option-enum-and-its-advantages-over-null-values"><h3>The <code>Option</code> Enum and Its Advantages Over Null Values</h3></a>
<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 explores 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 something or it
could be nothing. 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 exclude are important too. Rust doesn’t have the
null feature that many other languages have. <em>Null</em> 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>In “Null References: The Billion Dollar Mistake,” Tony Hoare, 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>
</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>However, the concept that null is trying to express is still a useful one: a
null is a value that is currently invalid or absent for some reason.</p>
<p>The problem isn’t with the actual concept 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. In addition, so are its variants: you can
use <code>Some</code> and <code>None</code> directly without prefixing them with <code>Option::</code>.
<code>Option&lt;T&gt;</code> is still just a regular enum, and <code>Some(T)</code> and <code>None</code> are still
variants of type <code>Option&lt;T&gt;</code>.</p>
<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 <code>&lt;T&gt;</code> 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, because the compiler can't infer the type that the <code>Some</code>
variant will hold by looking only at a <code>None</code> value.</p>
<p>When we have a <code>Some</code> value, we know that a value is present, and the value is
held within the <code>Some</code>. When we have a <code>None</code> value, in some sense, it means
the same thing as null: we don’t have a valid value. So why is having
<code>Option&lt;T&gt;</code> any better than having 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, the compiler won’t let us use an <code>Option&lt;T&gt;</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! In effect, this error message means that Rust doesn’t understand how
to add an <code>Option&lt;i8&gt;</code> and an <code>i8</code>, because 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
perform <code>T</code> operations with it. Generally, this helps catch one of the most
common issues with null: assuming that something isn’t null when it actually
is.</p>
<p>Not having to worry about missing an assumption of having a not-null value
helps you to be more confident in your code. In order to have a value that can
possibly be null, you must 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>
<p>So, how do 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 you can use that value? The <code>Option&lt;T&gt;</code> enum has a large
number of methods that are useful in a variety of situations; you can check
them out in <a href="../std/option/enum.Option.html">its documentation</a><!-- ignore -->. Becoming familiar with
the methods on <code>Option&lt;T&gt;</code> will be extremely useful in your journey with Rust.</p>
<p>In general, in order to use an <code>Option&lt;T&gt;</code> value, we want to have code that
will handle each variant. We want some code that will run only when we have a
<code>Some(T)</code> value, and this code is allowed to use the inner <code>T</code>. We want some
other 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>
<a class="header" href="#the-match-control-flow-operator" name="the-match-control-flow-operator"><h2>The <code>match</code> Control Flow Operator</h2></a>
<p>Rust has an extremely powerful control-flow operator called <code>match</code> that allows
us to compare a value against a series of patterns and then execute code based
on which pattern matches. Patterns can be made up of literal values, variable
names, wildcards, and many other things; Chapter 18 will be about all the
different kinds of patterns and what they do. The power of <code>match</code> 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 “fits,”
the value will fall into the associated code block to be used during execution.</p>
<p>Because we just mentioned coins, let’s use them as an example using <code>match</code>! We
can write a function that can take an unknown United States coin and, in a
similar way as the counting machine, determine which coin it is and return its
value in cents, as shown here in Listing 6-3:</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-3: An enum and a <code>match</code> expression that has the variants of the enum
as its patterns.</p>
</figcaption>
</figure>
<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 seems 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 defined in Listing 6-3.</p>
<p>Next are the <code>match</code> arms. 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> and 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: in Listing 6-3, our <code>match</code> 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
Listing 6-3 where each arm just returns a value. If you want to run multiple
lines of code in a match arm, you can use curly braces. For example, the
following code would print out “Lucky penny!” 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>
<a class="header" href="#patterns-that-bind-to-values" name="patterns-that-bind-to-values"><h3>Patterns that Bind to Values</h3></a>
<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 United States 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, which we've done here in Listing 6-4:</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-4: 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’ll also call out the name of
the state associated with each quarter so if it’s one our friend doesn’t have,
they can add it to their collection.</p>
<p>In the match expression for this code, we add a variable called <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>
<a class="header" href="#matching-with-optiont" name="matching-with-optiont"><h3>Matching with <code>Option&lt;T&gt;</code></h3></a>
<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 also handle <code>Option&lt;T&gt;</code> using <code>match</code> as we
did with the <code>Coin</code> enum! Instead of comparing coins, we’ll compare 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-5:</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-5: A function that uses a <code>match</code> expression on an <code>Option&lt;i32&gt;</code></p>
</figcaption>
</figure>
<a class="header" href="#matching-somet" name="matching-somet"><h4>Matching <code>Some(T)</code></h4></a>
<p>Let’s examine the first execution of <code>plus_one</code> in more detail. 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 then 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 to the
next arm.</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>
<a class="header" href="#matching-none" name="matching-none"><h4>Matching <code>None</code></h4></a>
<p>Now let’s consider the second call of <code>plus_one</code> in Listing 6-5 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>. Because the first arm matched, no other
arms are compared.</p>
<p>Combining <code>match</code> and enums is useful in many situations. You’ll see this
pattern a lot in Rust code: <code>match</code> against an enum, bind a variable to the
data inside, and 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>
<a class="header" href="#matches-are-exhaustive" name="matches-are-exhaustive"><h3>Matches Are Exhaustive</h3></a>
<p>There’s one other aspect of <code>match</code> we need to discuss. 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 code 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 didn’t cover every possible case and even knows which
pattern we forgot! Matches in Rust are <em>exhaustive</em>: we must exhaust every last
possibility in order for the code 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, thus making the billion dollar mistake discussed earlier.</p>
<a class="header" href="#the-_-placeholder" name="the-_-placeholder"><h3>The <code>_</code> Placeholder</h3></a>
<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 0 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. Fortunately, 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. As a result, we
can say that we want to do nothing for all the possible values that we don’t
list before the <code>_</code> placeholder.</p>
<p>However, the <code>match</code> expression can be a bit wordy in a situation in which we
only care about <em>one</em> of the cases. For this situation, Rust provides <code>if let</code>.</p>
<a class="header" href="#concise-control-flow-with-if-let" name="concise-control-flow-with-if-let"><h2>Concise Control Flow with <code>if let</code></h2></a>
<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 ignore the rest. Consider the program
in Listing 6-6 that matches on an <code>Option&lt;u8&gt;</code> value but only wants to execute
code if the value is three:</p>
<figure>
<pre><code class="language-rust">let some_u8_value = Some(0u8);
match some_u8_value {
Some(3) =&gt; println!(&quot;three&quot;),
_ =&gt; (),
}
</code></pre>
<figcaption>
<p>Listing 6-6: A <code>match</code> that only cares about executing code when the value is
<code>Some(3)</code></p>
</figcaption>
</figure>
<p>We want to do something with the <code>Some(3)</code> match but do nothing with any other
<code>Some&lt;u8&gt;</code> value or the <code>None</code> value. To satisfy the <code>match</code> expression, we
have to add <code>_ =&gt; ()</code> after processing just one variant, which is a lot of
boilerplate code to add.</p>
<p>Instead, we could write this in a shorter way using <code>if let</code>. The following
code behaves the same as the <code>match</code> in Listing 6-6:</p>
<pre><code class="language-rust"># let some_u8_value = Some(0u8);
if let Some(3) = some_u8_value {
println!(&quot;three&quot;);
}
</code></pre>
<p><code>if let</code> takes a pattern and an expression separated by an <code>=</code>. It works the
same way as 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 code. However, we’ve lost the exhaustive 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 situation and if gaining conciseness is an appropriate
trade-off for losing exhaustive 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> 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-4, 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 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 have a situation in which your program has logic that is too verbose to
express using a <code>match</code>, remember that <code>if let</code> is in your Rust toolbox as well.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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 modules.</p>
<a class="header" href="#modules" name="modules"><h1>Modules</h1></a>
<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 you find yourself with too many functions? Rust has a
module system that handles the problem of wanting 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 (including modules). You can use the
<code>pub</code> keyword to make a module public and therefore visible outside of its
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>
<a class="header" href="#mod-and-the-filesystem" name="mod-and-the-filesystem"><h2><code>mod</code> and the Filesystem</h2></a>
<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>
<a class="header" href="#module-definitions" name="module-definitions"><h3>Module Definitions</h3></a>
<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>src/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 it as shown in Listing 7-1:</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>src/lib.rs</em>. We could also make use of submodules in <em>src/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 in Listing
7-2:</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>
<a class="header" href="#moving-modules-to-other-files" name="moving-modules-to-other-files"><h3>Moving Modules to Other Files</h3></a>
<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 the code in Listing 7-3:</p>
<figure>
<span class="filename">Filename: 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 those functions were getting long, it
would be difficult to scroll through this file to find the code we wanted to
work with. Because the functions are nested inside one or more mod blocks, the
lines of code inside the functions will start getting long as well. These would
be good reasons 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.</p>
<p>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">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">mod client;
mod network {
fn connect() {
}
mod server {
fn connect() {
}
}
}
</code></pre>
<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">Filename: 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 the error shown in Listing 7-4:</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>
<pre><code class="language-text">note: maybe move this module `network` to its own directory via `network/mod.rs`
</code></pre>
<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
put the code for <code>network::server</code> in the <em>network</em> directory in
<em>src/network/server.rs</em>, instead of just being able to extract the
<code>network::server</code> module 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 with the following module
hierarchy, where all the definitions are 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>
<a class="header" href="#rules-of-module-file-systems" name="rules-of-module-file-systems"><h3>Rules of Module File Systems</h3></a>
<p>In summary, these are the rules of modules with regards to files:</p>
<ul>
<li>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>.</li>
<li>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>.</li>
</ul>
<p>These 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>
<p>The modules themselves should be declared in their parent module’s file using
the <code>mod</code> keyword.</p>
<p>Next, we’ll talk about the <code>pub</code> keyword, and get rid of those warnings!</p>
<a class="header" href="#controlling-visibility-with-pub" name="controlling-visibility-with-pub"><h2>Controlling Visibility with <code>pub</code></h2></a>
<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. To do
that, we’ll create 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>From the point of view of a crate outside of the <code>communicator</code> library looking
in, all of the modules we've been creating are within a module that has the
same name as the crate, <code>communicator</code>. We call the top-level module of a crate
the <em>root module</em>.</p>
<p>Also note that even if we're using an external crate within a submodule of our
project, the <code>extern crate</code> should go in our root module (so in <em>src/main.rs</em>
or <em>src/lib.rs</em>). Then, in our submodules, we can refer to items from external
crates as if the items are top-level modules.</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>
<a class="header" href="#making-a-function-public" name="making-a-function-public"><h3>Making a Function Public</h3></a>
<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 <em>src/client.rs</em> 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
<em>src/lib.rs</em> 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>
<a class="header" href="#privacy-rules" name="privacy-rules"><h3>Privacy Rules</h3></a>
<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>
<a class="header" href="#privacy-examples" name="privacy-examples"><h3>Privacy Examples</h3></a>
<p>Let’s look at a few more examples to get some practice. Create a new library
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>
<a class="header" href="#looking-at-the-errors" name="looking-at-the-errors"><h4>Looking at the Errors</h4></a>
<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>
<a class="header" href="#fixing-the-errors" name="fixing-the-errors"><h4>Fixing the Errors</h4></a>
<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 modules starting from the root module.)</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>
<a class="header" href="#importing-names" name="importing-names"><h2>Importing Names</h2></a>
<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>nested_modules</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 nested_modules() {}
}
}
}
fn main() {
a::series::of::nested_modules();
}
</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>
<a class="header" href="#concise-imports-with-use" name="concise-imports-with-use"><h3>Concise Imports with <code>use</code></h3></a>
<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> module 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 nested_modules() {}
}
}
}
use a::series::of;
fn main() {
of::nested_modules();
}
</code></pre>
<p>The line <code>use a::series::of;</code> means that rather than using the full
<code>a::series::of</code> path wherever we want to refer to the <code>of</code> module, we can use
<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::nested_modules</code> when we want to call the <code>nested_modules</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 nested_modules() {}
}
}
}
use a::series::of::nested_modules;
fn main() {
nested_modules();
}
</code></pre>
<p>This allows us to exclude all of the modules and reference the function
directly.</p>
<p>Since enums also form a sort of namespace like modules, 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>
<a class="header" href="#glob-imports-with-" name="glob-imports-with-"><h3>Glob Imports with <code>*</code></h3></a>
<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>
<a class="header" href="#using-super-to-access-a-parent-module" name="using-super-to-access-a-parent-module"><h3>Using <code>super</code> to Access a Parent Module</h3></a>
<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 <em>src/main.rs</em> 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>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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>
<a class="header" href="#common-collections" name="common-collections"><h1>Common Collections</h1></a>
<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. It's a
particular implementation of the more general data structure called a <em>map</em>.</li>
</ul>
<p>To learn about the other kinds of collections provided by the standard library,
see <a href="../std/collections">the documentation</a>.</p>
<p>We’re going to discuss how to create and update vectors, strings, and hash
maps, as well as what makes each special.</p>
<a class="header" href="#vectors" name="vectors"><h2>Vectors</h2></a>
<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>
<a class="header" href="#creating-a-new-vector" name="creating-a-new-vector"><h3>Creating a New Vector</h3></a>
<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 homogeneous: 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>
<a class="header" href="#updating-a-vector" name="updating-a-vector"><h3>Updating a Vector</h3></a>
<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 of type <code>i32</code>, and Rust infers this from the
data, so we don’t need the <code>Vec&lt;i32&gt;</code> annotation.</p>
<a class="header" href="#dropping-a-vector-drops-its-elements" name="dropping-a-vector-drops-its-elements"><h3>Dropping a Vector Drops its Elements</h3></a>
<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>
<a class="header" href="#reading-elements-of-vectors" name="reading-elements-of-vectors"><h3>Reading Elements of Vectors</h3></a>
<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>, 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 panicking. 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>
<a class="header" href="#invalid-references" name="invalid-references"><h4>Invalid References</h4></a>
<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 The Nomicon at
<em>https://doc.rust-lang.org/stable/nomicon/vec.html</em>.</p>
</blockquote>
<a class="header" href="#using-an-enum-to-store-multiple-types" name="using-an-enum-to-store-multiple-types"><h3>Using an Enum to Store Multiple Types</h3></a>
<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, so when we need
to store elements of a different type in a vector, 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>
<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. Instead, you can use a trait object, which we’ll cover in
Chapter 17.</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>
<a class="header" href="#strings" name="strings"><h2>Strings</h2></a>
<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>
<a class="header" href="#what-is-a-string" name="what-is-a-string"><h3>What is a String?</h3></a>
<p>Before we can dig into those aspects, we need to talk about what exactly we
mean by the term <em>string</em>. 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>
<a class="header" href="#creating-a-new-string" name="creating-a-new-string"><h3>Creating a New String</h3></a>
<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>
<a class="header" href="#updating-a-string" name="updating-a-string"><h3>Updating a String</h3></a>
<p>A <code>String</code> 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>
<a class="header" href="#appending-to-a-string-with-push" name="appending-to-a-string-with-push"><h4>Appending to a String with Push</h4></a>
<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 “foobar” 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
parameter. 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 have a single character as a parameter 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 “lol”.</p>
<a class="header" href="#concatenation-with-the--operator-or-the-format-macro" name="concatenation-with-the--operator-or-the-format-macro"><h4>Concatenation with the + Operator or the <code>format!</code> Macro</h4></a>
<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. We'll be discussing generics in Chapter</p>
<ol start="10">
<li>This signature gives us the clues we need to understand the tricky bits of
the <code>+</code> operator.</li>
</ol>
<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> parameter 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> values 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 parameter, <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 the contents
of <code>s2</code>, 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 “tic-tac-toe” 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>
<p>This code will also set <code>s</code> to “tic-tac-toe”. 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 parameters.</p>
<a class="header" href="#indexing-into-strings" name="indexing-into-strings"><h3>Indexing into Strings</h3></a>
<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>
<a class="header" href="#internal-representation" name="internal-representation"><h4>Internal Representation</h4></a>
<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 = String::from(&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
“Hola” 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 = String::from(&quot;Здравствуйте&quot;).len();
</code></pre>
<p>A person asked how long the string is might say 12. However, Rust’s answer is</p>
<ol start="24">
<li>This is the number of bytes that it takes to encode “Здравствуйте” in
UTF-8, since each Unicode scalar value takes two bytes of storage. Therefore,
an index into the string’s bytes will not always correlate to a valid Unicode
scalar value.</li>
</ol>
<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>
<a class="header" href="#bytes-and-scalar-values-and-grapheme-clusters-oh-my" name="bytes-and-scalar-values-and-grapheme-clusters-oh-my"><h4>Bytes and Scalar Values and Grapheme Clusters! Oh my!</h4></a>
<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 <em>letters</em>).</p>
<p>If we look at the Hindi word “नमस्ते” 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>
<a class="header" href="#slicing-strings" name="slicing-strings"><h3>Slicing Strings</h3></a>
<p>Because it's not clear what the return type of string indexing should be, and
it is often a bad idea to index into a string, Rust dissuades you from doing so
by asking you to be more specific if you really need it. The way you can be
more specific than indexing using <code>[]</code> with a single number is using <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 “Зд”.</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>
<a class="header" href="#methods-for-iterating-over-strings" name="methods-for-iterating-over-strings"><h3>Methods for Iterating Over Strings</h3></a>
<p>Luckily, there are other ways we can access elements in a String.</p>
<p>If we need to perform operations on individual Unicode scalar values, the best
way to do so is to use the <code>chars</code> method. Calling <code>chars</code> on “नमस्ते”
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 Unicode scalar values may be made up of
more than one byte.</p>
<p>Getting grapheme clusters from strings 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>
<a class="header" href="#strings-are-not-so-simple" name="strings-are-not-so-simple"><h3>Strings are Not so Simple</h3></a>
<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>
<a class="header" href="#hash-maps" name="hash-maps"><h2>Hash Maps</h2></a>
<p>The last of our common 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>
<a class="header" href="#creating-a-new-hash-map" name="creating-a-new-hash-map"><h3>Creating a New Hash Map</h3></a>
<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 common 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>String</code> and values of type <code>i32</code>. Like vectors, hash maps are
homogeneous: 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 “Blue” 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>
<a class="header" href="#hash-maps-and-ownership" name="hash-maps-and-ownership"><h3>Hash Maps and Ownership</h3></a>
<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>
<a class="header" href="#accessing-values-in-a-hash-map" name="accessing-values-in-a-hash-map"><h3>Accessing Values in a Hash Map</h3></a>
<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>
<a class="header" href="#updating-a-hash-map" name="updating-a-hash-map"><h3>Updating a Hash Map</h3></a>
<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>
<a class="header" href="#overwriting-a-value" name="overwriting-a-value"><h4>Overwriting a Value</h4></a>
<p>If we insert a key and a value into a hash map, 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 10 has been overwritten.</p>
<a class="header" href="#only-insert-if-the-key-has-no-value" name="only-insert-if-the-key-has-no-value"><h4>Only Insert If the Key Has No Value</h4></a>
<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 corresponding
<code>Entry</code> key if it exists, and if not, inserts its argument as the new value for
this key and returns the modified <code>Entry</code>. 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>
<a class="header" href="#update-a-value-based-on-the-old-value" name="update-a-value-based-on-the-old-value"><h4>Update a Value Based on the Old Value</h4></a>
<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>
<a class="header" href="#hashing-function" name="hashing-function"><h3>Hashing Function</h3></a>
<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. You don't necessarily have to implement your own
hasher from scratch; crates.io has libraries that others have shared that
provide hashers implementing many common hashing algorithms.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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>
<ul>
<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 “ay”, so “first” becomes “irst-fay”.
Words that start with a vowel get “hay” added to the end instead (“apple”
becomes “apple-hay”). 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, “Add Sally to
Engineering” or “Add Amir to Sales”. Then let the user retrieve a list of all
people in a department or all people in the company by department, sorted
alphabetically.</li>
</ul>
<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>
<a class="header" href="#error-handling" name="error-handling"><h1>Error Handling</h1></a>
<p>Rust’s commitment to reliability extends to error handling. Errors are a fact
of life in software, so Rust has a number of features for handling situations
in which something goes wrong. In many cases, Rust will require you to
acknowledge the possibility of an error occurring and take some action before
your code will compile. This makes your program more robust by ensuring that
you won’t only discover errors after you’ve deployed your code to production.</p>
<p>Rust groups errors into two major categories: <em>recoverable</em> and <em>unrecoverable</em>
errors. Recoverable errors are situations when it’s usually reasonable to
report the problem to the user and retry the operation, like a file not being
found. Unrecoverable errors are always symptoms of bugs, like trying to access
a location beyond the end of an array.</p>
<p>Most languages don’t distinguish between the two kinds of errors, and handle
both 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> for recoverable errors and
the <code>panic!</code> macro that stops execution when it encounters unrecoverable
errors. This chapter will cover calling <code>panic!</code> first, then talk about
returning <code>Result&lt;T, E&gt;</code> values. Finally, we’ll discuss considerations to take
into account when deciding whether to try to recover from an error or to stop
execution.</p>
<a class="header" href="#unrecoverable-errors-with-panic" name="unrecoverable-errors-with-panic"><h2>Unrecoverable Errors with <code>panic!</code></h2></a>
<p>Sometimes, bad things happen, and there’s nothing that you can do about it. For
these cases, Rust has the <code>panic!</code> macro. When this macro executes, your
program will print a failure message, unwind and clean up the stack, and then
quit. The most common situation this occurs in is when a bug of some kind has
been detected and it’s not clear to the programmer how to handle the error.</p>
<blockquote>
<a class="header" href="#unwinding-the-stack-versus-aborting-on-panic" name="unwinding-the-stack-versus-aborting-on-panic"><h3>Unwinding the Stack Versus Aborting on Panic</h3></a>
<p>By default, when a <code>panic!</code> occurs, the program starts
<em>unwinding</em>, which means Rust walks back up the stack and cleans up the data
from each function it encounters, but this walking and cleanup is a lot of
work. The alternative is to immediately <em>abort</em>, which ends the program
without cleaning up. Memory that the program was using will then need to be
cleaned up by the operating system. If in your project you need to make the
resulting binary as small as possible, you can switch from unwinding to
aborting on panic by adding <code>panic = 'abort'</code> to the appropriate <code>[profile]</code>
sections in your <em>Cargo.toml</em>. For example, if you want to abort on panic in
release mode:</p>
<pre><code class="language-toml">[profile.release]
panic = 'abort'
</code></pre>
</blockquote>
<p>Let’s try 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>The last three lines contain the error message caused by the call to <code>panic!</code>.
The first line shows our panic message and the place in our source code where
the panic occurred: <em>src/main.rs:2</em> indicates that it’s the second line of our
<em>src/main.rs</em> file.</p>
<p>In this case, the line indicated is part of our code, and if we go to that line
we see the <code>panic!</code> macro call. In other cases, the <code>panic!</code> call might be in
code that our code calls. The filename and line number reported by the error
message will be someone else’s code where the <code>panic!</code> macro is called, not the
line of our code that eventually led to the <code>panic!</code>. We can use the backtrace
of the functions the <code>panic!</code> call came from to figure this out.</p>
<a class="header" href="#using-a-panic-backtrace" name="using-a-panic-backtrace"><h3>Using a <code>panic!</code> Backtrace</h3></a>
<p>Let’s look at another example to see what it’s like when a <code>panic!</code> call comes
from a library because of a bug in our code instead of from our code calling
the macro 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, but if you pass an invalid index, 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. 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', /stable-dist-rustc/build/src/libcollections/vec.rs:1362
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>libcollections/vec.rs</em>. That’s the
implementation of <code>Vec&lt;T&gt;</code> in the standard library. The code that gets run when
we use <code>[]</code> on our vector <code>v</code> is in <em>libcollections/vec.rs</em>, and that is where
the <code>panic!</code> is actually happening.</p>
<p>The next note line tells us that we can set the <code>RUST_BACKTRACE</code> environment
variable to get a backtrace of exactly what happened to cause the error. 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', /stable-dist-rustc/build/src/libcollections/vec.rs:1395
stack backtrace:
1: 0x10922522c -
std::sys::imp::backtrace::tracing::imp::write::h1204ab053b688140
2: 0x10922649e -
std::panicking::default_hook::{{closure}}::h1204ab053b688140
3: 0x109226140 - std::panicking::default_hook::h1204ab053b688140
4: 0x109226897 -
std::panicking::rust_panic_with_hook::h1204ab053b688140
5: 0x1092266f4 - std::panicking::begin_panic::h1204ab053b688140
6: 0x109226662 - std::panicking::begin_panic_fmt::h1204ab053b688140
7: 0x1092265c7 - rust_begin_unwind
8: 0x1092486f0 - core::panicking::panic_fmt::h1204ab053b688140
9: 0x109248668 -
core::panicking::panic_bounds_check::h1204ab053b688140
10: 0x1092205b5 - &lt;collections::vec::Vec&lt;T&gt; as
core::ops::Index&lt;usize&gt;&gt;::index::h1204ab053b688140
11: 0x10922066a - panic::main::h1204ab053b688140
12: 0x1092282ba - __rust_maybe_catch_panic
13: 0x109226b16 - std::rt::lang_start::h1204ab053b688140
14: 0x1092206e9 - main
</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. A backtrace is a list of
all the functions that have been called to get to this point. Backtraces in
Rust work like they do in other languages: the key to reading the backtrace is
to start from the top and read until you see files you wrote. That’s the spot
where the problem originated. The lines above the lines mentioning your files
are code that your code called; the lines below are code that called your code.
These lines might include core Rust code, standard library code, or crates that
you’re using.</p>
<p>If we don’t want our program to panic, the location pointed to by the first
line mentioning a file we wrote is where we should start investigating in order
to figure out how we got to this location with values that caused the panic. In
our example where we deliberately wrote code that would panic in order to
demonstrate how to use backtraces, the way to fix the panic is to not try to
request an element at index 100 from a vector that only contains three items.
When your code panics in the future, you’ll need to figure out for your
particular case what action the code is taking with what values that causes the
panic and what the code should do instead.</p>
<p>We’ll come back to <code>panic!</code> and when we should and should not use these methods
later in the chapter. Next, we’ll now look at how to recover from an error with
<code>Result</code>.</p>
<a class="header" href="#recoverable-errors-with-result" name="recoverable-errors-with-result"><h2>Recoverable Errors with <code>Result</code></h2></a>
<p>Most errors aren’t serious enough to require the program to stop entirely.
Sometimes, when a function fails, it’s for a reason that we can easily
interpret and respond to. For example, if we try to open a file and that
operation fails because the file doesn’t exist, we might want to create the
file instead of terminating the process.</p>
<p>Recall from Chapter 2 the section on “<a href="ch02-00-guessing-game-tutorial.md#handling-potential-failure-with-the-result-type">Handling Potential Failure with the
<code>Result</code> Type</a><!-- ignore -->” that the <code>Result</code> enum is defined
as having two variants, <code>Ok</code> and <code>Err</code>, as follows:</p>
<pre><code class="language-rust">enum Result&lt;T, E&gt; {
Ok(T),
Err(E),
}
</code></pre>
<p>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 right now is that <code>T</code> represents
the type of the value that will be returned in a success case within the <code>Ok</code>
variant, and <code>E</code> represents the type of the error that will be returned in a
failure case within the <code>Err</code> variant. Because <code>Result</code> has these generic type
parameters, we can use the <code>Result</code> type and the functions that the standard
library has defined on it in many different situations where the successful
value and error value we want to return may differ.</p>
<p>Let’s call a function that returns a <code>Result</code> value because the function could
fail: opening a file, shown in Listing 9-2.</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>How do we know <code>File::open</code> returns a <code>Result</code>? We could look at the standard
library API documentation, or we could ask the compiler! If we give <code>f</code> a type
annotation of some type that we know the return type of the function is <em>not</em>,
then we try to compile the code, the compiler will tell us that the types don’t
match. The error message will then tell us what the type of <code>f</code> <em>is</em>! Let’s try
it: we know that the return type of <code>File::open</code> isn’t of type <code>u32</code>, so let’s
change the <code>let f</code> statement to:</p>
<pre><code class="language-rust,ignore">let f: u32 = File::open(&quot;hello.txt&quot;);
</code></pre>
<p>Attempting to compile now gives us:</p>
<pre><code class="language-text">error[E0308]: mismatched types
--&gt; src/main.rs:4:18
|
4 | let f: u32 = File::open(&quot;hello.txt&quot;);
| ^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum
`std::result::Result`
|
= note: expected type `u32`
= note: found type `std::result::Result&lt;std::fs::File, std::io::Error&gt;`
</code></pre>
<p>This tells us the return type of the <code>File::open</code> function is a <code>Result&lt;T, E&gt;</code>.
The generic parameter <code>T</code> has been filled in here with the type of the success
value, <code>std::fs::File</code>, which is a file handle. The type of <code>E</code> used in the
error value is <code>std::io::Error</code>.</p>
<p>This return type means the call to <code>File::open</code> might succeed and return to us
a file handle that we can read from or write to. The function call also might
fail: for example, the file might not exist, or we might not have permission to
access the file. The <code>File::open</code> function needs to have a way to tell us
whether it succeeded or failed, and at the same time give us either the file
handle or error information. This information is exactly what the <code>Result</code> enum
conveys.</p>
<p>In the case where <code>File::open</code> succeeds, the value we will have in the variable
<code>f</code> will be an instance of <code>Ok</code> that contains a file handle. In the case where
it fails, the value in <code>f</code> will be an instance of <code>Err</code> that contains more
information about the kind of error that happened.</p>
<p>We need to add to the code from Listing 9-2 to take different actions depending
on the value <code>File::open</code> returned. 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>
<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>Note that, like the <code>Option</code> enum, the <code>Result</code> enum and its variants have been
imported in the prelude, so we don’t need to specify <code>Result::</code> before the <code>Ok</code>
and <code>Err</code> variants in the <code>match</code> arms.</p>
<p>Here we tell Rust that when the result is <code>Ok</code>, return the inner <code>file</code> value
out of the <code>Ok</code> variant, and we then assign that file handle value to the
variable <code>f</code>. After the <code>match</code>, we can then use the file handle for reading or
writing.</p>
<p>The other arm of the <code>match</code> handles the case where we get an <code>Err</code> value from
<code>File::open</code>. In this example, we’ve chosen to call the <code>panic!</code> macro. If
there’s no file named <em>hello.txt</em> in our current directory and we run this
code, we’ll see the following output from the <code>panic!</code> macro:</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>
<a class="header" href="#matching-on-different-errors" name="matching-on-different-errors"><h3>Matching on Different Errors</h3></a>
<p>The code in Listing 9-3 will <code>panic!</code> no matter the reason that <code>File::open</code>
failed. What we’d really like to do instead is take different actions for
different failure reasons: if <code>File::open</code> failed because the file doesn’t
exist, we want to create the file and return the handle to the new file. If
<code>File::open</code> failed for any other reason, for example because we didn’t have
permission to open the file, we still want to <code>panic!</code> in the same way as we
did in Listing 9-3. Let’s look at Listing 9-4, which adds another arm to the
<code>match</code>:</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>
<p>The type of the value that <code>File::open</code> returns inside the <code>Err</code> variant is
<code>io::Error</code>, which is a struct provided by the standard library. This struct
has a method <code>kind</code> that we can call to get an <code>io::ErrorKind</code> value.
<code>io::ErrorKind</code> is an enum provided by the standard library that has variants
representing the different kinds of errors that might result from an <code>io</code>
operation. The variant we’re interested in is <code>ErrorKind::NotFound</code>, which
indicates the file we’re trying to open doesn’t exist yet.</p>
<p>The condition <code>if error.kind() == ErrorKind::NotFound</code> is called a <em>match
guard</em>: it’s an extra condition on a <code>match</code> arm that further refines the arm’s
pattern. This condition must be true in order for that arm’s code to get run;
otherwise, the pattern matching will move on to consider the next arm in the
<code>match</code>. The <code>ref</code> in the pattern is needed so that <code>error</code> is not moved into
the guard condition but is merely referenced by it. The reason <code>ref</code> is used to
take a reference in a pattern instead of <code>&amp;</code> will be covered in detail in
Chapter 18. In short, in the context of a pattern, <code>&amp;</code> matches a reference and
gives us its value, but <code>ref</code> matches a value and gives us a reference to it.</p>
<p>The condition we want to check in the match guard is whether the value returned
by <code>error.kind()</code> is the <code>NotFound</code> variant of the <code>ErrorKind</code> enum. If it is,
we try to create the file with <code>File::create</code>. However, since <code>File::create</code>
could also fail, we need to add an inner <code>match</code> statement as well! When the
file can’t be opened, a different error message will be printed. The last arm
of the outer <code>match</code> stays the same so that the program panics on any error
besides the missing file error.</p>
<a class="header" href="#shortcuts-for-panic-on-error-unwrap-and-expect" name="shortcuts-for-panic-on-error-unwrap-and-expect"><h3>Shortcuts for Panic on Error: <code>unwrap</code> and <code>expect</code></h3></a>
<p>Using <code>match</code> works well enough, but it can be a bit verbose and 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. One of those methods, called <code>unwrap</code>, is a
shortcut method that is implemented just like the <code>match</code> statement we wrote in
Listing 9-3. If the <code>Result</code> value is the <code>Ok</code> variant, <code>unwrap</code> will return
the value inside the <code>Ok</code>. If the <code>Result</code> is the <code>Err</code> variant, <code>unwrap</code> will
call the <code>panic!</code> macro for us.</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>If we run this code without a <em>hello.txt</em> file, we’ll see an error message from
the <code>panic!</code> call that the <code>unwrap</code> method makes:</p>
<pre><code class="language-text">thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error {
repr: Os { code: 2, message: &quot;No such file or directory&quot; } }',
/stable-dist-rustc/build/src/libcore/result.rs:868
</code></pre>
<p>There’s another method similar to <code>unwrap</code> that lets us also choose the
<code>panic!</code> 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. The syntax of <code>expect</code> looks like this:</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>We use <code>expect</code> in the same way as <code>unwrap</code>: to return the file handle or call
the <code>panic!</code> macro. The error message that <code>expect</code> uses in its call to
<code>panic!</code> will be the parameter that we pass to <code>expect</code> instead of the default
<code>panic!</code> message that <code>unwrap</code> uses. Here’s what it looks like:</p>
<pre><code class="language-text">thread 'main' panicked at 'Failed to open hello.txt: Error { repr: Os { code:
2, message: &quot;No such file or directory&quot; } }',
/stable-dist-rustc/build/src/libcore/result.rs:868
</code></pre>
<a class="header" href="#propagating-errors" name="propagating-errors"><h3>Propagating Errors</h3></a>
<p>When writing a function whose implementation calls something that might fail,
instead of handling the error within this function, you can choose to let your
caller know about the error so they can decide what to do. This is known as
<em>propagating</em> the error, and gives more control to the calling code where there
might be more information or logic that dictates how the error should be
handled than what you have available in the context of your code.</p>
<p>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::io;
use std::io::Read;
use std::fs::File;
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>Let’s look at the return type of the function first: <code>Result&lt;String, io::Error&gt;</code>. This means that the function is returning a value of the type
<code>Result&lt;T, E&gt;</code> where the generic parameter <code>T</code> has been filled in with the
concrete type <code>String</code>, and the generic type <code>E</code> has been filled in with the
concrete type <code>io::Error</code>. If this function succeeds without any problems, the
caller of this function will receive an <code>Ok</code> value that holds a <code>String</code> — the
username that this function read from the file. If this function encounters any
problems, the caller of this function will receive an <code>Err</code> value that holds an
instance of <code>io::Error</code> that contains more information about what the problems
were. We chose <code>io::Error</code> as the return type of this function because that
happens to be the type of the error value returned from both of the operations
we’re calling in this function’s body that might fail: the <code>File::open</code>
function and the <code>read_to_string</code> method.</p>
<p>The body of the function starts by calling the <code>File::open</code> function. Then we
handle the <code>Result</code> value returned with a <code>match</code> similar to the <code>match</code> in
Listing 9-3, only instead of calling <code>panic!</code> in the <code>Err</code> case, we return
early from this function and pass the error value from <code>File::open</code> back to the
caller as this function’s error value. If <code>File::open</code> succeeds, we store the
file handle in the variable <code>f</code> and continue.</p>
<p>Then we create a new <code>String</code> in variable <code>s</code> and call the <code>read_to_string</code>
method on the file handle in <code>f</code> in order to read the contents of the file into
<code>s</code>. The <code>read_to_string</code> method also returns a <code>Result</code> because it might fail,
even though <code>File::open</code> succeeded. So we need another <code>match</code> to handle that
<code>Result</code>: if <code>read_to_string</code> succeeds, then our function has succeeded, and we
return the username from the file that’s now in <code>s</code> wrapped in an <code>Ok</code>. If
<code>read_to_string</code> fails, we return the error value in the same way that we
returned the error value in the <code>match</code> that handled the return value of
<code>File::open</code>. We don’t need to explicitly say <code>return</code>, however, since this is
the last expression in the function.</p>
<p>The code that calls this code will then handle getting either an <code>Ok</code> value
that contains a username or an <code>Err</code> value that contains an <code>io::Error</code>. We
don’t know what the caller will do with those values. If they get an <code>Err</code>
value, they could choose to call <code>panic!</code> and crash their program, use a
default username, or look up the username from somewhere other than a file, for
example. We don’t have enough information on what the caller is actually trying
to do, so we propagate all the success or error information upwards for them to
handle as they see fit.</p>
<p>This pattern of propagating errors is so common in Rust that there is dedicated
syntax to make this easier: <code>?</code>.</p>
<a class="header" href="#a-shortcut-for-propagating-errors-" name="a-shortcut-for-propagating-errors-"><h3>A Shortcut for Propagating Errors: <code>?</code></h3></a>
<p>Listing 9-6 shows an implementation of <code>read_username_from_file</code> that has the
same functionality as it had in Listing 9-5, but this implementation uses the
question mark operator:</p>
<figure>
<pre><code class="language-rust">use std::io;
use std::fs::File;
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-6: A function that returns errors to the calling code using <code>?</code></p>
</figcaption>
</figure>
<p>The <code>?</code> placed after a <code>Result</code> value is defined to work the exact same way as
the <code>match</code> expressions we defined to handle the <code>Result</code> values in Listing
9-5. If the value of the <code>Result</code> is an <code>Ok</code>, the value inside the <code>Ok</code> will
get returned from this expression and the program will continue. If the value
is an <code>Err</code>, the value inside the <code>Err</code> will be returned from the whole
function as if we had used the <code>return</code> keyword so that the error value gets
propagated to the caller.</p>
<p>In the context of Listing 9-6, the <code>?</code> at the end of the <code>File::open</code> call will
return the value inside an <code>Ok</code> to the variable <code>f</code>. If an error occurs, <code>?</code>
will return early out of the whole function and give any <code>Err</code> value 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 <code>?</code> eliminates a lot of boilerplate and makes this function’s
implementation simpler. We could even shorten this code further by chaining
method calls immediately after the <code>?</code>:</p>
<pre><code class="language-rust">use std::io;
use std::io::Read;
use std::fs::File;
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>We’ve moved the creation of the new <code>String</code> in <code>s</code> to the beginning of the
function; that part hasn’t changed. Instead of creating a variable <code>f</code>, we’ve
chained the call to <code>read_to_string</code> directly onto the result of
<code>File::open(&quot;hello.txt&quot;)?</code>. We still have a <code>?</code> at the end of the
<code>read_to_string</code> call, and we still return an <code>Ok</code> value containing the
username in <code>s</code> when both <code>File::open</code> and <code>read_to_string</code> succeed rather than
returning errors. The functionality is again the same as in Listing 9-5 and
Listing 9-6, this is just a different, more ergonomic way to write it.</p>
<a class="header" href="#-can-only-be-used-in-functions-that-return-result" name="-can-only-be-used-in-functions-that-return-result"><h3><code>?</code> Can Only Be Used in Functions That Return <code>Result</code></h3></a>
<p>The <code>?</code> can only be used in functions that have a return type of <code>Result</code>,
since it is defined to work in exactly the same way as the <code>match</code> expression
we defined in Listing 9-5. The part of the <code>match</code> that requires a return type
of <code>Result</code> is <code>return Err(e)</code>, so the return type of the function must be a
<code>Result</code> to be compatible with this <code>return</code>.</p>
<p>Let’s look at what happens if use <code>?</code> in the <code>main</code> function, which you’ll
recall has a return type of <code>()</code>:</p>
<pre><code class="language-rust,ignore">use std::fs::File;
fn main() {
let f = File::open(&quot;hello.txt&quot;)?;
}
</code></pre>
<!-- NOTE: as of 2016-12-21, the error message when calling `?` in a function
that doesn't return a result is STILL confusing. Since we want to only explain
`?` now, I've changed the example, but if you try running this code you WON'T
get the error message below.
<p>I'm bugging people to try and get
https://github.com/rust-lang/rust/issues/35946 fixed soon, hopefully before this
chapter gets through copy editing-- at that point I'll make sure to update this
error message. /Carol --&gt;</p>
<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 = 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>This error is pointing out that we have mismatched types: the <code>main</code> function
has a return type of <code>()</code>, but the <code>?</code> might return a <code>Result</code>. 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 <code>Result</code> methods to handle it,
instead of using <code>?</code> to potentially propagate the error to the caller.</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 to use in which
cases.</p>
<a class="header" href="#to-panic-or-not-to-panic" name="to-panic-or-not-to-panic"><h2>To <code>panic!</code> or Not To <code>panic!</code></h2></a>
<p>So how do you decide when you should <code>panic!</code> and when you should return
<code>Result</code>? When code panics, there’s no way to recover. You could choose to call
<code>panic!</code> for any error situation, whether there’s a possible way to recover or
not, but then you’re making the decision for your callers that a situation is
unrecoverable. When you choose to return a <code>Result</code> value, you give your caller
options, rather than making the decision for them. They could choose to attempt
to recover in a way that’s appropriate for their situation, or they could
decide that actually, an <code>Err</code> value in this case is unrecoverable, so they can
call <code>panic!</code> and turn your recoverable error into an unrecoverable one.
Therefore, returning <code>Result</code> is a good default choice when you’re defining a
function that might fail.</p>
<p>There are a few situations in which it’s more appropriate to write code that
panics instead of returning a <code>Result</code>, but they are less common. Let’s discuss
why it’s appropriate to panic in examples, prototype code, and tests, then
situations where you as a human can know a method won’t fail that the compiler
can’t reason about, and conclude with some general guidelines on how to decide
whether to panic in library code.</p>
<a class="header" href="#examples-prototype-code-and-tests-perfectly-fine-to-panic" name="examples-prototype-code-and-tests-perfectly-fine-to-panic"><h3>Examples, Prototype Code, and Tests: Perfectly Fine to Panic</h3></a>
<p>When you’re writing an example to illustrate some concept, having robust error
handling code in the example as well can make the example less clear. In
examples, it’s understood that a call to a method like <code>unwrap</code> that could
<code>panic!</code> is meant as a placeholder for the way that you’d actually like your
application to handle errors, which can differ based on what the rest of your
code is doing.</p>
<p>Similarly, the <code>unwrap</code> and <code>expect</code> methods are very handy when prototyping,
before you’re ready to decide how to handle errors. They leave clear markers in
your code for when you’re ready to make your program more robust.</p>
<p>If a method call fails in a test, we’d want the whole test to fail, even if
that method isn’t the functionality under test. Because <code>panic!</code> is how a test
gets marked as a failure, calling <code>unwrap</code> or <code>expect</code> is exactly what makes
sense to do.</p>
<a class="header" href="#cases-when-you-have-more-information-than-the-compiler" name="cases-when-you-have-more-information-than-the-compiler"><h3>Cases When You Have More Information Than The Compiler</h3></a>
<p>It would also be appropriate to call <code>unwrap</code> when you 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. You’ll still have a <code>Result</code> value that you
need to handle: whatever operation you’re calling still has the possibility of
failing in general, even though it’s logically impossible in your particular
situation. 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>127.0.0.1</code> is a valid IP address, so it’s acceptable to use <code>unwrap</code>
here. However, having a hardcoded, valid string doesn’t change the return type
of the <code>parse</code> method: we still get a <code>Result</code> value, and the compiler will
still make us handle the <code>Result</code> as if the <code>Err</code> variant is still a
possibility since the compiler isn’t smart enough to see that this string is
always a valid IP address. If the IP address string came from a user instead of
being hardcoded into the program, and therefore <em>did</em> have a possibility of
failure, we’d definitely want to handle the <code>Result</code> in a more robust way
instead.</p>
<a class="header" href="#guidelines-for-error-handling" name="guidelines-for-error-handling"><h3>Guidelines for Error Handling</h3></a>
<p>It’s advisable to have your code <code>panic!</code> when it’s possible that you could end
up in a bad state—in this context, bad state is when some assumption,
guarantee, contract, or invariant has been broken, such as when invalid values,
contradictory values, or missing values are passed to your code—plus one or
more of the following:</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>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’re calling external code that is out of your
control, and it returns an invalid state that you have no way of fixing.</p>
<p>When a bad state is reached, but it’s expected to happen no matter how well you
write your code, it’s still more appropriate to return a <code>Result</code> rather than
calling <code>panic!</code>. Examples of this include a parser being given malformed data,
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> in order to propagate these bad states upwards so that the
caller can decide how they would like to handle the problem. To <code>panic!</code>
wouldn’t 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, and <code>panic!</code> if the values aren’t valid. 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 panic, 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, you can 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
has a particular type as a parameter, 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>, your program expects to
have <em>something</em> rather than <em>nothing</em>. Your code then doesn’t have to handle
two cases for the <code>Some</code> and <code>None</code> variants, it will only have one case for
definitely having a value. Code trying to pass nothing to your function won’t
even compile, so your function doesn’t have to check for that case at runtime.
Another example is using an unsigned integer type like <code>u32</code>, which ensures the
parameter is never negative.</p>
<a class="header" href="#creating-custom-types-for-validation" name="creating-custom-types-for-validation"><h3>Creating Custom Types for Validation</h3></a>
<p>Let’s take the idea of using Rust’s type system to ensure we have a valid value
one step further, and look at 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 “Too high” or “Too low” would still be correct. It would be a useful
enhancement to guide the user towards valid guesses, though, and have different
behavior when a user guesses a number that’s out of range versus when a user
types, for example, letters instead.</p>
<p>One way to do this would be to parse the guess as an <code>i32</code> instead of only a
<code>u32</code>, to allow potentially negative numbers, then add a check for the number
being in range:</p>
<pre><code class="language-rust,ignore">loop {
// snip
let guess: i32 = 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>
<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 <code>guess</code> is
between 1 and 100.</p>
<p>However, this is not an ideal solution: if it was absolutely critical that the
program only operated on values between 1 and 100, and it had many functions
with this requirement, it would be tedious (and potentially impact performance)
to have a check like this in every function.</p>
<p>Instead, we can make a new type and put the validations in a function to create
an instance of the type rather than repeating the validations everywhere. That
way, it’s safe for functions to use the new type in their signatures and
confidently use the values they receive. 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
receives 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 continue with values between 1 and
100</p>
</figcaption>
</figure>
<p>First, we define a struct named <code>Guess</code> that has a field named <code>value</code> that
holds a <code>u32</code>. This is where the number will be stored.</p>
<p>Then we implement an associated function named <code>new</code> on <code>Guess</code> that creates
instances of <code>Guess</code> values. The <code>new</code> function is defined to have one
parameter named <code>value</code> of type <code>u32</code> and to return a <code>Guess</code>. The code in the
body of the <code>new</code> function tests <code>value</code> to make sure it is between 1 and 100.
If <code>value</code> doesn’t pass this test, we call <code>panic!</code>, which will alert the
programmer who is calling this code that they have a bug they need to fix,
since creating a <code>Guess</code> with a <code>value</code> outside this range would violate the
contract that <code>Guess::new</code> is relying on. The conditions in which <code>Guess::new</code>
might panic should be discussed in its public-facing API documentation; we’ll
cover documentation conventions around indicating the possibility of a <code>panic!</code>
in the API documentation that you create in Chapter 14. If <code>value</code> does pass
the test, we create a new <code>Guess</code> with its <code>value</code> field set to the <code>value</code>
parameter and return the <code>Guess</code>.</p>
<p>Next, we implement a method named <code>value</code> that borrows <code>self</code>, doesn’t have any
other parameters, and returns a <code>u32</code>. This is a kind of method sometimes
called a <em>getter</em>, since its purpose is to get some data from its fields and
return it. This public method is necessary because the <code>value</code> field of the
<code>Guess</code> struct is private. It’s important that the <code>value</code> field is private so
that code using the <code>Guess</code> struct is not allowed to set <code>value</code> directly:
callers <em>must</em> use the <code>Guess::new</code> function to create an instance of <code>Guess</code>,
which ensures there’s no way for a <code>Guess</code> to have a <code>value</code> that hasn’t been
checked by the conditions in the <code>Guess::new</code> function.</p>
<p>A function that has a parameter or returns only numbers between 1 and 100 could
then declare in its signature that it takes or returns a <code>Guess</code> rather than a
<code>u32</code>, and wouldn’t need to do any additional checks in its body.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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 to indicate that
operations might fail in a way that your code could recover from. You can use
<code>Result</code> to tell code that calls your code that it needs to handle potential
success or failure as well. Using <code>panic!</code> and <code>Result</code> in the appropriate
situations will make your code 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>
<a class="header" href="#generic-types-traits-and-lifetimes" name="generic-types-traits-and-lifetimes"><h1>Generic Types, Traits, and Lifetimes</h1></a>
<p>Every programming language has tools to deal effectively with duplication of
concepts; in Rust, one of those tools is <em>generics</em>. Generics are abstract
stand-ins for concrete types or other properties. We can express properties of
generics, such as their behavior or how they relate to other generics, without
needing to know when we're writing and compiling the code what will actually be
in their place.</p>
<p>In the same way that a function takes parameters whose value we don't know in
order to write code once that will be run on multiple concrete values, we can
write functions that take parameters of some generic type instead of a concrete
type like <code>i32</code> or <code>String</code>. We've already used generics in Chapter 6 with
<code>Option&lt;T&gt;</code>, Chapter 8 with <code>Vec&lt;T&gt;</code> and <code>HashMap&lt;K, V&gt;</code>, and Chapter 9 with
<code>Result&lt;T, E&gt;</code>. In this chapter, we'll explore how to define our own types,
functions, and methods with generics!</p>
<p>First, we're going to review the mechanics of extracting a function that
reduces code duplication. Then we'll use the same mechanics to make a generic
function out of two functions that only differ in the types of their
parameters. We'll go over using generic types in struct and enum definitions
too.</p>
<p>After that, we'll discuss <em>traits</em>, which are a way to define behavior in a
generic way. Traits can be combined with generic types in order to constrain a
generic type to those types that have a particular behavior, rather than any
type at all.</p>
<p>Finally, we'll discuss <em>lifetimes</em>, which are a kind of generic that let us
give the compiler information about how references are related to each other.
Lifetimes are the feature in Rust that allow us to borrow values in many
situations and still have the compiler check that references will be valid.</p>
<a class="header" href="#removing-duplication-by-extracting-a-function" name="removing-duplication-by-extracting-a-function"><h2>Removing Duplication by Extracting a Function</h2></a>
<p>Before getting into generics syntax, let's first review a technique for dealing
with duplication that doesn't use generic types: extracting a function. Once
that's fresh in our minds, we'll use the same mechanics with generics to
extract a generic function! In the same way that you recognize duplicated code
to extract into a function, you'll start to recognize duplicated code that can
use generics.</p>
<p>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);
# assert_eq!(largest, 100);
}
</code></pre>
<figcaption>
<p>Listing 10-1: Code to find the largest number in a list of numbers</p>
</figcaption>
</figure>
<p>This code takes a list of integers, stored here in the variable <code>numbers</code>. It
puts the first item in the list in a variable named <code>largest</code>. Then it iterates
through all the numbers in the list, and if the current value is greater than
the number stored in <code>largest</code>, it replaces the value in <code>largest</code>. If the
current value is smaller than the largest value seen so far, <code>largest</code> is not
changed. When all the items in the list have been considered, <code>largest</code> will
hold the largest value, which in this case is 100.</p>
<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, as in Listing 10-2:</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);
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>
<figcaption>
<p>Listing 10-2: Code to find the largest number in <em>two</em> lists of numbers</p>
</figcaption>
</figure>
<p>While this code works, duplicating code is tedious and error-prone, and means
we have multiple places to update the logic if we need to change it.</p>
<!-- Are we safe assuming the reader will be familiar with the term
"abstraction" in this context, or do we want to give a brief definition? -->
<!-- Yes, our audience will be familiar with this term. /Carol -->
<p>To eliminate this duplication, we can create an abstraction, which in this case
will be in the form of a function that operates on any list of integers given
to the function in a parameter. This will increase the clarity of our code and
let us communicate and reason about the concept of finding the largest number
in a list independently of the specific places this concept is used.</p>
<p>In the program in Listing 10-3, we've extracted the code 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>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn largest(list: &amp;[i32]) -&gt; i32 {
let mut largest = list[0];
for &amp;item in list.iter() {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let result = largest(&amp;numbers);
println!(&quot;The largest number is {}&quot;, result);
# assert_eq!(result, 100);
let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];
let result = largest(&amp;numbers);
println!(&quot;The largest number is {}&quot;, result);
# assert_eq!(result, 6000);
}
</code></pre>
<figcaption>
<p>Listing 10-3: Abstracted code to find the largest number in two lists</p>
</figcaption>
</figure>
<p>The function has a parameter, <code>list</code>, which represents any concrete slice of
<code>i32</code> values that we might pass into the function. The code in the function
definition operates on the <code>list</code> representation of any <code>&amp;[i32]</code>. When we call
the <code>largest</code> function, the code actually runs on the specific values that we
pass in.</p>
<p>The mechanics we went through to get from Listing 10-2 to Listing 10-3 were
these steps:</p>
<ol>
<li>We noticed there was duplicate code.</li>
<li>We extracted the duplicate code into the body of the function, and specified
the inputs and return values of that code in the function signature.</li>
<li>We replaced the two concrete places that had the duplicated code to call the
function instead.</li>
</ol>
<p>We can use these same steps with generics to reduce code duplication in
different ways in different scenarios. In the same way that the function body
is now operating on an abstract <code>list</code> instead of concrete values, code using
generics will operate on abstract types. The concepts powering generics are the
same concepts you already know that power functions, just applied in different
ways.</p>
<p>What if we had two functions, one that found the largest item in a slice of
<code>i32</code> values and one that found the largest item in a slice of <code>char</code> values?
How would we get rid of that duplication? Let's find out!</p>
<a class="header" href="#generic-data-types" name="generic-data-types"><h2>Generic Data Types</h2></a>
<p>Using generics where we usually place types, like in function signatures or
structs, lets us create definitions that we can use for many different concrete
data types. Let's take a look at how to define functions, structs, enums, and
methods using generics, and at the end of this section we'll discuss the
performance of code using generics.</p>
<a class="header" href="#using-generic-data-types-in-function-definitions" name="using-generic-data-types-in-function-definitions"><h3>Using Generic Data Types in Function Definitions</h3></a>
<p>We can define functions that use generics in the signature of the function
where the data types of the parameters and return value go. In this way, the
code we write can be more flexible and provide more functionality to callers of
our function, while not introducing code duplication.</p>
<p>Continuing with our <code>largest</code> function, Listing 10-4 shows two functions
providing the same functionality to find the largest value in a slice. The
first function is the one we extracted in Listing 10-3 that finds the largest
<code>i32</code> in a slice. The second function finds the largest <code>char</code> in a slice:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn largest_i32(list: &amp;[i32]) -&gt; i32 {
let mut largest = list[0];
for &amp;item in list.iter() {
if item &gt; largest {
largest = item;
}
}
largest
}
fn largest_char(list: &amp;[char]) -&gt; char {
let mut largest = list[0];
for &amp;item in list.iter() {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let result = largest_i32(&amp;numbers);
println!(&quot;The largest number is {}&quot;, result);
# assert_eq!(result, 100);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest_char(&amp;chars);
println!(&quot;The largest char is {}&quot;, result);
# assert_eq!(result, 'y');
}
</code></pre>
<figcaption>
<p>Listing 10-4: Two functions that differ only in their names and the types in
their signatures</p>
</figcaption>
</figure>
<p>Here, the functions <code>largest_i32</code> and <code>largest_char</code> have the exact same body,
so it would be nice if we could turn these two functions into one and get rid
of the duplication. Luckily, we can do that by introducing a generic type
parameter!</p>
<p>To parameterize the types in the signature of the one function we're going to
define, we need to create a name for the type parameter, just like how we give
names for the value parameters to a function. We're going to choose the name
<code>T</code>. Any identifier can be used as a type parameter name, but we're choosing
<code>T</code> because Rust's type naming convention is CamelCase. Generic type parameter
names also tend to be short by convention, often just one letter. Short for
&quot;type&quot;, <code>T</code> is the default choice of most Rust programmers.</p>
<p>When we use a parameter in the body of the function, we have to declare the
parameter in the signature so that the compiler knows what that name in the
body means. Similarly, when we use a type parameter name in a function
signature, we have to declare the type parameter name before we use it. Type
name declarations go in angle brackets between the name of the function and the
parameter list.</p>
<p>The function signature of the generic <code>largest</code> function we're going to define
will look like this:</p>
<pre><code class="language-rust,ignore">fn largest&lt;T&gt;(list: &amp;[T]) -&gt; T {
</code></pre>
<p>We would read this as: the function <code>largest</code> is generic over some type <code>T</code>. It
has one parameter named <code>list</code>, and the type of <code>list</code> is a slice of values of
type <code>T</code>. The <code>largest</code> function will return a value of the same type <code>T</code>.</p>
<p>Listing 10-5 shows the unified <code>largest</code> function definition using the generic
data type in its signature, and shows how we'll be able to call <code>largest</code> with
either a slice of <code>i32</code> values or <code>char</code> values. Note that this code won't
compile yet!</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">fn largest&lt;T&gt;(list: &amp;[T]) -&gt; T {
let mut largest = list[0];
for &amp;item in list.iter() {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let result = largest(&amp;numbers);
println!(&quot;The largest number is {}&quot;, result);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest(&amp;chars);
println!(&quot;The largest char is {}&quot;, result);
}
</code></pre>
<figcaption>
<p>Listing 10-5: A definition of the <code>largest</code> function that uses generic type
parameters but doesn't compile yet</p>
</figcaption>
</figure>
<p>If we try to compile this code right now, we'll get this error:</p>
<pre><code class="language-text">error[E0369]: binary operation `&gt;` cannot be applied to type `T`
|
5 | if item &gt; largest {
| ^^^^
|
note: an implementation of `std::cmp::PartialOrd` might be missing for `T`
</code></pre>
<p>The note mentions <code>std::cmp::PartialOrd</code>, which is a <em>trait</em>. We're going to
talk about traits in the next section, but briefly, what this error is saying
is that the body of <code>largest</code> won't work for all possible types that <code>T</code> could
be; since we want to compare values of type <code>T</code> in the body, we can only use
types that know how to be ordered. The standard library has defined the trait
<code>std::cmp::PartialOrd</code> that types can implement to enable comparisons. We'll
come back to traits and how to specify that a generic type has a particular
trait in the next section, but let's set this example aside for a moment and
explore other places we can use generic type parameters first.</p>
<!-- Liz: this is the reason we had the topics in the order we did in the first
draft of this chapter; it's hard to do anything interesting with generic types
in functions unless you also know about traits and trait bounds. I think this
ordering could work out okay, though, and keep a stronger thread with the
`longest` function going through the whole chapter, but we do pause with a
not-yet-compiling example here, which I know isn't ideal either. Let us know
what you think. /Carol -->
<a class="header" href="#using-generic-data-types-in-struct-definitions" name="using-generic-data-types-in-struct-definitions"><h3>Using Generic Data Types in Struct Definitions</h3></a>
<p>We can define structs to use a generic type parameter in one or more of the
struct's fields with the <code>&lt;&gt;</code> syntax too. Listing 10-6 shows the definition and
use of a <code>Point</code> struct that can hold <code>x</code> and <code>y</code> coordinate values of 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-6: 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 similar to using generics in function definitions. First, we have
to declare the name of the type parameter within angle brackets just after the
name of the struct. Then we can use the generic type in the struct definition
where we would specify concrete data types.</p>
<p>Note that because we've only used one generic type in the definition of
<code>Point</code>, what we're saying is that the <code>Point</code> struct is generic over some type
<code>T</code>, and the fields <code>x</code> and <code>y</code> are <em>both</em> that same type, whatever it ends up
being. If we try to create an instance of a <code>Point</code> that has values of
different types, as in Listing 10-7, our code won't compile:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">struct Point&lt;T&gt; {
x: T,
y: T,
}
fn main() {
let wont_work = Point { x: 5, y: 4.0 };
}
</code></pre>
<figcaption>
<p>Listing 10-7: The fields <code>x</code> and <code>y</code> must be the same type because both have
the same generic data type <code>T</code></p>
</figcaption>
</figure>
<p>If we try to compile this, we'll get the following error:</p>
<pre><code class="language-text">error[E0308]: mismatched types
--&gt;
|
7 | let wont_work = Point { x: 5, y: 4.0 };
| ^^^ expected integral variable, found
floating-point variable
|
= note: expected type `{integer}`
= note: found type `{float}`
</code></pre>
<p>When we assigned the integer value 5 to <code>x</code>, the compiler then knows for this
instance of <code>Point</code> that the generic type <code>T</code> will be an integer. Then when we
specified 4.0 for <code>y</code>, which is defined to have the same type as <code>x</code>, we get a
type mismatch error.</p>
<p>If we wanted to define a <code>Point</code> struct where <code>x</code> and <code>y</code> could have different
types but still have those types be generic, we can use multiple generic type
parameters. In listing 10-8, we've changed the definition of <code>Point</code> to be
generic over types <code>T</code> and <code>U</code>. The field <code>x</code> is of type <code>T</code>, and the field <code>y</code>
is of type <code>U</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Point&lt;T, U&gt; {
x: T,
y: U,
}
fn main() {
let both_integer = Point { x: 5, y: 10 };
let both_float = Point { x: 1.0, y: 4.0 };
let integer_and_float = Point { x: 5, y: 4.0 };
}
</code></pre>
<figcaption>
<p>Listing 10-8: A <code>Point</code> generic over two types so that <code>x</code> and <code>y</code> may be
values of different types</p>
</figcaption>
</figure>
<p>Now all of these instances of <code>Point</code> are allowed! You can use as many generic
type parameters in a definition as you want, but using more than a few gets
hard to read and understand. If you get to a point of needing lots of generic
types, it's probably a sign that your code could use some restructuring to be
separated into smaller pieces.</p>
<a class="header" href="#using-generic-data-types-in-enum-definitions" name="using-generic-data-types-in-enum-definitions"><h3>Using Generic Data Types in Enum Definitions</h3></a>
<p>Similarly to structs, enums can be defined to hold generic data types in their
variants. We used the <code>Option&lt;T&gt;</code> enum provided by the standard library in
Chapter 6, and now its definition should make more sense. Let's take another
look:</p>
<pre><code class="language-rust">enum Option&lt;T&gt; {
Some(T),
None,
}
</code></pre>
<p>In other words, <code>Option&lt;T&gt;</code> is an enum generic in type <code>T</code>. It has two
variants: <code>Some</code>, which holds one value of type <code>T</code>, and a <code>None</code> variant that
doesn't hold any value. The standard library only has to have this one
definition to support the creation of values of this enum that have any
concrete type. The idea of &quot;an optional value&quot; is a more abstract concept than
one specific type, and Rust lets us express this abstract concept without lots
of duplication.</p>
<p>Enums can use multiple generic types as well. The definition of the <code>Result</code>
enum that we used in Chapter 9 is one example:</p>
<pre><code class="language-rust">enum Result&lt;T, E&gt; {
Ok(T),
Err(E),
}
</code></pre>
<p>The <code>Result</code> enum is generic over two types, <code>T</code> and <code>E</code>. <code>Result</code> has two
variants: <code>Ok</code>, which holds a value of type <code>T</code>, and <code>Err</code>, which holds a value
of type <code>E</code>. This definition makes it convenient to use the <code>Result</code> enum
anywhere we have an operation that might succeed (and return a value of some
type <code>T</code>) or fail (and return an error of some type <code>E</code>). Recall Listing 9-2
when we opened a file: in that case, <code>T</code> was filled in with the type
<code>std::fs::File</code> when the file was opened successfully and <code>E</code> was filled in
with the type <code>std::io::Error</code> when there were problems opening the file.</p>
<p>When you recognize situations in your code with multiple struct or enum
definitions that differ only in the types of the values they hold, you can
remove the duplication by using the same process we used with the function
definitions to introduce generic types instead.</p>
<a class="header" href="#using-generic-data-types-in-method-definitions" name="using-generic-data-types-in-method-definitions"><h3>Using Generic Data Types in Method Definitions</h3></a>
<p>Like we did in Chapter 5, we can implement methods on structs and enums that
have generic types in their definitions. Listing 10-9 shows the <code>Point&lt;T&gt;</code>
struct we defined in Listing 10-6. We've then defined a method named <code>x</code> on
<code>Point&lt;T&gt;</code> that returns a reference to the data in the field <code>x</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Point&lt;T&gt; {
x: T,
y: T,
}
impl&lt;T&gt; Point&lt;T&gt; {
fn x(&amp;self) -&gt; &amp;T {
&amp;self.x
}
}
fn main() {
let p = Point { x: 5, y: 10 };
println!(&quot;p.x = {}&quot;, p.x());
}
</code></pre>
<figcaption>
<p>Listing 10-9: Implementing a method named <code>x</code> on the <code>Point&lt;T&gt;</code> struct that
will return a reference to the <code>x</code> field, which is of type <code>T</code>.</p>
</figcaption>
</figure>
<p>Note that we have to declare <code>T</code> just after <code>impl</code>, so that we can use it when
we specify that we're implementing methods on the type <code>Point&lt;T&gt;</code>.</p>
<p>Generic type parameters in a struct definition aren't always the same generic
type parameters you want to use in that struct's method signatures. Listing
10-10 defines a method <code>mixup</code> on the <code>Point&lt;T, U&gt;</code> struct from Listing 10-8.
The method takes another <code>Point</code> as a parameter, which might have different
types than the <code>self</code> <code>Point</code> that we're calling <code>mixup</code> on. The method creates
a new <code>Point</code> instance that has the <code>x</code> value from the <code>self</code> <code>Point</code> (which is
of type <code>T</code>) and the <code>y</code> value from the passed-in <code>Point</code> (which is of type
<code>W</code>):</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct Point&lt;T, U&gt; {
x: T,
y: U,
}
impl&lt;T, U&gt; Point&lt;T, U&gt; {
fn mixup&lt;V, W&gt;(&amp;self, other: &amp;Point&lt;V, W&gt;) -&gt; Point&lt;T, W&gt; {
Point {
x: self.x,
y: other.y,
}
}
}
fn main() {
let p1 = Point { x: 5, y: 10.4 };
let p2 = Point { x: &quot;Hello&quot;, y: 'c'};
let p3 = p1.mixup(p2);
println!(&quot;p3.x = {}, p3.y = {}&quot;, p3.x, p3.y);
}
</code></pre>
<figcaption>
<p>Listing 10-10: Methods that use different generic types than their struct's
definition</p>
</figcaption>
</figure>
<p>In <code>main</code>, we've defined a <code>Point</code> that has an <code>i32</code> for <code>x</code> (with value <code>5</code>)
and an <code>f64</code> for <code>y</code> (with value <code>10.4</code>). <code>p2</code> is a <code>Point</code> that has a string
slice for <code>x</code> (with value <code>&quot;Hello&quot;</code>) and a <code>char</code> for <code>y</code> (with value <code>c</code>).
Calling <code>mixup</code> on <code>p1</code> with the argument <code>p2</code> gives us <code>p3</code>, which will have
an <code>i32</code> for <code>x</code>, since <code>x</code> came from <code>p1</code>. <code>p3</code> will have a <code>char</code> for <code>y</code>,
since <code>y</code> came from <code>p2</code>. The <code>println!</code> will print <code>p3.x = 5, p3.y = c</code>.</p>
<p>Note that the generic parameters <code>T</code> and <code>U</code> are declared after <code>impl</code>, since
they go with the struct definition. The generic parameters <code>V</code> and <code>W</code> are
declared after <code>fn mixup</code>, since they are only relevant to the method.</p>
<a class="header" href="#performance-of-code-using-generics" name="performance-of-code-using-generics"><h3>Performance of Code Using Generics</h3></a>
<p>You may have been reading this section and wondering if there's a run-time cost
to using generic type parameters. Good news: the way that Rust has implemented
generics means that your code will not run any slower than if you had specified
concrete types instead of generic type parameters!</p>
<p>Rust accomplishes this by performing <em>monomorphization</em> of code using generics
at compile time. Monomorphization is the process of turning generic code into
specific code with the concrete types that are actually used filled in.</p>
<p>What the compiler does is the opposite of the steps that we performed to create
the generic function in Listing 10-5. The compiler looks at all the places that
generic code is called and generates code for the concrete types that the
generic code is called with.</p>
<p>Let's work through an example that uses the standard library's <code>Option</code> enum:</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. The compiler
will read the values that have been passed to <code>Option</code> and see that we have two
kinds of <code>Option&lt;T&gt;</code>: one is <code>i32</code>, and one 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.</p>
<p>The monomorphized version of our code that the compiler generates looks like
this, with the uses of the generic <code>Option</code> replaced with the specific
definitions created by the compiler:</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>We can write the non-duplicated code using generics, and Rust will compile that
into code that specifies the type in each instance. That means we pay no
runtime cost for using generics; when the code runs, it performs just like it
would if we had duplicated each particular definition by hand. The process of
monomorphization is what makes Rust's generics extremely efficient at runtime.</p>
<a class="header" href="#traits-defining-shared-behavior" name="traits-defining-shared-behavior"><h2>Traits: Defining Shared Behavior</h2></a>
<p>Traits allow us to use another kind of abstraction: they let us abstract over
behavior that types can have in common. A <em>trait</em> tells the Rust compiler about
functionality a particular type has and might share with other types. In
situations where we use generic type parameters, we can use <em>trait bounds</em> to
specify, at compile time, that the generic type may be any type that implements
a trait and therefore has the behavior we want to use in that situation.</p>
<blockquote>
<p>Note: <em>Traits</em> are similar to a feature often called 'interfaces' in other
languages, though with some differences.</p>
</blockquote>
<a class="header" href="#defining-a-trait" name="defining-a-trait"><h3>Defining a Trait</h3></a>
<p>The behavior of a type consists of the methods we can call on that type.
Different types share the same behavior if we can call the same methods on all
of those types. Trait definitions are a way to group method signatures together
in order to define a set of behaviors necessary to accomplish some purpose.</p>
<p>For example, say we have multiple structs that hold various kinds and amounts
of text: a <code>NewsArticle</code> struct that holds a news story filed in a particular
place in the world, and a <code>Tweet</code> that can have at most 140 characters in its
content along with metadata like whether it was a retweet or a reply to another
tweet.</p>
<p>We want to make a media aggregator library that can display summaries of data
that might be stored in a <code>NewsArticle</code> or <code>Tweet</code> instance. The behavior we
need each struct to have is that it's able to be summarized, and that we can
ask for that summary by calling a <code>summary</code> method on an instance. Listing
10-11 shows the definition of a <code>Summarizable</code> trait that expresses this
concept:</p>
<figure>
<span class="filename">Filename: lib.rs</span>
<pre><code class="language-rust">pub trait Summarizable {
fn summary(&amp;self) -&gt; String;
}
</code></pre>
<figcaption>
<p>Listing 10-11: Definition of a <code>Summarizable</code> trait that consists of the
behavior provided by a <code>summary</code> method</p>
</figcaption>
</figure>
<p>We declare a trait with the <code>trait</code> keyword, then the trait's name, in this
case <code>Summarizable</code>. Inside curly braces we declare the method signatures that
describe the behaviors that types that implement this trait will need to have,
in this case <code>fn summary(&amp;self) -&gt; String</code>. After the method signature, instead
of providing an implementation within curly braces, we put a semicolon. Each
type that implements this trait must then provide its own custom behavior for
the body of the method, but the compiler will enforce that any type that has
the <code>Summarizable</code> trait will have the method <code>summary</code> defined for it with
this signature exactly.</p>
<p>A trait can have multiple methods in its body, with the method signatures
listed one per line and each line ending in a semicolon.</p>
<a class="header" href="#implementing-a-trait-on-a-type" name="implementing-a-trait-on-a-type"><h3>Implementing a Trait on a Type</h3></a>
<p>Now that we've defined the <code>Summarizable</code> trait, we can implement it on the
types in our media aggregator that we want to have this behavior. Listing 10-12
shows an implementation of the <code>Summarizable</code> trait on the <code>NewsArticle</code> struct
that uses the headline, the author, and the location to create the return value
of <code>summary</code>. For the <code>Tweet</code> struct, we've chosen to define <code>summary</code> as the
username followed by the whole text of the tweet, assuming that tweet content
is already limited to 140 characters.</p>
<figure>
<span class="filename">Filename: lib.rs</span>
<pre><code class="language-rust"># pub trait Summarizable {
# fn summary(&amp;self) -&gt; String;
# }
#
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summarizable for NewsArticle {
fn summary(&amp;self) -&gt; String {
format!(&quot;{}, by {} ({})&quot;, self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summarizable for Tweet {
fn summary(&amp;self) -&gt; String {
format!(&quot;{}: {}&quot;, self.username, self.content)
}
}
</code></pre>
<figcaption>
<p>Listing 10-12: Implementing the <code>Summarizable</code> trait on the <code>NewsArticle</code> and
<code>Tweet</code> types</p>
</figcaption>
</figure>
<p>Implementing a trait on a type is similar to implementing methods that aren't
related to a trait. The difference is after <code>impl</code>, we put the trait name that
we want to implement, then say <code>for</code> and the name of the type that we want to
implement the trait for. Within the <code>impl</code> block, we put the method signatures
that the trait definition has defined, but instead of putting a semicolon after
each signature, we put curly braces and fill in the method body with the
specific behavior that we want the methods of the trait to have for the
particular type.</p>
<p>Once we've implemented the trait, we can call the methods on instances of
<code>NewsArticle</code> and <code>Tweet</code> in the same manner that we call methods that aren't
part of a trait:</p>
<pre><code class="language-rust,ignore">let tweet = Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(&quot;of course, as you probably already know, people&quot;),
reply: false,
retweet: false,
};
println!(&quot;1 new tweet: {}&quot;, tweet.summary());
</code></pre>
<p>This will print <code>1 new tweet: horse_ebooks: of course, as you probably already know, people</code>.</p>
<p>Note that because we've defined the <code>Summarizable</code> trait and the <code>NewsArticle</code>
and <code>Tweet</code> types all in the same <code>lib.rs</code> in Listing 10-12, they're all in the
same scope. If this <code>lib.rs</code> is for a crate we've called <code>aggregator</code>, and
someone else wants to use our crate's functionality plus implement the
<code>Summarizable</code> trait on their <code>WeatherForecast</code> struct, their code would need
to import the <code>Summarizable</code> trait into their scope first before they could
implement it, like in Listing 10-13:</p>
<figure>
<span class="filename">Filename: lib.rs</span>
<pre><code class="language-rust,ignore">extern crate aggregator;
use aggregator::Summarizable;
struct WeatherForecast {
high_temp: f64,
low_temp: f64,
chance_of_precipitation: f64,
}
impl Summarizable for WeatherForecast {
fn summary(&amp;self) -&gt; String {
format!(&quot;The high will be {}, and the low will be {}. The chance of
precipitation is {}%.&quot;, self.high_temp, self.low_temp,
self.chance_of_precipitation)
}
}
</code></pre>
<figcaption>
<p>Listing 10-13: Bringing the <code>Summarizable</code> trait from our <code>aggregator</code> crate
into scope in another crate</p>
</figcaption>
</figure>
<p>This code also assumes <code>Summarizable</code> is a public trait, which it is because we
put the <code>pub</code> keyword before <code>trait</code> in Listing 10-11.</p>
<p>One restriction to note with trait implementations: we may implement a trait on
a type as long as either the trait or the type are local to our crate. In other
words, we aren't allowed to implement external traits on external types. We
can't implement the <code>Display</code> trait on <code>Vec</code>, for example, since both <code>Display</code>
and <code>Vec</code> are defined in the standard library. We are allowed to implement
standard library traits like <code>Display</code> on a custom type like <code>Tweet</code> as part of
our <code>aggregator</code> crate functionality. We could also implement <code>Summarizable</code> on
<code>Vec</code> in our <code>aggregator</code> crate, since we've defined <code>Summarizable</code> there. This
restriction is part of what's called the <em>orphan rule</em>, which you can look up
if you're interested in type theory. Briefly, it's called the orphan rule
because the parent type is not present. Without this rule, two crates could
implement the same trait for the same type, and the two implementations would
conflict: Rust wouldn't know which implementation to use. Because Rust enforces
the orphan rule, other people's code can't break your code and vice versa.</p>
<a class="header" href="#default-implementations" name="default-implementations"><h3>Default Implementations</h3></a>
<p>Sometimes it's useful to have default behavior for some or all of the methods
in a trait, instead of making every implementation on every type define custom
behavior. When we implement the trait on a particular type, we can choose to
keep or override each method's default behavior.</p>
<p>Listing 10-14 shows how we could have chosen to specify a default string for
the <code>summary</code> method of the <code>Summarize</code> trait instead of only choosing to only
define the method signature like we did in Listing 10-11:</p>
<figure>
<span class="filename">Filename: lib.rs</span>
<pre><code class="language-rust">pub trait Summarizable {
fn summary(&amp;self) -&gt; String {
String::from(&quot;(Read more...)&quot;)
}
}
</code></pre>
<figcaption>
<p>Listing 10-14: Definition of a <code>Summarizable</code> trait with a default
implementation of the <code>summary</code> method</p>
</figcaption>
</figure>
<p>If we wanted to use this default implementation to summarize instances of
<code>NewsArticle</code> instead of defining a custom implementation like we did in
Listing 10-12, we would specify an empty <code>impl</code> block:</p>
<pre><code class="language-rust,ignore">impl Summarizable for NewsArticle {}
</code></pre>
<p>Even though we're no longer choosing to define the <code>summary</code> method on
<code>NewsArticle</code> directly, since the <code>summary</code> method has a default implementation
and we specified that <code>NewsArticle</code> implements the <code>Summarizable</code> trait, we can
still call the <code>summary</code> method on an instance of <code>NewsArticle</code>:</p>
<pre><code class="language-rust,ignore">let article = NewsArticle {
headline: String::from(&quot;Penguins win the Stanley Cup Championship!&quot;),
location: String::from(&quot;Pittsburgh, PA, USA&quot;),
author: String::from(&quot;Iceburgh&quot;),
content: String::from(&quot;The Pittsburgh Penguins once again are the best
hockey team in the NHL.&quot;),
};
println!(&quot;New article available! {}&quot;, article.summary());
</code></pre>
<p>This code prints <code>New article available! (Read more...)</code>.</p>
<p>Changing the <code>Summarizable</code> trait to have a default implementation for
<code>summary</code> does not require us to change anything about the implementations of
<code>Summarizable</code> on <code>Tweet</code> in Listing 10-12 or <code>WeatherForecast</code> in Listing
10-13: the syntax for overriding a default implementation is exactly the same
as the syntax for implementing a trait method that doesn't have a default
implementation.</p>
<p>Default implementations are allowed to call the other methods in the same
trait, even if those other methods don't have a default implementation. In this
way, a trait can provide a lot of useful functionality and only require
implementers to specify a small part of it. We could choose to have the
<code>Summarizable</code> trait also have an <code>author_summary</code> method whose implementation
is required, then a <code>summary</code> method that has a default implementation that
calls the <code>author_summary</code> method:</p>
<pre><code class="language-rust">pub trait Summarizable {
fn author_summary(&amp;self) -&gt; String;
fn summary(&amp;self) -&gt; String {
format!(&quot;(Read more from {}...)&quot;, self.author_summary())
}
}
</code></pre>
<p>In order to use this version of <code>Summarizable</code>, we're only required to define
<code>author_summary</code> when we implement the trait on a type:</p>
<pre><code class="language-rust,ignore">impl Summarizable for Tweet {
fn author_summary(&amp;self) -&gt; String {
format!(&quot;@{}&quot;, self.username)
}
}
</code></pre>
<p>Once we define <code>author_summary</code>, we can call <code>summary</code> on instances of the
<code>Tweet</code> struct, and the default implementation of <code>summary</code> will call the
definition of <code>author_summary</code> that we've provided.</p>
<pre><code class="language-rust,ignore">let tweet = Tweet {
username: String::from(&quot;horse_ebooks&quot;),
content: String::from(&quot;of course, as you probably already know, people&quot;),
reply: false,
retweet: false,
};
println!(&quot;1 new tweet: {}&quot;, tweet.summary());
</code></pre>
<p>This will print <code>1 new tweet: (Read more from @horse_ebooks...)</code>.</p>
<p>Note that it is not possible to call the default implementation from an
overridden implementation.</p>
<a class="header" href="#trait-bounds" name="trait-bounds"><h3>Trait Bounds</h3></a>
<p>Now that we've defined traits and implemented those traits on types, we can use
traits with generic type parameters. We can constrain generic types so that
rather than being any type, the compiler will ensure that the type will be
limited to those types that implement a particular trait and thus have the
behavior that we need the types to have. This is called specifying <em>trait
bounds</em> on a generic type.</p>
<p>For example, in Listing 10-12, we implemented the <code>Summarizable</code> trait on the
types <code>NewsArticle</code> and <code>Tweet</code>. We can define a function <code>notify</code> that calls
the <code>summary</code> method on its parameter <code>item</code>, which is of the generic type <code>T</code>.
To be able to call <code>summary</code> on <code>item</code> without getting an error, we can use
trait bounds on <code>T</code> to specify that <code>item</code> must be of a type that implements
the <code>Summarizable</code> trait:</p>
<pre><code class="language-rust,ignore">pub fn notify&lt;T: Summarizable&gt;(item: T) {
println!(&quot;Breaking news! {}&quot;, item.summary());
}
</code></pre>
<p>Trait bounds go with the declaration of the generic type parameter, after a
colon and within the angle brackets. Because of the trait bound on <code>T</code>, we can
call <code>notify</code> and pass in any instance of <code>NewsArticle</code> or <code>Tweet</code>. The
external code from Listing 10-13 that's using our <code>aggregator</code> crate can call
our <code>notify</code> function and pass in an instance of <code>WeatherForecast</code>, since
<code>Summarizable</code> is implemented for <code>WeatherForecast</code> as well. Code that calls
<code>notify</code> with any other type, like a <code>String</code> or an <code>i32</code>, won't compile, since
those types do not implement <code>Summarizable</code>.</p>
<p>We can specify multiple trait bounds on a generic type by using <code>+</code>. If we
needed to be able to use display formatting on the type <code>T</code> in a function as
well as the <code>summary</code> method, we can use the trait bounds <code>T: Summarizable + Display</code>. This means <code>T</code> can be any type that implements both <code>Summarizable</code>
and <code>Display</code>.</p>
<p>For functions that have multiple generic type parameters, each generic has its
own trait bounds. Specifying lots of trait bound information in the angle
brackets between a function's name and its parameter list can get hard to read,
so there's an alternate syntax for specifying trait bounds that lets us move
them to a <code>where</code> clause after the function signature. So instead of:</p>
<pre><code class="language-rust,ignore">fn some_function&lt;T: Display + Clone, U: Clone + Debug&gt;(t: T, u: U) -&gt; i32 {
</code></pre>
<p>We can write this instead with a <code>where</code> clause:</p>
<pre><code class="language-rust,ignore">fn some_function&lt;T, U&gt;(t: T, u: U) -&gt; i32
where T: Display + Clone,
U: Clone + Debug
{
</code></pre>
<p>This is less cluttered and makes this function's signature look more similar to
a function without lots of trait bounds, in that the function name, parameter
list, and return type are close together.</p>
<a class="header" href="#fixing-the-largest-function-with-trait-bounds" name="fixing-the-largest-function-with-trait-bounds"><h3>Fixing the <code>largest</code> Function with Trait Bounds</h3></a>
<p>So any time you want to use behavior defined by a trait on a generic, you need
to specify that trait in the generic type parameter's type bounds. We can now
fix the definition of the <code>largest</code> function that uses a generic type parameter
from Listing 10-5! When we set that code aside, we were getting this error:</p>
<pre><code class="language-text">error[E0369]: binary operation `&gt;` cannot be applied to type `T`
|
5 | if item &gt; largest {
| ^^^^
|
note: an implementation of `std::cmp::PartialOrd` might be missing for `T`
</code></pre>
<p>In the body of <code>largest</code> we wanted to be able to compare two values of type <code>T</code>
using the greater-than operator. That operator is defined as a default method
on the standard library trait <code>std::cmp::PartialOrd</code>. So in order to be able to
use the greater-than operator, we need to specify <code>PartialOrd</code> in the trait
bounds for <code>T</code> so that the <code>largest</code> function will work on slices of any type
that can be compared. We don't need to bring <code>PartialOrd</code> into scope because
it's in the prelude.</p>
<pre><code class="language-rust,ignore">fn largest&lt;T: PartialOrd&gt;(list: &amp;[T]) -&gt; T {
</code></pre>
<p>If we try to compile this, we'll get different errors:</p>
<pre><code class="language-text">error[E0508]: cannot move out of type `[T]`, a non-copy array
--&gt; src/main.rs:4:23
|
4 | let mut largest = list[0];
| ----------- ^^^^^^^ cannot move out of here
| |
| hint: to prevent move, use `ref largest` or `ref mut largest`
error[E0507]: cannot move out of borrowed content
--&gt; src/main.rs:6:9
|
6 | for &amp;item in list.iter() {
| ^----
| ||
| |hint: to prevent move, use `ref item` or `ref mut item`
| cannot move out of borrowed content
</code></pre>
<p>The key to this error is <code>cannot move out of type [T], a non-copy array</code>.
With our non-generic versions of the <code>largest</code> function, we were only trying to
find the largest <code>i32</code> or <code>char</code>. As we discussed in Chapter 4, types like
<code>i32</code> and <code>char</code> that have a known size can be stored on the stack, so they
implement the <code>Copy</code> trait. When we changed the <code>largest</code> function to be
generic, it's now possible that the <code>list</code> parameter could have types in it
that don't implement the <code>Copy</code> trait, which means we wouldn't be able to move
the value out of <code>list[0]</code> and into the <code>largest</code> variable.</p>
<p>If we only want to be able to call this code with types that are <code>Copy</code>, we can
add <code>Copy</code> to the trait bounds of <code>T</code>! Listing 10-15 shows the complete code of
a generic <code>largest</code> function that will compile as long as the types of the
values in the slice that we pass into <code>largest</code> implement both the <code>PartialOrd</code>
and <code>Copy</code> traits, like <code>i32</code> and <code>char</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">use std::cmp::PartialOrd;
fn largest&lt;T: PartialOrd + Copy&gt;(list: &amp;[T]) -&gt; T {
let mut largest = list[0];
for &amp;item in list.iter() {
if item &gt; largest {
largest = item;
}
}
largest
}
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
let result = largest(&amp;numbers);
println!(&quot;The largest number is {}&quot;, result);
let chars = vec!['y', 'm', 'a', 'q'];
let result = largest(&amp;chars);
println!(&quot;The largest char is {}&quot;, result);
}
</code></pre>
<figcaption>
<p>Listing 10-15: A working definition of the <code>largest</code> function that works on any
generic type that implements the <code>PartialOrd</code> and <code>Copy</code> traits</p>
</figcaption>
</figure>
<p>If we don't want to restrict our <code>largest</code> function to only types that
implement the <code>Copy</code> trait, we could specify that <code>T</code> has the trait bound
<code>Clone</code> instead of <code>Copy</code> and clone each value in the slice when we want the
<code>largest</code> function to have ownership. Using the <code>clone</code> function means we're
potentially making more heap allocations, though, and heap allocations can be
slow if we're working with large amounts of data. Another way we could
implement <code>largest</code> is for the function to return a reference to a <code>T</code> value in
the slice. If we change the return type to be <code>&amp;T</code> instead of <code>T</code> and change
the body of the function to return a reference, we wouldn't need either the
<code>Clone</code> or <code>Copy</code> trait bounds and we wouldn't be doing any heap allocations.
Try implementing these alternate solutions on your own!</p>
<p>Traits and trait bounds let us write code that uses generic type parameters in
order to reduce duplication, but still specify to the compiler exactly what
behavior our code needs the generic type to have. Because we've given the trait
bound information to the compiler, it can check that all the concrete types
used with our code provide the right behavior. In dynamically typed languages,
if we tried to call a method on a type that the type didn't implement, we'd get
an error at runtime. Rust moves these errors to compile time so that we're
forced to fix the problems before our code is even able to run. Additionally,
we don't have to write code that checks for behavior at runtime since we've
already checked at compile time, which improves performance compared to other
languages without having to give up the flexibility of generics.</p>
<p>There's another kind of generics that we've been using without even realizing
it called <em>lifetimes</em>. Rather than helping us ensure that a type has the
behavior we need it to have, lifetimes help us ensure that references are valid
as long as we need them to be. Let's learn how lifetimes do that.</p>
<a class="header" href="#validating-references-with-lifetimes" name="validating-references-with-lifetimes"><h2>Validating References with Lifetimes</h2></a>
<p>When we talked about references in Chapter 4, we left out an important detail:
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 and inferred, just
like most of the time types are inferred. Similarly to when we have to annotate
types because multiple types are possible, there are cases where the lifetimes
of references could be related in a few different ways, so Rust needs us to
annotate the relationships using generic lifetime parameters so that it can
make sure the actual references used at runtime will definitely be valid.</p>
<p>Yes, it's a bit unusual, and will be different to tools you've used in other
programming languages. Lifetimes are, in some ways, Rust's most distinctive
feature.</p>
<p>Lifetimes are a big topic that can't be covered in entirety in this chapter, so
we'll cover common ways you might encounter lifetime syntax in this chapter to
get you familiar with the concepts. Chapter 19 will contain more advanced
information about everything lifetimes can do.</p>
<a class="header" href="#lifetimes-prevent-dangling-references" name="lifetimes-prevent-dangling-references"><h3>Lifetimes Prevent Dangling References</h3></a>
<p>The main aim of lifetimes is to prevent dangling references, which will cause a
program to reference data other than the data we're intending to reference.
Consider the program in Listing 10-16, with 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> as 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>
<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-16: An attempt to use a reference whose value has gone out of scope</p>
</figcaption>
</figure>
<blockquote>
<a class="header" href="#uninitialized-variables-cannot-be-used" name="uninitialized-variables-cannot-be-used"><h4>Uninitialized Variables Cannot Be Used</h4></a>
<p>The next few examples declare variables without giving them an initial value,
so that the variable name exists in the outer scope. This might appear to be
in conflict with Rust not having null. However, if we try to use a variable
before giving it a value, we'll get a compile-time error. Try it out!</p>
</blockquote>
<p>When we compile this code, we'll get an error:</p>
<pre><code class="language-text">error: `x` does not live long enough
|
6 | r = &amp;x;
| - borrow occurs here
7 | }
| ^ `x` dropped here while still borrowed
...
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, and
anything we tried to do with <code>r</code> wouldn't work correctly. So how does Rust
determine that this code should not be allowed?</p>
<a class="header" href="#the-borrow-checker" name="the-borrow-checker"><h4>The Borrow Checker</h4></a>
<p>The part of the compiler called the <em>borrow checker</em> compares scopes to
determine that all borrows are valid. Listing 10-17 shows the same example from
Listing 10-16 with annotations showing the lifetimes of the variables:</p>
<figure>
<pre><code class="language-rust,ignore">{
let r; // -------+-- 'a
// |
{ // |
let x = 5; // -+-----+-- 'b
r = &amp;x; // | |
} // -+ |
// |
println!(&quot;r: {}&quot;, r); // |
// |
// -------+
}
</code></pre>
<figcaption>
<p>Listing 10-17: Annotations of the lifetimes of <code>x</code> and <code>r</code>, named <code>'a</code> and <code>'b</code>
respectively</p>
</figcaption>
</figure>
<!-- Just checking I'm reading this right: the inside block is the b lifetime,
correct? I want to leave a note for production, make sure we can make that
clear -->
<!-- Yes, the inside block for the `'b` lifetime starts with the `let x = 5;`
line and ends with the first closing curly brace on the 7th line. Do you think
the text art comments work or should we make an SVG diagram that has nicer
looking arrows and labels? /Carol -->
<p>We've annotated the lifetime of <code>r</code> with <code>'a</code> and the lifetime of <code>x</code> with
<code>'b</code>. As you can see, the inner <code>'b</code> block is much smaller than the outer <code>'a</code>
lifetime block. At compile time, Rust compares the size of the two lifetimes
and sees that <code>r</code> has a lifetime of <code>'a</code>, but that it refers to an object with
a lifetime of <code>'b</code>. The program is rejected because the lifetime <code>'b</code> is
shorter than the lifetime of <code>'a</code>: the subject of the reference does not live
as long as the reference.</p>
<p>Let's look at an example in Listing 10-18 that doesn't try to make a dangling
reference and compiles without any errors:</p>
<figure>
<pre><code class="language-rust">{
let x = 5; // -----+-- 'b
// |
let r = &amp;x; // --+--+-- 'a
// | |
println!(&quot;r: {}&quot;, r); // | |
// --+ |
} // -----+
</code></pre>
<figcaption>
<p>Listing 10-18: A valid reference because the data has a longer lifetime than
the reference</p>
</figcaption>
</figure>
<p>Here, <code>x</code> has the lifetime <code>'b</code>, which in this case is larger than <code>'a</code>. This
means <code>r</code> can reference <code>x</code>: Rust knows that the reference in <code>r</code> will always
be valid while <code>x</code> is valid.</p>
<p>Now that we've shown where the lifetimes of references are in a concrete
example and discussed how Rust analyzes lifetimes to ensure references will
always be valid, let's talk about generic lifetimes of parameters and return
values in the context of functions.</p>
<a class="header" href="#generic-lifetimes-in-functions" name="generic-lifetimes-in-functions"><h3>Generic Lifetimes in Functions</h3></a>
<p>Let's write a function that will return the longest of two string slices. We
want to be able to call this function by passing it two string slices, and we
want to get back a string slice. The code in Listing 10-19 should print <code>The longest string is abcd</code> once we've implemented the <code>longest</code> function:</p>
<figure>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust">fn main() {
let string1 = String::from(&quot;abcd&quot;);
let string2 = &quot;xyz&quot;;
let result = longest(string1.as_str(), string2);
println!(&quot;The longest string is {}&quot;, result);
}
</code></pre>
<figcaption>
<p>Listing 10-19: A <code>main</code> function that calls the <code>longest</code> function to find the
longest of two string slices</p>
</figcaption>
</figure>
<p>Note that we want the function to take string slices (which are references, as
we talked about in Chapter 4) since we don't want the <code>longest</code> function to
take ownership of its arguments. We want the function to be able to accept
slices of a <code>String</code> (which is the type of the variable <code>string1</code>) as well as
string literals (which is what variable <code>string2</code> contains).</p>
<!-- why is `a` a slice and `b` a literal? You mean "a" from the string "abcd"? -->
<!-- I've changed the variable names to remove ambiguity between the variable
name `a` and the "a" from the string "abcd". `string1` is not a slice, it's a
`String`, but we're going to pass a slice that refers to that `String` to the
`longest` function (`string1.as_str()` creates a slice that references the
`String` stored in `string1`). We chose to have `string2` be a literal since
the reader might have code with both `String`s and string literals, and the way
most readers first get into problems with lifetimes is involving string slices,
so we wanted to demonstrate the flexibility of taking string slices as
arguments but the issues you might run into because string slices are
references.
All of the `String`/string slice/string literal concepts here are covered
thoroughly in Chapter 4, which is why we put two back references here (above
and below). If these topics are confusing you in this context, I'd be
interested to know if rereading Chapter 4 clears up that confusion.
/Carol -->
<p>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>If we try to implement the <code>longest</code> function as shown in Listing 10-20, it
won't compile:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<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>
<figcaption>
<p>Listing 10-20: An implementation of the <code>longest</code> function that returns the
longest of two string slices, but does not yet compile</p>
</figcaption>
</figure>
<p>Instead we get the following 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 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 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>!</p>
<p>As we're defining this function, we don't know the concrete values that will be
passed into this function, so we don't know whether the <code>if</code> case or the <code>else</code>
case will execute. We also don't know the concrete lifetimes of the references
that will be passed in, so we can't look at the scopes like we did in Listings
10-17 and 10-18 in order to determine that the reference we return will always
be valid. The borrow checker can't determine this either, because it doesn't
know how the lifetimes of <code>x</code> and <code>y</code> relate to the lifetime of the return
value. We're going to add generic lifetime parameters that will define the
relationship between the references so that the borrow checker can perform its
analysis.</p>
<a class="header" href="#lifetime-annotation-syntax" name="lifetime-annotation-syntax"><h3>Lifetime Annotation Syntax</h3></a>
<p>Lifetime annotations don't 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. What lifetime
annotations do is relate the lifetimes of multiple references to each other.</p>
<p>Lifetime annotations have a slightly unusual syntax: the names of lifetime
parameters must start with an apostrophe <code>'</code>. The names of lifetime parameters
are usually all lowercase, and like generic types, their names are usually very
short. <code>'a</code> is the name most people use as a default. Lifetime parameter
annotations go after the <code>&amp;</code> of a reference, and a space separates the lifetime
annotation from the reference's type.</p>
<p>Here's some examples: we've got a reference to an <code>i32</code> without a lifetime
parameter, a reference to an <code>i32</code> that has a lifetime parameter named <code>'a</code>,
and a mutable reference to an <code>i32</code> that also has the lifetime <code>'a</code>:</p>
<pre><code class="language-rust,ignore">&amp;i32 // a reference
&amp;'a i32 // a reference with an explicit lifetime
&amp;'a mut i32 // a mutable reference with an explicit lifetime
</code></pre>
<p>One lifetime annotation by itself doesn't have much meaning: lifetime
annotations tell Rust how the generic lifetime parameters of multiple
references relate to each other. If we have a function with the parameter
<code>first</code> that is a reference to an <code>i32</code> that has the lifetime <code>'a</code>, and the
function has another parameter named <code>second</code> that is another reference to an
<code>i32</code> that also has the lifetime <code>'a</code>, these two lifetime annotations that have
the same name indicate that the references <code>first</code> and <code>second</code> must both live
as long as the same generic lifetime.</p>
<a class="header" href="#lifetime-annotations-in-function-signatures" name="lifetime-annotations-in-function-signatures"><h3>Lifetime Annotations in Function Signatures</h3></a>
<p>Let's look at lifetime annotations in the context of the <code>longest</code> function
we're working on. Just like generic type parameters, generic lifetime
parameters need to be declared within angle brackets between the function name
and the parameter list. The constraint we want to tell Rust about for the
references in the parameters and the return value is that they all must have
the same lifetime, which we'll name <code>'a</code> and add to each reference as shown in
Listing 10-21:</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
}
}
</code></pre>
<figcaption>
<p>Listing 10-21: The <code>longest</code> function definition that specifies all the
references in the signature must have the same lifetime, <code>'a</code></p>
</figcaption>
</figure>
<p>This will compile and will produce the result we want when used with the <code>main</code>
function in Listing 10-19.</p>
<p>The function signature now says that for some lifetime <code>'a</code>, the function will
get two parameters, both of 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.</p>
<p>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, but only needs to know that there is some scope that
can be substituted for <code>'a</code> that will satisfy this signature.</p>
<p>When annotating lifetimes in functions, the annotations go on the function
signature, and not in any of the code in the function body. This is because
Rust is able to analyze the code within the function without any help, but when
a function has references to or from code outside that function, the lifetimes
of the arguments or return values will potentially be different each time the
function is called. This would be incredibly costly and often impossible for
Rust to figure out. In this case, we need to annotate the lifetimes ourselves.</p>
<p>When concrete references are passed to <code>longest</code>, the concrete lifetime that
gets substituted for <code>'a</code> is the part of the scope of <code>x</code> that overlaps with
the scope of <code>y</code>. Since scopes always nest, another way to say this is that the
generic lifetime <code>'a</code> will get the concrete lifetime equal to the smaller of
the lifetimes of <code>x</code> and <code>y</code>. Because we've annotated the returned reference
with the same lifetime parameter <code>'a</code>, the returned reference will therefore be
guaranteed to be valid as long as the shorter of the lifetimes of <code>x</code> and <code>y</code>.</p>
<p>Let's see how this restricts the usage of the <code>longest</code> function by passing in
references that have different concrete lifetimes. Listing 10-22 is a
straightforward example that should match your intuition from any language:
<code>string1</code> is valid until the end of the outer scope, <code>string2</code> is valid until
the end of the inner scope, and <code>result</code> references something that is valid
until the end of the outer scope. The borrow checker approves of this code; it
will compile and print <code>The longest string is long string is long</code> when run:</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 string1 = String::from(&quot;long string is long&quot;);
{
let string2 = String::from(&quot;xyz&quot;);
let result = longest(string1.as_str(), string2.as_str());
println!(&quot;The longest string is {}&quot;, result);
}
}
</code></pre>
<figcaption>
<p>Listing 10-22: Using the <code>longest</code> function with references to <code>String</code> values
that have different concrete lifetimes</p>
</figcaption>
</figure>
<p>Next, let's try an example that will show that the lifetime of the reference in
<code>result</code> must be the smaller lifetime of the two arguments. We'll move the
declaration of the <code>result</code> variable outside the inner scope, but leave the
assignment of the value to the <code>result</code> variable inside the scope with
<code>string2</code>. Next, we'll move the <code>println!</code> that uses <code>result</code> outside of the
inner scope, after it has ended. The code in Listing 10-23 will not compile:</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 string1 = String::from(&quot;long string is long&quot;);
let result;
{
let string2 = String::from(&quot;xyz&quot;);
result = longest(string1.as_str(), string2.as_str());
}
println!(&quot;The longest string is {}&quot;, result);
}
</code></pre>
<figcaption>
<p>Listing 10-23: Attempting to use <code>result</code> after <code>string2</code> has gone out of scope
won't compile</p>
</figcaption>
</figure>
<p>If we try to compile this, we'll get this error:</p>
<pre><code class="language-text">error: `string2` does not live long enough
|
6 | result = longest(string1.as_str(), string2.as_str());
| ------- borrow occurs here
7 | }
| ^ `string2` dropped here while still borrowed
8 | println!(&quot;The longest string is {}&quot;, result);
9 | }
| - borrowed value needs to live until here
</code></pre>
<p>The error is saying that in order for <code>result</code> to be valid for the <code>println!</code>,
<code>string2</code> would need to be valid until the end of the outer scope. Rust knows
this because we annotated the lifetimes of the function parameters and return
values with the same lifetime parameter, <code>'a</code>.</p>
<p>We can look at this code as humans and see that <code>string1</code> is longer, and
therefore <code>result</code> will contain a reference to <code>string1</code>. Because <code>string1</code> has
not gone out of scope yet, a reference to <code>string1</code> will still be valid for the
<code>println!</code>. However, what we've told Rust with the lifetime parameters is that
the lifetime of the reference returned by the <code>longest</code> function is the same as
the smaller of the lifetimes of the references passed in. Therefore, the borrow
checker disallows the code in Listing 10-23 as possibly having an invalid
reference.</p>
<p>Try designing some more experiments that vary the values and lifetimes of the
references passed in to the <code>longest</code> function and how the returned reference
is used. Make hypotheses about whether your experiments will pass the borrow
checker or not before you compile, then check to see if you're right!</p>
<a class="header" href="#thinking-in-terms-of-lifetimes" name="thinking-in-terms-of-lifetimes"><h3>Thinking in Terms of Lifetimes</h3></a>
<p>The exact way to specify lifetime parameters depends on what your function is
doing. For example, if we changed the implementation of the <code>longest</code> function
to always return the first argument rather than the longest string slice, we
wouldn't need to specify a lifetime on the <code>y</code> parameter. 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>In this example, we've specified a lifetime parameter <code>'a</code> for the parameter
<code>x</code> and the return type, but not for the parameter <code>y</code>, since the lifetime of
<code>y</code> does not have any relationship with the lifetime of <code>x</code> or the return value.</p>
<p>When returning a reference from a function, the lifetime parameter for the
return type needs to match the lifetime parameter of one of the arguments. 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, which
would be a dangling reference since the value will go out of scope at the end
of the function. Consider this attempted implementation of the <code>longest</code>
function that won't compile:</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 parameter <code>'a</code> for the return type, this
implementation fails to compile because the return value lifetime is not
related to the lifetime of the parameters at all. Here's the error message we
get:</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>
<a class="header" href="#lifetime-annotations-in-struct-definitions" name="lifetime-annotations-in-struct-definitions"><h3>Lifetime Annotations in Struct Definitions</h3></a>
<p>Up until now, we've only defined structs to hold owned types. It is possible
for structs to hold references, but we need to add a lifetime annotation on
every reference in the struct's definition. Listing 10-24 has a struct named
<code>ImportantExcerpt</code> that holds a string slice:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">struct ImportantExcerpt&lt;'a&gt; {
part: &amp;'a str,
}
fn main() {
let novel = String::from(&quot;Call me Ishmael. Some years ago...&quot;);
let first_sentence = novel.split('.')
.next()
.expect(&quot;Could not find a '.'&quot;);
let i = ImportantExcerpt { part: first_sentence };
}
</code></pre>
<figcaption>
<p>Listing 10-24: A struct that holds a reference, so its definition needs a
lifetime annotation</p>
</figcaption>
</figure>
<p>This struct has one field, <code>part</code>, that holds a string slice, which is a
reference. Just like with generic data types, we have to declare the name of
the generic lifetime parameter inside angle brackets after the name of the
struct so that we can use the lifetime parameter in the body of the struct
definition.</p>
<p>The <code>main</code> function here creates an instance of the <code>ImportantExcerpt</code> struct
that holds a reference to the first sentence of the <code>String</code> owned by the
variable <code>novel</code>.</p>
<a class="header" href="#lifetime-elision" name="lifetime-elision"><h3>Lifetime Elision</h3></a>
<p>In this section, we've learned that every reference has a lifetime, and we need
to specify lifetime parameters for functions or structs that use references.
However, in Chapter 4 we had a function in the &quot;String Slices&quot; section, shown
again in Listing 10-25, that compiled without lifetime annotations:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<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>
<figcaption>
<p>Listing 10-25: A function we defined in Chapter 4 that compiled without
lifetime annotations, even though the parameter and return type are references</p>
</figcaption>
</figure>
<p>The reason this function compiles without lifetime annotations is historical:
in early versions of pre-1.0 Rust, this indeed wouldn't 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, the Rust team found that Rust programmers
were typing the same lifetime annotations over and over in particular
situations. These situations were predictable and followed a few deterministic
patterns. The Rust team then programmed these patterns into the Rust compiler's
code so that the borrow checker can infer the lifetimes in these situations
without forcing the programmer to explicitly add the annotations.</p>
<p>We mention this piece of Rust history because it's entirely possible that more
deterministic patterns will emerge and be added to the compiler. In the future,
even fewer lifetime annotations might be required.</p>
<p>The patterns programmed into Rust's analysis of references are called the
<em>lifetime elision rules</em>. These aren't rules for programmers to follow; the
rules are a set of particular cases that the compiler will consider, and if
your code fits these cases, you don't need to write the lifetimes explicitly.</p>
<p>The elision rules don't provide full inference: if Rust deterministically
applies the rules but there's still ambiguity as to what lifetimes the
references have, it won't guess what the lifetime of the remaining references
should be. In this case, the compiler will give you an error that can be
resolved by adding the lifetime annotations that correspond to your intentions
for how the references relate to each other.</p>
<p>First, some definitions: Lifetimes on function or method parameters are called
<em>input lifetimes</em>, and lifetimes on return values are called <em>output lifetimes</em>.</p>
<p>Now, on to the rules that the compiler uses to figure out what lifetimes
references have when there aren't explicit annotations. The first rule applies
to input lifetimes, and the second two rules apply to output lifetimes. If the
compiler gets to the end of the three rules and there are still references that
it can't figure out lifetimes for, the compiler will stop with an error.</p>
<ol>
<li>
<p>Each parameter that is a reference gets its own lifetime parameter. In other
words, a function with one parameter 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.</p>
</li>
<li>
<p>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>.</p>
</li>
<li>
<p>If there are multiple input lifetime parameters, but one of them is <code>&amp;self</code>
or <code>&amp;mut self</code> because this is a method, then the lifetime of <code>self</code> is
assigned to all output lifetime parameters. This makes writing methods much
nicer.</p>
</li>
</ol>
<p>Let's pretend we're the compiler and apply these rules to figure out what the
lifetimes of the references in the signature of the <code>first_word</code> function in
Listing 10-25 are. The signatures starts without any lifetimes associated with
the references:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Then we (as the compiler) apply the first rule, which says each parameter gets
its own lifetime. We're going to call it <code>'a</code> as usual, so now the signature is:</p>
<pre><code class="language-rust,ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;str {
</code></pre>
<p>On to the second rule, which applies because there is exactly one input
lifetime. The second rule says the lifetime of the one input parameter gets
assigned to the output lifetime, so now the signature is:</p>
<pre><code class="language-rust,ignore">fn first_word&lt;'a&gt;(s: &amp;'a str) -&gt; &amp;'a str {
</code></pre>
<p>Now all the references in this function signature have lifetimes, and the
compiler can continue its analysis without needing the programmer to annotate
the lifetimes in this function signature.</p>
<p>Let's do another example, this time with the <code>longest</code> function that had no
lifetime parameters when we started working with in Listing 10-20:</p>
<pre><code class="language-rust,ignore">fn longest(x: &amp;str, y: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Pretending we're the compiler again, let's apply the first rule: each parameter
gets its own lifetime. This time we have two parameters, so we have two
lifetimes:</p>
<pre><code class="language-rust,ignore">fn longest&lt;'a, 'b&gt;(x: &amp;'a str, y: &amp;'b str) -&gt; &amp;str {
</code></pre>
<p>Looking at the second rule, it doesn't apply since there is more than one input
lifetime. Looking at the third rule, this also does not apply because this is a
function rather than a method, so none of the parameters are <code>self</code>. So we're
out of rules, but we haven't figured out what the return type's lifetime is.
This is why we got an error trying to compile the code from Listing 10-20: the
compiler worked through the lifetime elision rules it knows, but still can't
figure out all the lifetimes of the references in the signature.</p>
<p>Because the third rule only really applies in method signatures, let's look at
lifetimes in that context now, and see why the third rule means we don't have
to annotate lifetimes in method signatures very often.</p>
<a class="header" href="#lifetime-annotations-in-method-definitions" name="lifetime-annotations-in-method-definitions"><h3>Lifetime Annotations in Method Definitions</h3></a>
<!-- Is this different to the reference lifetime annotations, or just a
finalized explanation? -->
<!-- This is about lifetimes on references in method signatures, which is where
the 3rd lifetime elision rule kicks in. It can also be confusing where lifetime
parameters need to be declared and used since the lifetime parameters could go
with the struct's fields or with references passed into or returned from
methods. /Carol -->
<p>When we implement methods on a struct with lifetimes, the syntax is again the
same as that of generic type parameters that we showed in Listing 10-10: the
place that lifetime parameters are declared and used depends on whether the
lifetime parameter is related to the struct fields or the method arguments and
return values.</p>
<p>Lifetime names for struct fields always need to be declared after the <code>impl</code>
keyword and then used after the struct's name, since those lifetimes are part
of the struct's type.</p>
<p>In method signatures inside the <code>impl</code> block, references might be tied to the
lifetime of references in the struct's fields, or they might be independent. In
addition, the lifetime elision rules often make it so that lifetime annotations
aren't necessary in method signatures. Let's look at some examples using the
struct named <code>ImportantExcerpt</code> that we defined in Listing 10-24.</p>
<p>First, here's a method named <code>level</code>. The only parameter is a reference to
<code>self</code>, and the return value is just an <code>i32</code>, not a reference to anything:</p>
<pre><code class="language-rust"># struct ImportantExcerpt&lt;'a&gt; {
# part: &amp;'a str,
# }
#
impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn level(&amp;self) -&gt; i32 {
3
}
}
</code></pre>
<p>The lifetime parameter declaration after <code>impl</code> and use after the type name is
required, but we're not required to annotate the lifetime of the reference to
<code>self</code> because of the first elision rule.</p>
<p>Here's an example where the third lifetime elision rule applies:</p>
<pre><code class="language-rust"># struct ImportantExcerpt&lt;'a&gt; {
# part: &amp;'a str,
# }
#
impl&lt;'a&gt; ImportantExcerpt&lt;'a&gt; {
fn announce_and_return_part(&amp;self, announcement: &amp;str) -&gt; &amp;str {
println!(&quot;Attention please: {}&quot;, announcement);
self.part
}
}
</code></pre>
<p>There are two input lifetimes, so Rust applies the first lifetime elision rule
and gives both <code>&amp;self</code> and <code>announcement</code> their own lifetimes. Then, because
one of the parameters is <code>&amp;self</code>, the return type gets the lifetime of <code>&amp;self</code>,
and all lifetimes have been accounted for.</p>
<a class="header" href="#the-static-lifetime" name="the-static-lifetime"><h3>The Static Lifetime</h3></a>
<p>There is <em>one</em> special lifetime we need to discuss: <code>'static</code>. The <code>'static</code>
lifetime is the entire duration of the program. All string literals have the
<code>'static</code> lifetime, which we can choose to annotate as follows:</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>.</p>
<!-- How would you add a static lifetime (below)? -->
<!-- Just like you'd specify any lifetime, see above where it shows `&'static str`. /Carol -->
<p>You may see suggestions to use the <code>'static</code> lifetime in error message help
text, but before specifying <code>'static</code> as the lifetime for a reference, 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>
<a class="header" href="#generic-type-parameters-trait-bounds-and-lifetimes-together" name="generic-type-parameters-trait-bounds-and-lifetimes-together"><h3>Generic Type Parameters, Trait Bounds, and Lifetimes Together</h3></a>
<p>Let's briefly look at the syntax of specifying generic type parameters, trait
bounds, and lifetimes all in one function!</p>
<pre><code class="language-rust">use std::fmt::Display;
fn longest_with_an_announcement&lt;'a, T&gt;(x: &amp;'a str, y: &amp;'a str, ann: T) -&gt; &amp;'a str
where T: Display
{
println!(&quot;Announcement! {}&quot;, ann);
if x.len() &gt; y.len() {
x
} else {
y
}
}
</code></pre>
<p>This is the <code>longest</code> function from Listing 10-21 that returns the longest of
two string slices, but with an extra argument named <code>ann</code>. The type of <code>ann</code> is
the generic type <code>T</code>, which may be filled in by any type that implements the
<code>Display</code> trait as specified by the <code>where</code> clause. This extra argument will be
printed out before the function compares the lengths of the string slices,
which is why the <code>Display</code> trait bound is necessary. Because lifetimes are a
type of generic, the declarations of both the lifetime parameter <code>'a</code> and the
generic type parameter <code>T</code> go in the same list within the angle brackets after
the function name.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<p>We covered a lot in this chapter! Now that you know about generic type
parameters, traits and trait bounds, and generic lifetime parameters, you're
ready to write code that isn't duplicated but can be used in many different
situations. Generic type parameters mean the code can be applied to different
types. Traits and trait bounds ensure that even though the types are generic,
those types will have the behavior the code needs. Relationships between the
lifetimes of references specified by lifetime annotations ensure that this
flexible code won't have any dangling references. And all of this happens at
compile time so that run-time performance isn't affected!</p>
<p>Believe it or not, there's even more to learn in these areas: Chapter 17 will
discuss trait objects, which are another way to use traits. Chapter 19 will be
covering more complex scenarios involving lifetime annotations. Chapter 20 will
get to some advanced type system features. Up next, though, let's talk about
how to write tests in Rust so that we can make sure our code using all these
features is working the way we want it to!</p>
<a class="header" href="#testing" name="testing"><h1>Testing</h1></a>
<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 has
an integer as a parameter 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 parameter plus two and
not the parameter plus 10 or the parameter 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>
<a class="header" href="#writing-tests" name="writing-tests"><h2>Writing Tests</h2></a>
<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>
<a class="header" href="#the-test-attribute" name="the-test-attribute"><h3>The <code>test</code> attribute</h3></a>
<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-abcabcabc
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>
<a class="header" href="#the-assert-macro" name="the-assert-macro"><h3>The <code>assert!</code> macro</h3></a>
<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-abcabcabc
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>
<a class="header" href="#testing-equality-with-the-assert_eq-and-assert_ne-macros" name="testing-equality-with-the-assert_eq-and-assert_ne-macros"><h3>Testing equality with the <code>assert_eq!</code> and <code>assert_ne!</code> macros</h3></a>
<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 because <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 parameters 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>
<a class="header" href="#test-for-failure-with-should_panic" name="test-for-failure-with-should_panic"><h2>Test for failure with <code>should_panic</code></h2></a>
<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>
<a class="header" href="#running-tests" name="running-tests"><h2>Running tests</h2></a>
<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>
<a class="header" href="#tests-run-in-parallel" name="tests-run-in-parallel"><h3>Tests Run in Parallel</h3></a>
<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>
<a class="header" href="#tests-capture-output" name="tests-capture-output"><h3>Tests Capture Output</h3></a>
<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>
<a class="header" href="#running-a-subset-of-tests-by-name" name="running-a-subset-of-tests-by-name"><h3>Running a Subset of Tests by Name</h3></a>
<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-abcabcabc
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-abcabcabc
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-abcabcabc
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-abcabcabc
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-abcabcabc
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>
<a class="header" href="#ignore-some-tests-unless-specifically-requested" name="ignore-some-tests-unless-specifically-requested"><h3>Ignore Some Tests Unless Specifically Requested</h3></a>
<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-abcabcabc
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-abcabcabc
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>
<a class="header" href="#test-organization" name="test-organization"><h2>Test Organization</h2></a>
<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>
<a class="header" href="#unit-tests" name="unit-tests"><h3>Unit Tests</h3></a>
<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>
<a class="header" href="#the-tests-module-and-cfgtest" name="the-tests-module-and-cfgtest"><h4>The Tests Module and <code>cfg(test)</code></h4></a>
<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>
<a class="header" href="#testing-private-functions" name="testing-private-functions"><h4>Testing Private Functions</h4></a>
<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>
<a class="header" href="#integration-tests" name="integration-tests"><h3>Integration Tests</h3></a>
<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>
<a class="header" href="#the-tests-directory" name="the-tests-directory"><h4>The <em>tests</em> Directory</h4></a>
<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-abcabcabc
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>
<a class="header" href="#submodules-in-integration-tests" name="submodules-in-integration-tests"><h4>Submodules in Integration Tests</h4></a>
<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>
<a class="header" href="#integration-tests-for-binary-crates" name="integration-tests-for-binary-crates"><h4>Integration Tests for Binary Crates</h4></a>
<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>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<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>
<a class="header" href="#an-io-project" name="an-io-project"><h1>An I/O Project</h1></a>
<p>We've learned a lot over the last few chapters. Let's take that new knowledge
and apply it by building a project together. Along the way, we'll learn a bit
more about Rust's standard library.</p>
<p>So what should we build? One that uses Rust's strengths. A great use of Rust is
for command line tools: Rust's speed, safety, 'single binary' output, and
cross-platform support make it a good language choice for this kind of task. So
we'll make our own version of a classic command line tool: <code>grep</code>. <code>grep</code> is
short for &quot;Globally search a Regular Expression and Print.&quot; In the
simplest use case, it does this:</p>
<ol>
<li>Takes a filename and a string as arguments.</li>
<li>Reads the file.</li>
<li>Finds lines in the file that contain the string argument.</li>
<li>Prints out those lines.</li>
</ol>
<p>In addition, we'll add one extra feature: an environment variable that will
allow us to search for the string argument in a case-insensitive way.</p>
<p>There's another great reason to use <code>grep</code> as an example project: a very
fully-featured version of <code>grep</code> has already been created in Rust by a
community member, Andrew Gallant. It's called <code>ripgrep</code>, and it's very,
very fast. While our version of <code>grep</code> will be fairly simple, you'll have
some of the background knowledge to understand that project if you want to see
something more real-world.</p>
<p>This project will bring together a number of things we learned previously:</p>
<ul>
<li>Organize code (using what we learned in modules, Chapter 7)</li>
<li>Use vectors and strings (collections, Chapter 8)</li>
<li>Handle errors (Chapter 9)</li>
<li>Use traits and lifetimes where appropriate (Chapter 10)</li>
<li>Have tests (Chapter 11)</li>
</ul>
<p>Additionally, we'll briefly introduce closures, iterators, and trait objects,
which Chapters XX, YY, and ZZ respectively are about to cover in detail.</p>
<p>Let's create a new project with, as always, <code>cargo new</code>:</p>
<pre><code class="language-text">$ cargo new --bin greprs
Created binary (application) `greprs` project
$ cd greprs
</code></pre>
<p>We're calling our version of <code>grep</code> 'greprs', so that we don't confuse any of
our users into thinking that it's the more fully-featured version of <code>grep</code>
they may already have installed on their system.</p>
<a class="header" href="#accepting-command-line-arguments" name="accepting-command-line-arguments"><h2>Accepting Command Line Arguments</h2></a>
<p>Our first task is to have <code>greprs</code> accept its two command line arguments. There
are some existing libraries on crates.io that can help us do this, but since
we're learning, we'll implement this ourselves.</p>
<p>We'll need to call a function provided in Rust's standard library:
<code>std::env::args</code>. This function returns an <em>iterator</em> of the command line
arguments that were given to our program. We haven't discussed iterators yet;
Chapter 13 will cover them fully. For our purposes, though, we don't need to
understand much about how they work in order to use them. We only need to
understand two things:</p>
<ol>
<li>Iterators produce a series of values.</li>
<li>We can call the <code>collect</code> function on an iterator to turn it into a vector
containing all of the elements the iterator produces.</li>
</ol>
<p>Let's give it a try as shown in Listing 12-1:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">use std::env;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
println!(&quot;{:?}&quot;, args);
}
</code></pre>
<figcaption>
<p>Listing 12-1: Collect the command line arguments into a vector and print them out</p>
</figcaption>
</figure>
<!-- Will add wingdings in libreoffice /Carol -->
<p>First, we have a <code>use</code> statement to bring the <code>std::env</code> module into scope.
When using a function that's nested in more than one level of module, like
<code>std::env::args</code> is, it's conventional to use <code>use</code> to bring the parent module
into scope, rather than the function itself. <code>env::args</code> is less ambiguous than
a lone <code>args</code>. Also, if we end up using more than one function in <code>std::env</code>,
we only need a single <code>use</code>.</p>
<p>On the first line of <code>main</code>, we call <code>env::args</code>, and immediately use <code>collect</code>
to create a vector out of it. We're also explicitly annotating the type of
<code>args</code> here: <code>collect</code> can be used to create many kinds of collections. Rust
won't be able to infer what kind of type we want, so the annotation is
required. We very rarely need to annotate types in Rust, but <code>collect</code> is one
function where you often need to.</p>
<p>Finally, we print out the vector with the debug formatter, <code>:?</code>. Let's try
running our code with no arguments, and then with two arguments:</p>
<pre><code class="language-text">$ cargo run
[&quot;target/debug/greprs&quot;]
$ cargo run needle haystack
...snip...
[&quot;target/debug/greprs&quot;, &quot;needle&quot;, &quot;haystack&quot;]
</code></pre>
<p>You'll notice one interesting thing: the name of the binary is the first
argument. The reasons for this are out of the scope of this chapter, but it's
something we'll have to remember to account for.</p>
<p>Now that we have a way to access all of the arguments, let's find the ones we
care about and save them in variables as shown in Listing 12-2:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">use std::env;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let search = &amp;args[1];
let filename = &amp;args[2];
println!(&quot;Searching for {}&quot;, search);
println!(&quot;In file {}&quot;, filename);
}
</code></pre>
<figcaption>
<p>Listing 12-2: Create variables to hold the search argument and filename argument</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Remember, the program's name is the first argument, so we don't need <code>args[0]</code>.
We've decided that the first argument will be the string we're searching for,
so we put a reference to the first argument in the variable <code>search</code>. The
second argument will be the filename, so we put a reference to the second
argument in the variable <code>filename</code>. Let's try running this program again:</p>
<pre><code class="language-text">$ cargo run test sample.txt
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe test sample.txt`
Searching for test
In file sample.txt
</code></pre>
<p>Great! There's one problem, though. Let's try giving it no arguments:</p>
<pre><code class="language-text">$ cargo run
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe`
thread 'main' panicked at 'index out of bounds: the len is 1
but the index is 1', ../src/libcollections\vec.rs:1307
note: Run with `RUST_BACKTRACE=1` for a backtrace.
</code></pre>
<p>Because our vector only has one element, the program's name, but we tried to
access the second element, our program panics with a message about the
out-of-bound access. While this error message is <em>accurate</em>, it's not
meaningful to users of our program at all. We could fix this problem right now,
but let's push forward: we'll improve this situation before we're finished.</p>
<a class="header" href="#reading-a-file" name="reading-a-file"><h2>Reading a File</h2></a>
<p>Now that we have some variables containing the information that we need, let's
try using them. The next step is to open the file that we want to search. To do
that, we need a file. Create one called <code>poem.txt</code> at the root level of your
project, and fill it up with some Emily Dickinson:</p>
<p><span class="filename">Filename: poem.txt</span></p>
<pre><code class="language-text">I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us — don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<!-- Public domain Emily Dickinson poem. This will work best with something
short, but that has multiple lines and some repetition. We could search through
code; that gets a bit meta and possibly confusing... Changes to this are most
welcome. /Carol -->
<p>With that in place, let's edit <em>src/main.rs</em> and add code to open the file as
shown in Listing 12-3:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">use std::env;
use std::fs::File;
use std::io::prelude::*;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let search = &amp;args[1];
let filename = &amp;args[2];
println!(&quot;Searching for {}&quot;, search);
println!(&quot;In file {}&quot;, filename);
let mut f = File::open(filename).expect(&quot;file not found&quot;);
let mut contents = String::new();
f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
println!(&quot;With text:\n{}&quot;, contents);
}
</code></pre>
<figcaption>
<p>Listing 12-3: Read the contents of the file specified by the second argument</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>We've added a few things. First of all, we need some more <code>use</code> statements to
bring in the relevant parts of the standard library: we need <code>std::fs::File</code>
for dealing with files, and <code>std::io::prelude::*</code> contains various traits that
are useful when doing I/O, including file I/O. In the same way that Rust has a
general prelude that brings certain things into scope automatically, the
<code>std::io</code> module has its own prelude of common things you'll need when working
with I/O. Unlike the default prelude, we must explicitly <code>use</code> the prelude in
<code>std::io</code>.</p>
<p>In <code>main</code>, we've added three things: first, we get a handle to the file and
open it by using the <code>File::open</code> function and passing it the name of the file
specified in the second argument. Second, we create a mutable, empty <code>String</code>
in the variable <code>contents</code>, then call <code>read_to_string</code> on our file handle with
our <code>contents</code> string as the argument; <code>contents</code> is where <code>read_to_string</code>
will place the data it reads. Finally, we print out the entire file contents,
which is a way for us to be sure our program is working so far.</p>
<p>Let's try running this code, specifying any string for the first argument (since
we haven't implemented the searching part yet) and our <em>poem.txt</em> file as the
second argument:</p>
<pre><code class="language-text">$ cargo run the poem.txt
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us — don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>Great! Our code is working. However, it's got a few flaws. Because our program
is still small, these flaws aren't a huge deal, but as our program grows, it
will be harder and harder to fix them in a clean way. Let's do the refactoring
now, instead of waiting. The refactoring will be much easier to do with only
this small amount of code.</p>
<a class="header" href="#improving-error-handling-and-modularity" name="improving-error-handling-and-modularity"><h2>Improving Error Handling and Modularity</h2></a>
<p>There are four problems that we'd like to fix to improve our program, and they
all have to do with potential errors and the way the program is structured. The
first problem is where we open the file: we've used <code>expect</code> to print out an
error message if opening the file fails, but the error message only says &quot;file
not found&quot;. There are a number of ways that opening a file can fail, but we're
always assuming that it's due to the file being missing. For example, the file
could exist, but we might not have permission to open it: right now, we print
an error message that says the wrong thing!</p>
<p>Secondly, our use of <code>expect</code> over and over is similar to the earlier issue we
noted with the <code>panic!</code> on indexing if we don't pass any command line
arguments: while it <em>works</em>, it's a bit unprincipled, and we're doing it all
throughout our program. It would be nice to put our error handling in one spot.</p>
<p>The third problem is that our <code>main</code> function now does two things: it parses
arguments, and it opens up files. For such a small function, this isn't a huge
problem. However, as we keep growing our program inside of <code>main</code>, the number of
separate tasks in the <code>main</code> function will get larger and larger. As one
function gains many responsibilities, it gets harder to reason about, harder to
test, and harder to change without breaking one of its parts.</p>
<p>This also ties into our fourth problem: while <code>search</code> and <code>filename</code> are
configuration variables to our program, variables like <code>f</code> and <code>contents</code> are
used to perform our program's logic. The longer <code>main</code> gets, the more variables
we're going to bring into scope, and the more variables we have in scope, the
harder it is to keep track of which ones we need for which purpose. It would be
better if we grouped the configuration variables into one structure to make
their purpose clear.</p>
<p>Let's address these problems by restructuring our project.</p>
<a class="header" href="#separation-of-concerns-for-binary-projects" name="separation-of-concerns-for-binary-projects"><h3>Separation of Concerns for Binary Projects</h3></a>
<p>These kinds of organizational problems are common to many similar kinds of
projects, so the Rust community has developed a pattern for organizing the
separate concerns. This pattern is useful for organizing any binary project
you'll build in Rust, so we can justify doing this refactoring a bit earlier,
since we know that our project fits the pattern. The pattern looks like this:</p>
<ol>
<li>Split your program into both a <em>main.rs</em> and a <em>lib.rs</em>.</li>
<li>Place your command line parsing logic into <em>main.rs</em>.</li>
<li>Place your program's logic into <em>lib.rs</em>.</li>
<li>The job of the <code>main</code> function is:
<ul>
<li>parse arguments</li>
<li>set up any other configuration</li>
<li>call a <code>run</code> function in <em>lib.rs</em></li>
<li>if <code>run</code> returns an error, handle that error</li>
</ul>
</li>
</ol>
<p>Whew! The pattern sounds more complicated than it is, honestly. It's all about
separating concerns: <em>main.rs</em> handles actually running the program, and
<em>lib.rs</em> handles all of the actual logic of the task at hand. Let's re-work our
program into this pattern. First, let's extract a function whose purpose is
only to parse arguments. Listing 12-4 shows the new start of <code>main</code> that calls
a new function <code>parse_config</code>, which we're still going to define in
<em>src/main.rs</em>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let (search, filename) = parse_config(&amp;args);
println!(&quot;Searching for {}&quot;, search);
println!(&quot;In file {}&quot;, filename);
// ...snip...
#
# let mut f = File::open(filename).expect(&quot;file not found&quot;);
#
# let mut contents = String::new();
# f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
#
# println!(&quot;With text:\n{}&quot;, contents);
}
fn parse_config(args: &amp;[String]) -&gt; (&amp;str, &amp;str) {
let search = &amp;args[1];
let filename = &amp;args[2];
(search, filename)
}
</code></pre>
<figcaption>
<p>Listing 12-4: Extract a <code>parse_config</code> function from <code>main</code></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>This may seem like overkill, but we're working in small steps. After making
this change, run the program again to verify that the argument parsing still
works. It's good to check your progress often, so that you have a better idea
of which change caused a problem, should you encounter one.</p>
<a class="header" href="#grouping-configuration-values" name="grouping-configuration-values"><h3>Grouping Configuration Values</h3></a>
<p>Now that we have a function, let's improve it. Our code still has an indication
that there's a better design possible: we return a tuple, but then immediately
break that tuple up into individual parts again. This code isn't bad on its
own, but there's one other sign we have room for improvement: we called our
function <code>parse_config</code>. The <code>config</code> part of the name is saying the two values
we return should really be bound together, since they're both part of one
configuration value.</p>
<blockquote>
<p>Note: some people call this anti-pattern of using primitive values when a
complex type would be more appropriate <em>primitive obsession</em>.</p>
</blockquote>
<p>Let's introduce a struct to hold all of our configuration. Listing 12-5 shows
the addition of the <code>Config</code> struct definition, the refactoring of
<code>parse_config</code>, and updates to <code>main</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = parse_config(&amp;args);
println!(&quot;Searching for {}&quot;, config.search);
println!(&quot;In file {}&quot;, config.filename);
let mut f = File::open(config.filename).expect(&quot;file not found&quot;);
// ...snip...
# let mut contents = String::new();
# f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
#
# println!(&quot;With text:\n{}&quot;, contents);
}
struct Config {
search: String,
filename: String,
}
fn parse_config(args: &amp;[String]) -&gt; Config {
let search = args[1].clone();
let filename = args[2].clone();
Config {
search: search,
filename: filename,
}
}
</code></pre>
<figcaption>
<p>Listing 12-5: Refactoring <code>parse_config</code> to return an instance of a <code>Config</code>
struct</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>The signature of <code>parse_config</code> now indicates that it returns a <code>Config</code> value.
In the body of <code>parse_config</code>, we used to be returning string slices that were
references to <code>String</code> values in <code>args</code>, but we've defined <code>Config</code> to contain
owned <code>String</code> values. Because the argument to <code>parse_config</code> is a slice of
<code>String</code> values, the <code>Config</code> instance can't take ownership of the <code>String</code>
values: that violates Rust's borrowing rules, since the <code>args</code> variable in
<code>main</code> owns the <code>String</code> values and is only letting the <code>parse_config</code> function
borrow them.</p>
<p>There are a number of different ways we could manage the <code>String</code> data; for
now, we'll take the easy but less efficient route, and call the <code>clone</code> method
on the string slices. The call to <code>clone</code> will make a full copy of the string's
data for the <code>Config</code> instance to own, which does take more time and memory
than storing a reference to the string data, but cloning the data makes our
code very straightforward.</p>
<!-- PROD: START BOX -->
<blockquote>
<a class="header" href="#the-tradeoffs-of-using-clone" name="the-tradeoffs-of-using-clone"><h4>The Tradeoffs of Using <code>clone</code></h4></a>
<p>There's a tendency amongst many Rustaceans to prefer not to use <code>clone</code> to fix
ownership problems due to its runtime cost. In Chapter XX on iterators, we'll
learn how to make this situation more efficient. For now, it's okay to copy a
few strings to keep making progress. We're only going to be making these
copies once, and our filename and search string are both very small. It's
better to have a working program that's a bit inefficient than try to
hyper-optimize code on your first pass. As you get more experienced with Rust,
it'll be easier to skip this step, but for now, it's perfectly acceptable to
call <code>clone</code>.</p>
</blockquote>
<!-- PROD: END BOX -->
<p>We've updated <code>main</code> to put the instance of <code>Config</code> that <code>parse_config</code>
returns in a variable named <code>config</code>, and we've updated the code that was using
the separate <code>search</code> and <code>filename</code> variables to use the fields on the
<code>Config</code> struct instead.</p>
<a class="header" href="#creating-a-constructor-for-config" name="creating-a-constructor-for-config"><h3>Creating a Constructor for <code>Config</code></h3></a>
<p>Let's now think about the purpose of <code>parse_config</code>: it's a function that
creates a <code>Config</code> instance. We've already seen a convention for functions that
create instances: a <code>new</code> function, like <code>String::new</code>. Listing 12-6 shows the
result of transforming <code>parse_config</code> into a <code>new</code> function associated with our
<code>Config</code> struct:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::new(&amp;args);
println!(&quot;Searching for {}&quot;, config.search);
println!(&quot;In file {}&quot;, config.filename);
// ...snip...
# let mut f = File::open(config.filename).expect(&quot;file not found&quot;);
#
# let mut contents = String::new();
# f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
#
# println!(&quot;With text:\n{}&quot;, contents);
}
# struct Config {
# search: String,
# filename: String,
# }
#
// ...snip...
impl Config {
fn new(args: &amp;[String]) -&gt; Config {
let search = args[1].clone();
let filename = args[2].clone();
Config {
search: search,
filename: filename,
}
}
}
</code></pre>
<figcaption>
<p>Listing 12-6: Changing <code>parse_config</code> into <code>Config::new</code></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>We've changed the name of <code>parse_config</code> to <code>new</code> and moved it within an <code>impl</code>
block. We've also updated the callsite in <code>main</code>. Try compiling this again to
make sure it works.</p>
<a class="header" href="#returning-a-result-from-the-constructor" name="returning-a-result-from-the-constructor"><h3>Returning a <code>Result</code> from the Constructor</h3></a>
<p>Here's our last refactoring of this method: remember how accessing the vector
with indices 1 and 2 panics when it contains fewer than 3 items and gives a bad
error message? Let's fix that! Listing 12-7 shows how we can check that our
slice is long enough before accessing those locations, and panic with a better
error message:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
# fn main() {
# let args: Vec&lt;String&gt; = env::args().collect();
#
# let config = Config::new(&amp;args);
#
# println!(&quot;Searching for {}&quot;, config.search);
# println!(&quot;In file {}&quot;, config.filename);
#
# let mut f = File::open(config.filename).expect(&quot;file not found&quot;);
#
# let mut contents = String::new();
# f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
#
# println!(&quot;With text:\n{}&quot;, contents);
# }
#
# struct Config {
# search: String,
# filename: String,
# }
#
# impl Config {
// ...snip...
fn new(args: &amp;[String]) -&gt; Config {
if args.len() &lt; 3 {
panic!(&quot;not enough arguments&quot;);
}
let search = args[1].clone();
// ...snip...
# let filename = args[2].clone();
#
# Config {
# search: search,
# filename: filename,
# }
}
# }
</code></pre>
<figcaption>
<p>Listing 12-7: Adding a check for the number of arguments</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>With these extra few lines of code in <code>new</code>, let's try running our program
without any arguments:</p>
<pre><code class="language-text">$ cargo run
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe`
thread 'main' panicked at 'not enough arguments', src\main.rs:29
note: Run with `RUST_BACKTRACE=1` for a backtrace.
</code></pre>
<p>This is a bit better! We at least have a reasonable error message here.
However, we also have a bunch of extra information that we don't want to give
to our users. We can do better by changing the type signature of <code>new</code>. Right
now, it returns only a <code>Config</code>, so there's no way to indicate that an error
happened while creating our <code>Config</code>. Instead, we can return a <code>Result</code>, as
shown in Listing 12-8:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
# use std::process;
#
# fn main() {
# let args: Vec&lt;String&gt; = env::args().collect();
#
# let config = Config::new(&amp;args).unwrap_or_else(|err| {
# println!(&quot;Problem parsing arguments: {}&quot;, err);
# process::exit(1);
# });
#
# println!(&quot;Searching for {}&quot;, config.search);
# println!(&quot;In file {}&quot;, config.filename);
#
# let mut f = File::open(config.filename).expect(&quot;file not found&quot;);
#
# let mut contents = String::new();
# f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
#
# println!(&quot;With text:\n{}&quot;, contents);
# }
# struct Config {
# search: String,
# filename: String,
# }
#
impl Config {
fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err(&quot;not enough arguments&quot;);
}
let search = args[1].clone();
let filename = args[2].clone();
Ok(Config {
search: search,
filename: filename,
})
}
}
</code></pre>
<figcaption>
<p>Listing 12-8: Return a <code>Result</code> from <code>Config::new</code></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Our <code>new</code> function now returns a <code>Result</code>, with a <code>Config</code> instance in the
success case and a <code>&amp;'static str</code> when an error happens. Recall from &quot;The
Static Lifetime&quot; section in Chapter 10 <code>&amp;'static str</code> is the type of string
literals, which is what our error message is for now.</p>
<p>We've made two changes in the body of the <code>new</code> function: instead of calling
<code>panic!</code> if there aren't enough arguments, we now return an <code>Err</code> value. We
wrapped the <code>Config</code> return value in an <code>Ok</code>. These changes make the function
conform to its new type signature.</p>
<a class="header" href="#calling-confignew-and-handling-errors" name="calling-confignew-and-handling-errors"><h3>Calling <code>Config::new</code> and Handling Errors</h3></a>
<p>Now we need to make some changes to <code>main</code> as shown in Listing 12-9:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
// ...snip...
use std::process;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::new(&amp;args).unwrap_or_else(|err| {
println!(&quot;Problem parsing arguments: {}&quot;, err);
process::exit(1);
});
println!(&quot;Searching for {}&quot;, config.search);
println!(&quot;In file {}&quot;, config.filename);
// ...snip...
#
# let mut f = File::open(config.filename).expect(&quot;file not found&quot;);
#
# let mut contents = String::new();
# f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
#
# println!(&quot;With text:\n{}&quot;, contents);
# }
#
# struct Config {
# search: String,
# filename: String,
# }
#
# impl Config {
# fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
# if args.len() &lt; 3 {
# return Err(&quot;not enough arguments&quot;);
# }
#
# let search = args[1].clone();
# let filename = args[2].clone();
#
# Ok(Config {
# search: search,
# filename: filename,
# })
# }
# }
</code></pre>
<figcaption>
<p>Listing 12-9: Exiting with an error code if creating a new <code>Config</code> fails</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>We've added a new <code>use</code> line to import <code>process</code> from the standard library.
In the <code>main</code> function itself, we'll handle the <code>Result</code> value returned
from the <code>new</code> function and exit the process in a cleaner way if <code>Config::new</code>
returns an <code>Err</code> value.</p>
<p>We're using a method we haven't covered before that's defined on <code>Result&lt;T, E&gt;</code>
by the standard library: <code>unwrap_or_else</code>. This method has similar behavior as
<code>unwrap</code> if the <code>Result</code> is an <code>Ok</code> value: it returns the inner value <code>Ok</code> is
wrapping. Unlike <code>unwrap</code>, if the value is an <code>Err</code> value, this method calls a
<em>closure</em> which is an anonymous function that we define and pass as an argument
to <code>unwrap_or_else</code>. We'll be covering closures in more detail in Chapter XX;
the important part to understand in this case is that <code>unwrap_or_else</code> will
pass the inner value of the <code>Err</code> to our closure in the parameter <code>err</code> that
appears between the vertical pipes. Using <code>unwrap_or_else</code> lets us do some
custom, non-<code>panic!</code> error handling.</p>
<p>Said error handling is only two lines: we print out the error, then call
<code>std::process::exit</code>. That function will stop our program's execution
immediately and return the number passed to it as a return code. By convention,
a zero means success and any other value means failure. In the end, this has
similar characteristics to our <code>panic!</code>-based handling we had in Listing 12-7,
but we no longer get all the extra output. Let's try it:</p>
<pre><code class="language-text">$ cargo run
Compiling greprs v0.1.0 (file:///projects/greprs)
Finished debug [unoptimized + debuginfo] target(s) in 0.48 secs
Running `target\debug\greprs.exe`
Problem parsing arguments: not enough arguments
</code></pre>
<p>Great! This output is much friendlier for our users.</p>
<a class="header" href="#handling-errors-from-the-run-function" name="handling-errors-from-the-run-function"><h3>Handling Errors from the <code>run</code> Function</h3></a>
<p>Now that we're done refactoring our configuration parsing, let's improve our
program's logic. Listing 12-10 shows the code after extracting a function named
<code>run</code> that we'll call from <code>main</code>. The <code>run</code> function contains the code that
was in <code>main</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust"># use std::env;
# use std::fs::File;
# use std::io::prelude::*;
# use std::process;
#
fn main() {
# let args: Vec&lt;String&gt; = env::args().collect();
#
# let config = Config::new(&amp;args).unwrap_or_else(|err| {
# println!(&quot;Problem parsing arguments: {}&quot;, err);
# process::exit(1);
# });
// ...snip...
println!(&quot;Searching for {}&quot;, config.search);
println!(&quot;In file {}&quot;, config.filename);
run(config);
}
fn run(config: Config) {
let mut f = File::open(config.filename).expect(&quot;file not found&quot;);
let mut contents = String::new();
f.read_to_string(&amp;mut contents).expect(&quot;something went wrong reading the file&quot;);
println!(&quot;With text:\n{}&quot;, contents);
}
// ...snip...
#
# struct Config {
# search: String,
# filename: String,
# }
#
# impl Config {
# fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
# if args.len() &lt; 3 {
# return Err(&quot;not enough arguments&quot;);
# }
#
# let search = args[1].clone();
# let filename = args[2].clone();
#
# Ok(Config {
# search: search,
# filename: filename,
# })
# }
# }
</code></pre>
<figcaption>
<p>Listing 12-10: Extracting a <code>run</code> functionality for the rest of the program logic</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>The contents of <code>run</code> are the previous lines that were in <code>main</code>, and the <code>run</code>
function takes a <code>Config</code> as an argument. Now that we have a separate function,
we can make a similar improvement to the one we made to <code>Config::new</code> in
Listing 12-8: let's return a <code>Result&lt;T, E&gt;</code> instead of calling <code>panic!</code> via
<code>expect</code>. Listing 12-11 shows the addition of a <code>use</code> statement to bring
<code>std::error::Error</code> struct into scope and the changes to the <code>run</code> function
to return a <code>Result</code>:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">use std::error::Error;
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
# use std::process;
// ...snip...
# fn main() {
# let args: Vec&lt;String&gt; = env::args().collect();
#
# let config = Config::new(&amp;args).unwrap_or_else(|err| {
# println!(&quot;Problem parsing arguments: {}&quot;, err);
# process::exit(1);
# });
#
# println!(&quot;Searching for {}&quot;, config.search);
# println!(&quot;In file {}&quot;, config.filename);
#
# run(config);
#
# }
fn run(config: Config) -&gt; Result&lt;(), Box&lt;Error&gt;&gt; {
let mut f = File::open(config.filename)?;
let mut contents = String::new();
f.read_to_string(&amp;mut contents)?;
println!(&quot;With text:\n{}&quot;, contents);
Ok(())
}
#
# struct Config {
# search: String,
# filename: String,
# }
#
# impl Config {
# fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
# if args.len() &lt; 3 {
# return Err(&quot;not enough arguments&quot;);
# }
#
# let search = args[1].clone();
# let filename = args[2].clone();
#
# Ok(Config {
# search: search,
# filename: filename,
# })
# }
# }
</code></pre>
<figcaption>
<p>Listing 12-11: Changing the <code>run</code> function to return <code>Result</code></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>We've made three big changes here. The first is the return type of the <code>run</code>
function is now <code>Result&lt;(), Box&lt;Error&gt;&gt;</code>. Previously, our function returned the
unit type, <code>()</code>, so that's still the value returned in the <code>Ok</code> case. For our
error type, we're going to use <code>Box&lt;Error&gt;</code>. This is called a <em>trait object</em>,
which we'll be covering in Chapter XX. For now, think of it like this:
<code>Box&lt;Error&gt;</code> means the function will return some kind of type that implements
the <code>Error</code> trait, but we're not specifying what particular type the return
value will be. This gives us flexibility to return error values that may be of
different types in different error cases. <code>Box</code> is a smart pointer to heap
data, and we'll be going into detail about <code>Box</code> in Chapter YY.</p>
<p>The second change is that we've removed our calls to <code>expect</code> in favor of <code>?</code>,
like we talked about in Chapter 9. Rather than <code>panic!</code> on an error, this will
return the error value from the function we're in for the caller to handle.</p>
<p>The third change is that we're now returning an <code>Ok</code> value from this function
in the success case. Because we've declared the <code>run</code> function's success type
as <code>()</code> in the signature, we need to wrap the unit type value in the <code>Ok</code>
value. <code>Ok(())</code> looks a bit strange at first, but using <code>()</code> in this way is the
idiomatic way to indicate that we're calling <code>run</code> for its side effects only;
it doesn't return anything interesting.</p>
<p>This will compile, but with a warning:</p>
<pre><code class="language-text">warning: unused result which must be used, #[warn(unused_must_use)] on by default
--&gt; src\main.rs:39:5
|
39 | run(config);
| ^^^^^^^^^^^^
</code></pre>
<p>Rust is trying to tell us that we're ignoring our <code>Result</code>, which might be an
error value. Let's handle that now. We'll use a similar technique as the way we
handled failure with <code>Config::new</code> in Listing 12-9, but with a slight
difference:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
// ...snip...
println!(&quot;Searching for {}&quot;, config.search);
println!(&quot;In file {}&quot;, config.filename);
if let Err(e) = run(config) {
println!(&quot;Application error: {}&quot;, e);
process::exit(1);
}
}
fn run(config: Config) -&gt; Result&lt;(), Box&lt;Error&gt;&gt; {
let mut f = File::open(config.filename)?;
let mut contents = String::new();
f.read_to_string(&amp;mut contents)?;
println!(&quot;With text:\n{}&quot;, contents);
Ok(())
}
</code></pre>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Instead of <code>unwrap_or_else</code>, we use <code>if let</code> to see if <code>run</code> returns an <code>Err</code>
value and call <code>process::exit(1)</code> if so. Why? The distinction between this case
and the <code>Config::new</code> case is a bit subtle. With <code>Config::new</code>, we cared about
two things:</p>
<ol>
<li>Detecting any errors that happen</li>
<li>Getting a <code>Config</code> if no errors happened</li>
</ol>
<p>In this case, because <code>run</code> returns a <code>()</code> in the success case, the only thing
we care about is the first case: detecting an error. If we used
<code>unwrap_or_else</code>, we'd get its return value, which would be <code>()</code>. That's not
very useful.</p>
<p>The bodies of the <code>if let</code> and of the <code>unwrap_or_else</code> are the same in both
cases though: we print out an error and exit.</p>
<a class="header" href="#split-code-into-a-library-crate" name="split-code-into-a-library-crate"><h3>Split Code into a Library Crate</h3></a>
<p>This is looking pretty good! There's one more thing we haven't done yet: split
the <em>src/main.rs</em> up and put some code into <em>src/lib.rs</em> Let's do that now:
move the <code>run</code> function from <em>src/main.rs</em> to a new file, <em>src/lib.rs</em>. You'll
also need to move the relevant <code>use</code> statements and the definition of <code>Config</code>
and its <code>new</code> method as well. Your <em>src/lib.rs</em> should now look like Listing
12-12:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
pub struct Config {
pub search: String,
pub filename: String,
}
impl Config {
pub fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err(&quot;not enough arguments&quot;);
}
let search = args[1].clone();
let filename = args[2].clone();
Ok(Config {
search: search,
filename: filename,
})
}
}
pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;Error&gt;&gt;{
let mut f = File::open(config.filename)?;
let mut contents = String::new();
f.read_to_string(&amp;mut contents)?;
println!(&quot;With text:\n{}&quot;, contents);
Ok(())
}
</code></pre>
<figcaption>
<p>Listing 12-12: Moving <code>Config</code> and <code>run</code> into <em>src/lib.rs</em></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Notice we also made liberal use of <code>pub</code>: on <code>Config</code>, its fields and its <code>new</code>
method, and on the <code>run</code> function.</p>
<p>Now in <em>src/main.rs</em>, we need to bring in the code that's now in <em>src/lib.rs</em>
through <code>extern crate greprs</code>. Then we need to add a <code>use greprs::Config</code> line
to bring <code>Config</code> into scope, and prefix the <code>run</code> function with our crate name
as shown in Listing 12-13:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate greprs;
use std::env;
use std::process;
use greprs::Config;
fn main() {
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::new(&amp;args).unwrap_or_else(|err| {
println!(&quot;Problem parsing arguments: {}&quot;, err);
process::exit(1);
});
println!(&quot;Searching for {}&quot;, config.search);
println!(&quot;In file {}&quot;, config.filename);
if let Err(e) = greprs::run(config) {
println!(&quot;Application error: {}&quot;, e);
process::exit(1);
}
}
</code></pre>
<figcaption>
<p>Listing 12-13: Bringing the <code>greprs</code> crate into the scope of <em>src/main.rs</em></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>With that, everything should work again. Give it a few <code>cargo run</code>s and make
sure you haven't broken anything. Whew! That all was a lot of work, but we've
set ourselves up for success in the future. We've set up a way to handle errors
in a much nicer fashion, and we've made our code slightly more modular. Almost
all of our work will be done in <em>src/lib.rs</em> from here on out.</p>
<p>Let's take advantage of this newfound modularity by doing something that would
have been hard with our old code, but is easy with our new code: write some
tests!</p>
<a class="header" href="#testing-the-librarys-functionality" name="testing-the-librarys-functionality"><h2>Testing the Library's Functionality</h2></a>
<p>Writing tests for the core functionality of our code is now easier since we
extracted the logic into <em>src/lib.rs</em> and left all the argument parsing and
error handling in <em>src/main.rs</em>. We can now call our code directly with various
arguments and check return values without having to call our binary from the
command line.</p>
<p>We're going to write a function named <code>grep</code> that takes our search term and the
text to search and produces a list of search results. Let's remove that
<code>println!</code> from <code>run</code> (and from <em>src/main.rs</em> as well, as we don't really need
those anymore either), and call the new <code>grep</code> function with the options we've
collected. We'll add a placeholder implementation of the function for now, and
a test that specifies the behavior we'd like the <code>grep</code> function to have. The
test will fail with our placeholder implementation, of course, but we can make
sure the code compiles and that we get the failure message we expect. Listing
12-14 shows these modifications:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust"># use std::error::Error;
# use std::fs::File;
# use std::io::prelude::*;
#
# pub struct Config {
# pub search: String,
# pub filename: String,
# }
#
// ...snip...
fn grep&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
vec![]
}
pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;Error&gt;&gt;{
let mut f = File::open(config.filename)?;
let mut contents = String::new();
f.read_to_string(&amp;mut contents)?;
grep(&amp;config.search, &amp;contents);
Ok(())
}
#[cfg(test)]
mod test {
use grep;
#[test]
fn one_result() {
let search = &quot;duct&quot;;
let contents = &quot;\
Rust:
safe, fast, productive.
Pick three.&quot;;
assert_eq!(
vec![&quot;safe, fast, productive.&quot;],
grep(search, contents)
);
}
}
</code></pre>
<figcaption>
<p>Listing 12-14: Creating a function where our logic will go and a failing test
for that function</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Notice that we need an explicit lifetime <code>'a</code> declared in the signature of
<code>grep</code> and used with the <code>contents</code> parameter and the return value. Remember,
lifetime parameters are used to specify which function parameters' lifetimes
connect to the lifetime of the return value. In this case, we're indicating that
the vector we're returning is going to contain string slices that reference
slices of the parameter <code>contents</code>, as opposed to referencing slices of the
parameter <code>search</code>. Another way to think about what we're telling Rust is that
the data returned by the <code>grep</code> function will live as long as the data passed
into this function in the <code>contents</code> parameter. This is important! Given that
the data a slice references needs to be valid in order for the reference to be
valid, if the compiler thought that we were making string slices of <code>search</code>
rather than <code>contents</code>, it would do its safety checking incorrectly. If we tried
to compile this function without lifetimes, we would get this error:</p>
<pre><code class="language-text">error[E0106]: missing lifetime specifier
--&gt; src\lib.rs:37:46
|
37 | fn grep(search: &amp;str, contents: &amp;str) -&gt; Vec&lt;&amp;str&gt; {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value, but the
signature does not say whether it is borrowed from `search` or
`contents`
</code></pre>
<p>Rust can't possibly know which of the two parameters we need, so it needs us to
tell it. Because <code>contents</code> is the parameter that contains all of our text and
we want to return the parts of that text that match, we know <code>contents</code> is the
parameter that should be connected to the return value using the lifetime
syntax.</p>
<p>Connecting parameters to return values in the signature is something that other
programming languages don't make you do, so don't worry if this still feels
strange! Knowing how to specify lifetimes gets easier over time, and practice
makes perfect. You may want to re-read the above section or go back and compare
this example with the Lifetime Syntax section in Chapter 10.</p>
<p>Now let's try running our test:</p>
<pre><code class="language-text">$ cargo test
...warnings...
Finished debug [unoptimized + debuginfo] target(s) in 0.43 secs
Running target/debug/deps/greprs-abcabcabc
running 1 test
test test::one_result ... FAILED
failures:
---- test::one_result stdout ----
thread 'test::one_result' panicked at 'assertion failed: `(left == right)`
(left: `[&quot;safe, fast, productive.&quot;]`, right: `[]`)', src/lib.rs:16
note: Run with `RUST_BACKTRACE=1` for a backtrace.
failures:
test::one_result
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
error: test failed
</code></pre>
<p>Great, our test fails, exactly as we expected. Let's get the test to pass! It's
failing because we always return an empty vector. Here's what we're going to do
to implement <code>grep</code>:</p>
<ol>
<li>Iterate through each line of the contents.</li>
<li>Check if the line contains our search string.
<ul>
<li>If it does, add it to the list of values we're returning.</li>
<li>If not, do nothing.</li>
</ul>
</li>
<li>Return the list of results that match.</li>
</ol>
<p>Let's take each step at a time, starting with iterating through lines. Strings
have a helpful method to handle this, conveniently named <code>lines</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">fn grep&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
for line in contents.lines() {
// do something with line
}
}
</code></pre>
<!-- Will add wingdings in libreoffice /Carol -->
<p>We're using a <code>for</code> loop along with the <code>lines</code> method to get each line in turn.
Next, let's see if our line contains the search string. Luckily, strings have a
helpful method named <code>contains</code> that does this for us! Using the <code>contains</code>
method looks like this:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">fn grep&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
for line in contents.lines() {
if line.contains(search) {
// do something with line
}
}
}
</code></pre>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Finally, we need a way to store the lines that contain our search string. For
that, we can make a mutable vector before the <code>for</code> loop and call the <code>push</code>
method to store a <code>line</code> in the vector. After the <code>for</code> loop, we return the
vector. Listing 12-15 has the full implementation:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">fn grep&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(search) {
results.push(line);
}
}
results
}
</code></pre>
<figcaption>
<p>Listing 12-15: Fully functioning implementation of the <code>grep</code> function</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Let's give it a try:</p>
<pre><code class="language-text">$ cargo test
running 1 test
test test::one_result ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Running target/debug/greprs-2f55ee8cd1721808
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
Doc-tests greprs
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Great! It works. Now that our test is passing, we could consider opportunities
for refactoring the implementation of <code>grep</code> and be certain we maintain the
same functionality while we do so. This code isn't bad, but it isn't taking
advantage of some useful features of iterators. We'll be coming back to this
example in Chapter 13 where we'll explore iterators in detail and see how to
improve it.</p>
<p>Now that the <code>grep</code> function is working, we need to do one last thing inside of
the <code>run</code> function: we never printed out the results! We'll do that by adding
a <code>for</code> loop that prints each line returned from the <code>grep</code> function:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;Error&gt;&gt; {
let mut f = File::open(config.filename)?;
let mut contents = String::new();
f.read_to_string(&amp;mut contents)?;
for line in grep(&amp;config.search, &amp;contents) {
println!(&quot;{}&quot;, line);
}
Ok(())
}
</code></pre>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Now our whole program should be working! Let's try it out:</p>
<pre><code class="language-text">$ cargo run the poem.txt
Compiling greprs v0.1.0 (file:///projects/greprs)
Finished debug [unoptimized + debuginfo] target(s) in 0.38 secs
Running `target\debug\greprs.exe the poem.txt`
Then there's a pair of us - don't tell!
To tell your name the livelong day
$ cargo run a poem.txt
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe a poem.txt`
I'm nobody! Who are you?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>Excellent! We've built our own version of a classic tool, and learned a lot
about how to structure applications. We've also learned a bit about file input
and output, lifetimes, testing, and command line parsing.</p>
<a class="header" href="#working-with-environment-variables" name="working-with-environment-variables"><h2>Working with Environment Variables</h2></a>
<p>Let's add one more feature: case insensitive searching. In addition, this
setting won't be a command line option: it'll be an environment variable
instead. We could choose to make case insensitivity a command line option, but
our users have requested an environment variable that they could set once and
make all their searches case insensitive in that terminal session.</p>
<a class="header" href="#implement-and-test-a-case-insensitive-grep-function" name="implement-and-test-a-case-insensitive-grep-function"><h3>Implement and Test a Case-Insensitive <code>grep</code> Function</h3></a>
<p>First, let's add a new function that we will call when the environment variable
is on. Let's start by adding a new test and re-naming our existing one:</p>
<pre><code class="language-rust,ignore">#[cfg(test)]
mod test {
use {grep, grep_case_insensitive};
#[test]
fn case_sensitive() {
let search = &quot;duct&quot;;
let contents = &quot;\
Rust:
safe, fast, productive.
Pick three.
Duct tape.&quot;;
assert_eq!(
vec![&quot;safe, fast, productive.&quot;],
grep(search, contents)
);
}
#[test]
fn case_insensitive() {
let search = &quot;rust&quot;;
let contents = &quot;\
Rust:
safe, fast, productive.
Pick three.
Trust me.&quot;;
assert_eq!(
vec![&quot;Rust:&quot;, &quot;Trust me.&quot;],
grep_case_insensitive(search, contents)
);
}
}
</code></pre>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>We're going to define a new function named <code>grep_case_insensitive</code>. Its
implementation will be almost the same as the <code>grep</code> function, but with some
minor changes as shown in Listing 12-16:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">fn grep_case_insensitive&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let search = search.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&amp;search) {
results.push(line);
}
}
results
}
</code></pre>
<figcaption>
<p>Listing 12-16: Implementing a <code>grep_case_insensitive</code> function by changing the
search string and the lines of the contents to lowercase before comparing them</p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>First, we lowercase the <code>search</code> string, and store it in a shadowed variable
with the same name. Note that <code>search</code> is now a <code>String</code> rather than a string
slice, so we need to add an ampersand when we pass <code>search</code> to <code>contains</code> since
<code>contains</code> takes a string slice.</p>
<p>Second, we add a call to <code>to_lowercase</code> each <code>line</code> before we check if it
contains <code>search</code>. Since we've converted both <code>line</code> and <code>search</code> into all
lowercase, we'll find matches no matter what case they used in the file and the
command line arguments, respectively. Let's see if this passes the tests:</p>
<pre><code class="language-text"> Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target\debug\deps\greprs-e58e9b12d35dc861.exe
running 2 tests
test test::case_insensitive ... ok
test test::case_sensitive ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
Running target\debug\greprs-8a7faa2662b5030a.exe
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
Doc-tests greprs
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Great! Now, we have to actually use the new <code>grep_case_insensitive</code> function.
First, let's add a configuration option for it to the <code>Config</code> struct:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">pub struct Config {
pub search: String,
pub filename: String,
pub case_sensitive: bool,
}
</code></pre>
<!-- Will add ghosting in libreoffice /Carol -->
<p>And then check for that option inside of the <code>run</code> function, and decide which
function to call based on the value of the <code>case_sensitive</code> function:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust,ignore">pub fn run(config: Config) -&gt; Result&lt;(), Box&lt;Error&gt;&gt;{
let mut f = File::open(config.filename)?;
let mut contents = String::new();
f.read_to_string(&amp;mut contents)?;
let results = if config.case_sensitive {
grep(&amp;config.search, &amp;contents)
} else {
grep_case_insensitive(&amp;config.search, &amp;contents)
};
for line in results {
println!(&quot;{}&quot;, line);
}
Ok(())
}
</code></pre>
<!-- Will add ghosting in libreoffice /Carol -->
<p>Finally, we need to actually check the environment for the variable. To bring
the <code>env</code> module from the standard library into our project, we add a <code>use</code> line
at the top of <em>src/lib.rs</em>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">use std::env;
</code></pre>
<p>And then use the <code>vars</code> method from the <code>env</code> module inside of <code>Config::new</code>:</p>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust"># use std::env;
#
# struct Config {
# search: String,
# filename: String,
# case_sensitive: bool,
# }
#
impl Config {
pub fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err(&quot;not enough arguments&quot;);
}
let search = args[1].clone();
let filename = args[2].clone();
let mut case_sensitive = true;
for (name, _) in env::vars() {
if name == &quot;CASE_INSENSITIVE&quot; {
case_sensitive = false;
}
}
Ok(Config {
search: search,
filename: filename,
case_sensitive: case_sensitive,
})
}
}
</code></pre>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Here, we call <code>env::vars</code>, which works in a similar way as <code>env::args</code>. The
difference is <code>env::vars</code> returns an iterator of environment variables rather
than command line arguments. Instead of using <code>collect</code> to create a vector of
all of the environment variables, we're using a <code>for</code> loop. <code>env::vars</code> returns
tuples: the name of the environment variable and its value. We never care about
the values, only if the variable is set at all, so we use the <code>_</code> placeholder
instead of a name to let Rust know that it shouldn't warn us about an unused
variable. Finally, we have a <code>case_sensitive</code> variable, which is set to true by
default. If we ever find a <code>CASE_INSENSITIVE</code> environment variable, we set the
<code>case_sensitive</code> variable to false instead. Then we return the value as part of
the <code>Config</code>.</p>
<p>Let's give it a try!</p>
<pre><code class="language-text">$ cargo run to poem.txt
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe to poem.txt`
Are you nobody, too?
How dreary to be somebody!
</code></pre>
<pre><code class="language-text">$ CASE_INSENSITIVE=1 cargo run to poem.txt
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target\debug\greprs.exe to poem.txt`
Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!
</code></pre>
<p>Excellent! Our <code>greprs</code> program can now do case insensitive searching controlled
by an environment variable. Now you know how to manage options set using
either command line arguments or environment variables!</p>
<p>Some programs allow both arguments <em>and</em> environment variables for the same
configuration. In those cases, the programs decide that one or the other of
arguments or environment variables take precedence. For another exercise on
your own, try controlling case insensitivity through a command line argument as
well, and decide which should take precedence if you run the program with
contradictory values.</p>
<p>The <code>std::env</code> module contains many more useful features for dealing with
environment variables; check out its documentation to see what's available.</p>
<a class="header" href="#write-to-stderr-instead-of-stdout" name="write-to-stderr-instead-of-stdout"><h2>Write to <code>stderr</code> Instead of <code>stdout</code></h2></a>
<p>Right now, we're writing all of our output to the terminal with <code>println!</code>.
This works, but most terminals provide two kinds of output: &quot;standard out&quot; is
used for most information, but &quot;standard error&quot; is used for error messages. This
makes it easier to do things like &quot;Print error messages to my terminal, but
write other output to a file.&quot;</p>
<p>We can see that our program is only capable of printing to <code>stdout</code> by
redirecting it to a file using <code>&gt;</code> on the command line, and running our program
without any arguments, which causes an error:</p>
<pre><code class="language-text">$ cargo run &gt; output.txt
</code></pre>
<p>The <code>&gt;</code> syntax tells the shell to write the contents of standard out to
<em>output.txt</em> instead of the screen. However, if we open <em>output.txt</em> after
running we'll see our error message:</p>
<pre><code class="language-text">Problem parsing arguments: not enough arguments
</code></pre>
<p>We'd like this to be printed to the screen instead, and only have the output
from a successful run end up in the file if we run our program this way. Let's
change how error messages are printed as shown in Listing 12-17:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate greprs;
use std::env;
use std::process;
use std::io::prelude::*;
use greprs::Config;
fn main() {
let mut stderr = std::io::stderr();
let args: Vec&lt;String&gt; = env::args().collect();
let config = Config::new(&amp;args).unwrap_or_else(|err| {
writeln!(
&amp;mut stderr,
&quot;Problem parsing arguments: {}&quot;,
err
).expect(&quot;Could not write to stderr&quot;);
process::exit(1);
});
if let Err(e) = greprs::run(config) {
writeln!(
&amp;mut stderr,
&quot;Application error: {}&quot;,
e
).expect(&quot;Could not write to stderr&quot;);
process::exit(1);
}
}
</code></pre>
<figcaption>
<p>Listing 12-17: Writing error messages to <code>stderr</code> instead of <code>stdout</code></p>
</figcaption>
</figure>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Rust does not have a convenient function like <code>println!</code> for writing to
standard error. Instead, we use the <code>writeln!</code> macro, which is sort of like
<code>println!</code>, but it takes an extra argument. The first thing we pass to it is
what to write to. We can acquire a handle to standard error through the
<code>std::io::stderr</code> function. We give a mutable reference to <code>stderr</code> to
<code>writeln!</code>; we need it to be mutable so we can write to it! The second and
third arguments to <code>writeln!</code> are like the first and second arguments to
<code>println!</code>: a format string and any variables we're interpolating.</p>
<p>Let's try running the program again in the same way, without any arguments and
redirecting <code>stdout</code> with <code>&gt;</code>:</p>
<pre><code class="language-text">$ cargo run &gt; output.txt
Problem parsing arguments: not enough arguments
</code></pre>
<p>Now we see our error on the screen, but <code>output.txt</code> contains nothing. If we
try it again with arguments that work:</p>
<pre><code class="language-text">$ cargo run to poem.txt &gt; output.txt
</code></pre>
<p>We'll see no output to our terminal, but <code>output.txt</code> will contain
our results:</p>
<p><span class="filename">Filename: output.txt</span></p>
<pre><code class="language-text">Are you nobody, too?
How dreary to be somebody!
</code></pre>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<p>In this chapter, we've covered how to do common I/O operations in a Rust
context. By using command line arguments, files, environment variables, and the
ability to write to <code>stderr</code>, you're now prepared to write command line
applications. By using the concepts from previous chapters, your code will be
well-organized, be able to store data effectively in the appropriate data
structures, handle errors nicely, and be well tested. We also saw a real-world
scenario where lifetime annotations are needed to ensure references are
always valid.</p>
<p>Next, let's explore how to make use of some features of Rust that were
influenced by functional languages: closures and iterators.</p>
<a class="header" href="#functional-language-features-in-rust---iterators-and-closures" name="functional-language-features-in-rust---iterators-and-closures"><h1>Functional Language features in Rust - Iterators and Closures</h1></a>
<p>Rust's design has taken inspiration from a lot of previous work. One of Rust's
influences is functional programming, where functions are values that can be
used as arguments or return values to other functions, assigned to variables,
and so forth. We're going to sidestep the issue of what, exactly, functional
programming is or is not, and instead show off some features of Rust that
are similar to features in many languages referred to as functional.</p>
<p>More specifically, we're going to cover:</p>
<ul>
<li><em>Closures</em>, a function-like construct you can store in a variable.</li>
<li><em>Iterators</em>, a way of processing series of elements.</li>
<li>How to use these features to improve upon the project from the last chapter.</li>
<li>The performance of these features. Spoiler alert: they're faster than you
might think!</li>
</ul>
<p>This is not a complete list of Rust's influence from the functional style:
pattern matching, enums, and many other features are too. But mastering
closures and iterators are an important part of writing idiomatic, fast Rust
code.</p>
<a class="header" href="#closures" name="closures"><h2>Closures</h2></a>
<p>Rust gives you the ability to define <em>closures</em>, which are similar to
functions. Instead of starting with a technical definition, let's see what
closures look like, syntactically, and then we'll return to defining what they
are. Listing 13-1 shows a small closure whose definition is assigned to the
variable <code>add_one</code>, which we can then use to call the closure:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let add_one = |x| x + 1;
let five = add_one(4);
assert_eq!(5, five);
}
</code></pre>
<figcaption>
<p>Listing 13-1: A closure that takes one parameter and adds one to it, assigned to
the variable <code>add_one</code></p>
</figcaption>
</figure>
<p>The closure definition, on the first line, shows that the closure takes one
parameter named <code>x</code>. Parameters to closures go in between vertical pipes (<code>|</code>).</p>
<p>This is a minimal closure with only one expression as its body. Listing 13-2 has
a closure with a bit more complexity:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let calculate = |a, b| {
let mut result = a * 2;
result += b;
result
};
assert_eq!(7, calculate(2, 3)); // 2 * 2 + 3 == 7
assert_eq!(13, calculate(4, 5)); // 4 * 2 + 5 == 13
}
</code></pre>
<figcaption>
<p>Listing 13-2: A closure with two parameters and multiple expressions in its body</p>
</figcaption>
</figure>
<p>We can use curly brackets to define a closure body with more than one
expression.</p>
<p>You'll notice a few things about closures that are different from functions
defined with the <code>fn</code> keyword. The first difference is that we did not need to
annotate the types of the parameters the closure takes or the value it returns.
We can choose to add type annotations if we want; Listing 13-3 shows the
closure from Listing 13-1 with annotations for the parameter's and return
value's types:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let add_one = |x: i32| -&gt; i32 { x + 1 };
assert_eq!(2, add_one(1));
}
</code></pre>
<figcaption>
<p>Listing 13-3: A closure definition with optional parameter and return value
type annotations</p>
</figcaption>
</figure>
<p>The syntax of closures and functions looks more similar with type annotations.
Let's compare the different ways we can specify closures with the syntax for
defining a function more directly. We've added some spaces here to line up the
relevant parts:</p>
<pre><code class="language-rust,ignore">fn add_one_v1 (x: i32) -&gt; i32 { x + 1 } // a function
let add_one_v2 = |x: i32| -&gt; i32 { x + 1 }; // the full syntax for a closure
let add_one_v3 = |x| { x + 1 }; // a closure eliding types
let add_one_v4 = |x| x + 1 ; // without braces
</code></pre>
<p>The reason type annotations are not required for defining a closure but are
required for defining a function is that functions are part of an explicit
interface exposed to your users, so defining this interface rigidly is
important for ensuring that everyone agrees on what types of values a function
uses and returns. Closures aren't used in an exposed interface like this,
though: they're stored in bindings and called directly. Being forced to
annotate the types would be a significant ergonomic loss for little advantage.</p>
<p>Closure definitions do have one type inferred for each of their parameters and
for their return value. For instance, if we call the closure without type
annotations from Listing 13-1 using an <code>i8</code>, we'll get an error if we then try
to call the same closure with an <code>i32</code>:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">let add_one = |x| x + 1;
let five = add_one(4i8);
assert_eq!(5i8, five);
let three = add_one(2i32);
</code></pre>
<p>The compiler gives us this error:</p>
<pre><code class="language-text">error[E0308]: mismatched types
--&gt;
|
7 | let three = add_one(2i32);
| ^^^^ expected i8, found i32
</code></pre>
<p>Since closures' types can be inferred reliably since they're called directly,
it would be tedious if we were required to annotate their types.</p>
<p>Another reason to have a different syntax from functions for closures is that
they have different behavior than functions: closures possess an <em>environment</em>.</p>
<a class="header" href="#closures-can-reference-their-environment" name="closures-can-reference-their-environment"><h3>Closures Can Reference Their Environment</h3></a>
<p>We've learned that functions can only use variables that are in scope, either
by being <code>const</code> or being declared as parameters. Closures can do more: they're
allowed to access variables from their enclosing scope. Listing 13-4 has an
example of a closure in the variable <code>equal_to_x</code> that uses the variable <code>x</code>
from the closure's surrounding environment:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">fn main() {
let x = 4;
let equal_to_x = |z| z == x;
let y = 4;
assert!(equal_to_x(y));
}
</code></pre>
<figcaption>
<p>Listing 13-4: Example of a closure that refers to a variable in its enclosing
scope</p>
</figcaption>
</figure>
<p>Here, even though <code>x</code> is not one of the parameters of <code>equal_to_x</code>, the
<code>equal_to_x</code> closure is allowed to use <code>x</code>, since <code>x</code> is a variable defined in
the scope that <code>equal_to_x</code> is defined. We aren't allowed to do the same thing
that Listing 13-4 does with functions; let's see what happens if we try:</p>
<p><span class="filename">Filename: src/main.rs</span></p>
<pre><code class="language-rust,ignore">fn main() {
let x = 4;
fn equal_to_x(z: i32) -&gt; bool { z == x }
let y = 4;
assert!(equal_to_x(y));
}
</code></pre>
<p>We get an error:</p>
<pre><code class="language-text">error[E0434]: can't capture dynamic environment in a fn item; use the || { ... }
closure form instead
--&gt;
|
4 | fn equal_to_x(z: i32) -&gt; bool { z == x }
| ^
</code></pre>
<p>The compiler even reminds us that this only works with closures!</p>
<p>Creating closures that capture values from their environment is mostly used in
the context of starting new threads. We'll show some more examples and explain
more detail about this feature of closures in Chapter 16 when we talk about
concurrency.</p>
<a class="header" href="#closures-as-function-parameters-using-the-fn-traits" name="closures-as-function-parameters-using-the-fn-traits"><h3>Closures as Function Parameters Using the <code>Fn</code> Traits</h3></a>
<p>While we can bind closures to variables, that's not the most useful thing we
can do with them. We can also define functions that have closures as parameters
by using the <code>Fn</code> traits. Here's an example of a function named <code>call_with_one</code>
whose signature has a closure as a parameter:</p>
<pre><code class="language-rust">fn call_with_one&lt;F&gt;(some_closure: F) -&gt; i32
where F: Fn(i32) -&gt; i32 {
some_closure(1)
}
let answer = call_with_one(|x| x + 2);
assert_eq!(3, answer);
</code></pre>
<p>We pass the closure <code>|x| x + 2</code>, to <code>call_with_one</code>, and <code>call_with_one</code> calls
that closure with <code>1</code> as an argument. The return value of the call to
<code>some_closure</code> is then returned from <code>call_with_one</code>.</p>
<p>The signature of <code>call_with_one</code> is using the <code>where</code> syntax discussed in the
Traits section of Chapter 10. The <code>some_closure</code> parameter has the generic type
<code>F</code>, which in the <code>where</code> clause is defined as having the trait bounds
<code>Fn(i32) -&gt; i32</code>. The <code>Fn</code> trait represents a closure, and we can add types to
the <code>Fn</code> trait to represent a specific type of closure. In this case, our
closure has a parameter of type <code>i32</code> and returns an <code>i32</code>, so the generic bound
we specify is <code>Fn(i32) -&gt; i32</code>.</p>
<p>Specifying a function signature that contains a closure requires the use of
generics and trait bounds. Each closure has a unique type, so we can't write
the type of a closure directly, we have to use generics.</p>
<p><code>Fn</code> isn't the only trait bound available for specifying closures, however.
There are three: <code>Fn</code>, <code>FnMut</code>, and <code>FnOnce</code>. This continues the patterns of
threes we've seen elsewhere in Rust: borrowing, borrowing mutably, and
ownership. Using <code>Fn</code> specifies that the closure used may only borrow values in
its environment. To specify a closure that mutates the environment, use
<code>FnMut</code>, and if the closure takes ownership of the environment, <code>FnOnce</code>. Most
of the time, you can start with <code>Fn</code>, and the compiler will tell you if you
need <code>FnMut</code> or <code>FnOnce</code> based on what happens when the function calls the
closure.</p>
<p>To illustrate a situation where it's useful for a function to have a parameter
that's a closure, let's move on to our next topic: iterators.</p>
<a class="header" href="#iterators" name="iterators"><h2>Iterators</h2></a>
<p>Iterators are a pattern in Rust that allows you to do some processing on a
sequence of items. For example, the code in Listing 13-5 adds one to each
number in a vector:</p>
<figure>
<pre><code class="language-rust">let v1 = vec![1, 2, 3];
let v2: Vec&lt;i32&gt; = v1.iter().map(|x| x + 1).collect();
assert_eq!(v2, [2, 3, 4]);
</code></pre>
<figcaption>
<p>Listing 13-5: Using an iterator, <code>map</code>, and <code>collect</code> to add one to each number
in a vector</p>
</figcaption>
</figure>
<!-- Will add wingdings in libreoffice /Carol -->
<p>The <code>iter</code> method on vectors allows us to produce an <em>iterator</em> from the
vector. Next, the <code>map</code> method called on the iterator allows us to process each
element: in this case, we've passed a closure to <code>map</code> that specifies for every
element <code>x</code>, add one to it. <code>map</code> is one of the most basic ways of interacting
with an iterator, as processing each element in turn is very useful! Finally,
the <code>collect</code> method consumes the iterator and puts the iterator's elements
into a new data structure. In this case, since we've said that <code>v2</code> has the
type <code>Vec&lt;i32&gt;</code>, <code>collect</code> will create a new vector out of the <code>i32</code> values.</p>
<p>Methods on iterators like <code>map</code> are sometimes called <em>iterator adaptors</em>
because they take one iterator and produce a new iterator. That is, <code>map</code>
builds on top of our previous iterator and produces another iterator by calling
the closure it's passed to create the new sequence of values.</p>
<p>So, to recap, this line of code does the following:</p>
<ol>
<li>Creates an iterator from the vector.</li>
<li>Uses the <code>map</code> adaptor with a closure argument to add one to each element.</li>
<li>Uses the <code>collect</code> adaptor to consume the iterator and make a new vector.</li>
</ol>
<p>That's how we end up with <code>[2, 3, 4]</code>. As you can see, closures are a very
important part of using iterators: they provide a way of customizing the
behavior of an iterator adaptor like <code>map</code>.</p>
<a class="header" href="#iterators-are-lazy" name="iterators-are-lazy"><h3>Iterators are Lazy</h3></a>
<p>In the previous section, you may have noticed a subtle difference in wording:
we said that <code>map</code> <em>adapts</em> an iterator, but <code>collect</code> <em>consumes</em> one. That was
intentional. By themselves, iterators won't do anything; they're lazy. That is,
if we write code like Listing 13-5 except we don't call <code>collect</code>:</p>
<pre><code class="language-rust">let v1: Vec&lt;i32&gt; = vec![1, 2, 3];
v1.iter().map(|x| x + 1); // without collect
</code></pre>
<p>It will compile, but it will give us a warning:</p>
<pre><code class="language-text">warning: unused result which must be used: iterator adaptors are lazy and do
nothing unless consumed, #[warn(unused_must_use)] on by default
--&gt; src/main.rs:4:1
|
4 | v1.iter().map(|x| x + 1); // without collect
| ^^^^^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>We get this warning because iterator adaptors won't start actually doing the
processing on their own. They need some other method that causes the iterator
chain to evaluate. We call those <em>consuming adaptors</em>, and <code>collect</code> is one of
them.</p>
<p>So how do we tell which iterator methods consume the iterator or not? And what
adaptors are available? For that, let's look at the <code>Iterator</code> trait.</p>
<a class="header" href="#the-iterator-trait" name="the-iterator-trait"><h3>The <code>Iterator</code> trait</h3></a>
<p>Iterators all implement a trait named <code>Iterator</code> that is defined in the standard
library. The definition of the trait looks like this:</p>
<pre><code class="language-rust">trait Iterator {
type Item;
fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt;;
}
</code></pre>
<p>There's some new syntax that we haven't covered here yet: <code>type Item</code> and
<code>Self::Item</code> are defining an <em>associated type</em> with this trait, and we'll talk
about associated types in depth in Chapter XX. For now, all you need to know is
that this code says the <code>Iterator</code> trait requires that you also define an
<code>Item</code> type, and this <code>Item</code> type is used in the return type of the <code>next</code>
method. In other words, the <code>Item</code> type will be the type of element that's
returned from the iterator.</p>
<p>Let's make an iterator named <code>Counter</code> that will count from <code>1</code> to <code>5</code>, using
the <code>Iterator</code> trait. First, we need to create a struct that holds the current
state of the iterator, which is one field named <code>count</code> that will hold a <code>u32</code>.
We'll also define a <code>new</code> method, which isn't strictly necessary. We want our
<code>Counter</code> to go from one to five, though, so we're always going to have it
holding a zero to start:</p>
<pre><code class="language-rust">struct Counter {
count: u32,
}
impl Counter {
fn new() -&gt; Counter {
Counter { count: 0 }
}
}
</code></pre>
<p>Next, we're going to implement the <code>Iterator</code> trait for our <code>Counter</code> type by
defining the body of the <code>next</code> method. The way we want our iterator to work
is to add one to the state (which is why we initialized <code>count</code> to 0, since we
want our iterator to return one first). If <code>count</code> is still less than six, we'll
return the current value, but if <code>count</code> is six or higher, our iterator will
return <code>None</code>, as shown in Listing 13-6:</p>
<figure>
<pre><code class="language-rust"># struct Counter {
# count: u32,
# }
#
impl Iterator for Counter {
// Our iterator will produce u32s
type Item = u32;
fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
// increment our count. This is why we started at zero.
self.count += 1;
// check to see if we've finished counting or not.
if self.count &lt; 6 {
Some(self.count)
} else {
None
}
}
}
</code></pre>
<figcaption>
<p>Listing 13-6: Implementing the <code>Iterator</code> trait on our <code>Counter</code> struct</p>
</figcaption>
</figure>
<!-- I will add wingdings in libreoffice /Carol -->
<p>The <code>type Item = u32</code> line is saying that the associated <code>Item</code> type will be
a <code>u32</code> for our iterator. Again, don't worry about associated types yet, because
we'll be covering them in Chapter XX.</p>
<p>The <code>next</code> method is the main interface into an iterator, and it returns an
<code>Option</code>. If the option is <code>Some(value)</code>, we have gotten another value from the
iterator. If it's <code>None</code>, iteration is finished. Inside of the <code>next</code> method,
we do whatever kind of calculation our iterator needs to do. In this case, we
add one, then check to see if we're still below six. If we are, we can return
<code>Some(self.count)</code> to produce the next value. If we're at six or more,
iteration is over, so we return <code>None</code>.</p>
<p>The iterator trait specifies that when an iterator returns <code>None</code>, that
indicates iteration is finished. The trait does not mandate anything about the
behavior an iterator must have if the <code>next</code> method is called again after
having returned one <code>None</code> value. In this case, every time we call <code>next</code> after
getting the first <code>None</code> value will still return <code>None</code>, but the internal
<code>count</code> field will continue to be incremented by one each time. If we call
<code>next</code> as many times as the maximum value a <code>u32</code> value can hold, <code>count</code> will
overflow (which will <code>panic!</code> in debug mode and wrap in release mode). Other
iterator implementations choose to start iterating again. If you need to be
sure to have an iterator that will always return <code>None</code> on subsequent calls to
the <code>next</code> method after the first <code>None</code> value is returned, you can use the
<code>fuse</code> method to create an iterator with that characteristic out of any other
iterator.</p>
<p>Once we've implemented the <code>Iterator</code> trait, we have an iterator! We can use
the iterator functionality that our <code>Counter</code> struct now has by calling the
<code>next</code> method on it repeatedly:</p>
<pre><code class="language-rust,ignore">let mut counter = Counter::new();
let x = counter.next();
println!(&quot;{:?}&quot;, x);
let x = counter.next();
println!(&quot;{:?}&quot;, x);
let x = counter.next();
println!(&quot;{:?}&quot;, x);
let x = counter.next();
println!(&quot;{:?}&quot;, x);
let x = counter.next();
println!(&quot;{:?}&quot;, x);
let x = counter.next();
println!(&quot;{:?}&quot;, x);
</code></pre>
<p>This will print <code>Some(1)</code> through <code>Some(5)</code> and then <code>None</code>, each on their own
line.</p>
<a class="header" href="#all-sorts-of-iterator-adaptors" name="all-sorts-of-iterator-adaptors"><h3>All Sorts of <code>Iterator</code> Adaptors</h3></a>
<p>In Listing 13-5, we had iterators and we called methods like <code>map</code> and
<code>collect</code> on them. In Listing 13-6, however, we only implemented the <code>next</code>
method on our <code>Counter</code>. How do we get methods like <code>map</code> and <code>collect</code> on our
<code>Counter</code>?</p>
<p>Well, when we told you about the definition of <code>Iterator</code>, we committed a small
lie of omission. The <code>Iterator</code> trait has a number of other useful methods
defined on it that come with default implementations that call the <code>next</code>
method. Since <code>next</code> is the only method of the <code>Iterator</code> trait that does not
have a default implementation, once you've done that, you get all of the other
<code>Iterator</code> adaptors for free. There are a lot of them!</p>
<p>For example, if for some reason we wanted to take the first five values that
an instance of <code>Counter</code> produces, pair those values with values produced by
another <code>Counter</code> instance after skipping the first value that instance
produces, multiply each pair together, keep only those results that are
divisible by three, and add all the resulting values together, we could do so:</p>
<pre><code class="language-rust"># struct Counter {
# count: u32,
# }
#
# impl Counter {
# fn new() -&gt; Counter {
# Counter { count: 0 }
# }
# }
#
# impl Iterator for Counter {
# // Our iterator will produce u32s
# type Item = u32;
#
# fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {
# // increment our count. This is why we started at zero.
# self.count += 1;
#
# // check to see if we've finished counting or not.
# if self.count &lt; 6 {
# Some(self.count)
# } else {
# None
# }
# }
# }
let sum: u32 = Counter::new().take(5)
.zip(Counter::new().skip(1))
.map(|(a, b)| a * b)
.filter(|x| x % 3 == 0)
.sum();
assert_eq!(18, sum);
</code></pre>
<p>Note that zip() produces only four pairs; the theoretical fifth pair (5, None)
is never produced because zip() returns None when either of its input iterators
return None.</p>
<p>All of these method calls are possible because we implemented the <code>Iterator</code>
trait by specifying how the <code>next</code> method works. Use the standard library
documentation to find more useful methods that will come in handy when you're
working with iterators.</p>
<a class="header" href="#improving-our-io-project" name="improving-our-io-project"><h2>Improving our I/O Project</h2></a>
<p>In our I/O project implementing <code>grep</code> in the last chapter, there are some
places where the code could be made clearer and more concise using iterators.
Let's take a look at how iterators can improve our implementation of the
<code>Config::new</code> function and the <code>grep</code> function.</p>
<a class="header" href="#removing-a-clone-by-using-an-iterator" name="removing-a-clone-by-using-an-iterator"><h3>Removing a <code>clone</code> by Using an Iterator</h3></a>
<p>Back in listing 12-8, we had this code that took a slice of <code>String</code> values and
created an instance of the <code>Config</code> struct by checking for the right number of
arguments, indexing into the slice, and cloning the values so that the <code>Config</code>
struct could own those values:</p>
<pre><code class="language-rust,ignore">impl Config {
fn new(args: &amp;[String]) -&gt; Result&lt;Config, &amp;'static str&gt; {
if args.len() &lt; 3 {
return Err(&quot;not enough arguments&quot;);
}
let search = args[1].clone();
let filename = args[2].clone();
Ok(Config {
search: search,
filename: filename,
})
}
}
</code></pre>
<p>At the time, we said not to worry about the <code>clone</code> calls here, and that we
could remove them in the future. Well, that time is now! So, why do we need
<code>clone</code> here? The issue is that we have a slice with <code>String</code> elements in the
parameter <code>args</code>, and the <code>new</code> function does not own <code>args</code>. In order to be
able to return ownership of a <code>Config</code> instance, we need to clone the values
that we put in the <code>search</code> and <code>filename</code> fields of <code>Config</code>, so that the
<code>Config</code> instance can own its values.</p>
<p>Now that we know more about iterators, we can change the <code>new</code> function to
instead take ownership of an iterator as its argument. We'll use the iterator
functionality instead of having to check the length of the slice and index into
specific locations. Since we've taken ownership of the iterator, and we won't be
using indexing operations that borrow anymore, we can move the <code>String</code> values
from the iterator into <code>Config</code> instead of calling <code>clone</code> and making a new
allocation.</p>
<p>First, let's take <code>main</code> as it was in Listing 12-6, and change it to pass the
return value of <code>env::args</code> to <code>Config::new</code>, instead of calling <code>collect</code> and
passing a slice:</p>
<pre><code class="language-rust,ignore">fn main() {
let config = Config::new(env::args());
// ...snip...
</code></pre>
<!-- Will add ghosting in libreoffice /Carol -->
<p>If we look in the standard library documentation for the <code>env::args</code> function,
we'll see that its return type is <code>std::env::Args</code>. So next we'll update the
signature of the <code>Config::new</code> function so that the parameter <code>args</code> has the
type <code>std::env::Args</code> instead of <code>&amp;[String]</code>:</p>
<pre><code class="language-rust,ignore">impl Config {
fn new(args: std::env::Args) -&gt; Result&lt;Config, &amp;'static str&gt; {
// ...snip...
</code></pre>
<!-- Will add ghosting in libreoffice /Carol -->
<p>Next, we'll fix the body of <code>Config::new</code>. As we can also see in the standard
library documentation, <code>std::env::Args</code> implements the <code>Iterator</code> trait, so we
know we can call the <code>next</code> method on it! Here's the new code:</p>
<pre><code class="language-rust"># struct Config {
# search: String,
# filename: String,
# }
#
impl Config {
fn new(mut args: std::env::Args) -&gt; Result&lt;Config, &amp;'static str&gt; {
args.next();
let search = match args.next() {
Some(arg) =&gt; arg,
None =&gt; return Err(&quot;Didn't get a search string&quot;),
};
let filename = match args.next() {
Some(arg) =&gt; arg,
None =&gt; return Err(&quot;Didn't get a file name&quot;),
};
Ok(Config {
search: search,
filename: filename,
})
}
}
</code></pre>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
<p>Remember that the first value in the return value of <code>env::args</code> is the name of
the program. We want to ignore that, so first we'll call <code>next</code> and not do
anything with the return value. The second time we call <code>next</code> should be the
value we want to put in the <code>search</code> field of <code>Config</code>. We use a <code>match</code> to
extract the value if <code>next</code> returns a <code>Some</code>, and we return early with an <code>Err</code>
value if there weren't enough arguments (which would cause this call to <code>next</code>
to return <code>None</code>).</p>
<p>We do the same thing for the <code>filename</code> value. It's slightly unfortunate that
the <code>match</code> expressions for <code>search</code> and <code>filename</code> are so similar. It would be
nice if we could use <code>?</code> on the <code>Option</code> returned from <code>next</code>, but <code>?</code> only
works with <code>Result</code> values currently. Even if we could use <code>?</code> on <code>Option</code> like
we can on <code>Result</code>, the value we would get would be borrowed, and we want to
move the <code>String</code> from the iterator into <code>Config</code>.</p>
<a class="header" href="#making-code-clearer-with-iterator-adaptors" name="making-code-clearer-with-iterator-adaptors"><h3>Making Code Clearer with Iterator Adaptors</h3></a>
<p>The other bit of code where we could take advantage of iterators was in the
<code>grep</code> function as implemented in Listing 12-15:</p>
<!-- We hadn't had a listing number for this code sample when we submitted
chapter 12; we'll fix the listing numbers in that chapter after you've
reviewed it. /Carol -->
<pre><code class="language-rust">fn grep&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(search) {
results.push(line);
}
}
results
}
</code></pre>
<p>We can write this code in a much shorter way, and avoiding having to have a
mutable intermediate <code>results</code> vector, by using iterator adaptor methods like
this instead:</p>
<pre><code class="language-rust">fn grep&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
contents.lines()
.filter(|line| line.contains(search))
.collect()
}
</code></pre>
<p>Here, we use the <code>filter</code> adaptor to only keep the lines that
<code>line.contains(search)</code> returns true for. We then collect them up into another
vector with <code>collect</code>. Much simpler!</p>
<p>We can use the same technique in the <code>grep_case_insensitive</code> function that we
defined in Listing 12-16 as follows:</p>
<!-- Similarly, the code snippet that will be 12-16 didn't have a listing
number when we sent you chapter 12, we will fix it. /Carol -->
<pre><code class="language-rust">fn grep_case_insensitive&lt;'a&gt;(search: &amp;str, contents: &amp;'a str) -&gt; Vec&lt;&amp;'a str&gt; {
let search = search.to_lowercase();
contents.lines()
.filter(|line| {
line.to_lowercase().contains(&amp;search)
}).collect()
}
</code></pre>
<p>Not too bad! So which style should you choose? Most Rust programmers prefer to
use the iterator style. It's a bit tougher to understand at first, but once you
gain an intuition for what the various iterator adaptors do, this is much
easier to understand. Instead of fiddling with the various bits of looping
and building a new vector, the code focuses on the high-level objective of the
loop, abstracting some of the commonplace code so that it's easier to see the
concepts that are unique to this usage of the code, like the condition on which
the code is filtering each element in the iterator.</p>
<p>But are they truly equivalent? Surely the more low-level loop will be faster.
Let's talk about performance.</p>
<a class="header" href="#performance" name="performance"><h2>Performance</h2></a>
<p>Which version of our <code>grep</code> functions is faster: the version with an explicit
<code>for</code> loop or the version with iterators? We ran a benchmark by loading the
entire contents of &quot;The Adventures of Sherlock Holmes&quot; by Sir Arthur Conan
Doyle into a <code>String</code> and looking for the word &quot;the&quot; in the contents. Here were
the results of the benchmark on the version of grep using the <code>for</code> loop and the
version using iterators:</p>
<pre><code class="language-text">test bench_grep_for ... bench: 19,620,300 ns/iter (+/- 915,700)
test bench_grep_iter ... bench: 19,234,900 ns/iter (+/- 657,200)
</code></pre>
<p>The iterator version ended up slightly faster! We're not going to go through
the benchmark code here, as the point is not to prove that they're exactly
equivalent, but to get a general sense of how these two implementations
compare. For a <em>real</em> benchmark, you'd want to check various texts of various
sizes, different words, words of different lengths, and all kinds of other
variations. The point is this: iterators, while a high-level abstraction, get
compiled down to roughly the same code as if you'd written the lower-level code
yourself. Iterators are one of Rust's <em>zero-cost abstractions</em>, by which we mean
using the abstraction imposes no additional runtime overhead in the same way
that Bjarne Stroustrup, the original designer and implementer of C++, defines
<em>zero-overhead</em>:</p>
<blockquote>
<p>In general, C++ implementations obey the zero-overhead principle: What you
don’t use, you don’t pay for. And further: What you do use, you couldn’t hand
code any better.</p>
<ul>
<li>Bjarne Stroustrup &quot;Foundations of C++&quot;</li>
</ul>
</blockquote>
<p>As another example, here is some code taken from an audio decoder. This code
uses an iterator chain to do some math on three variables in scope: a <code>buffer</code>
slice of data, an array of 12 <code>coefficients</code>, and an amount by which to shift
data in <code>qlp_shift</code>. We've declared the variables within this example but not
given them any values; while this code doesn't have much meaning outside of its
context, it's still a concise, real-world example of how Rust translates
high-level ideas to low-level code:</p>
<pre><code class="language-rust,ignore">let buffer: &amp;mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;
for i in 12..buffer.len() {
let prediction = coefficients.iter()
.zip(&amp;buffer[i - 12..i])
.map(|(&amp;c, &amp;s)| c * s as i64)
.sum::&lt;i64&gt;() &gt;&gt; qlp_shift;
let delta = buffer[i];
buffer[i] = prediction as i32 + delta;
}
</code></pre>
<p>In order to calculate the value of <code>prediction</code>, this code iterates through
each of the 12 values in <code>coefficients</code>, uses the <code>zip</code> method to pair the
coefficient values with the previous 12 values in <code>buffer</code>. Then for each pair,
multiply the values together, sum all the results, and shift the bits in the
sum <code>qlp_shift</code> bits to the right</p>
<p>Calculations in applications like audio decoders often prioritize performance
most highly. Here, we're creating an iterator, using two adaptors, then
consuming the value. What assembly code would this Rust code compile to? Well,
as of this writing, it compiles down to the same assembly you'd write by hand.
There's no loop at all corresponding to the iteration over the values in
<code>coefficients</code>: Rust knows that there are twelve iterations, so it &quot;unrolls&quot;
the loop. All of the coefficients get stored in registers (which means
accessing the values is very fast). There are no bounds checks on the array
access. It's extremely efficient.</p>
<p>Now that you know this, go use iterators and closures without fear! They make
code feel higher-level, but don't impose a runtime performance penalty for
doing so.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<p>Closures and iterators are Rust features inspired by functional programming
language ideas. They contribute to Rust's ability to clearly express high-level
ideas. The implementations of closures and iterators, as well as other zero-cost
abstractions in Rust, are such that runtime performance is not affected.</p>
<p>Now that we've improved the expressiveness of our I/O project, let's look at
some more features of <code>cargo</code> that would help us get ready to share the project
with the world.</p>
<a class="header" href="#more-about-cargo-and-cratesio" name="more-about-cargo-and-cratesio"><h1>More about Cargo and Crates.io</h1></a>
<p>We've used some features of Cargo in this book so far, but only the most basic
ones. We've used Cargo to build, run, and test our code, but it can do a lot
more. Let's go over some of its other features now. Cargo can do even more than
what we will cover in this chapter; for a full explanation, see its
documentation.</p>
<p>We're going to cover:</p>
<ul>
<li>Customizing your build through release profiles</li>
<li>Publishing libraries on crates.io</li>
<li>Organizing larger projects with workspaces</li>
<li>Installing binaries from crates.io</li>
<li>Extending Cargo with your own custom commands</li>
</ul>
<a class="header" href="#release-profiles" name="release-profiles"><h2>Release profiles</h2></a>
<p>Cargo supports a notion of <em>release profiles</em>. These profiles control various
options for compiling your code and let you configure each profile
independently of the others. You've seen a hint of this feature in the output
of your builds:</p>
<pre><code class="language-text">$ cargo build
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
$ cargo build --release
Finished release [optimized] target(s) in 0.0 secs
</code></pre>
<p>The &quot;debug&quot; and &quot;release&quot; notifications here indicate that the compiler is
using different profiles. Cargo supports four profiles:</p>
<ul>
<li><code>dev</code>: used for <code>cargo build</code></li>
<li><code>release</code> used for <code>cargo build --release</code></li>
<li><code>test</code> used for <code>cargo test</code></li>
<li><code>doc</code> used for <code>cargo doc</code></li>
</ul>
<p>We can customize our <code>Cargo.toml</code> file with <code>[profile.*]</code> sections to tweak
various compiler options for these profiles. For example, here's one of the
default options for the <code>dev</code> and <code>release</code> profiles:</p>
<pre><code class="language-toml">[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
</code></pre>
<p>The <code>opt-level</code> setting controls how many optimizations Rust will apply to your
code. The setting goes from zero to three. Applying more optimizations takes
more time. When you're compiling very often in development, you'd usually want
compiling to be fast at the expense of the resulting code running slower. When
you're ready to release, it's better to spend more time compiling the one time
that you build your code to trade off for code that will run faster every time
you use that compiled code.</p>
<p>We could override these defaults by changing them in <code>Cargo.toml</code>. For example,
if we wanted to use optimization level 1 in development:</p>
<pre><code class="language-toml">[profile.dev]
opt-level = 1
</code></pre>
<p>This overrides the default setting of <code>0</code>, and now our development builds will
use more optimizations. Not as much as a release build, but a little bit more.</p>
<p>For the full list of settings and the defaults for each profile, see <a href="http://doc.crates.io/">Cargo's
documentation.</a></p>
<a class="header" href="#publishing-a-crate-to-cratesio" name="publishing-a-crate-to-cratesio"><h2>Publishing a Crate to Crates.io</h2></a>
<p>We've added crates from crates.io as dependencies of our project. We can choose
to share our code for other people to use as well. Crates.io distributes the
source code of your packages, so it is primarily used to distribute code that's
open source.</p>
<p>Rust and Cargo have some features that can make your published package easier
for people to find and use. We'll talk about some of those features, then cover
how to publish a package.</p>
<a class="header" href="#documentation-comments" name="documentation-comments"><h3>Documentation Comments</h3></a>
<p>In Chapter 3, we saw comments in Rust that start with <code>//</code>. Rust also has a
second kind of comment: the <em>documentation comment</em>. While comments can be
useful if someone is reading your code, you can generate HTML documentation
that displays the contents of documentation comments for public API items meant
for someone who's interested in knowing how to <em>use</em> your crate, as opposed to
how your crate is <em>implemented</em>. Note that documentation is only generated for
library crates, since binary crates don't have a public API that people need to
know how to use.</p>
<p>Documentation comments use <code>///</code> instead of <code>//</code> and support Markdown notation
inside. They go just before the item they are documenting. Here's documentation
comments for an <code>add_one</code> function:</p>
<figure>
<p><span class="filename">Filename: src/lib.rs</span></p>
<pre><code class="language-rust">/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -&gt; i32 {
/// # x + 1
/// # }
/// ```
pub fn add_one(x: i32) -&gt; i32 {
x + 1
}
</code></pre>
<figcaption>
<p>Listing 14-1: A documentation comment for a function</p>
</figcaption>
</figure>
<p><code>cargo doc</code> runs a tool distributed with Rust, <code>rustdoc</code>, to generate HTML
documentation from these comments. To try this out locally, you can run <code>cargo doc --open</code>, which will build the documentation for your current crate (as well
as all of your crate's dependencies) and open it in a web browser. Navigate to
the <code>add_one</code> function and you'll see how the text in the documentation
comments gets rendered.</p>
<p>Adding examples in code blocks in your documentation comments is a way to
clearly demonstrate how to use your library. There's an additional bonus reason
to do this: <code>cargo test</code> will run the code examples in your documentation as
tests! Nothing is better than documentation with examples. Nothing is worse
than examples that don't actually work because the code has changed since the
documentation has been written. Try running <code>cargo test</code> with the documentation
for the <code>add_one</code> function in Listing 14-1; you'll see a section in the test
results like this:</p>
<pre><code class="language-test"> Doc-tests add-one
running 1 test
test add_one_0 ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Try changing the function or the example to see that <code>cargo test</code> will catch
that the example no longer works!</p>
<p>There's another style of doc comment, <code>//!</code>, to comment containing items (e.g.
crates, modules or functions), instead of the items following it. These are
typically used inside the crate root (lib.rs) or a module's root (mod.rs) to
document the crate or the module as a whole, respectively. Here's the
documentation within the <code>libstd</code> module that contains the entire standard
library:</p>
<pre><code>//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
</code></pre>
<a class="header" href="#exporting-a-convenient-public-api-with-pub-use" name="exporting-a-convenient-public-api-with-pub-use"><h3>Exporting a Convenient Public API with <code>pub use</code></h3></a>
<p>In Chapter 7, we covered how to organize our code into modules with the <code>mod</code>
keyword, how to make items public with the <code>pub</code> keyword, and how to bring
items into a scope with the <code>use</code> keyword. When publishing a crate for people
unfamiliar with the implementation to use, it's worth taking time to consider
if the structure of your crate that's useful for you as you're developing is
what would be useful for people depending on your crate. If the structure isn't
convenient to use from another library, you don't have to rearrange your
internal organization: you can choose to re-export items to make a different
public structure with <code>pub use</code>.</p>
<p>For example, say that we made a library named <code>art</code> consisting of a <code>kinds</code>
module containing an enum named <code>Color</code> and a <code>utils</code> module containing a
function named <code>mix</code> as shown in Listing 14-2:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">//! # Art
//!
//! A library for modeling artistic concepts.
pub mod kinds {
/// The primary colors according to the RYB color model.
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
/// The secondary colors according to the RYB color model.
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils {
use kinds::*;
/// Combines two primary colors in equal amounts to create
/// a secondary color.
pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -&gt; SecondaryColor {
// ...snip...
# SecondaryColor::Green
}
}
</code></pre>
<figcaption>
<p>Listing 14-2: An <code>art</code> library with items organized into <code>kinds</code> and <code>utils</code>
modules</p>
</figcaption>
</figure>
<p>In order to use this library, another crate would have <code>use</code> statements as in
Listing 14-3:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate art;
use art::kinds::PrimaryColor;
use art::utils::mix;
fn main() {
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}
</code></pre>
<figcaption>
<p>Listing 14-3: A program using the <code>art</code> crate's items with its internal
structure exported</p>
</figcaption>
</figure>
<p>Users of this crate shouldn't need to know that <code>PrimaryColor</code> and
<code>SecondaryColor</code> are in the <code>kinds</code> module, and <code>mix</code> is in the <code>utils</code> module;
that structure might be useful for internal organization but doesn't have much
meaning from the outside looking in.</p>
<p>To change this, we can add the following <code>pub use</code> statements to the code from
Listing 14-2 to re-export the types at the top level, as shown in Listing 14-4:</p>
<figure>
<span class="filename">Filename: src/lib.rs</span>
<pre><code class="language-rust">//! # Art
//!
//! A library for modeling artistic concepts.
pub use kinds::PrimaryColor;
pub use kinds::SecondaryColor;
pub use utils::mix;
pub mod kinds {
// ...snip...
# pub enum PrimaryColor;
# pub enum SecondaryColor;
# }
#
# pub mod utils {
# pub fn mix() {}
# }
</code></pre>
<figcaption>
<p>Listing 14-4: Adding <code>pub use</code> statements to re-export items</p>
</figcaption>
</figure>
<!-- Will add ghosting in libreoffice /Carol -->
<p>Re-exports are listed and linked on the front page of the crate's API
documentation. Users of the <code>art</code> crate can still see and choose to use the
internal structure as in Listing 14-3, or they can use the more convenient
structure from Listing 14-4, as shown in Listing 14-5:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust,ignore">extern crate art;
use art::PrimaryColor;
use art::mix;
fn main() {
// ...snip...
}
</code></pre>
<figcaption>
<p>Listing 14-5: Using the re-exported items from the <code>art</code> crate</p>
</figcaption>
</figure>
<!-- Will add ghosting in libreoffice /Carol -->
<p>Creating a useful public API structure is more of an art than a science.
Choosing <code>pub use</code> gives you flexibility in how you expose your crate's
internal structure to users. Take a look at some of the code of crates you've
installed to see if their internal structure differs from their public API.</p>
<a class="header" href="#before-your-first-publish" name="before-your-first-publish"><h3>Before Your First Publish</h3></a>
<p>Before being able to publish any crates, you'll need to create an account on
<a href="https://crates.io">crates.io</a> and get an API token. To do so, <a href="https://crates.io">visit the home page</a>
and log in via a GitHub account. A GitHub account is a requirement for now, but
the site might support other ways of creating an account in the future. Once
you're logged in, visit your <a href="https://crates.io/me">Account Settings</a> page and run the <code>cargo login</code>
command with the API key as the page specifies, which will look something like
this:</p>
<pre><code class="language-text">$ cargo login abcdefghijklmnopqrstuvwxyz012345
</code></pre>
<p>This command will inform Cargo of your API token and store it locally in
<em>~/.cargo/config</em>. Note that this token is a <strong>secret</strong> and should not be
shared with anyone else. If it gets shared with anyone for any reason, you
should regenerate it immediately.</p>
<a class="header" href="#before-publishing-a-new-crate" name="before-publishing-a-new-crate"><h3>Before Publishing a New Crate</h3></a>
<p>First, your crate will need a unique name. While you're working on a crate
locally, you may name a crate whatever you'd like, but crate names on
<a href="https://crates.io">crates.io</a> are allocated on a first-come-first- serve basis. Once a crate name
is taken, it cannot be used for another crate, so check on the site that the
name you'd like is available.</p>
<p>If you try to publish a crate as generated by <code>cargo new</code>, you'll get a warning
and then an error:</p>
<pre><code class="language-text">$ cargo publish
Updating registry `https://github.com/rust-lang/crates.io-index`
warning: manifest has no description, license, license-file, documentation,
homepage or repository.
...snip...
error: api errors: missing or empty metadata fields: description, license.
Please see http://doc.crates.io/manifest.html#package-metadata for how to
upload metadata
</code></pre>
<p>We can include more information about our package in <em>Cargo.toml</em>. Some of
these fields are optional, but a description and a license are required in
order to publish so that people will know what your crate does and under what
terms they may use it.</p>
<p>The description appears with your crate in search results and on your crate's
page. Descriptions are usually a sentence or two. The <code>license</code> field takes a
license identifier value, and the possible values have been specified by the
Linux Foundation's <a href="http://spdx.org/licenses/">Software Package Data Exchange (SPDX)</a>. If you would
like to use a license that doesn't appear there, instead of the <code>license</code> key,
you can use <code>license-file</code> to specify the name of a file in your project that
contains the text of the license you want to use.</p>
<p>Guidance on which license is right for your project is out of scope for this
book. Many people in the Rust community choose to license their projects in the
same way as Rust itself, with a dual license of <code>MIT/Apache-2.0</code>, which
demonstrates that you can specify multiple license identifiers separated by a
slash. So the <em>Cargo.toml</em> for a project that is ready to publish might look
like this:</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;]
description = &quot;A fun game where you guess what number the computer has chosen.&quot;
license = &quot;MIT/Apache-2.0&quot;
[dependencies]
</code></pre>
<p>Be sure to check out the <a href="http://doc.crates.io/manifest.html#package-metadata">documentation on crates.io</a> that
describes other metadata you can specify to ensure your crate can be discovered
and used more easily!</p>
<a class="header" href="#publishing-to-cratesio" name="publishing-to-cratesio"><h3>Publishing to Crates.io</h3></a>
<p>Now that we've created an account, saved our API token, chosen a name for our
crate, and specified the required metadata, we're ready to publish! Publishing
a crate is when a specific version is uploaded to be hosted on crates.io.</p>
<p>Take care when publishing a crate, because a publish is <strong>permanent</strong>. The
version can never be overwritten, and the code cannot be deleted. However,
there is no limit to the number of versions which can be published.</p>
<p>Let's run the <code>cargo publish</code> command, which should succeed this time since
we've now specified the required metadata:</p>
<pre><code class="language-text">$ cargo publish
Updating registry `https://github.com/rust-lang/crates.io-index`
Packaging guessing_game v0.1.0 (file:///projects/guessing_game)
Verifying guessing_game v0.1.0 (file:///projects/guessing_game)
Compiling guessing_game v0.1.0
(file:///projects/guessing_game/target/package/guessing_game-0.1.0)
Finished debug [unoptimized + debuginfo] target(s) in 0.19 secs
Uploading guessing_game v0.1.0 (file:///projects/guessing_game)
</code></pre>
<p>Congratulations! You've now shared your code with the Rust community, and
anyone can easily add your crate as a dependency to their project.</p>
<a class="header" href="#publishing-a-new-version-of-an-existing-crate" name="publishing-a-new-version-of-an-existing-crate"><h3>Publishing a New Version of an Existing Crate</h3></a>
<p>When you've made changes to your crate and are ready to release a new version,
change the <code>version</code> value specified in your <em>Cargo.toml</em>. Use the <a href="http://semver.org/">Semantic
Versioning rules</a> to decide what an appropriate next version number is
based on the kinds of changes you've made. Then run <code>cargo publish</code> to upload
the new version.</p>
<a class="header" href="#removing-versions-from-cratesio-with-cargo-yank" name="removing-versions-from-cratesio-with-cargo-yank"><h3>Removing Versions from Crates.io with <code>cargo yank</code></h3></a>
<p>Occasions may arise where you publish a version of a crate that actually ends
up being broken for one reason or another, such as a syntax error or forgetting
to include a file. For situations such as this, Cargo supports <em>yanking</em> a
version of a crate.</p>
<p>Marking a version of a crate as yanked means that no projects will be able to
start depending on that version, but all existing projects that depend on that
version will continue to be allowed to download and depend on that version. One
of the major goals of crates.io is to act as a permanent archive of code so
that builds of all projects will continue to work, and allowing deletion of a
version would go against this goal. Essentially, a yank means that all projects
with a <em>Cargo.lock</em> will not break, while any future <em>Cargo.lock</em> files
generated will not use the yanked version.</p>
<p>A yank <strong>does not</strong> delete any code. The yank feature is not intended for
deleting accidentally uploaded secrets, for example. If that happens, you must
reset those secrets immediately.</p>
<p>To yank a version of a crate, run <code>cargo yank</code> and specify which version you
want to yank:</p>
<pre><code class="language-text">$ cargo yank --vers 1.0.1
</code></pre>
<p>You can also undo a yank, and allow projects to start depending on a version
again, by adding <code>--undo</code> to the command:</p>
<pre><code class="language-text">$ cargo yank --vers 1.0.1 --undo
</code></pre>
<a class="header" href="#cargo-workspaces" name="cargo-workspaces"><h2>Cargo Workspaces</h2></a>
<p>In Chapter 12, we built a package that included both a binary crate and a
library crate. But what if the library crate continues to get bigger and we
want to split our package up further into multiple library crates? As packages
grow, separating out major components can be quite useful. In this situation,
Cargo has a feature called <em>workspaces</em> that can help us manage multiple
related packages that are developed in tandem.</p>
<p>A <em>workspace</em> is a set of packages that will all share the same <em>Cargo.lock</em>
and output directory. Let's make a project using a workspace where the code
will be trivial so that we can concentrate on the structure of a workspace.
We'll have a binary that uses two libraries: one that will provide an <code>add_one</code>
method and a second that will provide an <code>add_two</code> method. Let's start by
creating a new crate for the binary:</p>
<pre><code class="language-text">$ cargo new --bin adder
Created binary (application) `adder` project
$ cd adder
</code></pre>
<p>We need to modify the binary package's <em>Cargo.toml</em> to tell Cargo the <code>adder</code>
package is a workspace. Add this at the bottom of the file:</p>
<pre><code class="language-toml">[workspace]
</code></pre>
<p>Like many Cargo features, workspaces support convention over configuration: we
don't need to say anything more than this as long as we follow the convention.
The convention is that any crates that we depend on as sub-directories will be
part of the workspace. Let's add a path dependency to the <code>adder</code> crate by
changing the <code>[dependencies]</code> section of <em>Cargo.toml</em> to look like this:</p>
<pre><code class="language-toml">[dependencies]
add-one = { path = &quot;add-one&quot; }
</code></pre>
<p>If we add dependencies that don't have a <code>path</code> specified, those will be normal
dependencies that aren't in this workspace.</p>
<p>Next, generate the <code>add-one</code> crate within the <code>adder</code> directory:</p>
<pre><code class="language-text">$ cargo new add-one
Created library `add-one` project
</code></pre>
<p>Your <code>adder</code> directory should now have these directories and files:</p>
<pre><code class="language-text">├── Cargo.toml
├── add-one
│   ├── Cargo.toml
│   └── src
│   └── lib.rs
└── src
└── main.rs
</code></pre>
<p>In <em>add-one/src/lib.rs</em>, let's add an implementation of an <code>add_one</code> function:</p>
<p><span class="filename">Filename: add-one/src/lib.rs</span></p>
<pre><code class="language-rust">pub fn add_one(x: i32) -&gt; i32 {
x + 1
}
</code></pre>
<p>Open up <em>src/main.rs</em> for <code>adder</code> and add an <code>extern crate</code> line to bring the
new <code>add-one</code> library crate into scope, and change the <code>main</code> function to use
the <code>add_one</code> function:</p>
<pre><code class="language-rust,ignore">extern crate add_one;
fn main() {
let num = 10;
println!(&quot;Hello, world! {} plus one is {}!&quot;, num, add_one::add_one(num));
}
</code></pre>
<p>Let's build it!</p>
<pre><code class="language-text">$ cargo build
Compiling add-one v0.1.0 (file:///projects/adder/add-one)
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 0.68 secs
</code></pre>
<p>Note that running <code>cargo build</code> in the <em>adder</em> directory built both that crate
and the <code>add-one</code> crate in <em>adder/add-one</em>, but created only one <em>Cargo.lock</em>
and one <em>target</em> directory, both in the <em>adder</em> directory. See if you can add
an <code>add-two</code> crate in the same way.</p>
<p>Let's now say that we'd like to use the <code>rand</code> crate in our <code>add-one</code> crate.
As usual, we'll add it to the <code>[dependencies]</code> section in the <code>Cargo.toml</code> for
that crate:</p>
<p><span class="filename">Filename: add-one/Cargo.toml</span></p>
<pre><code class="language-toml">[dependencies]
rand = &quot;0.3.14&quot;
</code></pre>
<p>And if we add <code>extern crate rand;</code> to <em>add-one/src/lib.rs</em> then run <code>cargo build</code>, it will succeed:</p>
<pre><code class="language-text">$ cargo build
Updating registry `https://github.com/rust-lang/crates.io-index`
Downloading rand v0.3.14
...snip...
Compiling rand v0.3.14
Compiling add-one v0.1.0 (file:///projects/adder/add-one)
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 10.18 secs
</code></pre>
<p>The top level <em>Cargo.lock</em> now contains information about the dependency
<code>add-one</code> has on <code>rand</code>. However, even though <code>rand</code> is used somewhere in the
workspace, we can't use it in other crates in the workspace unless we add
<code>rand</code> to their <em>Cargo.toml</em> as well. If we add <code>extern crate rand;</code> to
<em>src/main.rs</em> for the top level <code>adder</code> crate, for example, we'll get an error:</p>
<pre><code class="language-text">$ cargo build
Compiling adder v0.1.0 (file:///projects/adder)
error[E0463]: can't find crate for `rand`
--&gt; src/main.rs:1:1
|
1 | extern crate rand;
| ^^^^^^^^^^^^^^^^^^^ can't find crate
</code></pre>
<p>To fix this, edit <em>Cargo.toml</em> for the top level and indicate that <code>rand</code> is a
dependency for the <code>adder</code> crate.</p>
<p>For another enhancement, let's add a test of the <code>add_one::add_one</code> function
within that crate:</p>
<p><span class="filename">Filename: add-one/src/lib.rs</span></p>
<pre><code class="language-rust">pub fn add_one(x: i32) -&gt; i32 {
x + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(3, add_one(2));
}
}
</code></pre>
<p>Now run <code>cargo test</code> in the top-level <em>adder</em> directory:</p>
<pre><code class="language-text">$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished debug [unoptimized + debuginfo] target(s) in 0.27 secs
Running target/debug/adder-f0253159197f7841
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Wait a second, zero tests? We just added one! If we look at the output, we can
see that <code>cargo test</code> in a workspace only runs the tests for the top level
crate. To run tests for the other crates, we need to use the <code>-p</code> argument to
indicate we want to run tests for a particular package:</p>
<pre><code class="language-text">$ cargo test -p add-one
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
Running target/debug/deps/add_one-abcabcabc
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
Doc-tests add-one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
</code></pre>
<p>Similarly, if you choose to publish the workspace to crates.io, each crate in
the workspace will get published separately.</p>
<p>As your project grows, consider a workspace: smaller components are easier to
understand individually than one big blob of code. Keeping the crates in a
workspace can make coordination among them easier if they work together and are
often changed at the same time.</p>
<a class="header" href="#installing-binaries-from-cratesio-with-cargo-install" name="installing-binaries-from-cratesio-with-cargo-install"><h2>Installing Binaries from Crates.io with <code>cargo install</code></h2></a>
<p>The <code>cargo install</code> command allows you to install and use binary crates
locally. This isn't intended to replace system packages; it's meant to be a
convenient way for Rust developers to install tools that others have shared on
crates.io. Only packages which have binary targets can be installed, and all
binaries are installed into the installation root's <em>bin</em> folder. If you
installed Rust using <em>rustup.rs</em> and don't have any custom configurations, this
will be <code>$HOME/.cargo/bin</code>. Add that directory to your <code>$PATH</code> to be able to
run programs you've gotten through <code>cargo install</code>.</p>
<p>For example, we mentioned in Chapter 12 that there's a Rust implementation of
the <code>grep</code> tool for searching files called <code>ripgrep</code>. If we want to install
<code>ripgrep</code>, we can run:</p>
<pre><code class="language-text">$ cargo install ripgrep
Updating registry `https://github.com/rust-lang/crates.io-index`
Downloading ripgrep v0.3.2
...snip...
Compiling ripgrep v0.3.2
Finished release [optimized + debuginfo] target(s) in 97.91 secs
Installing ~/.cargo/bin/rg
</code></pre>
<p>The last line of the output shows the location and the name of the installed
binary, which in the case of <code>ripgrep</code> is named <code>rg</code>. As long as the
installation directory is in our <code>$PATH</code> as mentioned above, we can then run
<code>rg --help</code> and start using a faster, rustier tool for searching files!</p>
<a class="header" href="#extending-cargo-with-custom-commands" name="extending-cargo-with-custom-commands"><h2>Extending Cargo with Custom Commands</h2></a>
<p>Cargo is designed to be extensible with new subcommands without having to
modify Cargo itself. If a binary in your <code>$PATH</code> is named <code>cargo-something</code>,
you can run it as if it were a Cargo subcommand by running <code>cargo something</code>.
Custom commands like this are also listed when you run <code>cargo --list</code>. It's
convenient to <code>cargo install</code> extensions to Cargo then be able to run them just
like the built-in Cargo tools!</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<p>Sharing code with Cargo and crates.io is part of what makes the Rust ecosystem
useful for many different tasks. Rust's standard library is small and stable,
but crates are easy to share, use, and improve on a different timeline than the
language itself. Don't be shy about sharing code that's useful to you on
crates.io; it's likely that it will be useful to someone else as well!</p>
<a class="header" href="#smart-pointers" name="smart-pointers"><h1>Smart Pointers</h1></a>
<p>By smart pointers we mean a reference with more characteristics.</p>
<p>Example of something that doesn't work</p>
<p>Surprise! Vec and String are technically smart pointers too!</p>
<p>This chapter is not a comprehensive list, but will give some examples of the
ones in the standard library.</p>
<a class="header" href="#boxt" name="boxt"><h2><code>Box&lt;T&gt;</code></h2></a>
<p>Don't use very often in your own code
Heap allocated
Express Ownership of a heap allocated thing</p>
<p>The three situations to use Box</p>
<ol>
<li>Trait objects</li>
<li>Recursive data structures</li>
<li>Extend the lifetime of something</li>
</ol>
<p>How this interacts with the Drop trait</p>
<a class="header" href="#rct" name="rct"><h2><code>Rc&lt;T&gt;</code></h2></a>
<p>Reference counted. Rc is for <em>multiple ownership</em> - this thing should get
deallocated when all of the owners go out of scope.</p>
<p>Show the data structure:</p>
<pre><code class="language-rust">struct Rc&lt;T&gt; {
data: Box&lt;T&gt;,
strong_reference_count: usize,
weak_reference_count: usize,
}
</code></pre>
<p>Talk through this.</p>
<p>This only works if the data is immutable.</p>
<p>What happens when you clone an Rc: data isn't cloned, increase the strong count.
When an Rc clone goes out of scope, the count goes down.</p>
<a class="header" href="#rc-cycles" name="rc-cycles"><h3>Rc Cycles</h3></a>
<p>This is how you leak memory in rust, which btw is totally safe.</p>
<p>Is this garbage collecting? Well it's not tracing GC... if you use Rc and had
a cycle detector, it would be functionally equivalent to a tracing GC. Different
runtime characteristics tho.</p>
<a class="header" href="#solution-turn-an-rc-into-a-weakt" name="solution-turn-an-rc-into-a-weakt"><h4>Solution: turn an Rc into a <code>Weak&lt;T&gt;</code></h4></a>
<p>Same as Rc, but doesn't count towards the strong ref count. When you do this, the
strong ref count goes down and the weak count goes up.</p>
<p>Data gets cleaned up when the strong count is 0, no matter what the weak count is.
However, Rc structure is kept until weak reference count also goes to zero, so weak pointers do not become dangling pointers.
At this point, attempt to upgrade Weak pointer will result into None.
Only when weak reference counter also reduces to zero, Rc structure is freed.</p>
<a class="header" href="#refcellt" name="refcellt"><h2><code>RefCell&lt;T&gt;</code></h2></a>
<p>Single owner of mutable data</p>
<p>The ownership rules checked at runtime instead of compile time.</p>
<p>Only single threaded. See next chapter.</p>
<a class="header" href="#borrow-and-borrow_mut-methods" name="borrow-and-borrow_mut-methods"><h3><code>borrow</code> and <code>borrow_mut</code> methods</h3></a>
<p>Checks all the rules and panics at runtime if the code violates them.</p>
<ol>
<li>
<p>The borrow checker is conservative and people can know more things. (no you
don't, but if you really want to go back to debugging segfaults, feel free)</p>
</li>
<li>
<p>For when you're only allowed to have an immutable thing (which could be <code>Rc</code>)
but you need to be able to mutate the underlying data.</p>
</li>
</ol>
<a class="header" href="#cellt" name="cellt"><h2><code>Cell&lt;T&gt;</code></h2></a>
<p>Same thing as RefCell but for types that are Copy. No borrow checking rules here
anyway. So just reason #2 above.</p>
<a class="header" href="#is-this-really-safe-yes" name="is-this-really-safe-yes"><h2>Is this really safe? Yes!</h2></a>
<p>RefCell is still doing the checks, just at runtime
Cell is safe bc Copy types don't need the ownership rules anyway</p>
<a class="header" href="#the-interior-mutability-pattern" name="the-interior-mutability-pattern"><h3>The Interior Mutability Pattern</h3></a>
<p>The Interior Mutability Pattern is super unsafe internally but safe to use
from the outside and is totally safe, totally, trust us, seriously, it's safe.</p>
<p>Allude to <code>UnsafeCell&lt;T&gt;</code> maybe. Affects optimizations since &amp;mut T is unique.
UnsafeCell turns off those optimizations so that everything doesn't break.</p>
<p>This is how you can opt-out of the default of Rust's ownership rules and opt
in to different guarantees.</p>
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
<p>If you want to implement your own smart pointer, go read the Nomicon.</p>
<p>Now let's talk about concurrency, and some smart pointers that can be used
with multiple threads.</p>
<a class="header" href="#fearless-concurrency" name="fearless-concurrency"><h1>Fearless Concurrency</h1></a>
<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>This is a library abstraction.</p>
<p>Shared mutable state is a problem. Both useful. Functional languages get rid of
mutability.</p>
<p>Ownership rules (that tame the &quot;shared&quot; aspect) enable fearless concurrency: the
compiler is making sure you don't shoot yourself in your foot.</p>
<a class="header" href="#what-are-threads" name="what-are-threads"><h2>What are threads</h2></a>
<a class="header" href="#rusts-concurrency-tradeoffs" name="rusts-concurrency-tradeoffs"><h2>Rust's concurrency tradeoffs</h2></a>
<p>Lots of different languages tackle this problem in different ways. We are not
going to talk about that: exercise for the reader is investigate other languages
and compare and contrast with Rust's approach.</p>
<p>This is how Rust does it, what rust means by threads</p>
<p>OS threads are exposed in the standard library bc a systems programming language
should integrate with your system.</p>
<p>If you have a different threaded mechanism, you need a runtime, rust is trying
to not have a heavy runtime.</p>
<p>These are the reasons Rust's concurrency model is this way as opposed to other
language's ways, which are optimizing for different things.</p>
<a class="header" href="#lets-get-a-thread-threadspawn" name="lets-get-a-thread-threadspawn"><h2>Let's get a thread: <code>thread::spawn</code></h2></a>
<p>Code examples - just print stuff, no data sharing</p>
<a class="header" href="#communicating-between-threads" name="communicating-between-threads"><h2>Communicating between threads</h2></a>
<a class="header" href="#closures-ownership-and-borrowing" name="closures-ownership-and-borrowing"><h3>Closures, Ownership, and Borrowing</h3></a>
<p>The property of being allowed to use variables from the surrounding scope is
also subject to all of the usual rules around ownership and borrowing. Since
closures attempt to infer the types of their parameters, they also infer how
those parameters are borrowed. Closures make that inference by looking at how
they are used. Consider the example in Listing 13-5 that has functions that
borrow immutably, borrow mutably, and move their parameters, then closures that
reference values from their environment and call each of the functions. We'll
see how this affects inference of when a value is borrowed:</p>
<figure>
<span class="filename">Filename: src/main.rs</span>
<pre><code class="language-rust">#[derive(Debug)]
struct Foo;
fn borrows(f: &amp;Foo) {
println!(&quot;Took {:?} by reference.&quot;, f);
}
fn borrows_mut(f: &amp;mut Foo) {
println!(&quot;Took {:?} by mutable reference.&quot;, f);
}
fn moves(f: Foo) {
println!(&quot;Took ownership of {:?}.&quot;, f);
}
fn main() {
let f1 = Foo;
let closure_that_borrows = |x| borrows(x);
closure_that_borrows(&amp;f1);
let mut f2 = Foo;
let closure_that_borrows_mut = |y| borrows_mut(y);
closure_that_borrows_mut(&amp;mut f2);
let f3 = Foo;
let closure_that_moves = |z| moves(z);
closure_that_moves(f3);
}
</code></pre>
<figcaption>
<p>Listing 16-something: Closures that borrow, borrow mutably, and take ownership
of their parameters, which is inferred from how the closure body uses the
parameters</p>
</figcaption>
</figure>
<p>Here, Rust is able to look at how we use the parameters of each closure inside
their bodies. If the closure passes its parameter it to a function that takes
<code>&amp;Foo</code>, then the type of the parameter must be <code>&amp;Foo</code>. If it passes the
parameter to a function that takes <code>&amp;mut Foo</code>, then the type of parameter must
be <code>&amp;mut Foo</code>, and so on. If we try to use <code>f3</code> after the call to
<code>closure_that_moves</code> in the last line of <code>main</code>, we'll get a compiler error
since ownership of <code>f3</code> was transferred to <code>closure_that_moves</code>, which
transferred ownership to the function <code>moves</code>.</p>
<a class="header" href="#overriding-inferred-borrowing-with-the-move-keyword" name="overriding-inferred-borrowing-with-the-move-keyword"><h3>Overriding Inferred Borrowing with the <code>move</code> Keyword</h3></a>
<p>Rust will allow you to override the borrowing inference by using the <code>move</code>
keyword. This will cause all of the closure's parameters to be taken by
ownership, instead of whatever they were inferred as. Consider this example:</p>
<pre><code class="language-rust">let mut num = 4;
{
let mut add_num = |x| num += x;
add_num(6);
}
assert_eq!(10, num);
</code></pre>
<p>In this case, the <code>add_num</code> closure took a mutable reference to <code>num</code>, then
when we called <code>add_num</code>, it mutated the underlying value. In the last line,
<code>num</code> contains 10, as we'd expect. We also needed to declare <code>add_num</code> itself
as <code>mut</code> too, because we're mutating its environment.</p>
<p>If we change the definition of <code>add_num</code> to a <code>move</code> closure, the behavior is
different:</p>
<pre><code class="language-rust">let mut num = 4;
{
let mut add_num = move |x| num += x;
add_num(6);
}
assert_eq!(4, num);
</code></pre>
<p>In the last line, <code>num</code> now contains 4: <code>add_num</code> took ownership of a copy of
<code>num</code>, rather than mutably borrowing <code>num</code>.</p>
<p>One of the most common places you'll see the <code>move</code> keyword used is with
threads, since it's important that one thread is no longer allowed to use a
value once the value has been transferred to another thread through a closure
in order to prevent data races. We'll talk more about that in Chapter XX.</p>
<a class="header" href="#closures-and-lifetimes" name="closures-and-lifetimes"><h3>Closures and Lifetimes</h3></a>
<p>Remember Listing 10-8 from the Lifetime Syntax section of Chapter 10? It looked
like this:</p>
<pre><code class="language-rust,ignore">{
let r;
{
let x = 5;
r = &amp;x;
}
println!(&quot;r: {}&quot;, r);
}
</code></pre>
<p>This example doesn't compile since <code>x</code> doesn't have a long enough lifetime.
Because closures may borrow variables from their enclosing scope, we can
construct a similar example with a closure that borrows <code>x</code> and tries to return
that borrowed value. The code in Listing 13-6 also won't compile:</p>
<figure>
<pre><code class="language-rust,ignore">{
let closure;
{
let x = 4;
closure = || x ; // A closure that takes no arguments and returns x.
}
}
</code></pre>
<figcaption>
<p>Listing 16-something: A closure that tries to return a borrowed value that does
not live long enough</p>
</figcaption>
</figure>
<p>We get an error because <code>x</code> does not live long enough:</p>
<pre><code class="language-text">error: `x` does not live long enough
--&gt;
|
8 | closure = || x ; // A closure that takes no arguments and returns x.
| -- ^ does not live long enough
| |
| capture occurs here
9 | }
| - borrowed value only lives until here
10 | }
| - borrowed value needs to live until here
</code></pre>
<p>To fix the error in the code in Listing 13-6, we can use the <code>move</code> keyword
from the last section to make the closure take ownership of <code>x</code>. Because <code>x</code> is
a number, it is a <code>Copy</code> type and therefore will be copied into the closure.
The code in Listing 13-7 will compile:</p>
<figure>
<pre><code class="language-rust">{
let closure;
{
let mut x = 4;
closure = move || x ; // A closure that takes no arguments and returns x.
x = 5;
assert_eq!(closure(), 4);
}
}
</code></pre>
<figcaption>
<p>Listing 16-something: Moving a value into the closure to fix the lifetime error</p>
</figcaption>
</figure>
<p>Even though we modified <code>x</code> between the closure definition and <code>assert_eq!</code>,
since <code>closure</code> now has its own version, the changes to <code>x</code> won't change the
version of <code>x</code> that's in the closure.</p>
<p>Rust doesn't provide a way to say that some values a closure uses should be
borrowed and some should be moved; it's either all by inference or all moved by
adding the <code>move</code> keyword. However, we can accomplish the goal of borrowing
some values and taking ownership of others by combining <code>move</code> with some extra
bindings. Consider this example where we want to borrow <code>s1</code> but take ownership
of <code>s2</code>:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = String::from(&quot;goodbye&quot;);
let r = &amp;s1;
let calculation = move || {
r;
s2;
};
println!(&quot;Can still use s1 here but not s2: {}&quot;, s1);
</code></pre>
<p>We've declared <code>calculation</code> to <code>move</code> all the values it references. Before
defining <code>calculation</code>, we declare a new variable <code>r</code> that borrows <code>s1</code>. Then
in the body of the <code>calculation</code> closure, we use <code>r</code> instead of using <code>s1</code>
directly. The closure takes ownership of <code>r</code>, but <code>r</code> is a reference, so the
closure hasn't taken ownership of <code>s1</code> even though <code>calculation</code> uses <code>move</code>.</p>
<a class="header" href="#channels" name="channels"><h3><code>Channels</code></h3></a>
<p>Look up examples of cases where channels are useful</p>
<p>Can match modeling of certain problems</p>
<a class="header" href="#send" name="send"><h4><code>Send</code></h4></a>
<p>Send is a trait that means i'm allowed to transfer ownership to another thread
down a channel</p>
<p>What things can be send and what can't?</p>
<a class="header" href="#sharing-data-between-threads" name="sharing-data-between-threads"><h2>Sharing data between threads</h2></a>
<p>Try to share data and get an error about which trait it doesn't implement</p>
<a class="header" href="#sync" name="sync"><h3><code>Sync</code></h3></a>
<p>It's ok to access a thing from multiple threads at once</p>
<p>Immutable things can be sync easily.</p>
<a class="header" href="#arct" name="arct"><h3><code>Arc&lt;T&gt;</code></h3></a>
<p>Atomic Reference Counting. Inner data still has to be immutable.</p>
<p>Steve knows the motivating code that goes here.</p>
<a class="header" href="#mutext" name="mutext"><h3><code>Mutex&lt;T&gt;</code></h3></a>
<p>For mutable data.</p>
<p><code>lock</code> method, you get a Mutex guard. Change, then unlock, which usually happens
automatically when the Mutex guard goes out of scope. If you do this wrong, your
code will hang.</p>
<p>Deadlocks are safe, you have to manage that yourself. Deadlock bugs usually
happen bc you forget to unlock, but drop unlocks automatically.</p>
<a class="header" href="#maybe-make-the-io-project-concurrent" name="maybe-make-the-io-project-concurrent"><h2>Maybe make the I/O project concurrent?</h2></a>
<p>Might be a lot of boilerplate without scoped threads, maybe just allude.</p>
<p>This is a really rough sketch of some ideas that this chapter might cover.</p>
<p>From a comment of steveklabnik's on <a href="https://news.ycombinator.com/item?id=13078384">the definitely not orange website</a>. &quot;that paper&quot; refers to <a href="http://www.hpl.hp.com/techreports/2004/HPL-2004-209.pdf">Boehm 2004</a>.</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 correctness constraints and hence could generate the code
containing 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 <a href="https://github.com/rust-lang/rust/blob/f8614c397313db00e4b4626d1ba77ae00dbf7549/src/libcore/slice.rs#L344-L355">small utility function</a>, 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>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>
<a class="header" href="#arc" name="arc"><h2>Arc</h2></a>
<p>Check out <a href="http://stackoverflow.com/a/40985661/51683">this awesome explanation of <code>Arc</code></a>.</p>
<a class="header" href="#is-rust-oop" name="is-rust-oop"><h1>Is Rust OOP?</h1></a>
<p>Aphorism: DRY</p>
<p>So how do you share code?</p>
<p>I'm used to doing things to solve problems, what do i do instead?
Why do i need to do different things in Rust? Let's look at an example
with the Command pattern.</p>
<a class="header" href="#command-pattern" name="command-pattern"><h2>Command pattern</h2></a>
<p>Look up official def</p>
<p>Want caller to be able to customize what gets done</p>
<p>Method takes command object, calls a run fn</p>
<p>How do we say &quot;we want a thing that has a run function&quot;? Answer: Traits!</p>
<p>where T: Run</p>
<p>This is the definition of the Fn trait! So we wouldn't implement this, we'd just
pass closures in</p>
<a class="header" href="#supertraits" name="supertraits"><h2>Supertraits</h2></a>
<p>Trait constraints that use other traits</p>
<p>Copy requires Clone because Copy is a subset of Clone's behavior, since if you
have one, you can trivially implement the other.</p>
<p>Traits that need behavior of another trait in a default method or something.</p>
<a class="header" href="#trait-objects" name="trait-objects"><h2>Trait objects</h2></a>
<p>Runtime decisions about deciding what shared code we use</p>
<p>Give example code</p>
<p>With traits, libraries are extensible. This is why trait objects are different
than having an enum and a match statement that has to be exhaustive at compile
time and we have to know all the things at compile time and no one can add
new things to the set of possible things</p>
<p>T: trait is a compile time decision, monomorphization == static dispatch</p>
<p>when you implement this trait, you get this other shared behavior</p>
<p>dynamic dispatch (C++)</p>
<a class="header" href="#implementation-details" name="implementation-details"><h3>Implementation details</h3></a>
<ul>
<li>Like how other languages implement oo.</li>
</ul>
<a class="header" href="#how-to-use-it" name="how-to-use-it"><h3>How to use it</h3></a>
<ul>
<li>Statically checked duck typing</li>
</ul>
<a class="header" href="#builder-pattern" name="builder-pattern"><h2>Builder pattern</h2></a>
<p>When you don't know how many arguments you're going to have</p>
<a class="header" href="#delegation" name="delegation"><h2>Delegation</h2></a>
<p>Deref - be mad</p>
<p>Deref is a way to delegate everything, if you don't want that, then write
boilerplate. Sending messages to your components.</p>
<a class="header" href="#how-do-you-share-data" name="how-do-you-share-data"><h2>How do you share data?</h2></a>
<p>Answer: get and set methods, this is awkward and might get better someday.</p>
<a class="header" href="#patterns" name="patterns"><h1>Patterns</h1></a>
<p>We've actually used patterns a few times so far: they're used in <code>let</code>
statements, in function parameters, 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>
<a class="header" href="#let-statements" name="let-statements"><h2><code>let</code> statements</h2></a>
<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 judgment call.</p>
<a class="header" href="#type-annotations" name="type-annotations"><h2>Type annotations</h2></a>
<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>
<a class="header" href="#literals--_" name="literals--_"><h2>Literals &amp; _</h2></a>
<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>
<a class="header" href="#multiple-patterns" name="multiple-patterns"><h1>Multiple patterns</h1></a>
<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>
<a class="header" href="#ref-and-ref-mut" name="ref-and-ref-mut"><h2>ref and ref mut</h2></a>
<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>
<a class="header" href="#destructuring" name="destructuring"><h2>Destructuring</h2></a>
<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>
<a class="header" href="#shadowing" name="shadowing"><h2>Shadowing</h2></a>
<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>
<a class="header" href="#ignoring-values" name="ignoring-values"><h2>Ignoring values</h2></a>
<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>
<a class="header" href="#ranges" name="ranges"><h2>Ranges</h2></a>
<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>
<a class="header" href="#guards" name="guards"><h2>Guards</h2></a>
<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>
<a class="header" href="#bindings" name="bindings"><h2>Bindings</h2></a>
<p>You can bind values to names with <code>@</code>:</p>
<a class="header" href="#more-lifetimes" name="more-lifetimes"><h1>More Lifetimes</h1></a>
<a class="header" href="#lifetimes-that-depend-on-other-lifetimes" name="lifetimes-that-depend-on-other-lifetimes"><h2>Lifetimes that depend on other lifetimes</h2></a>
<p>'a: 'b stuff: subtyping</p>
<a class="header" href="#higher-ranked-trait-bounds" name="higher-ranked-trait-bounds"><h2>Higher ranked trait bounds</h2></a>
<p>for&lt;'a&gt;</p>
<p>Needed for closures</p>
<a class="header" href="#advanced-type-system-features" name="advanced-type-system-features"><h1>Advanced Type System Features</h1></a>
<a class="header" href="#unsafe-rust" name="unsafe-rust"><h2>Unsafe Rust</h2></a>
<p>Things you may do in an unsafe block that you may not in safe rust</p>
<ul>
<li>deref a raw pointer</li>
<li>call an unsafe fn</li>
<li>access or modify a static variable</li>
<li>impl an unsafe trait</li>
</ul>
<p>Go see other stuff</p>
<p>Here's the syntax tho</p>
<p>You know unsafe blocks are the cause of any crashes</p>
<p>wrap all the unsafe, make it as small as possible, present a safe public API</p>
<a class="header" href="#raw-pointers" name="raw-pointers"><h3>Raw Pointers</h3></a>
<a class="header" href="#unsafe-functions" name="unsafe-functions"><h3>Unsafe Functions</h3></a>
<a class="header" href="#transmute" name="transmute"><h4><code>transmute</code></h4></a>
<p>never ever. don't. stop.</p>
<a class="header" href="#extern-fn" name="extern-fn"><h4><code>extern fn</code></h4></a>
<p>You have to write unsafe code to FFI</p>
<a class="header" href="#static" name="static"><h3><code>static</code></h3></a>
<a class="header" href="#unsafe-traits" name="unsafe-traits"><h3>Unsafe Traits</h3></a>
<a class="header" href="#associated-types" name="associated-types"><h2>Associated Types</h2></a>
<p>More common than the other things, less common than the rest of the book</p>
<p>why this is a thing instead of a generic</p>
<a class="header" href="#the-thing-formerly-known-as-ufcs" name="the-thing-formerly-known-as-ufcs"><h2>The Thing Formerly Known as UFCS</h2></a>
<p>Only needed when implementing super generic code</p>
<p>Lots of things are syntax sugar for this</p>
<p>Two traits that impl the same method - how to disambiguate</p>
<a class="header" href="#coherence" name="coherence"><h2>Coherence</h2></a>
<p>Show examples of when you control traits and types or not</p>
<p>Ex: Cannot impl Debug on someone else's type</p>
<p>Solution: newtype</p>
<a class="header" href="#appendix" name="appendix"><h1>Appendix</h1></a>
<p>The following sections contain reference material you may find useful in your
Rust journey.</p>
<a class="header" href="#keywords" name="keywords"><h2>Keywords</h2></a>
<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 parameters.</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>
<a class="header" href="#operators" name="operators"><h2>Operators</h2></a>
<a class="header" href="#unary-operator-expressions" name="unary-operator-expressions"><h3>Unary operator expressions</h3></a>
<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>
<a class="header" href="#binary-operator-expressions" name="binary-operator-expressions"><h3>Binary operator expressions</h3></a>
<p>Binary operators expressions are given in order of operator precedence.</p>
<a class="header" href="#arithmetic-operators" name="arithmetic-operators"><h4>Arithmetic operators</h4></a>
<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>
<a class="header" href="#bitwise-operators" name="bitwise-operators"><h4>Bitwise operators</h4></a>
<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>
<a class="header" href="#lazy-boolean-operators" name="lazy-boolean-operators"><h4>Lazy boolean operators</h4></a>
<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>
<a class="header" href="#comparison-operators" name="comparison-operators"><h4>Comparison operators</h4></a>
<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>
<a class="header" href="#type-cast-expressions" name="type-cast-expressions"><h4>Type cast expressions</h4></a>
<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>
<a class="header" href="#assignment-expressions" name="assignment-expressions"><h4>Assignment expressions</h4></a>
<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>
<a class="header" href="#compound-assignment-expressions" name="compound-assignment-expressions"><h4>Compound assignment expressions</h4></a>
<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>
<a class="header" href="#operator-precedence" name="operator-precedence"><h4>Operator precedence</h4></a>
<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>
<a class="header" href="#derivable-traits" name="derivable-traits"><h2>Derivable Traits</h2></a>
<a class="header" href="#nightly-rust" name="nightly-rust"><h1>Nightly Rust</h1></a>
<a class="header" href="#macros" name="macros"><h1>Macros</h1></a>
<a class="header" href="#basics-of-writing-your-own-macros" name="basics-of-writing-your-own-macros"><h2>Basics of writing your own macros</h2></a>
<a class="header" href="#macros-are-changing-go-see-x-for-more-info" name="macros-are-changing-go-see-x-for-more-info"><h2>Macros are changing, go see X for more info</h2></a>
<a class="header" href="#translations-of-the-book" name="translations-of-the-book"><h2>Translations of the Book</h2></a>
<p>For resources in languages other than English. Most are still in progress; see
<a href="https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations">the Translations label</a> to help or let us know about a new translation!</p>
<ul>
<li><a href="https://coreh.github.io/rust-book-pt-br/">Português</a></li>
<li><a href="https://rust-vietnam.github.io/book/">Tiếng việt</a></li>
<li><a href="http://www.broadview.com.cn/article/144">简体中文</a></li>
</ul>
</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>