mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:34:52 -06:00
11181 lines
562 KiB
HTML
11181 lines
562 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>The Rust Programming Language</title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body class="light">
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums</a></li><li><ul class="section"><li><a href="ch06-01-option.html"><strong>6.1.</strong> Option</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> Match</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-fundamental-collections.html"><strong>8.</strong> Fundamental Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generics</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Syntax</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Lifetime syntax</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><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 - Iterators and Closures</a></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></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><strong>21.</strong> Macros</li><li><ul class="section"><li><strong>21.1.</strong> Writing Your Own Macros</li></ul></li><li><a href="appendix-00.html"><strong>22.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>22.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>22.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>22.3.</strong> Derivable Traits</a></li><li><a href="appendix-04-nightly-rust.html"><strong>22.4.</strong> Nightly Rust</a></li></ul></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar" class="menu-bar">
|
||
<div class="left-buttons">
|
||
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
||
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Rust Programming Language</h1>
|
||
|
||
<div class="right-buttons">
|
||
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="content" class="content">
|
||
<h1>Introduction</h1>
|
||
<p>Welcome to “The Rust Programming Language,” an introductory book about Rust.
|
||
Rust is a programming language that’s focused on safety, speed, and
|
||
concurrency. Its design lets you create programs that have the performance and
|
||
control of a low-level language, but with the powerful abstractions of a
|
||
high-level language. These properties make Rust suitable for programmers who
|
||
have experience in languages like C and are looking for a safer alternative, as
|
||
well as those from languages like Python who are looking for ways to write code
|
||
that performs better without sacrificing expressiveness.</p>
|
||
<p>Rust performs the majority of its safety checks and memory management decisions
|
||
at compile time, so that your program's runtime performance isn't impacted. This
|
||
makes it useful in a number of use cases that other languages aren’t good at:
|
||
programs with predictable space and time requirements, embedding in other
|
||
languages, and writing low-level code, like device drivers and operating
|
||
systems. It's also great for web applications: it powers the Rust package
|
||
registry site, crates.io! We're excited to see what <em>you</em> create with Rust.</p>
|
||
<p>This book is written for a reader who already knows how to program in at least
|
||
one programming language. After reading this book, you should be comfortable
|
||
writing Rust programs. We’ll be learning Rust through small, focused examples
|
||
that build on each other to demonstrate how to use various features of Rust as
|
||
well as how they work behind the scenes.</p>
|
||
<h2>Contributing to the book</h2>
|
||
<p>This book is open source. If you find an error, please don’t hesitate to file an
|
||
issue or send a pull request <a href="https://github.com/rust-lang/book">on GitHub</a>.</p>
|
||
<h2>Installation</h2>
|
||
<p>The first step to using Rust is to install it. You’ll need an internet
|
||
connection to run the commands in this chapter, as we’ll be downloading Rust
|
||
from the internet.</p>
|
||
<p>We’ll be showing off a number of commands using a terminal, and those lines all
|
||
start with <code>$</code>. You don't need to type in the <code>$</code> character; they are there to indicate
|
||
the start of each command. You’ll see many tutorials and examples around the web
|
||
that follow this convention: <code>$</code> for commands run as a regular user, and <code>#</code>
|
||
for commands you should be running as an administrator. Lines that don't start
|
||
with <code>$</code> are typically showing the output of the previous command.</p>
|
||
<h3>Installing on Linux or Mac</h3>
|
||
<p>If you're on Linux or a Mac, all you need to do is open a terminal and type
|
||
this:</p>
|
||
<pre><code class="language-text">$ curl https://sh.rustup.rs -sSf | sh
|
||
</code></pre>
|
||
<p>This will download a script and start the installation. You may be prompted for
|
||
your password. If it all goes well, you’ll see this appear:</p>
|
||
<pre><code class="language-text">Rust is installed now. Great!
|
||
</code></pre>
|
||
<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>
|
||
<h3>Installing on Windows</h3>
|
||
<p>On Windows, go to <a href="https://rustup.rs/">https://rustup.rs</a><!-- ignore --> and
|
||
follow the instructions to download rustup-init.exe. Run that and follow the
|
||
rest of the instructions it gives you.</p>
|
||
<p>The rest of the Windows-specific commands in the book will assume that you are
|
||
using <code>cmd</code> as your shell. If you use a different shell, you may be able to run
|
||
the same commands that Linux and Mac users do. If neither work, consult the
|
||
documentation for the shell you are using.</p>
|
||
<h3>Custom installations</h3>
|
||
<p>If you have reasons for preferring not to use rustup.rs, please see <a href="https://www.rust-lang.org/install.html">the Rust
|
||
installation page</a> for other options.</p>
|
||
<h3>Uninstalling</h3>
|
||
<p>Uninstalling Rust is as easy as installing it. From your shell, run
|
||
the uninstall script:</p>
|
||
<pre><code class="language-text">$ rustup self uninstall
|
||
</code></pre>
|
||
<h3>Troubleshooting</h3>
|
||
<p>If you've got Rust installed, you can open up a shell, and type this:</p>
|
||
<pre><code class="language-text">$ rustc --version
|
||
</code></pre>
|
||
<p>You should see the version number, commit hash, and commit date in a format
|
||
similar to this for the latest stable version at the time you install:</p>
|
||
<pre><code class="language-text">rustc x.y.z (abcabcabc yyyy-mm-dd)
|
||
</code></pre>
|
||
<p>If you see this, Rust has been installed successfully!
|
||
Congrats!</p>
|
||
<p>If you don't and you're on Windows, check that Rust is in your <code>%PATH%</code> system
|
||
variable.</p>
|
||
<p>If it still isn't working, there are a number of places where you can get help.
|
||
The easiest is <a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a><!-- ignore -->,
|
||
which you can access through <a href="http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust">Mibbit</a>. Go to that address, and you'll
|
||
be chatting with other Rustaceans (a silly nickname we call ourselves) who can
|
||
help you out. Other great resources include <a href="https://users.rust-lang.org/">the user’s forum</a> and
|
||
<a href="http://stackoverflow.com/questions/tagged/rust">Stack Overflow</a>.</p>
|
||
<h3>Local documentation</h3>
|
||
<p>The installer also includes a copy of the documentation locally, so you can
|
||
read it offline. Run <code>rustup doc</code> to open the local documentation in your
|
||
browser.</p>
|
||
<p>Any time there's a type or function provided by the standard library and you're
|
||
not sure what it does, use the API documentation to find out!</p>
|
||
<h2>Hello, World!</h2>
|
||
<p>Now that you have Rust installed, let’s write your first Rust program. It's
|
||
traditional when learning a new language to write a little program to print the
|
||
text “Hello, world!” to the screen, and in this section, we'll follow that
|
||
tradition.</p>
|
||
<blockquote>
|
||
<p>Note: This book assumes basic familiarity with the command line. Rust itself
|
||
makes no specific demands about your editing, tooling, or where your code
|
||
lives, so if you prefer an IDE to the command line, feel free to use your
|
||
favorite IDE.</p>
|
||
</blockquote>
|
||
<h3>Creating a Project File</h3>
|
||
<p>First, make a file to put your Rust code in. Rust doesn't care where your code
|
||
lives, but for this book, we'd suggest making a <em>projects</em> directory in your
|
||
home directory and keeping all your projects there. Open a terminal and enter
|
||
the following commands to make a directory for this particular project:</p>
|
||
<p>Linux and Mac:</p>
|
||
<pre><code class="language-text">$ mkdir ~/projects
|
||
$ cd ~/projects
|
||
$ mkdir hello_world
|
||
$ cd hello_world
|
||
</code></pre>
|
||
<p>Windows:</p>
|
||
<pre><code class="language-cmd">> mkdir %USERPROFILE%\projects
|
||
> cd %USERPROFILE%\projects
|
||
> mkdir hello_world
|
||
> cd hello_world
|
||
</code></pre>
|
||
<h3>Writing and Running a Rust Program</h3>
|
||
<p>Next, make a new source file and call it <em>main.rs</em>. Rust files always end with
|
||
the <em>.rs</em> extension. If you’re using more than one word in your filename, use
|
||
an underscore to separate them. For example, you'd use <em>hello_world.rs</em> rather
|
||
than <em>helloworld.rs</em>.</p>
|
||
<p>Now open the <em>main.rs</em> file you just created, and type the following code:</p>
|
||
<p><span class="filename">Filename: main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Save the file, and go back to your terminal window. On Linux or OSX, enter the
|
||
following commands:</p>
|
||
<pre><code class="language-text">$ rustc main.rs
|
||
$ ./main
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>On Windows, just replace <code>./main</code> with <code>.\main.exe</code>. Regardless of your
|
||
operating system, you should see the string <code>Hello, world!</code> print to the
|
||
terminal. If you did, then congratulations! You've officially written a Rust
|
||
program. That makes you a Rust programmer! Welcome.</p>
|
||
<h3>Anatomy of a Rust Program</h3>
|
||
<p>Now, let’s go over what just happened in your "Hello, world!" program in
|
||
detail. Here's the first piece of the puzzle:</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
|
||
}
|
||
</code></pre>
|
||
<p>These lines define a <em>function</em> in Rust. The <code>main</code> function is special: it's
|
||
the first thing that is run for every executable Rust program. The first line
|
||
says, “I’m declaring a function named <code>main</code> that takes no arguments and
|
||
returns nothing.” If there were arguments, they would go inside the parentheses,
|
||
<code>(</code> and <code>)</code>.</p>
|
||
<p>Also note that the function body is wrapped in curly braces, <code>{</code> and <code>}</code>. Rust
|
||
requires these around all function bodies. It's considered good style to put
|
||
the opening curly brace on the same line as the function declaration, with one
|
||
space in between.</p>
|
||
<p>Inside the <code>main</code> function:</p>
|
||
<pre><code class="language-rust"> println!("Hello, world!");
|
||
</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>"Hello, world!"</code> which is a <em>string</em>. We pass this string as an
|
||
argument to <code>println!</code>, which prints the string to the screen. Easy enough!</p>
|
||
<p>The line ends with a semicolon (<code>;</code>). The <code>;</code> indicates that this expression is
|
||
over, and the next one is ready to begin. Most lines of Rust code end with a
|
||
<code>;</code>.</p>
|
||
<h3>Compiling and Running Are Separate Steps</h3>
|
||
<p>In "Writing and Running a Rust Program", 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">> 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 "Hello, world!" program, this would print <code>Hello, world!</code> to your terminal.</p>
|
||
<p>If you come from a dynamic language like Ruby, Python, or JavaScript, you may
|
||
not be used to compiling and running a program being separate steps. Rust is an
|
||
<em>ahead-of-time compiled</em> language, which means that you can compile a program,
|
||
give it to someone else, and they can run it even without having Rust
|
||
installed. If you give someone a <code>.rb</code>, <code>.py</code>, or <code>.js</code> file, on the other
|
||
hand, they need to have a Ruby, Python, or JavaScript implementation installed
|
||
(respectively), but you only need one command to both compile and run your
|
||
program. Everything is a tradeoff in language design.</p>
|
||
<p>Just compiling with <code>rustc</code> is fine for simple programs, but as your project
|
||
grows, you'll want to be able to manage all of the options your project has
|
||
and make it easy to share your code with other people and projects. Next, we'll
|
||
introduce you to a tool called Cargo, which will help you write real-world Rust
|
||
programs.</p>
|
||
<h2>Hello, Cargo!</h2>
|
||
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
|
||
manage their Rust projects because it makes a lot of tasks easier. For example,
|
||
Cargo takes care of building your code, downloading the libraries your code
|
||
depends on, and building those libraries. We call libraries your code needs
|
||
<em>dependencies</em>.</p>
|
||
<p>The simplest Rust programs, like the one we've written so far, don’t have any
|
||
dependencies, so right now, you'd only be using the part of Cargo that can take
|
||
care of building your code. As you write more complex Rust programs, you’ll
|
||
want to add dependencies, and if you start off using Cargo, that will be a lot
|
||
easier to do.</p>
|
||
<p>As the vast, vast majority of Rust projects use Cargo, we will assume that
|
||
you’re using it for the rest of the book. Cargo comes installed with Rust
|
||
itself, if you used the official installers as covered in the Installation
|
||
chapter. If you installed Rust through some other means, you can check if you
|
||
have Cargo installed by typing the following into your terminal:</p>
|
||
<pre><code class="language-text">$ cargo --version
|
||
</code></pre>
|
||
<p>If you see a version number, great! If you see an error like <code>command not found</code>, then you should look at the documentation for your method of
|
||
installation to determine how to install Cargo separately.</p>
|
||
<h3>Creating a Project with Cargo</h3>
|
||
<p>Let's create a new project using Cargo and look at how it differs from our
|
||
project in <code>hello_world</code>. Go back to your projects directory (or wherever you
|
||
decided to put your code):</p>
|
||
<p>Linux and Mac:</p>
|
||
<pre><code class="language-text">$ cd ~/projects
|
||
</code></pre>
|
||
<p>Windows:</p>
|
||
<pre><code class="language-cmd">> 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 = "hello_cargo"
|
||
version = "0.1.0"
|
||
authors = ["Your Name <you@example.com>"]
|
||
|
||
[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!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Cargo has generated a "Hello World!" for you, just like the one we wrote
|
||
earlier! So that part is the same. The differences between our previous project
|
||
and the project generated by Cargo that we've seen so far are:</p>
|
||
<ul>
|
||
<li>Our code goes in the <em>src</em> directory</li>
|
||
<li>The top level contains a <em>Cargo.toml</em> configuration file</li>
|
||
</ul>
|
||
<p>Cargo expects your source files to live inside the <em>src</em> directory so that the
|
||
top-level project directory is just for READMEs, license information,
|
||
configuration files, and anything else not related to your code. In this way,
|
||
using Cargo helps you keep your projects nice and tidy. There's a place for
|
||
everything, and everything is in its place.</p>
|
||
<p>If you started a project that doesn't use Cargo, as we did with our project in
|
||
the <em>hello_world</em> directory, you can convert it to a project that does use
|
||
Cargo by moving your code into the <em>src</em> directory and creating an appropriate
|
||
<em>Cargo.toml</em>.</p>
|
||
<h3>Building and Running a Cargo Project</h3>
|
||
<p>Now let's look at what's different about building and running your Hello World
|
||
program through Cargo! To do so, enter the following commands:</p>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
|
||
</code></pre>
|
||
<p>This should have created an executable file in <em>target/debug/hello_cargo</em> (or
|
||
<em>target\debug\hello_cargo.exe</em> on Windows), which you can run with this command:</p>
|
||
<pre><code class="language-text">$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
|
||
<p>Running <code>cargo build</code> for the first time also causes Cargo to create a new file
|
||
at the top level called <em>Cargo.lock</em>, which looks like this:</p>
|
||
<p><span class="filename">Filename: Cargo.lock</span></p>
|
||
<pre><code class="language-toml">[root]
|
||
name = "hello_cargo"
|
||
version = "0.1.0"
|
||
</code></pre>
|
||
<p>Cargo uses the <em>Cargo.lock</em> to keep track of dependencies in your application.
|
||
This project doesn't have dependencies, so the file is a bit sparse.
|
||
Realistically, you won't ever need to touch this file yourself; just let Cargo
|
||
handle it.</p>
|
||
<p>We just built a project with <code>cargo build</code> and ran it with
|
||
<code>./target/debug/hello_cargo</code>, but we can also use <code>cargo run</code> to compile
|
||
and then run:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Running `target/debug/hello_cargo`
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>Notice that this time, we didn't see the output telling us that Cargo was
|
||
compiling <code>hello_cargo</code>. Cargo figured out that the files haven’t changed, so
|
||
it just ran the binary. If you had modified your source code, Cargo would have
|
||
rebuilt the project before running it, and you would have seen something like
|
||
this:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
|
||
Running `target/debug/hello_cargo`
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>So a few more differences we've now seen:</p>
|
||
<ul>
|
||
<li>Instead of using <code>rustc</code>, build a project using <code>cargo build</code> (or build and
|
||
run it in one step with <code>cargo run</code>)</li>
|
||
<li>Instead of the result of the build being put in the same directory as our
|
||
code, Cargo will put it in the <em>target/debug</em> directory.</li>
|
||
</ul>
|
||
<p>The other advantage of using Cargo is that the commands are the same no matter
|
||
what operating system you're on, so at this point we will no longer be
|
||
providing specific instructions for Linux and Mac versus Windows.</p>
|
||
<h3>Building for Release</h3>
|
||
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. This will create an
|
||
executable in <em>target/release</em> instead of <em>target/debug</em>. These optimizations
|
||
make your Rust code run faster, but turning them on makes your program take
|
||
longer to compile. This is why there are two different profiles: one for
|
||
development when you want to be able to rebuild quickly and often, and one for
|
||
building the final program you’ll give to a user that won't be rebuilt and
|
||
that we want to run as fast as possible. If you're benchmarking the running
|
||
time of your code, be sure to run <code>cargo build --release</code> and benchmark with
|
||
the executable in <em>target/release</em>.</p>
|
||
<h3>Cargo as Convention</h3>
|
||
<p>With simple projects, Cargo doesn't provide a whole lot of value over just
|
||
using <code>rustc</code>, but it will prove its worth as you continue. With complex
|
||
projects composed of multiple crates, it’s much easier to let Cargo coordinate
|
||
the build. With Cargo, you can just run <code>cargo build</code>, and it should work the
|
||
right way. Even though this project is simple, it now uses much of the real
|
||
tooling you’ll use for the rest of your Rust career. In fact, you can get
|
||
started with virtually all Rust projects you want to work
|
||
on with the following commands:</p>
|
||
<pre><code class="language-text">$ git clone someurl.com/someproject
|
||
$ cd someproject
|
||
$ cargo build
|
||
</code></pre>
|
||
<blockquote>
|
||
<p>Note: If you want to look at Cargo in more detail, check out the official
|
||
<a href="http://doc.crates.io/guide.html">Cargo guide</a>, which covers all of its features.</p>
|
||
</blockquote>
|
||
<h1>Guessing Game</h1>
|
||
<p>Let’s jump into Rust by working through a hands-on project together! This
|
||
chapter introduces you to a few common Rust concepts by showing you how to use
|
||
them in a real program. You’ll learn about <code>let</code>, <code>match</code>, methods, associated
|
||
functions, using external crates, and more! The following chapters will explore
|
||
these ideas in more detail. In this chapter, you’ll practice the fundamentals.</p>
|
||
<p>We’ll implement a classic beginner programming problem: a guessing game. Here’s
|
||
how it works: the program will generate a random integer between 1 and 100. It
|
||
will then prompt the player to enter a guess. After entering a guess, it will
|
||
indicate whether the guess is too low or too high. If the guess is correct, the
|
||
game will print congratulations and exit.</p>
|
||
<h2>Setting Up a New Project</h2>
|
||
<p>To set up a new project, go to the <em>projects</em> directory that you created in
|
||
Chapter 1, and make a new project using Cargo, like so:</p>
|
||
<pre><code class="language-text">$ cargo new guessing_game --bin
|
||
$ cd guessing_game
|
||
</code></pre>
|
||
<p>The first command, <code>cargo new</code>, takes the name of the project (<code>guessing_game</code>)
|
||
as the first argument. The <code>--bin</code> flag tells Cargo to make a binary project,
|
||
similar to the one in Chapter 1. The second command changes to the new
|
||
project’s directory.</p>
|
||
<p>Look at the generated <em>Cargo.toml</em> file:</p>
|
||
<p><span class="filename">Filename: Cargo.toml</span></p>
|
||
<pre><code class="language-toml">[package]
|
||
name = "guessing_game"
|
||
version = "0.1.0"
|
||
authors = ["Your Name <you@example.com>"]
|
||
|
||
[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!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Now let’s compile this “Hello, world!” program and run it in the same step
|
||
using the <code>cargo run</code> command:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>The <code>run</code> command comes in handy when you need to rapidly iterate on a project,
|
||
and this game is such a project: we want to quickly test each iteration
|
||
before moving on to the next one.</p>
|
||
<p>Reopen the <em>src/main.rs</em> file. You’ll be writing all the code in this file.</p>
|
||
<h2>Processing a Guess</h2>
|
||
<p>The first part of the program will ask for user input, process that input, and
|
||
check that the input is in the expected form. To start, we’ll allow the player
|
||
to input a guess. Enter the code in Listing 2-1 into <em>src/main.rs</em>.</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">use std::io;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-1: Code to get a guess from the user and print it out</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>This code contains a lot of information, so let’s go over it bit by bit. To
|
||
obtain user input and then print the result as output, we need to import the
|
||
<code>io</code> (input/output) library from the standard library (which is known as <code>std</code>):</p>
|
||
<pre><code class="language-rust,ignore">use std::io;
|
||
</code></pre>
|
||
<p>By default, Rust imports only a few types into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
|
||
<em>prelude</em></a><!-- ignore -->. If a type you want to use isn’t in the
|
||
prelude, you have to import that type into your program explicitly with a <code>use</code>
|
||
statement. Using the <code>std::io</code> library provides you with a number of useful
|
||
<code>io</code>-related features, including the functionality to accept user input.</p>
|
||
<p>As you saw in Chapter 1, the <code>main</code> function is the entry point into the
|
||
program:</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
</code></pre>
|
||
<p>The <code>fn</code> syntax declares a new function, the <code>()</code> indicate there are no
|
||
arguments, and <code>{</code> starts the body of the function.</p>
|
||
<p>As you also learned in Chapter 1, <code>println!</code> is a macro that prints a string to
|
||
the screen:</p>
|
||
<pre><code class="language-rust,ignore">println!("Guess the number!");
|
||
|
||
println!("Please input your guess.");
|
||
</code></pre>
|
||
<p>This code is just printing a prompt stating what the game is and requesting
|
||
input from the user.</p>
|
||
<h3>Storing Values with Variables</h3>
|
||
<p>Next, we’ll create a place to store the user input, like this:</p>
|
||
<pre><code class="language-rust,ignore">let mut guess = String::new();
|
||
</code></pre>
|
||
<p>Now the program is getting interesting! There’s a lot going on in this little
|
||
line. Notice that this is a <code>let</code> statement, which is used to create
|
||
<em>variables</em>. Here’s another example:</p>
|
||
<pre><code class="language-rust,ignore">let foo = bar;
|
||
</code></pre>
|
||
<p>This line will create a new variable named <code>foo</code> and bind it to the value
|
||
<code>bar</code>. In Rust, variables are immutable by default. The following example shows
|
||
how to use <code>mut</code> before the variable name to make a variable mutable:</p>
|
||
<pre><code class="language-rust">let foo = 5; // immutable
|
||
let mut bar = 5; // mutable
|
||
</code></pre>
|
||
<blockquote>
|
||
<p>Note: The <code>//</code> syntax starts a comment that continues until the end of the
|
||
line. Rust ignores everything in comments.</p>
|
||
</blockquote>
|
||
<p>Now you know that <code>let mut guess</code> will introduce a mutable variable named
|
||
<code>guess</code>. On the other side of the equal sign (<code>=</code>) is the value that <code>guess</code> is
|
||
bound to, which is the result of calling <code>String::new</code>, a function that returns
|
||
a new instance of a <code>String</code>. <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a string
|
||
type provided by the standard library that is a growable, UTF-8 encoded bit of
|
||
text.</p>
|
||
<p>The <code>::</code> syntax in the <code>::new</code> line indicates that <code>new</code> is an <em>associated
|
||
function</em> of the <code>String</code> type. An associated function is implemented on a type,
|
||
in this case <code>String</code>, rather than on a particular instance of a <code>String</code>. Some
|
||
languages call this a <em>static method</em>.</p>
|
||
<p>This <code>new</code> function creates a new, empty <code>String</code>. You’ll find a <code>new</code> function
|
||
on many types, because it’s a common name for a function that makes a new value
|
||
of some kind.</p>
|
||
<p>To summarize, the <code>let mut guess = String::new();</code> line has created a mutable
|
||
variable that is currently bound to a new, empty instance of a <code>String</code>. Whew!</p>
|
||
<p>Recall that we included the input/output functionality from the standard
|
||
library with <code>use std::io;</code> on the first line of the program. Now we’ll call an
|
||
associated function, <code>stdin</code>, on <code>io</code>:</p>
|
||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
</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(&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>&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>&</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>&mut guess</code> rather than <code>&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("Failed to read line");
|
||
</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(&mut guess).expect("Failed to read line");
|
||
</code></pre>
|
||
<p>However, one long line is difficult to read, so it’s best to divide it, two
|
||
lines for two method calls. Now let’s discuss what this line does.</p>
|
||
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
|
||
<p>As mentioned earlier, <code>read_line</code> puts what the user types into the string we’re
|
||
passing it, but it also returns a value—in this case, an
|
||
<a href="../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
|
||
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore --> as
|
||
well as specific versions for submodules, such as <code>io::Result</code>.</p>
|
||
<p>The <code>Result</code> types are <a href="ch06-00-enums.html"><em>enumerations</em></a><!-- ignore -->, often referred
|
||
to as <em>enums</em>. An enumeration is a type that can have a fixed set of values,
|
||
and those values are called the enum’s <em>variants</em>. Chapter 6 will cover enums
|
||
in more detail.</p>
|
||
<p>For <code>Result</code>, the variants are <code>Ok</code> or <code>Err</code>. <code>Ok</code> indicates the operation was
|
||
successful, and inside the <code>Ok</code> variant is the successfully generated value.
|
||
<code>Err</code> means the operation failed, and <code>Err</code> contains information about how or
|
||
why the operation failed.</p>
|
||
<p>The purpose of these <code>Result</code> types is to encode error handling information.
|
||
Values of the <code>Result</code> type, like any type, have methods defined on them. An
|
||
instance of <code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that
|
||
you can call. If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will
|
||
cause the program to crash and display the message that you passed as an
|
||
argument to <code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would
|
||
likely be the result of an error coming from the underlying operating system.
|
||
If this instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the
|
||
return value that <code>Ok</code> is holding and return just that value to you so you
|
||
could use it. In this case, that value is the number of characters the user
|
||
entered into standard input.</p>
|
||
<p>If we don’t call <code>expect</code>, the program will compile, but we’ll get a warning:</p>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||
#[warn(unused_must_use)] on by default
|
||
src/main.rs:10 io::stdin().read_line(&mut guess);
|
||
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
</code></pre>
|
||
<p>Rust warns that we haven’t used the <code>Result</code> value returned from <code>read_line</code>,
|
||
indicating that the program hasn’t handled a possible error. The right way to
|
||
suppress the warning is to actually write error handling, but since we just
|
||
want to crash this program when a problem occurs, we can use <code>expect</code>. You’ll
|
||
learn about recovering from errors in Chapter 9.</p>
|
||
<h3>Printing Values with <code>println!</code> Placeholders</h3>
|
||
<p>Aside from the closing curly brace, there’s only one more line to discuss in
|
||
the code added so far, which is the following:</p>
|
||
<pre><code class="language-rust,ignore">println!("You guessed: {}", 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!("x = {} and y = {}", x, y);
|
||
</code></pre>
|
||
<p>This code would print out <code>x = 5 and y = 10</code>.</p>
|
||
<h3>Testing the First Part</h3>
|
||
<p>Let’s test the first part of the guessing game. You can run it using <code>cargo run</code>:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
Please input your guess.
|
||
6
|
||
You guessed: 6
|
||
</code></pre>
|
||
<p>At this point, the first part of the game is done: we’re getting input from the
|
||
keyboard and then printing it.</p>
|
||
<h2>Generating a Secret Number</h2>
|
||
<p>Next, we need to generate a secret number that the user will try to guess. The
|
||
secret number should be different every time so the game is fun to play more
|
||
than once. Let’s use a random number between 1 and 100 so the game isn’t too
|
||
difficult. Rust doesn’t yet include random number functionality in its standard
|
||
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
|
||
<h3>Using a Crate to Get More Functionality</h3>
|
||
<p>Remember that a <em>crate</em> is a package of Rust code. The project we’ve been
|
||
building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is a
|
||
<em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||
<p>Cargo’s use of external crates is where it really shines. Before we can write
|
||
code that uses <code>rand</code>, we need to modify the <em>Cargo.toml</em> file to include the
|
||
<code>rand</code> crate as a dependency. Open that file now and add the following line to
|
||
the bottom beneath the <code>[dependencies]</code> section header that Cargo created for
|
||
you:</p>
|
||
<p><span class="filename">Filename: Cargo.toml</span></p>
|
||
<pre><code class="language-toml">[dependencies]
|
||
|
||
rand = "0.3.14"
|
||
</code></pre>
|
||
<p>In the <em>Cargo.toml</em> file, everything that follows a header is part of a section
|
||
that continues until another section starts. The <code>[dependencies]</code> section is
|
||
where you tell Cargo which external crates your project depends on and which
|
||
versions of those crates you require. In this case, we’ll specify the <code>rand</code>
|
||
crate with the semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
|
||
Versioning</a><!-- ignore --> (sometimes called <em>SemVer</em>), which is a
|
||
standard for writing version numbers. The number <code>0.3.14</code> is actually shorthand
|
||
for <code>^0.3.14</code>, which means “any version that has a public API compatible with
|
||
version 0.3.14.”</p>
|
||
<p>Now, without changing any of the code, let’s build the project, as shown in
|
||
Listing 2-2:</p>
|
||
<figure>
|
||
<pre><code class="language-text">$ cargo build
|
||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||
Downloading rand v0.3.14
|
||
Downloading libc v0.2.14
|
||
Compiling libc v0.2.14
|
||
Compiling rand v0.3.14
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-2: The output from running <code>cargo build</code> after adding the rand crate
|
||
as a dependency</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>You may see different version numbers (but they will all be compatible with
|
||
the code, thanks to SemVer!), and the lines may be in a different order.</p>
|
||
<p>Now that we have an external dependency, Cargo fetches the latest versions of
|
||
everything from the <em>registry</em>, which is a copy of data from
|
||
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem post
|
||
their open source Rust projects for others to use.</p>
|
||
<p>After updating the registry, Cargo checks the <code>[dependencies]</code> section and
|
||
downloads any you don’t have yet. In this case, although we only listed <code>rand</code>
|
||
as a dependency, Cargo also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
|
||
<code>libc</code> to work. After downloading them, Rust compiles them and then compiles
|
||
the project with the dependencies available.</p>
|
||
<p>If you immediately run <code>cargo build</code> again without making any changes, you won’t
|
||
get any output. Cargo knows it has already downloaded and compiled the
|
||
dependencies, and you haven't changed anything about them in your <em>Cargo.toml</em>
|
||
file. Cargo also knows that you haven't changed anything about your code, so it
|
||
doesn't recompile that either. With nothing to do, it simply exits. If you open
|
||
up the <em>src/main.rs</em> file, make a trivial change, then save it and build again,
|
||
you’ll only see one line of output:</p>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
</code></pre>
|
||
<p>This line shows Cargo only updates the build with your tiny change to the
|
||
<em>src/main.rs</em> file. Your dependencies haven't changed, so Cargo knows it can
|
||
reuse what it has already downloaded and compiled for those. It just rebuilds
|
||
your part of the code.</p>
|
||
<h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4>
|
||
<p>Cargo has a mechanism that ensures you can rebuild the same artifact every time
|
||
you or anyone else builds your code: Cargo will use only the versions of the
|
||
dependencies you specified until you indicate otherwise. For example, what
|
||
happens if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out and
|
||
contains an important bug fix but also contains a regression that will break
|
||
your code?</p>
|
||
<p>The answer to this problem is the <em>Cargo.lock</em> file, which was created the
|
||
first time you ran <code>cargo build</code> and is now in your <em>guessing_game</em> directory.
|
||
When you build a project for the first time, Cargo figures out all the
|
||
versions of the dependencies that fit the criteria and then writes them to
|
||
the <em>Cargo.lock</em> file. When you build your project in the future, Cargo will
|
||
see that the <em>Cargo.lock</em> file exists and use the versions specified there
|
||
rather than doing all the work of figuring out versions again. This lets you
|
||
have a reproducible build automatically. In other words, your project will
|
||
remain at <code>0.3.14</code> until you explicitly upgrade, thanks to the <em>Cargo.lock</em>
|
||
file.</p>
|
||
<h4>Updating a Crate to Get a New Version</h4>
|
||
<p>When you <em>do</em> want to update a crate, Cargo provides another command, <code>update</code>,
|
||
which will:</p>
|
||
<ol>
|
||
<li>Ignore the <em>Cargo.lock</em> file and figure out all the latest versions that fit
|
||
your specifications in <em>Cargo.toml</em>.</li>
|
||
<li>If that works, Cargo will write those versions to the <em>Cargo.lock</em> file.</li>
|
||
</ol>
|
||
<p>But by default, Cargo will only look for versions larger than <code>0.3.0</code> and
|
||
smaller than <code>0.4.0</code>. If the <code>rand</code> crate has released two new versions,
|
||
<code>0.3.15</code> and <code>0.4.0</code>, you would see the following if you ran <code>cargo update</code>:</p>
|
||
<pre><code class="language-text">$ cargo update
|
||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||
Updating rand v0.3.14 -> 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 = "0.4.0"
|
||
</code></pre>
|
||
<p>The next time you run <code>cargo build</code>, Cargo will update the registry of crates
|
||
available and reevaluate your <code>rand</code> requirements according to the new version
|
||
you specified.</p>
|
||
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a><!-- ignore --> and <a href="http://doc.crates.io/crates-io.html">its
|
||
ecosystem</a><!-- ignore --> that Chapter 14 will discuss, but for
|
||
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
|
||
so Rustaceans are able to write smaller projects that are assembled from a
|
||
number of packages.</p>
|
||
<h3>Generating a Random Number</h3>
|
||
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <em>src/main.rs</em>, as shown
|
||
in Listing 2-3:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-3: Code changes needed in order to generate a random number</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>We’re adding a <code>extern crate rand;</code> line to the top that lets Rust know we’ll be
|
||
using that external dependency. This also does the equivalent of calling <code>use rand</code>, so now we can call anything in the <code>rand</code> crate by prefixing it with
|
||
<code>rand::</code>.</p>
|
||
<p>Next, we’re adding another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
|
||
defines methods that random number generators implement, and this trait must be
|
||
in scope for us to use those methods. Chapter 10 will cover traits in detail.</p>
|
||
<p>Also, we’re adding two more lines in the middle. The <code>rand::thread_rng</code> function
|
||
will give us the particular random number generator that we’re going to use:
|
||
one that is local to the current thread of execution and seeded by the
|
||
operating system. Next, we call the <code>gen_range</code> method on the random number
|
||
generator. This method is defined by the <code>Rng</code> trait that we brought into
|
||
scope with the <code>use rand::Rng</code> statement. The <code>gen_range</code> method takes two
|
||
numbers as arguments and generates a random number between them. It’s inclusive
|
||
on the lower bound but exclusive on the upper bound, so we need to specify <code>1</code>
|
||
and <code>101</code> to request a number between 1 and 100.</p>
|
||
<p>Knowing which traits to import and which functions and methods to use from a
|
||
crate isn’t something that you’ll just <em>know</em>. Instructions for using a crate
|
||
are in each crate’s documentation. Another neat feature of Cargo is that you
|
||
can run the <code>cargo doc --open</code> command that will build documentation provided
|
||
by all of your dependencies locally and open it in your browser. If you’re
|
||
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> and click <code>rand</code> in the sidebar on the left.</p>
|
||
<p>The second line that we added to the code prints the secret number. This is
|
||
useful while we’re developing the program to be able to test it, but we’ll
|
||
delete it from the final version. It’s not much of a game if the program prints
|
||
the answer as soon as it starts!</p>
|
||
<p>Try running the program a few times:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 7
|
||
Please input your guess.
|
||
4
|
||
You guessed: 4
|
||
$ cargo run
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 83
|
||
Please input your guess.
|
||
5
|
||
You guessed: 5
|
||
</code></pre>
|
||
<p>You should get different random numbers, and they should all be numbers between
|
||
1 and 100. Great job!</p>
|
||
<h2>Comparing the Guess to the Secret Number</h2>
|
||
<p>Now that we have user input and a random number, we can compare them. That
|
||
step is shown in Listing 2-4:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
</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(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
</code></pre>
|
||
<p>The <code>cmp</code> method compares two values and can be called on anything that can be
|
||
compared. It takes a reference to whatever you want to compare with: here it’s
|
||
comparing the <code>guess</code> to the <code>secret_number</code>. <code>cmp</code> returns a variant of the
|
||
<code>Ordering</code> enum we imported with the <code>use</code> statement. We use a
|
||
<a href="ch06-02-match.html"><code>match</code></a><!-- ignore --> expression to decide what to do next based on
|
||
which variant of <code>Ordering</code> was returned from the call to <code>cmp</code> with the values
|
||
in <code>guess</code> and <code>secret_number</code>.</p>
|
||
<p>A <code>match</code> expression is made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
|
||
the code that should be run if the value given to the beginning of the <code>match</code>
|
||
expression fits that arm’s pattern. Rust takes the value given to <code>match</code> and
|
||
looks through each arm’s pattern in turn. The <code>match</code> construct and patterns
|
||
are powerful features in Rust that let you express a variety of situations your
|
||
code might encounter and helps ensure that you handle them all. These features
|
||
will be covered in detail in Chapter 6 and Chapter 19, respectively.</p>
|
||
<p>Let’s walk through an example of what would happen with the <code>match</code> expression
|
||
used here. Say that the user has guessed 50, and the randomly generated secret
|
||
number this time is 38. When the code compares 50 to 38, the <code>cmp</code> method will
|
||
return <code>Ordering::Greater</code>, because 50 is greater than 38. <code>Ordering::Greater</code>
|
||
is the value that the <code>match</code> expression gets. It looks at the first arm’s
|
||
pattern, <code>Ordering::Less</code>, but the value <code>Ordering::Greater</code> does not match
|
||
<code>Ordering::Less</code>. So it ignores the code in that arm and moves to the next arm.
|
||
The next arm’s pattern, <code>Ordering::Greater</code>, <em>does</em> match
|
||
<code>Ordering::Greater</code>! The associated code in that arm will execute and print
|
||
<code>Too big!</code> to the screen. The <code>match</code> expression ends because it has no need to
|
||
look at the last arm in this particular scenario.</p>
|
||
<p>However, the code in Listing 2-4 won’t compile yet. Let’s try it:</p>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
error[E0308]: mismatched types
|
||
--> src/main.rs:23:21
|
||
|
|
||
23 | match guess.cmp(&secret_number) {
|
||
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integral variable
|
||
|
|
||
= note: expected type `&std::string::String`
|
||
= note: found type `&{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!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>The two new lines are:</p>
|
||
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
</code></pre>
|
||
<p>We create a variable named <code>guess</code>. But wait, doesn’t the program
|
||
already have a variable named <code>guess</code>? It does, but Rust allows us to
|
||
<em>shadow</em> the previous value of <code>guess</code> with a new one. This feature is often
|
||
used in similar situations in which you want to convert a value from one type
|
||
to another type. Shadowing lets us reuse the <code>guess</code> variable name rather than
|
||
forcing us to create two unique variables, like <code>guess_str</code> and <code>guess</code> for
|
||
example. (Chapter 3 covers shadowing in more detail.)</p>
|
||
<p>We bind <code>guess</code> to the expression <code>guess.trim().parse()</code>. The <code>guess</code> in the
|
||
expression refers to the original <code>guess</code> that was a <code>String</code> with the input in
|
||
it. The <code>trim</code> method on a <code>String</code> instance will eliminate any whitespace at
|
||
the beginning and end. <code>u32</code> can only contain numerical characters, but the
|
||
user must press the Return key to satisfy <code>read_line</code>. When the user presses
|
||
Return, a newline character is added to the string. For example, if the user
|
||
types 5 and presses return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents
|
||
“newline,” the return key. The <code>trim</code> method eliminates <code>\n</code>, resulting in just
|
||
<code>5</code>.</p>
|
||
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into some
|
||
kind of number. Because this method can parse a variety of number types, we
|
||
need to tell Rust the exact number type we want by using <code>let guess: u32</code>. The
|
||
colon (<code>:</code>) after <code>guess</code> tells Rust we’ll annotate the variable’s type. Rust
|
||
has a few built-in number types; the <code>u32</code> seen here is an unsigned, 32-bit
|
||
integer. It’s a good default choice for a small positive number. You’ll learn
|
||
about other number types in Chapter 3. Additionally, the <code>u32</code> annotation in
|
||
this example program and the comparison with <code>secret_number</code> means that Rust
|
||
will infer that <code>secret_number</code> should be a <code>u32</code> as well. So now the
|
||
comparison will be between two values of the same type!</p>
|
||
<p>The call to <code>parse</code> could easily cause an error. If, for example, the string
|
||
contained <code>A👍%</code>, there would be no way to convert that to a number. Because it
|
||
might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
|
||
<code>read_line</code> method does as discussed earlier in “Handling Potential Failure
|
||
with the Result Type” on page XX. We’ll treat this <code>Result</code> the same way by
|
||
using the <code>expect</code> method again. If <code>parse</code> returns an <code>Err</code> <code>Result</code> variant
|
||
because it couldn’t create a number from the string, the <code>expect</code> call will
|
||
crash the game and print the message we give it. If <code>parse</code> can successfully
|
||
convert the string to a number, it will return the <code>Ok</code> variant of <code>Result</code>,
|
||
and <code>expect</code> will return the number that we want from the <code>Ok</code> value.</p>
|
||
<p>Let’s run the program now!</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 58
|
||
Please input your guess.
|
||
76
|
||
You guessed: 76
|
||
Too big!
|
||
</code></pre>
|
||
<p>Nice! Even though spaces were added before the guess, the program still figured
|
||
out that the user guessed 76. Run the program a few times to verify the
|
||
different behavior with different kinds of input: guess the number correctly,
|
||
guess a number that is too high, and guess a number that is too low.</p>
|
||
<p>We have most of the game working now, but the user can make only one guess.
|
||
Let’s change that by adding a loop!</p>
|
||
<h2>Allowing Multiple Guesses with Looping</h2>
|
||
<p>The <code>loop</code> keyword gives us an infinite loop. Add that now to give users more
|
||
chances at guessing the number:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>As you can see, we’ve moved everything into a loop from the guess input prompt
|
||
onward. Be sure to indent those lines another four spaces each, and run the
|
||
program again. Notice that there is a new problem because the program is doing
|
||
exactly what we told it to do: ask for another guess forever! It doesn’t seem
|
||
like the user can quit!</p>
|
||
<p>The user could always halt the program by using the keyboard shortcut <code>Ctrl-C</code>.
|
||
But there’s another way to escape this insatiable monster that we mentioned in
|
||
the <code>parse</code> discussion in “Comparing the Guesses” on page XX: if the user
|
||
enters a non-number answer, the program will crash. The user can take advantage
|
||
of that in order to quit, as shown here:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 59
|
||
Please input your guess.
|
||
45
|
||
You guessed: 45
|
||
Too small!
|
||
Please input your guess.
|
||
60
|
||
You guessed: 60
|
||
Too big!
|
||
Please input your guess.
|
||
59
|
||
You guessed: 59
|
||
You win!
|
||
Please input your guess.
|
||
quit
|
||
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
|
||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
|
||
</code></pre>
|
||
<p>Typing <code>quit</code> actually quits the game, but so will any other non-number input.
|
||
However, this is suboptimal to say the least. We want the game to automatically
|
||
stop when the correct number is guessed.</p>
|
||
<h3>Quitting After a Correct Guess</h3>
|
||
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => {
|
||
println!("You win!");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>By adding the <code>break</code> line after <code>You win!</code>, the program will exit the loop
|
||
when the user guesses the secret number correctly. Exiting the loop also means
|
||
exiting the program, because the loop is the last part of <code>main</code>.</p>
|
||
<h3>Handling Invalid Input</h3>
|
||
<p>To further refine the game’s behavior, rather than crashing the program when
|
||
the user inputs a non-number, let’s make the game ignore a non-number so the
|
||
user can continue guessing. We can do that by altering the line where <code>guess</code> is
|
||
converted from a <code>String</code> to a <code>u32</code>:</p>
|
||
<pre><code class="language-rust,ignore">let guess: u32 = match guess.trim().parse() {
|
||
Ok(num) => num,
|
||
Err(_) => 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!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = match guess.trim().parse() {
|
||
Ok(num) => num,
|
||
Err(_) => continue,
|
||
};
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => {
|
||
println!("You win!");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-5: Complete code of the guessing game</p>
|
||
</figcaption>
|
||
</figure>
|
||
<h2>Summary</h2>
|
||
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
|
||
<p>This project was a hands-on way to introduce you to many new Rust concepts:
|
||
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
|
||
In the next few chapters, you’ll learn about these concepts in more detail.
|
||
Chapter 3 covers concepts that most programming languages have, such as
|
||
variables, data types, and functions, and shows how to use them in Rust.
|
||
Chapter 4 explores ownership, which is a Rust feature that is most different
|
||
from other languages. Chapter 5 discusses structs and method syntax, and
|
||
Chapter 6 endeavors to explain enums.</p>
|
||
<h1>Common Programming Concepts</h1>
|
||
<p>This chapter covers concepts that appear in almost every programming language
|
||
and how they work in Rust. Many programming languages have much in common at
|
||
their core. None of the concepts presented in this chapter are unique to Rust,
|
||
but we’ll discuss them in the context of Rust and explain their conventions.</p>
|
||
<p>Specifically, you’ll learn about variables, basic types, functions, comments,
|
||
and control flow. These foundations will be in every Rust program, and learning
|
||
them early will give you a strong core to start from.</p>
|
||
<!-- PROD: START BOX -->
|
||
<blockquote>
|
||
<h3>Keywords</h3>
|
||
<p>The Rust language has a set of <em>keywords</em> that have been reserved for use by
|
||
the language only, much like other languages do. Keep in mind that you cannot
|
||
use these words as names of variables or functions. Most of the keywords have
|
||
special meanings, and you’ll be using them to do various tasks in your Rust
|
||
programs; a few have no current functionality associated with them but have
|
||
been reserved for functionality that might be added to Rust in the future. You
|
||
can find a list of the keywords in Appendix A.</p>
|
||
</blockquote>
|
||
<!-- PROD: END BOX -->
|
||
<h2>Variables and Mutability</h2>
|
||
<p>As mentioned in Chapter 2, by default variables are <em>immutable</em>. This is one of
|
||
many nudges in Rust that encourages you to write your code in a way that takes
|
||
advantage of the safety and easy concurrency that Rust offers. However, you
|
||
still have the option to make your variables mutable. Let’s explore how and why
|
||
Rust encourages you to favor immutability, and why you might want to opt out.</p>
|
||
<p>When a variable is immutable, that means mean once a value is bound to a name,
|
||
you can’t change that value. To illustrate, let’s generate a new project called
|
||
<em>variables</em> in your <em>projects</em> directory by using <code>cargo new --bin variables</code>.</p>
|
||
<p>Then, in your new <em>variables</em> directory, open <em>src/main.rs</em> and replace its
|
||
code with the following:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let x = 5;
|
||
println!("The value of x is: {}", x);
|
||
x = 6;
|
||
println!("The value of x is: {}", 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`
|
||
--> src/main.rs:4:5
|
||
|
|
||
2 | let x = 5;
|
||
| - first assignment to `x`
|
||
3 | println!("The value of x is: {}", 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!("The value of x is: {}", x);
|
||
x = 6;
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>When we run this program, we get the following:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling variables v0.1.0 (file:///projects/variables)
|
||
Running `target/debug/variables`
|
||
The value of x is: 5
|
||
The value of x is: 6
|
||
</code></pre>
|
||
<p>Using <code>mut</code>, we’re allowed to change the value that <code>x</code> binds to from <code>5</code> to
|
||
<code>6</code>. In some cases, you’ll want to make a variable mutable because it makes the
|
||
code more convenient to write than an implementation that only uses immutable
|
||
variables.</p>
|
||
<p>There are multiple trade-offs to consider, in addition to the prevention of
|
||
bugs. For example, in cases where you’re using large data structures, mutating
|
||
an instance in place may be faster than copying and returning newly allocated
|
||
instances. With smaller data structures, always creating new instances and
|
||
writing in a more functional programming style may be easier to reason about,
|
||
so the lower performance penalty might be worth it to gain that clarity.</p>
|
||
<h3>Differences Between Variables and Constants</h3>
|
||
<p>Not being able to change the value of a variable might have reminded you of
|
||
another programming concept that most languages have: <em>constants</em>. Constants
|
||
are also values bound to a name that are not allowed to change, but there are a
|
||
few differences between constants and variables. First, using <code>mut</code> with
|
||
constants is not allowed: constants aren't only immutable by default, they're
|
||
always immutable. Constants are declared using the <code>const</code> keyword instead of
|
||
the <code>let</code> keyword, and the type of the value <em>must</em> be annotated. We're about
|
||
to cover types and type annotations in the next section, “Data Types,” so don't
|
||
worry about the details right now. Constants can be declared in any scope,
|
||
including the global scope, which makes them useful for a value that many parts
|
||
of your code need to know about. The last difference is that constants may only
|
||
be set to a constant expression, not the result of a function call or any other
|
||
value that could only be used at runtime.</p>
|
||
<p>Here's an example of a constant declaration where the constant's name is
|
||
<code>MAX_POINTS</code> and its value is set to 100,000. Rust constant naming convention
|
||
is to use all upper case with underscores between words:</p>
|
||
<pre><code>const MAX_POINTS: u32 = 100_000;
|
||
</code></pre>
|
||
<p>Constants are valid for the entire lifetime of a program, within the scope they
|
||
were declared in. That makes constants useful for values in your application
|
||
domain that multiple part of the program might need to know about, such as the
|
||
maximum number of points any player of a game is allowed to earn or the number
|
||
of seconds in a year.</p>
|
||
<p>Documenting hardcoded values used throughout your program by naming them as
|
||
constants is useful to convey the meaning of that value to future maintainers
|
||
of the code. It also helps to have only one place in your code that you would
|
||
need to change if the hardcoded value needed to be updated in the future.</p>
|
||
<h3>Shadowing</h3>
|
||
<p>As we saw in the guessing game tutorial in Chapter 2, we can declare new
|
||
variables with the same name as a previous variables, and the new variable
|
||
<em>shadows</em> the previous variable. Rustaceans say that the first variable is
|
||
<em>shadowed</em> by the second, which means that the second variable’s value is what
|
||
we’ll see when we use the variable. We can shadow a variable by using the same
|
||
variable’s name and repeating the use of the <code>let</code> keyword as follows:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 5;
|
||
|
||
let x = x + 1;
|
||
|
||
let x = x * 2;
|
||
|
||
println!("The value of x is: {}", 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 = " ";
|
||
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 = " ";
|
||
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
|
||
--> src/main.rs:3:14
|
||
|
|
||
3 | spaces = spaces.len();
|
||
| ^^^^^^^^^^^^ expected &str, found usize
|
||
|
|
||
= note: expected type `&str`
|
||
= note: found type `usize`
|
||
</code></pre>
|
||
<p>Now that we’ve explored how variables work, let’s look at more data types they
|
||
can have.</p>
|
||
<h2>Data Types</h2>
|
||
<p>Every value in Rust is of a certain <em>type</em>, which tells Rust what kind of data
|
||
is being specified so it knows how to work with that data. In this section,
|
||
we’ll look at a number of types that are built into the language. We split the
|
||
types into two subsets: scalar and compound.</p>
|
||
<p>Throughout this section, keep in mind that Rust is a <em>statically typed</em>
|
||
language, which means that it must know the types of all variables at compile
|
||
time. The compiler can usually infer what type we want to use based on the
|
||
value and how we use it. In cases when many types are possible, such as when we
|
||
converted a <code>String</code> to a numeric type using <code>parse</code> in Chapter 2, we must add
|
||
a type annotation, like this:</p>
|
||
<pre><code class="language-rust">let guess: u32 = "42".parse().unwrap();
|
||
</code></pre>
|
||
<p>If we don’t add the type annotation here, Rust will display the following
|
||
error, which means the compiler needs more information from us to know which
|
||
possible type we want to use:</p>
|
||
<pre><code class="language-text">error[E0282]: unable to infer enough type information about `_`
|
||
--> src/main.rs:2:5
|
||
|
|
||
2 | let guess = "42".parse().unwrap();
|
||
| ^^^^^ cannot infer type for `_`
|
||
|
|
||
= note: type annotations or generic parameter binding required
|
||
</code></pre>
|
||
<p>You’ll see different type annotations as we discuss the various data types.</p>
|
||
<h3>Scalar Types</h3>
|
||
<p>A <em>scalar</em> type represents a single value. Rust has four primary scalar types:
|
||
integers, floating-point numbers, booleans, and characters. You’ll likely
|
||
recognize these from other programming languages, but let’s jump into how they
|
||
work in Rust.</p>
|
||
<h4>Integer Types</h4>
|
||
<p>An <em>integer</em> is a number without a fractional component. We used one integer
|
||
type earlier in this chapter, the <code>i32</code> type. This type declaration indicates
|
||
that the value it’s associated with should be a signed integer (hence the <code>i</code>,
|
||
as opposed to a <code>u</code> for unsigned) for a 32-bit system. Table 3-1 shows the
|
||
built-in integer types in Rust. Each variant in the Signed and Unsigned columns
|
||
(for example, <em>i32</em>) can be used to declare the type of an integer value.</p>
|
||
<figure>
|
||
<figcaption>
|
||
<p>Table 3-1: Integer Types in Rust</p>
|
||
</figcaption>
|
||
<table><thead><tr><td> Length </td><td> Signed </td><td> Unsigned </td></tr></thead>
|
||
<tr><td> 8-bit </td><td> i8 </td><td> u8 </td></tr>
|
||
<tr><td> 16-bit </td><td> i16 </td><td> u16 </td></tr>
|
||
<tr><td> 32-bit </td><td> i32 </td><td> u32 </td></tr>
|
||
<tr><td> 64-bit </td><td> i64 </td><td> u64 </td></tr>
|
||
<tr><td> arch </td><td> isize </td><td> usize </td></tr>
|
||
</table>
|
||
</figure>
|
||
<p>Each variant can be either signed or unsigned and has an explicit size.
|
||
Signed and unsigned refers to whether it’s possible for the number to be
|
||
negative or positive; in other words, whether the number needs to have a sign
|
||
with it (signed) or whether it will only ever be positive and can therefore be
|
||
represented without a sign (unsigned). It’s like writing numbers on paper: when
|
||
the sign matters, a number is shown with a plus sign or a minus sign; however,
|
||
when it’s safe to assume the number is positive, it’s shown with no sign.
|
||
Signed numbers are stored using two’s complement representation (if you’re
|
||
unsure what this is, you can search for it online; an explanation is outside
|
||
the scope of this book).</p>
|
||
<p>Each signed variant can store numbers from -(2<sup>n - 1</sup>) to 2<sup>n -
|
||
1</sup> - 1 inclusive, where <code>n</code> is the number of bits that variant uses. So an
|
||
<code>i8</code> can store numbers from -(2<sup>7</sup>) to 2<sup>7</sup> - 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>
|
||
<h4>Floating-Point Types</h4>
|
||
<p>Rust also has two primitive types for <em>floating-point numbers</em>, which are
|
||
numbers with decimal points. Rust’s floating-point types are <code>f32</code> and <code>f64</code>,
|
||
which are 32 bits and 64 bits in size, respectively. The default type is <code>f64</code>
|
||
because it’s roughly the same speed as <code>f32</code> but is capable of more precision.
|
||
It’s possible to use an <code>f64</code> type on 32-bit systems, but it will be slower
|
||
than using an <code>f32</code> type on those systems. Most of the time, trading potential
|
||
worse performance for better precision is a reasonable initial choice, and you
|
||
should benchmark your code if you suspect floating-point size is a problem in
|
||
your situation.</p>
|
||
<p>Here’s an example that shows floating-point numbers in action:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 2.0; // f64
|
||
|
||
let y: f32 = 3.0; // f32
|
||
}
|
||
</code></pre>
|
||
<p>Floating-point numbers are represented according to the IEEE-754 standard. The
|
||
<code>f32</code> type is a single-precision float, and <code>f64</code> has double precision.</p>
|
||
<h4>Numeric Operations</h4>
|
||
<p>Rust supports the usual basic mathematic operations you’d expect for all of the
|
||
number types: addition, subtraction, multiplication, division, and remainder.
|
||
The following code shows how you’d use each one in a <code>let</code> statement:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
// addition
|
||
let sum = 5 + 10;
|
||
|
||
// subtraction
|
||
let difference = 95.5 - 4.3;
|
||
|
||
// multiplication
|
||
let product = 4 * 30;
|
||
|
||
// division
|
||
let quotient = 56.7 / 32.2;
|
||
|
||
// remainder
|
||
let remainder = 43 % 5;
|
||
}
|
||
</code></pre>
|
||
<p>Each expression in these statements uses a mathematical operator and evaluates
|
||
to a single value, which is then bound to a variable. Appendix B contains a
|
||
list of all operators that Rust provides.</p>
|
||
<h4>The Boolean Type</h4>
|
||
<p>As in most other programming languages, a boolean type in Rust has two possible
|
||
values: <code>true</code> and <code>false</code>. The boolean type in Rust is specified using <code>bool</code>.
|
||
For example:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let t = true;
|
||
|
||
let f: bool = false; // with explicit type annotation
|
||
}
|
||
</code></pre>
|
||
<p>The main way to consume boolean values is through conditionals, such as an <code>if</code>
|
||
statement. We’ll cover how <code>if</code> statements work in Rust in the “Control Flow”
|
||
section.</p>
|
||
<h4>The Character Type</h4>
|
||
<p>So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
|
||
<code>char</code> type is the language’s most primitive alphabetic type, and the following
|
||
code shows one way to use it:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let c = 'z';
|
||
let z = 'ℤ';
|
||
let heart_eyed_cat = '😻';
|
||
}
|
||
</code></pre>
|
||
<p>Rust’s <code>char</code> type represents a Unicode Scalar Value, which means it can
|
||
represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
|
||
ideographs, emoji, and zero width spaces are all valid <code>char</code> types in Rust.
|
||
Unicode Scalar Values range from <code>U+0000</code> to <code>U+D7FF</code> and <code>U+E000</code> to
|
||
<code>U+10FFFF</code> inclusive. However, a “character” isn’t really a concept in Unicode,
|
||
so your human intuition for what a “character” is may not match up with what a
|
||
<code>char</code> is in Rust. We’ll discuss this topic in detail in the “Strings” section
|
||
in Chapter 8.</p>
|
||
<h3>Compound Types</h3>
|
||
<p><em>Compound types</em> can group multiple values of other types into one type. Rust
|
||
has two primitive compound types: tuples and arrays.</p>
|
||
<h4>Grouping Values into Tuples</h4>
|
||
<p>A tuple is a general way of grouping together some number of other values with
|
||
a variety of types into one compound type.</p>
|
||
<p>We create a tuple by writing a comma-separated list of values inside
|
||
parentheses. Each position in the tuple has a type, and the types of the
|
||
different values in the tuple don’t have to be the same. We’ve added optional
|
||
type annotations in this example:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let tup: (i32, f64, u8) = (500, 6.4, 1);
|
||
}
|
||
</code></pre>
|
||
<p>The variable <code>tup</code> binds to the entire tuple, since a tuple is considered a
|
||
single compound element. To get the individual values out of a tuple, we can
|
||
use pattern matching to destructure a tuple value, like this:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let tup = (500, 6.4, 1);
|
||
|
||
let (x, y, z) = tup;
|
||
|
||
println!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<p>This program first creates a tuple and binds it to the variable <code>tup</code>. It then
|
||
uses a pattern with <code>let</code> to take <code>tup</code> and turn it into three separate
|
||
variables, <code>x</code>, <code>y</code>, and <code>z</code>. This is called <em>destructuring</em>, because it breaks
|
||
the single tuple into three parts. Finally, the program prints the value of
|
||
<code>y</code>, which is <code>6.4</code>.</p>
|
||
<p>In addition to destructuring through pattern matching, we can also access a
|
||
tuple element directly by using a period (<code>.</code>) followed by the index of the
|
||
value we want to access. For example:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x: (i32, f64, u8) = (500, 6.4, 1);
|
||
|
||
let five_hundred = x.0;
|
||
|
||
let six_point_four = x.1;
|
||
|
||
let one = x.2;
|
||
}
|
||
</code></pre>
|
||
<p>This program creates a tuple, <code>x</code>, and then makes new variables for each
|
||
element by using their index. As with most programming languages, the first
|
||
index in a tuple is 0.</p>
|
||
<h4>Arrays</h4>
|
||
<p>Another way to have a collection of multiple values is with an <em>array</em>. Unlike
|
||
a tuple, every element of an array must have the same type. Arrays in Rust are
|
||
different than arrays in some other languages because arrays in Rust have a
|
||
fixed length: once declared, they cannot grow or shrink in size.</p>
|
||
<p>In Rust, the values going into an array are written as a comma-separated list
|
||
inside square brackets:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [1, 2, 3, 4, 5];
|
||
}
|
||
</code></pre>
|
||
<p>Arrays are useful when you want your data allocated on the stack rather than
|
||
the heap (we will discuss the stack and the heap more in Chapter 4), or when
|
||
you want to ensure you always have a fixed number of elements. They aren’t as
|
||
flexible as the vector type, though. The vector type is a similar collection
|
||
type provided by the standard library that <em>is</em> allowed to grow or shrink in
|
||
size. If you’re unsure whether to use an array or a vector, you should probably
|
||
use a vector: Chapter 8 discusses vectors in more detail.</p>
|
||
<p>An example of when you might want to use an array rather than a vector is in a
|
||
program that needs to know the names of the months of the year. It’s very
|
||
unlikely that such a program will need to add or remove months, so you can use
|
||
an array because you know it will always contain 12 items:</p>
|
||
<pre><code class="language-rust">let months = ["January", "February", "March", "April", "May", "June", "July",
|
||
"August", "September", "October", "November", "December"];
|
||
</code></pre>
|
||
<h5>Accessing Array Elements</h5>
|
||
<p>An array is a single chunk of memory allocated on the stack. We can access
|
||
elements of an array using indexing, like this:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [1, 2, 3, 4, 5];
|
||
|
||
let first = a[0];
|
||
let second = a[1];
|
||
}
|
||
</code></pre>
|
||
<p>In this example, the variable named <code>first</code> will get the value <code>1</code>, because
|
||
that is the value at index <code>[0]</code> in the array. The variable named <code>second</code> will
|
||
get the value <code>2</code> from index <code>[1]</code> in the array.</p>
|
||
<h5>Invalid Array Element Access</h5>
|
||
<p>What happens if we try to access an element of an array that is past the end of
|
||
the array? Say we change the example to the following:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let a = [1, 2, 3, 4, 5];
|
||
|
||
let element = a[10];
|
||
|
||
println!("The value of element is: {}", 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 '<main>' panicked at 'index out of bounds: the len is 5 but the index is
|
||
10', src/main.rs:4
|
||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||
error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
|
||
</code></pre>
|
||
<p>The compilation didn’t produce any errors, but the program results in a
|
||
<em>runtime</em> error and didn’t exit successfully. When you attempt to access an
|
||
element using indexing, Rust will check that the index you’ve specified is less
|
||
than the array length. If the index is greater than the length, Rust will
|
||
<em>panic</em>, which is the term Rust uses when a program exits with an error.</p>
|
||
<p>This is the first example of Rust’s safety principles in action. In many
|
||
low-level languages, this kind of check is not done, and when you provide an
|
||
incorrect index, invalid memory can be accessed. Rust protects you against this
|
||
kind of error by immediately exiting instead of allowing the memory access and
|
||
continuing. Chapter 9 discusses more of Rust’s error handling.</p>
|
||
<h2>How Functions Work</h2>
|
||
<p>Functions are pervasive in Rust code. You’ve already seen one of the most
|
||
important functions in the language: the <code>main</code> function, which is the entry
|
||
point of many programs. You’ve also seen the <code>fn</code> keyword, which allows you to
|
||
declare new functions.</p>
|
||
<p>Rust code uses <em>snake case</em> as the conventional style for function and variable
|
||
names. In snake case, all letters are lowercase and underscores separate words.
|
||
Here’s a program that contains an example function definition:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
|
||
another_function();
|
||
}
|
||
|
||
fn another_function() {
|
||
println!("Another function.");
|
||
}
|
||
</code></pre>
|
||
<p>Function definitions in Rust start with <code>fn</code> and have a set of parentheses
|
||
after the function name. The curly braces tell the compiler where the function
|
||
body begins and ends.</p>
|
||
<p>We can call any function we’ve defined by entering its name followed by a set
|
||
of parentheses. Because <code>another_function</code> is defined in the program, it can be
|
||
called from inside the <code>main</code> function. Note that we defined <code>another_function</code>
|
||
<em>after</em> the <code>main</code> function in the source code; we could have defined it before
|
||
as well. Rust doesn’t care where you define your functions, only that they’re
|
||
defined somewhere.</p>
|
||
<p>Let’s start a new binary project named <em>functions</em> to explore functions
|
||
further. Place the <code>another_function</code> example in <em>src/main.rs</em> and run it. You
|
||
should see the following output:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
Hello, world!
|
||
Another function.
|
||
</code></pre>
|
||
<p>The lines execute in the order in which they appear in the <code>main</code> function.
|
||
First, the “Hello, world!” message prints, and then <code>another_function</code> is
|
||
called and its message is printed.</p>
|
||
<h3>Function Arguments</h3>
|
||
<p>Functions can also take arguments. The following rewritten version of
|
||
<code>another_function</code> shows what arguments look like in Rust:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
another_function(5);
|
||
}
|
||
|
||
fn another_function(x: i32) {
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>Try running this program; you should get the following output:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
The value of x is: 5
|
||
</code></pre>
|
||
<p>The declaration of <code>another_function</code> has one argument named <code>x</code>. The type of
|
||
<code>x</code> is specified as <code>i32</code>. When <code>5</code> is passed to <code>another_function</code>, the
|
||
<code>println!</code> macro puts <code>5</code> where the pair of curly braces were in the format
|
||
string.</p>
|
||
<p>In function signatures, you <em>must</em> declare the type. This is a deliberate
|
||
decision in Rust’s design: requiring type annotations in function definitions
|
||
means the compiler almost never needs you to use them elsewhere in the code to
|
||
figure out what you mean.</p>
|
||
<p>When you want a function to have multiple arguments, separate them inside the
|
||
function signature with commas, like this:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
another_function(5, 6);
|
||
}
|
||
|
||
fn another_function(x: i32, y: i32) {
|
||
println!("The value of x is: {}", x);
|
||
println!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<p>This example creates a function with two arguments, both of which are <code>i32</code>
|
||
types. If your function has multiple arguments, the arguments don’t need to be
|
||
the same type, but they just happen to be in this example. The function then
|
||
prints out the values of both of its arguments.</p>
|
||
<p>Let’s try running this code. Replace the program currently in your <em>function</em>
|
||
project’s <em>src/main.rs</em> file with the preceding example, and run it using
|
||
<code>cargo run</code>:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
The value of x is: 5
|
||
The value of y is: 6
|
||
</code></pre>
|
||
<p>Because <code>5</code> is passed as the <code>x</code> argument and <code>6</code> is passed as the <code>y</code>
|
||
argument, the two strings are printed with these values.</p>
|
||
<h3>Function Bodies</h3>
|
||
<p>Function bodies are made up of a series of statements optionally ending in an
|
||
expression. So far, we’ve only covered functions without an ending expression,
|
||
but we have seen expressions as parts of statements. Because Rust is an
|
||
expression-based language, this is an important distinction to understand.
|
||
Other languages don’t have the same distinctions, so let’s look at what
|
||
statements and expressions are and how their differences affect the bodies of
|
||
functions.</p>
|
||
<h3>Statements and Expressions</h3>
|
||
<p>We’ve actually already used statements and expressions. <em>Statements</em> are
|
||
instructions that perform some action and do not return a value. <em>Expressions</em>
|
||
evaluate to a resulting value. Let’s look at some examples.</p>
|
||
<p>Creating a variable and assigning a value to it with the <code>let</code> keyword is a
|
||
statement. In Listing 3-3, <code>let y = 6;</code> is a statement:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let y = 6;
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 3-3: A <code>main</code> function declaration containing one statement.</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Function definitions are also statements; the entire preceding example is a
|
||
statement in itself.</p>
|
||
<p>Statements do not return values. Therefore, you can’t assign a <code>let</code> statement
|
||
to another variable, as the following code tries to do:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let x = (let y = 6);
|
||
}
|
||
</code></pre>
|
||
<p>When you run this program, you’ll get an error like this:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
error: expected expression, found statement (`let`)
|
||
--> 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!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<p>This expression:</p>
|
||
<pre><code class="language-rust,ignore">{
|
||
let x = 3;
|
||
x + 1
|
||
}
|
||
</code></pre>
|
||
<p>is a block that, in this case, evaluates to <code>4</code>. That value gets bound to <code>y</code>
|
||
as part of the <code>let</code> statement. Note the line without a semicolon at the end,
|
||
unlike most of the lines you’ve seen so far. Expressions do not include ending
|
||
semicolons. If you add a semicolon to the end of an expression, you turn it
|
||
into a statement, which will then not return a value. Keep this in mind as you
|
||
explore function return values and expressions next.</p>
|
||
<h3>Functions with Return Values</h3>
|
||
<p>Functions can return values to the code that calls them. We don’t name return
|
||
values, but we do declare their type after an arrow (<code>-></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() -> i32 {
|
||
5
|
||
}
|
||
|
||
fn main() {
|
||
let x = five();
|
||
|
||
println!("The value of x is: {}", 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>-> i32</code>. Try
|
||
running this code; the output should look like this:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
The value of x is: 5
|
||
</code></pre>
|
||
<p>The <code>5</code> in <code>five</code> is the function’s return value, which is why the return type
|
||
is <code>i32</code>. Let’s examine this in more detail. There are two important bits:
|
||
first, the line <code>let x = five();</code> shows that we’re using the return value of a
|
||
function to initialize a variable. Because the function <code>five</code> returns a <code>5</code>,
|
||
that line is the same as the following:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
</code></pre>
|
||
<p>Second, the <code>five</code> function requires no arguments and defines the type of the
|
||
return value, but the body of the function is a lonely <code>5</code> with no semicolon
|
||
because it’s an expression whose value we want to return. Let’s look at another
|
||
example:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = plus_one(5);
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
|
||
fn plus_one(x: i32) -> 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!("The value of x is: {}", x);
|
||
}
|
||
|
||
fn plus_one(x: i32) -> 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
|
||
--> src/main.rs:7:1
|
||
|
|
||
7 | fn plus_one(x: i32) -> i32 {
|
||
| ^
|
||
|
|
||
help: consider removing this semicolon:
|
||
--> src/main.rs:8:10
|
||
|
|
||
8 | x + 1;
|
||
| ^
|
||
</code></pre>
|
||
<p>The main error message, “not all control paths return a value,” reveals the
|
||
core issue with this code. The definition of the function <code>plus_one</code> says that
|
||
it will return an <code>i32</code>, but statements don’t evaluate to a value. Therefore,
|
||
nothing is returned, which contradicts the function definition and results in
|
||
an error. In this output, Rust provides a message to possibly help rectify this
|
||
issue: it suggests removing the semicolon, which would fix the error.</p>
|
||
<h2>Comments</h2>
|
||
<p>All programmers strive to make their code easy to understand, but sometimes
|
||
extra explanation is warranted. In these cases, programmers leave notes, or
|
||
<em>comments</em>, in their source code that the compiler will ignore but people
|
||
reading the source code may find useful.</p>
|
||
<p>Here’s a simple comment:</p>
|
||
<pre><code class="language-rust">// Hello, world.
|
||
</code></pre>
|
||
<p>In Rust, comments must start with two slashes and continue until the end of the
|
||
line. For comments that extend beyond a single line, you’ll need to include
|
||
<code>//</code> on each line, like this:</p>
|
||
<pre><code class="language-rust">// So we’re doing something complicated here, long enough that we need
|
||
// multiple lines of comments to do it! Whew! Hopefully, this comment will
|
||
// explain what’s going on.
|
||
</code></pre>
|
||
<p>Comments can also be placed at the end of lines containing code:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let lucky_number = 7; // I’m feeling lucky today.
|
||
}
|
||
</code></pre>
|
||
<p>But you’ll more often see them used in this format, with the comment on a
|
||
separate line above the code it's annotating:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
// I’m feeling lucky today.
|
||
let lucky_number = 7;
|
||
}
|
||
</code></pre>
|
||
<p>That’s all there is to comments. They’re not particularly complicated.</p>
|
||
<h2>Control Flow</h2>
|
||
<p>Deciding whether or not to run some code depending on if a condition is true or
|
||
deciding to run some code repeatedly while a condition is true are basic
|
||
building blocks in most programming languages. The most common constructs that
|
||
let you control the flow of execution of Rust code are <code>if</code> expressions and
|
||
loops.</p>
|
||
<h3><code>if</code> Expressions</h3>
|
||
<p>An <code>if</code> expression allows us to branch our code depending on conditions. We
|
||
provide a condition and then state, “If this condition is met, run this block
|
||
of code. If the condition is not met, do not run this block of code.”</p>
|
||
<p>Create a new project called <em>branches</em> in your <em>projects</em> directory to explore
|
||
the <code>if</code> expression. In the <em>src/main.rs</em> file, input the following:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let number = 3;
|
||
|
||
if number < 5 {
|
||
println!("condition was true");
|
||
} else {
|
||
println!("condition was false");
|
||
}
|
||
}
|
||
</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!("number was three");
|
||
}
|
||
}
|
||
</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
|
||
--> 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!("number was something other than zero");
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Running this code will print <code>number was something other than zero</code>.</p>
|
||
<h4>Multiple Conditions with <code>else if</code></h4>
|
||
<p>We can have multiple conditions by combining <code>if</code> and <code>else</code> in an <code>else if</code>
|
||
expression. For example:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let number = 6;
|
||
|
||
if number % 4 == 0 {
|
||
println!("number is divisible by 4");
|
||
} else if number % 3 == 0 {
|
||
println!("number is divisible by 3");
|
||
} else if number % 2 == 0 {
|
||
println!("number is divisible by 2");
|
||
} else {
|
||
println!("number is not divisible by 4, 3, or 2");
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>This program has four possible paths it can take. After running it, you should
|
||
see the following output:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling branches v0.1.0 (file:///projects/branches)
|
||
Running `target/debug/branches`
|
||
number is divisible by 3
|
||
</code></pre>
|
||
<p>When this program executes, it checks each <code>if</code> expression in turn and executes
|
||
the first body for which the condition holds true. Note that even though 6 is
|
||
divisible by 2, we don’t see the output <code>number is divisible by 2</code>, nor do we
|
||
see the <code>number is not divisible by 4, 3, or 2</code> text from the <code>else</code> block. The
|
||
reason is that Rust will only execute the block for the first true condition,
|
||
and once it finds one, it won’t even check the rest.</p>
|
||
<p>Using too many <code>else if</code> expressions can clutter your code, so if you have more
|
||
than one, you might want to refactor your code. Chapter 6 describes a powerful
|
||
Rust branching construct called <code>match</code> for these cases.</p>
|
||
<h4>Using <code>if</code> in a <code>let</code> statement</h4>
|
||
<p>Because <code>if</code> is an expression, we can use it on the right side of a <code>let</code>
|
||
statement, for instance in Listing 3-4:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let condition = true;
|
||
let number = if condition {
|
||
5
|
||
} else {
|
||
6
|
||
};
|
||
|
||
println!("The value of number is: {}", 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 {
|
||
"six"
|
||
};
|
||
|
||
println!("The value of number is: {}", 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
|
||
--> src/main.rs:4:18
|
||
|
|
||
4 | let number = if condition {
|
||
| ^ expected integral variable, found reference
|
||
|
|
||
= note: expected type `{integer}`
|
||
= note: found type `&’static str`
|
||
</code></pre>
|
||
<p>The expression in the <code>if</code> block evaluates to an integer, and the expression in
|
||
the <code>else</code> block evaluates to a string. This won’t work because variables must
|
||
have a single type. Rust needs to know at compile time what type the <code>number</code>
|
||
variable is, definitively, so it can verify at compile time that its type is
|
||
valid everywhere we use <code>number</code>. Rust wouldn’t be able to do that if the type
|
||
of <code>number</code> was only determined at runtime; the compiler would be more complex
|
||
and would make fewer guarantees about the code if it had to keep track of
|
||
multiple hypothetical types for any variable.</p>
|
||
<h3>Repetition with Loops</h3>
|
||
<p>It’s often useful to execute a block of code more than once. For this task,
|
||
Rust provides several <em>loops</em>. A loop runs through the code inside the loop
|
||
body to the end and then starts immediately back at the beginning. To
|
||
experiment with loops, let’s make a new project called <em>loops</em>.</p>
|
||
<p>Rust has three kinds of loops: <code>loop</code>, <code>while</code>, and <code>for</code>. Let’s try each one.</p>
|
||
<h4>Repeating Code with <code>loop</code></h4>
|
||
<p>The <code>loop</code> keyword tells Rust to execute a block of code over and over again
|
||
forever or until you explicitly tell it to stop.</p>
|
||
<p>As an example, change the <em>src/main.rs</em> file in your <em>loops</em> directory to look
|
||
like this:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
loop {
|
||
println!("again!");
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>When we run this program, we’ll see <code>again!</code> printed over and over continuously
|
||
until we stop the program manually. Most terminals support a keyboard shortcut,
|
||
ctrl-C, to halt a program that is stuck in a continual loop. Give it a try:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling loops v0.1.0 (file:///projects/loops)
|
||
Running `target/debug/loops`
|
||
again!
|
||
again!
|
||
again!
|
||
again!
|
||
^Cagain!
|
||
</code></pre>
|
||
<p>The symbol <code>^C</code> represents where you pressed ctrl-C. You may or may not see the
|
||
word <code>again!</code> printed after the <code>^C</code>, depending on where the code was in the
|
||
loop when it received the halt signal.</p>
|
||
<p>Fortunately, Rust provides another, more reliable way to break out of a loop.
|
||
You can place the <code>break</code> keyword within the loop to tell the program when to
|
||
stop executing the loop. Recall that we did this in the guessing game in the
|
||
“Quitting After a Correct Guess” section of Chapter 2 to exit the
|
||
program when the user won the game by guessing the correct number.</p>
|
||
<h4>Conditional Loops with <code>while</code></h4>
|
||
<p>It’s often useful for a program to evaluate a condition within a loop. While
|
||
the condition is true, the loop runs. When the condition ceases to be true, you
|
||
call <code>break</code>, stopping the loop. This loop type could be implemented using a
|
||
combination of <code>loop</code>, <code>if</code>, <code>else</code>, and <code>break</code>; you could try that now in a
|
||
program, if you’d like.</p>
|
||
<p>However, this pattern is so common that Rust has a built-in language construct
|
||
for it, and it’s called a <code>while</code> loop. The following example uses <code>while</code>: the
|
||
program loops three times, counting down each time. Then, after the loop, it
|
||
prints another message and exits:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let mut number = 3;
|
||
|
||
while number != 0 {
|
||
println!("{}!", number);
|
||
|
||
number = number - 1;
|
||
}
|
||
|
||
println!("LIFTOFF!!!");
|
||
}
|
||
</code></pre>
|
||
<p>This construct eliminates a lot of nesting that would be necessary if you used
|
||
<code>loop</code>, <code>if</code>, <code>else</code>, and <code>break</code>, and it’s clearer. While a condition holds
|
||
true, the code runs; otherwise, it exits the loop.</p>
|
||
<h4>Looping Through a Collection with <code>for</code></h4>
|
||
<p>You could use the <code>while</code> construct to loop over the elements of a collection,
|
||
such as an array. For example:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [10, 20, 30, 40, 50];
|
||
let mut index = 0;
|
||
|
||
while index < 5 {
|
||
println!("the value is: {}", 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 < 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 needs to
|
||
perform the conditional check on every element on every iteration through the
|
||
loop.</p>
|
||
<p>As a more efficient alternative, you can use a <code>for</code> loop and execute some code
|
||
for each item in a collection. A <code>for</code> loop looks like this:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [10, 20, 30, 40, 50];
|
||
|
||
for element in a.iter() {
|
||
println!("the value is: {}", 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 < 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!("{}!", number);
|
||
}
|
||
println!("LIFTOFF!!!");
|
||
}
|
||
</code></pre>
|
||
<p>This code is a bit nicer, isn’t it?</p>
|
||
<h2>Summary</h2>
|
||
<p>You made it! That was a sizable chapter: you learned about variables, scalar
|
||
and<code>if</code> expressions, and loops! If you want to practice with the concepts
|
||
discussed in this chapter, try building programs to do the following:</p>
|
||
<ul>
|
||
<li>Convert temperatures between Fahrenheit and Celsius.</li>
|
||
<li>Generate the nth Fibonacci number.</li>
|
||
<li>Print the lyrics to the Christmas carol “The Twelve Days of Christmas,”
|
||
taking advantage of the repetition in the song.</li>
|
||
</ul>
|
||
<p>When you’re ready to move on, we’ll talk about a concept in Rust that <em>doesn’t</em>
|
||
commonly exist in other programming languages: ownership.</p>
|
||
<h1>Understanding Ownership</h1>
|
||
<p>Ownership is Rust’s most unique feature, and 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>
|
||
<h2>What Is Ownership?</h2>
|
||
<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>
|
||
<h3>The Stack and the Heap</h3>
|
||
<p>In many programming languages, we don’t have to think about the stack and the
|
||
heap very often. But in a systems programming language like Rust, whether a
|
||
value is on the stack or the heap has more of an effect on how the language
|
||
behaves and why we have to make certain decisions. We’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 -->
|
||
<h3>Ownership Rules</h3>
|
||
<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>
|
||
<h3>Variable Scope</h3>
|
||
<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 = "hello";
|
||
</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 = "hello"; // 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>
|
||
<h3>The <code>String</code> Type</h3>
|
||
<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("hello");
|
||
</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("hello");
|
||
|
||
s.push_str(", world!"); // push_str() appends a literal to a String
|
||
|
||
println!("{}", 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>
|
||
<h3>Memory and Allocation</h3>
|
||
<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("hello"); // 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>
|
||
<h4>Ways Variables and Data Interact: Move</h4>
|
||
<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("hello");
|
||
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>"hello"</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("hello");
|
||
let s2 = s1;
|
||
|
||
println!("{}", 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">5:22 error: use of moved value: `s1` [E0382]
|
||
println!("{}", s1);
|
||
^~
|
||
5:24 note: in this expansion of println! (defined in <std macros>)
|
||
3:11 note: `s1` moved here because it has type `collections::string::String`,
|
||
which is moved by default
|
||
let s2 = s1;
|
||
^~
|
||
</code></pre>
|
||
<p>If you’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>
|
||
<h4>Ways Variables and Data Interact: Clone</h4>
|
||
<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("hello");
|
||
let s2 = s1.clone();
|
||
|
||
println!("s1 = {}, s2 = {}", 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>
|
||
<h4>Stack-Only Data: Copy</h4>
|
||
<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!("x = {}, y = {}", 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>
|
||
<h3>Ownership and Functions</h3>
|
||
<p>The semantics for passing a value to a function are similar to assigning a
|
||
value to a variable. Passing a variable to a function will move or copy, just
|
||
like assignment. 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("hello"); // 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!("{}", 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!("{}", 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>
|
||
<h3>Return Values and Scope</h3>
|
||
<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("hello"); // 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() -> String { // gives_ownership will move its
|
||
// return value into the function
|
||
// that calls it.
|
||
|
||
let some_string = String::from("hello"); // 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) -> 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("hello");
|
||
|
||
let (s2, len) = calculate_length(s1);
|
||
|
||
println!("The length of '{}' is {}.", s2, len);
|
||
}
|
||
|
||
fn calculate_length(s: String) -> (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>
|
||
<h2>References and Borrowing</h2>
|
||
<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 takes a
|
||
<em>reference</em> to an object as an argument instead of taking ownership of the
|
||
argument:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let s1 = String::from("hello");
|
||
|
||
let len = calculate_length(&s1);
|
||
|
||
println!("The length of '{}' is {}.", s1, len);
|
||
}
|
||
|
||
fn calculate_length(s: &String) -> 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>&s1</code> into
|
||
<code>calculate_length</code>, and in its definition, we take <code>&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>&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: &String) -> usize {
|
||
# s.len()
|
||
# }
|
||
let s1 = String::from("hello");
|
||
|
||
let len = calculate_length(&s1);
|
||
</code></pre>
|
||
<p>The <code>&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>&</code> to indicate that it takes a
|
||
reference as an argument. Let’s add some explanatory annotations:</p>
|
||
<pre><code class="language-rust">fn calculate_length(s: &String) -> 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
|
||
argument'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 take references as
|
||
arguments 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 taking references as function arguments <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("hello");
|
||
|
||
change(&s);
|
||
}
|
||
|
||
fn change(some_string: &String) {
|
||
some_string.push_str(", world");
|
||
}
|
||
</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
|
||
--> error.rs:8:5
|
||
|
|
||
8 | some_string.push_str(", world");
|
||
| ^^^^^^^^^^^
|
||
</code></pre>
|
||
<p>Just as variables are immutable by default, so are references. We’re not
|
||
allowed to modify something we have a reference to.</p>
|
||
<h3>Mutable References</h3>
|
||
<p>We can fix 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("hello");
|
||
|
||
change(&mut s);
|
||
}
|
||
|
||
fn change(some_string: &mut String) {
|
||
some_string.push_str(", world");
|
||
}
|
||
</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>&mut s</code> and accept a mutable reference with <code>some_string: &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("hello");
|
||
|
||
let r1 = &mut s;
|
||
let r2 = &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
|
||
--> borrow_twice.rs:5:19
|
||
|
|
||
4 | let r1 = &mut s;
|
||
| - first mutable borrow occurs here
|
||
5 | let r2 = &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("hello");
|
||
|
||
{
|
||
let r1 = &mut s;
|
||
|
||
} // r1 goes out of scope here, so we can make a new reference with no problems.
|
||
|
||
let r2 = &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("hello");
|
||
|
||
let r1 = &s; // no problem
|
||
let r2 = &s; // no problem
|
||
let r3 = &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
|
||
--> borrow_thrice.rs:6:19
|
||
|
|
||
4 | let r1 = &s; // no problem
|
||
| - immutable borrow occurs here
|
||
5 | let r2 = &s; // no problem
|
||
6 | let r3 = &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>
|
||
<h3>Dangling References</h3>
|
||
<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() -> &String {
|
||
let s = String::from("hello");
|
||
|
||
&s
|
||
}
|
||
</code></pre>
|
||
<p>Here’s the error:</p>
|
||
<pre><code class="language-text">error[E0106]: missing lifetime specifier
|
||
--> dangle.rs:5:16
|
||
|
|
||
5 | fn dangle() -> &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() -> &String { // dangle returns a reference to a String
|
||
|
||
let s = String::from("hello"); // s is a new String
|
||
|
||
&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() -> String {
|
||
let s = String::from("hello");
|
||
|
||
s
|
||
}
|
||
</code></pre>
|
||
<p>This works without any problems. Ownership is moved out, and nothing is
|
||
deallocated.</p>
|
||
<h3>The Rules of References</h3>
|
||
<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>
|
||
<h2>Slices</h2>
|
||
<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: &String) -> ?
|
||
</code></pre>
|
||
<p>This function, <code>first_word</code>, takes a <code>&String</code> as an argument. We don’t want
|
||
ownership, so this is fine. But what should we return? We don’t really have a
|
||
way to talk about <em>part</em> of a string. 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: &String) -> usize {
|
||
let bytes = s.as_bytes();
|
||
|
||
for (i, &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> argument</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, &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>&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>&</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>&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: &String) -> usize {
|
||
# let bytes = s.as_bytes();
|
||
#
|
||
# for (i, &item) in bytes.iter().enumerate() {
|
||
# if item == b' ' {
|
||
# return i;
|
||
# }
|
||
# }
|
||
#
|
||
# s.len()
|
||
# }
|
||
#
|
||
fn main() {
|
||
let mut s = String::from("hello world");
|
||
|
||
let word = first_word(&s); // word will get the value 5.
|
||
|
||
s.clear(); // This empties the String, making it equal to "".
|
||
|
||
// 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: &String) -> (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>
|
||
<h3>String Slices</h3>
|
||
<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("hello world");
|
||
|
||
let hello = &s[0..5];
|
||
let world = &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 = &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("hello");
|
||
|
||
let slice = &s[0..2];
|
||
let slice = &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("hello");
|
||
|
||
let len = s.len();
|
||
|
||
let slice = &s[3..len];
|
||
let slice = &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("hello");
|
||
|
||
let len = s.len();
|
||
|
||
let slice = &s[0..len];
|
||
let slice = &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>&str</code>:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn first_word(s: &String) -> &str {
|
||
let bytes = s.as_bytes();
|
||
|
||
for (i, &item) in bytes.iter().enumerate() {
|
||
if item == b' ' {
|
||
return &s[0..i];
|
||
}
|
||
}
|
||
|
||
&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: &String) -> &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("hello world");
|
||
|
||
let word = first_word(&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(&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>
|
||
<h4>String Literals Are Slices</h4>
|
||
<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 = "Hello, world!";
|
||
</code></pre>
|
||
<p>The type of <code>s</code> here is <code>&str</code>: it’s a slice pointing to that specific point of
|
||
the binary. This is also why string literals are immutable; <code>&str</code> is an
|
||
immutable reference.</p>
|
||
<h4>String Slices as Arguments</h4>
|
||
<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: &String) -> &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>&str</code>s:</p>
|
||
<pre><code class="language-rust,ignore">fn first_word(s: &str) -> &str {
|
||
</code></pre>
|
||
<p>If we have a string slice, we can pass that as the argument directly. If we
|
||
have a <code>String</code>, we can pass a slice of the entire <code>String</code>. Defining a
|
||
function to take a string slice argument 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: &str) -> &str {
|
||
# let bytes = s.as_bytes();
|
||
#
|
||
# for (i, &item) in bytes.iter().enumerate() {
|
||
# if item == b' ' {
|
||
# return &s[0..i];
|
||
# }
|
||
# }
|
||
#
|
||
# &s[..]
|
||
# }
|
||
fn main() {
|
||
let my_string = String::from("hello world");
|
||
|
||
// first_word works on slices of `String`s
|
||
let word = first_word(&my_string[..]);
|
||
|
||
let my_string_literal = "hello world";
|
||
|
||
// first_word works on slices of string literals
|
||
let word = first_word(&my_string_literal[..]);
|
||
|
||
// since string literals *are* string slices already,
|
||
// this works too, without the slice syntax!
|
||
let word = first_word(my_string_literal);
|
||
}
|
||
</code></pre>
|
||
<h3>Other Slices</h3>
|
||
<p>String slices, as you might imagine, are specific to strings. But there’s a
|
||
more general slice type, too. Consider this array:</p>
|
||
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
|
||
</code></pre>
|
||
<p>Just like we 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 = &a[1..3];
|
||
</code></pre>
|
||
<p>This slice has the type <code>&[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>
|
||
<h2>Summary</h2>
|
||
<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>
|
||
<h1>Structs</h1>
|
||
<p>A <code>struct</code>, short for <em>structure</em>, is a custom data type that lets us name and
|
||
package together multiple related values that make up a meaningful group. If
|
||
you come from an object-oriented language, a <code>struct</code> is like an object’s data
|
||
attributes. In the next section of this chapter, we’ll talk about how to define
|
||
methods on our structs; methods are how you specify the <em>behavior</em> that goes
|
||
along with a struct’s data. The <code>struct</code> and <code>enum</code> (that we will talk about in
|
||
Chapter 6) concepts are the building blocks for creating new types in your
|
||
program’s domain in order to take full advantage of Rust’s compile-time type
|
||
checking.</p>
|
||
<p>One way of thinking about structs is that they are similar to tuples, which we
|
||
talked about in Chapter 3. Like tuples, the pieces of a struct can be different
|
||
types. Unlike tuples, we name each piece of data so that it’s clearer what the
|
||
values mean. Structs are more flexible as a result of these names: we don’t
|
||
have to rely on the order of the data to specify or access the values of an
|
||
instance.</p>
|
||
<p>To define a struct, we enter the keyword <code>struct</code> and give the whole struct a
|
||
name. A struct’s name should describe what the significance is of these pieces
|
||
of data being grouped together. Then, inside curly braces, we define the names
|
||
of the pieces of data, which we call <em>fields</em>, and specify each field’s type.
|
||
For example, Listing 5-1 shows a struct to store information about a user
|
||
account:</p>
|
||
<figure>
|
||
<pre><code class="language-rust">struct User {
|
||
username: String,
|
||
email: String,
|
||
sign_in_count: u64,
|
||
active: bool,
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-1: A <code>User</code> struct definition</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>To use a struct once we've defined it, we create an <em>instance</em> of that struct
|
||
by specifying concrete values for each of the fields. Creating an instance is
|
||
done by stating the name of the struct, then curly braces with <code>key: value</code>
|
||
pairs inside it where the keys are the names of the fields and the values are
|
||
the data we want to store in those fields. The fields don’t have to be
|
||
specified in the same order in which the struct declared them. In other words,
|
||
the struct definition is like a general template for the type, and instances
|
||
fill in that template with particular data to create values of the type. For
|
||
example, we can declare a particular user like this:</p>
|
||
<pre><code class="language-rust"># struct User {
|
||
# username: String,
|
||
# email: String,
|
||
# sign_in_count: u64,
|
||
# active: bool,
|
||
# }
|
||
#
|
||
let user1 = User {
|
||
email: String::from("someone@example.com"),
|
||
username: String::from("someusername123"),
|
||
active: true,
|
||
sign_in_count: 1,
|
||
};
|
||
</code></pre>
|
||
<p>To get a particular value out of a struct, we can use dot notation. If we
|
||
wanted just this user’s email address, we can say <code>user1.email</code>.</p>
|
||
<h2>Ownership of Struct Data</h2>
|
||
<p>In the <code>User</code> struct definition in Listing 5-1, we used the owned <code>String</code> type
|
||
rather than the <code>&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: &str,
|
||
email: &str,
|
||
sign_in_count: u64,
|
||
active: bool,
|
||
}
|
||
|
||
fn main() {
|
||
let user1 = User {
|
||
email: "someone@example.com",
|
||
username: "someusername123",
|
||
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
|
||
-->
|
||
|
|
||
2 | username: &str,
|
||
| ^ expected lifetime parameter
|
||
|
||
error[E0106]: missing lifetime specifier
|
||
-->
|
||
|
|
||
3 | email: &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>&str</code>.</p>
|
||
<h2>An Example Program</h2>
|
||
<p>To understand when we might want to use structs, let’s write a program that
|
||
calculates the area of a rectangle. We’ll start off with single variables, then
|
||
refactor our program until we’re using structs instead.</p>
|
||
<p>Let’s make a new binary project with Cargo called <em>rectangles</em> that will take
|
||
the length and width of a rectangle specified in pixels and will calculate the
|
||
area of the rectangle. Listing 5-2 has a short program with one way of doing
|
||
just that in our project’s <em>src/main.rs</em>:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let length1 = 50;
|
||
let width1 = 30;
|
||
|
||
println!(
|
||
"The area of the rectangle is {} square pixels.",
|
||
area(length1, width1)
|
||
);
|
||
}
|
||
|
||
fn area(length: u32, width: u32) -> u32 {
|
||
length * width
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-2: Calculating the area of a rectangle specified by its length and
|
||
width in separate variables</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Let’s try running this program with <code>cargo run</code>:</p>
|
||
<pre><code class="language-text">The area of the rectangle is 1500 square pixels.
|
||
</code></pre>
|
||
<h3>Refactoring with Tuples</h3>
|
||
<p>Our little program works okay; it figures out the area of the rectangle by
|
||
calling the <code>area</code> function with each dimension. But we can do better. The
|
||
length and the width are related to each other since together they describe one
|
||
rectangle.</p>
|
||
<p>The issue with this method is evident in the signature of <code>area</code>:</p>
|
||
<pre><code class="language-rust,ignore">fn area(length: u32, width: u32) -> u32 {
|
||
</code></pre>
|
||
<p>The <code>area</code> function is supposed to calculate the area of one rectangle, but our
|
||
function takes two arguments. The arguments are related, but that’s not
|
||
expressed anywhere in our program itself. It would be more readable and more
|
||
manageable to group length and width together.</p>
|
||
<p>We’ve already discussed one way we might do that in Chapter 3: tuples. Listing
|
||
5-3 has a version of our program which uses tuples:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let rect1 = (50, 30);
|
||
|
||
println!(
|
||
"The area of the rectangle is {} square pixels.",
|
||
area(rect1)
|
||
);
|
||
}
|
||
|
||
fn area(dimensions: (u32, u32)) -> u32 {
|
||
dimensions.0 * dimensions.1
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-3: Specifying the length and width of the rectangle with a tuple</p>
|
||
</figcaption>
|
||
</figure>
|
||
<!-- I will add ghosting & wingdings once we're in libreoffice /Carol -->
|
||
<p>In one way, this is a little better. Tuples let us add a bit of structure, and
|
||
we’re now passing just one argument. But in another way this method less clear:
|
||
tuples don’t give names to their elements, so our calculation has gotten more
|
||
confusing because we have to index into the parts of the tuple:</p>
|
||
<!-- I will change this to use wingdings instead of repeating this code once
|
||
we're in libreoffice /Carol -->
|
||
<pre><code class="language-rust,ignore">dimensions.0 * dimensions.1
|
||
</code></pre>
|
||
<p>It doesn’t matter if we mix up length and width for the area calculation, but
|
||
if we were to draw the rectangle on the screen it would matter! We would have
|
||
to remember that <code>length</code> was the tuple index <code>0</code> and <code>width</code> was the tuple
|
||
index <code>1</code>. If someone else was to work on this code, they would have to figure
|
||
this out and remember it as well. It would be easy to forget or mix these
|
||
values up and cause errors, since we haven’t conveyed the meaning of our data
|
||
in our code.</p>
|
||
<h3>Refactoring with Structs: Adding More Meaning</h3>
|
||
<p>Here is where we bring in structs. We can transform our tuple into a data type
|
||
with a name for the whole as well as names for the parts, as shown in Listing
|
||
5-4:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">struct Rectangle {
|
||
length: u32,
|
||
width: u32,
|
||
}
|
||
|
||
fn main() {
|
||
let rect1 = Rectangle { length: 50, width: 30 };
|
||
|
||
println!(
|
||
"The area of the rectangle is {} square pixels.",
|
||
area(&rect1)
|
||
);
|
||
}
|
||
|
||
fn area(rectangle: &Rectangle) -> u32 {
|
||
rectangle.length * rectangle.width
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-4: Defining a <code>Rectangle</code> struct</p>
|
||
</figcaption>
|
||
</figure>
|
||
<!-- Will add ghosting & wingdings once we're in libreoffice /Carol -->
|
||
<p>Here we’ve defined a struct and given it the name <code>Rectangle</code>. Inside the <code>{}</code>
|
||
we defined the fields to be <code>length</code> and <code>width</code>, both of which have type
|
||
<code>u32</code>. Then in <code>main</code>, we create a particular instance of a <code>Rectangle</code> that
|
||
has a length of 50 and a width of 30.</p>
|
||
<p>Our <code>area</code> function now takes one argument that we’ve named <code>rectangle</code> whose
|
||
type is an immutable borrow of a struct <code>Rectangle</code> instance. As we covered in
|
||
Chapter 4, we want to borrow the struct rather than take ownership of it so
|
||
that <code>main</code> keeps its ownership and can continue using <code>rect1</code>, so that’s why
|
||
we have the <code>&</code> in the function signature and at the call site.</p>
|
||
<p>The <code>area</code> function accesses the <code>length</code> and <code>width</code> fields of the <code>Rectangle</code>
|
||
instance it got as an argument. Our function signature for <code>area</code> now says
|
||
exactly what we mean: calculate the area of a <code>Rectangle</code>, using its <code>length</code>
|
||
and <code>width</code> fields. This conveys that the length and width are related to each
|
||
other, and gives descriptive names to the values rather than using the tuple
|
||
index values of <code>0</code> and <code>1</code>. This is a win for clarity.</p>
|
||
<h3>Adding Useful Functionality with Derived Traits</h3>
|
||
<p>It’d be nice to be able to print out an instance of our <code>Rectangle</code> while we’re
|
||
debugging our program and see the values for all its fields. Listing 5-5 tries
|
||
using the <code>println!</code> macro as we have been:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">struct Rectangle {
|
||
length: u32,
|
||
width: u32,
|
||
}
|
||
|
||
fn main() {
|
||
let rect1 = Rectangle { length: 50, width: 30 };
|
||
|
||
println!("rect1 is {}", 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!("rect1 is {:?}", 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!("rect1 is {:?}", rect1);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-6: Adding the annotation to derive the <code>Debug</code> trait and printing the
|
||
<code>Rectangle</code> instance using debug formatting</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>At this point, if we run this program, we won’t get any errors and we’ll see
|
||
the following output:</p>
|
||
<pre><code class="language-text">rect1 is Rectangle { length: 50, width: 30 }
|
||
</code></pre>
|
||
<p>Nice! It’s not the prettiest output, but it shows the values of all the fields
|
||
for this instance, which would definitely help during debugging. If we want
|
||
output that is a bit prettier and easier to read, which can be helpful with
|
||
larger structs, we can use <code>{:#?}</code> in place of <code>{:?}</code> in the <code>println!</code> string.
|
||
If we use the pretty debug style in this example, the output will look like:</p>
|
||
<pre><code class="language-text">rect1 is Rectangle {
|
||
length: 50,
|
||
width: 30
|
||
}
|
||
</code></pre>
|
||
<p>There are a number of traits Rust has provided for us to use with the <code>derive</code>
|
||
annotation that can add useful behavior to our custom types. Those traits and
|
||
their behaviors are listed in Appendix C. We’ll be covering how to implement
|
||
these traits with custom behavior, as well as creating your own traits, in
|
||
Chapter 10.</p>
|
||
<p>Our <code>area</code> function is pretty specific—it only computes the area of rectangles.
|
||
It would be nice to tie this behavior together more closely with our
|
||
<code>Rectangle</code> struct, since it’s behavior that our <code>Rectangle</code> type has
|
||
specifically. Let’s now look at how we can continue to refactor this code by
|
||
turning the <code>area</code> function into an <code>area</code> <em>method</em> defined on our <code>Rectangle</code>
|
||
type.</p>
|
||
<h2>Method Syntax</h2>
|
||
<p><em>Methods</em> are similar to functions: they’re declared with the <code>fn</code> keyword and
|
||
their name, they can take arguments and return values, and they contain some
|
||
code that gets run when they’re called from somewhere else. Methods are
|
||
different from functions, however, because they’re defined within the context
|
||
of a struct (or an enum or a trait object, which we will cover in Chapters 6
|
||
and 13, respectively), and their first argument is always <code>self</code>, which
|
||
represents the instance of the struct that the method is being called on.</p>
|
||
<h3>Defining Methods</h3>
|
||
<p>Let’s change our <code>area</code> function that takes a <code>Rectangle</code> instance as an
|
||
argument and instead make an <code>area</code> method defined on the <code>Rectangle</code> struct,
|
||
as shown in Listing 5-7:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">#[derive(Debug)]
|
||
struct Rectangle {
|
||
length: u32,
|
||
width: u32,
|
||
}
|
||
|
||
impl Rectangle {
|
||
fn area(&self) -> u32 {
|
||
self.length * self.width
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
let rect1 = Rectangle { length: 50, width: 30 };
|
||
|
||
println!(
|
||
"The area of the rectangle is {} square pixels.",
|
||
rect1.area()
|
||
);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-7: Defining an <code>area</code> method on the <code>Rectangle</code> struct</p>
|
||
</figcaption>
|
||
</figure>
|
||
<!-- Will add ghosting and wingdings here in libreoffice /Carol -->
|
||
<p>In order to make the function be defined within the context of <code>Rectangle</code>, we
|
||
start an <code>impl</code> block (<code>impl</code> is short for <em>implementation</em>). Then we move the
|
||
function within the <code>impl</code> curly braces, and change the first (and in this
|
||
case, only) argument to be <code>self</code> in the signature and everywhere within the
|
||
body. Then in <code>main</code> where we called the <code>area</code> function and passed <code>rect1</code> as
|
||
an argument, we can instead use <em>method syntax</em> to call the <code>area</code> method on
|
||
our <code>Rectangle</code> instance. Method syntax is taking an instance and adding a dot
|
||
followed by the method name, parentheses, and any arguments.</p>
|
||
<p>In the signature for <code>area</code>, we get to use <code>&self</code> instead of <code>rectangle: &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>&</code> before <code>self</code>, just like we had <code>&Rectangle</code>. Methods can choose to
|
||
take ownership of <code>self</code>, borrow <code>self</code> immutably as we’ve done here, or borrow
|
||
<code>self</code> mutably, just like any other argument.</p>
|
||
<p>We’ve chosen <code>&self</code> here for the same reason we used <code>&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>&mut self</code> as the first argument instead. Having a method that
|
||
takes ownership of the instance by having just <code>self</code> as the first argument is
|
||
rarer; this is usually used when the method transforms <code>self</code> into something
|
||
else and we want to prevent the caller from using the original instance after
|
||
the transformation.</p>
|
||
<p>The main benefit of using methods over functions, in addition to getting to use
|
||
method syntax and not having to repeat the type of <code>self</code> in every method’s
|
||
signature, is for organization. We’ve put all the things we can do with an
|
||
instance of a type together in one <code>impl</code> block, rather than make future users
|
||
of our code search for capabilities of <code>Rectangle</code> all over the place.</p>
|
||
<!-- PROD: START BOX -->
|
||
<blockquote>
|
||
<h3>Where’s the <code>-></code> operator?</h3>
|
||
<p>In languages like C++, there are two different operators for calling methods:
|
||
<code>.</code> if you’re calling a method on the object directly, and <code>-></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->something()</code>
|
||
is like <code>(*object).something()</code>.</p>
|
||
<p>Rust doesn’t have an equivalent to the <code>-></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>&</code>, <code>&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(&self, other: &Point) -> 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(&p2);
|
||
(&p1).distance(&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>&self</code>), mutating (so <code>&mut self</code>), or
|
||
consuming (so <code>self</code>). The fact that Rust makes borrowing implicit for method
|
||
receivers is a big part of making ownership ergonomic in practice.</p>
|
||
</blockquote>
|
||
<!-- PROD: END BOX -->
|
||
<h3>Methods with More Arguments</h3>
|
||
<p>Let’s practice some more with methods by implementing a second method on our
|
||
<code>Rectangle</code> struct. This time, we’d like for an instance of <code>Rectangle</code> to take
|
||
another instance of <code>Rectangle</code> and return <code>true</code> if the second rectangle could
|
||
fit completely within <code>self</code> and <code>false</code> if it would not. That is, if we run
|
||
the code in Listing 5-8, once we've defined the <code>can_hold</code> method:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let rect1 = Rectangle { length: 50, width: 30 };
|
||
let rect2 = Rectangle { length: 40, width: 10 };
|
||
let rect3 = Rectangle { length: 45, width: 60 };
|
||
|
||
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
|
||
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 5-8: Demonstration of using the as-yet-unwritten <code>can_hold</code> method</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>We want to see this output, since both of <code>rect2</code>’s dimensions are smaller than
|
||
<code>rect1</code>’s, but <code>rect3</code> is wider than <code>rect1</code>:</p>
|
||
<pre><code class="language-text">Can rect1 hold rect2? true
|
||
Can rect1 hold rect3? false
|
||
</code></pre>
|
||
<p>We know we want to define a method, so it will be within the <code>impl Rectangle</code>
|
||
block. The method name will be <code>can_hold</code>, and it will take an immutable borrow
|
||
of another <code>Rectangle</code> as an argument. We can tell what the type of the
|
||
argument will be by looking at a call site: <code>rect1.can_hold(&rect2)</code> passes in
|
||
<code>&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(&self) -> u32 {
|
||
self.length * self.width
|
||
}
|
||
|
||
fn can_hold(&self, other: &Rectangle) -> bool {
|
||
self.length > other.length && self.width > other.width
|
||
}
|
||
}
|
||
</code></pre>
|
||
<!-- Will add ghosting here in libreoffice /Carol -->
|
||
<p>If we run this with the <code>main</code> from Listing 5-8, we will get our desired output!
|
||
Methods can take multiple arguments that we add to the signature after the
|
||
<code>self</code> parameter, and those arguments work just like arguments in functions do.</p>
|
||
<h3>Associated Functions</h3>
|
||
<p>One more useful feature of <code>impl</code> blocks: we’re allowed to define functions
|
||
within <code>impl</code> blocks that <em>don’t</em> take <code>self</code> as a parameter. These are called
|
||
<em>associated functions</em>, since they’re associated with the struct. They’re still
|
||
functions though, not methods, since they don’t have an instance of the struct
|
||
to work with. You’ve already used an associated function: <code>String::from</code>.</p>
|
||
<p>Associated functions are often used for constructors that will return a new
|
||
instance of the struct. For example, we could provide an associated function
|
||
that would take one dimension argument and use that as both length and width,
|
||
thus making it easier to create a square <code>Rectangle</code> rather than having to
|
||
specify the same value twice:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust"># #[derive(Debug)]
|
||
# struct Rectangle {
|
||
# length: u32,
|
||
# width: u32,
|
||
# }
|
||
#
|
||
impl Rectangle {
|
||
fn square(size: u32) -> 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>
|
||
<h2>Summary</h2>
|
||
<p>Structs let us create custom types that are meaningful for our domain. By using
|
||
structs, we can keep associated pieces of data connected to each other and name
|
||
each piece to make our code clear. Methods let us specify the behavior that
|
||
instances of our structs have, and associated functions let us namespace
|
||
functionality that is particular to our struct without having an instance
|
||
available.</p>
|
||
<p>Structs aren’t the only way we can create custom types, though; let’s turn to
|
||
the <code>enum</code> feature of Rust and add another tool to our toolbox.</p>
|
||
<!-- Hi Steve, Carol. I like this chapter, we're getting into some powerful
|
||
tools here! I saw that the copyeditor has suggested listing numbers, which I
|
||
think is a good idea. If you agree, could you suggest captions and add
|
||
numbering to those listings we reference again in the chapter? Also, if we are
|
||
going to include any of these in the source files can you add file names?
|
||
Thanks! /Liz -->
|
||
<!-- I added some listing numbers where the code examples were lengthy or
|
||
referred to again. I haven't added any file names-- the code in this chapter is
|
||
little snippets that would be useful in larger programs, but they could appear
|
||
anywhere and don't have to be in any particular file. /Carol -->
|
||
<h1>Enums</h1>
|
||
<p>In this chapter we'll look at <em>enumerations</em>, also referred to as <em>enums</em>.
|
||
Enums allow you to define a type by enumerating its possible values. First
|
||
we'll define and use an enum to show how an enum can encode meaning along with
|
||
data. Then we'll explore a particularly useful enum, <code>Option</code>, which expresses
|
||
that a value can be either something or nothing. Next we'll look at how pattern
|
||
matching in the <code>match</code> statement makes it easy to run different code for
|
||
different values of an enum. Finally, we'll cover how the <code>if let</code> construct is
|
||
another convenient and concise idiom you have available to handle enums in your
|
||
code.</p>
|
||
<p>Enums are a feature in many languages, but their capabilities differ
|
||
per-language. Rust’s enums are most similar to "algebraic data types" in
|
||
functional languages like F#, OCaml, or Haskell.</p>
|
||
<h2>Defining an Enum</h2>
|
||
<!-- I'm not sure what you meant by "looking inside it" when you said "I wasn't
|
||
clear throughout this section whether we were defining the IpAddrKind enum or
|
||
looking inside it", but I've tried to clarify. Please elaborate on what you
|
||
meant by that and why it's confusing if I haven't resolved the issue. /Carol -->
|
||
<p>Let's look at a situation we might want to express in code and see why enums
|
||
are useful and more appropriate than structs in this case. Say we need to work
|
||
with IP addresses. There are two major standards used for IP addresses today:
|
||
version four and version six. These are the only possibilities for an IP
|
||
address that our program will come across: we can <em>enumerate</em> all possible
|
||
values, which is where <em>enumeration</em> gets its name.</p>
|
||
<p>Any IP address can be either a version four or a version six address, but not
|
||
both at the same time. That property of IP addresses makes the enum data
|
||
structure appropriate for this case, since enum values can only be one of the
|
||
variants. Both version four and version six addresses are still fundamentally
|
||
IP addresses, though, so they should be treated as the same type when the code
|
||
is handling situations that apply to any kind of IP address.</p>
|
||
<p>We can express this concept in code by defining an <code>IpAddrKind</code> enumeration and
|
||
listing the possible kinds an IP address can be, <code>V4</code> and <code>V6</code>. These are known
|
||
as the <em>variants</em> of the enum:</p>
|
||
<pre><code class="language-rust">enum IpAddrKind {
|
||
V4,
|
||
V6,
|
||
}
|
||
</code></pre>
|
||
<p>This is now a custom data type that we can use elsewhere in our code.</p>
|
||
<h3>Enum Values</h3>
|
||
<!-- Liz: You seemed confused at this point about the differences between an
|
||
enum's definition, which includes its valid variants, and using the values of
|
||
the enum. You had changed this text to be:
|
||
<p>"Enum variants can optionally have associated values. We can create values of
|
||
<code>IpAddrKind</code> like this:"</p>
|
||
<p>While it's strictly true that enum values are "optional", there wouldn't be any
|
||
point in defining the enum unless you were going to use values of that type.
|
||
Also, "associated" has other meanings in Rust that we don't want to conflate
|
||
with.</p>
|
||
<p>We've tried to clear up the confusion here by relating enum definition and
|
||
instantiation to struct definition and instantiation, assuming the reader
|
||
understands structs at this point. We're having trouble figuring out just the
|
||
right wording here, though, so we have two options for you. Please let us
|
||
know which is clearest, or a combination of the two, or if you have any
|
||
suggestions in a totally different direction! /Carol --></p>
|
||
<!-- Option 1: -->
|
||
An `enum` definition is similar to a `struct` definition: it defines a new type
|
||
and a template of what instances of that new type will be like. When you want to
|
||
use a struct, you create an instance of the struct. When you want to use an
|
||
enum, you use an instance of the enum that is one of the variants the enum
|
||
allows.
|
||
<!-- Option 2: -->
|
||
When you want to use a struct, you create an instance of the *struct* itself.
|
||
When you want to use an enum, you create an instance of one of its *variants*.
|
||
Each variant is defined like a struct, and you instantiate both using the same
|
||
syntax.
|
||
<!-- end options -->
|
||
<p>We can create instances of each of the two variants of <code>IpAddrKind</code> like this:</p>
|
||
<pre><code class="language-rust"># enum IpAddrKind {
|
||
# V4,
|
||
# V6,
|
||
# }
|
||
#
|
||
let four = IpAddrKind::V4;
|
||
let six = IpAddrKind::V6;
|
||
</code></pre>
|
||
<p>Note that the variants of the enum are namespaced under its identifier, and we
|
||
use the double colon to separate the two. The reason this is useful is that now
|
||
both values <code>IpAddrKind::V4</code> and <code>IpAddrKind::V6</code> are of the same type:
|
||
<code>IpAddrKind</code>. We can then, for instance, define a function that takes any
|
||
<code>IpAddrKind</code> as an argument:</p>
|
||
<pre><code class="language-rust"># enum IpAddrKind {
|
||
# V4,
|
||
# V6,
|
||
# }
|
||
#
|
||
fn route(ip_type: IpAddrKind) { }
|
||
</code></pre>
|
||
<p>And we can call this function with either variant:</p>
|
||
<pre><code class="language-rust"># enum IpAddrKind {
|
||
# V4,
|
||
# V6,
|
||
# }
|
||
#
|
||
# fn route(ip_type: IpAddrKind) { }
|
||
#
|
||
route(IpAddrKind::V4);
|
||
route(IpAddrKind::V6);
|
||
</code></pre>
|
||
<p>Enums have more tricks up their sleeves, too. Thinking more about our IP
|
||
address type, at the moment we don’t have a way to store the actual <em>data</em> of
|
||
the IP address; we only know what <em>kind</em> it is. Given that you just learned
|
||
about structs, you might tackle this problem as in Listing 6-1:</p>
|
||
<figure>
|
||
<pre><code class="language-rust">enum IpAddrKind {
|
||
V4,
|
||
V6,
|
||
}
|
||
|
||
struct IpAddr {
|
||
kind: IpAddrKind,
|
||
address: String,
|
||
}
|
||
|
||
let home = IpAddr {
|
||
kind: IpAddrKind::V4,
|
||
address: String::from("127.0.0.1"),
|
||
};
|
||
|
||
let loopback = IpAddr {
|
||
kind: IpAddrKind::V6,
|
||
address: String::from("::1"),
|
||
};
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 6-1: Storing the data and type of an IP address using a <code>struct</code></p>
|
||
</figcaption>
|
||
</figure>
|
||
<!-- I will add wingdings here in libreoffice /Carol -->
|
||
<p>Here, we've defined a struct <code>IpAddr</code> that has two fields: a <code>kind</code> field that
|
||
is of type <code>IpAddrKind</code> (the enum we defined previously), and an <code>address</code>
|
||
field of type <code>String</code>. We have two instances of this struct. The first,
|
||
<code>home</code>, has the value <code>IpAddrKind::V4</code> as its <code>kind</code>, with associated address
|
||
data of <code>127.0.0.1</code>. The second instance, <code>loopback</code>, has the other variant of
|
||
<code>IpAddrKind</code> as its <code>kind</code> value, <code>V6</code>, and has address <code>::1</code> associated with
|
||
it. We’ve used a struct to bundle the <code>kind</code> and <code>address</code> values together, so
|
||
that now the kind is associated with the value itself.</p>
|
||
<p>We can represent the same concept in a more concise way using just an enum
|
||
rather than an enum as part of a struct by putting data directly into each enum
|
||
variant. This new definition of the <code>IpAddr</code> enum says that both <code>V4</code> and <code>V6</code>
|
||
variants will have associated <code>String</code> values:</p>
|
||
<pre><code class="language-rust">enum IpAddr {
|
||
V4(String),
|
||
V6(String),
|
||
}
|
||
|
||
let home = IpAddr::V4(String::from("127.0.0.1"));
|
||
|
||
let loopback = IpAddr::V6(String::from("::1"));
|
||
</code></pre>
|
||
<p>We attach data to each variant of the enum directly, no need for an extra
|
||
struct.</p>
|
||
<p>There's another advantage to using an enum over a struct: each variant can
|
||
store <em>different kinds</em> of data. Version four type IP addresses will always
|
||
have four numeric components that will have values between 0 and 255. If we
|
||
wanted to store <code>V4</code> addresses as four <code>u8</code>s but still express <code>V6</code> addresses
|
||
as <code>String</code>s, we wouldn't be able to with a <code>struct</code>. Enums handle this case
|
||
with ease:</p>
|
||
<pre><code class="language-rust">enum IpAddr {
|
||
V4(u8, u8, u8, u8),
|
||
V6(String),
|
||
}
|
||
|
||
let home = IpAddr::V4(127, 0, 0, 1);
|
||
|
||
let loopback = IpAddr::V6(String::from("::1"));
|
||
</code></pre>
|
||
<p>We've been showing a bunch of different possibilities that we could define in
|
||
our code for storing IP addresses of the two different kinds using an enum. It
|
||
turns out, though, that wanting to store IP addresses and encode which kind
|
||
they are is so common that <a href="../std/net/enum.IpAddr.html">the standard library has a definition we can
|
||
use!</a><!-- ignore --> Let's look at how the standard library defines
|
||
<code>IpAddr</code>: it has the exact enum and variants that we've defined and used, but
|
||
it chose to embed the address data inside the variants in the form of two
|
||
different structs, which are defined differently for each variant:</p>
|
||
<pre><code class="language-rust">struct Ipv4Addr {
|
||
// details elided
|
||
}
|
||
|
||
struct Ipv6Addr {
|
||
// details elided
|
||
}
|
||
|
||
enum IpAddr {
|
||
V4(Ipv4Addr),
|
||
V6(Ipv6Addr),
|
||
}
|
||
</code></pre>
|
||
<p>This illustrates you can put any kind of data inside of an enum variant:
|
||
strings, numeric types, structs, and you could even include another enum! Also,
|
||
standard library types are often not much more complicated than what you might
|
||
come up with.</p>
|
||
<p>Note that even though the standard library contains a definition for <code>IpAddr</code>,
|
||
we can still choose to create and use our own definition without conflict since
|
||
we haven't brought the standard library's definition into our scope. We'll talk
|
||
more about importing types in Chapter 7.</p>
|
||
<p>Let's look at another example: here’s an enum with a wide variety of types
|
||
embedded in its variants:</p>
|
||
<pre><code class="language-rust">enum Message {
|
||
Quit,
|
||
Move { x: i32, y: i32 },
|
||
Write(String),
|
||
ChangeColor(i32, i32, i32),
|
||
}
|
||
</code></pre>
|
||
<p>This enum has four variants with different types:</p>
|
||
<ul>
|
||
<li><code>Quit</code> has no data associated with it at all.</li>
|
||
<li><code>Move</code> includes an anonymous struct inside of it.</li>
|
||
<li><code>Write</code> includes a single <code>String</code>.</li>
|
||
<li><code>ChangeColor</code> includes three <code>i32</code>s.</li>
|
||
</ul>
|
||
<p>This is similar to different kinds of struct definitions, except without the
|
||
<code>struct</code> keyword and all grouped together under the <code>Message</code> type. The
|
||
following structs could hold the same data that the enum variants above hold:</p>
|
||
<pre><code class="language-rust">struct QuitMessage; // unit struct
|
||
struct MoveMessage {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
struct WriteMessage(String); // tuple struct
|
||
struct ChangeColorMessage(i32, i32, i32); // tuple struct
|
||
</code></pre>
|
||
<p>But if we used the different structs, we wouldn't be able to as easily define a
|
||
function that could take any of these kinds of messages as we could with the
|
||
<code>Message</code> enum defined above.</p>
|
||
<p>One more similarity between enums and structs: just as we are able to define
|
||
methods on structs using <code>impl</code>, we are also able to define methods on enums.
|
||
Here's a method, <code>call</code>, that we could define on our <code>Message</code> enum:</p>
|
||
<pre><code class="language-rust"># enum Message {
|
||
# Quit,
|
||
# Move { x: i32, y: i32 },
|
||
# Write(String),
|
||
# ChangeColor(i32, i32, i32),
|
||
# }
|
||
#
|
||
impl Message {
|
||
fn call(&self) {
|
||
// body would be defined here
|
||
}
|
||
}
|
||
|
||
let m = Message::Write(String::from("hello"));
|
||
m.call();
|
||
</code></pre>
|
||
<!-- I will add wingdings here /Carol -->
|
||
<p>The body of the method would use <code>self</code> to get the value that we called the
|
||
method on. In this example, we've created a variable <code>m</code> that has the value
|
||
<code>Message::Write("hello")</code>, and that is what <code>self</code> will be in the body of
|
||
the <code>call</code> method when <code>m.call()</code> runs.</p>
|
||
<p>Let's look at another enum in the standard library that is very common and
|
||
useful: <code>Option</code>.</p>
|
||
<h2>The <code>Option</code> Enum and its Advantages Over Null Values</h2>
|
||
<p>In the previous section, we looked at how the <code>IpAddr</code> enum let us use Rust's
|
||
type system to encode more information than just the data into our program.
|
||
This section is a case study of <code>Option</code>, which is another enum defined by the
|
||
standard library. The <code>Option</code> type is used in many places because it encodes
|
||
the very common scenario in which a value could be <em>something</em> or it could be
|
||
<em>nothing</em>. Expressing this concept in terms of the type system means the
|
||
compiler can check that you've handled all the cases you should be handling,
|
||
which can prevent bugs that are extremely common in other programming languages.</p>
|
||
<p>Programming language design is often thought of in terms of which features you
|
||
include, but the features you leave out are important too. Rust does not have
|
||
the <em>null</em> feature that many other languages have. Null is a value that means
|
||
there is no value there. In languages with null, variables can always be in one
|
||
of two states: null or not-null.</p>
|
||
<p>The inventor of null has this to say:</p>
|
||
<blockquote>
|
||
<p>I call it my billion-dollar mistake. At that time, I was designing the first
|
||
comprehensive type system for references in an object-oriented language. My
|
||
goal was to ensure that all use of references should be absolutely safe, with
|
||
checking performed automatically by the compiler. But I couldn't resist the
|
||
temptation to put in a null reference, simply because it was so easy to
|
||
implement. This has led to innumerable errors, vulnerabilities, and system
|
||
crashes, which have probably caused a billion dollars of pain and damage in
|
||
the last forty years.</p>
|
||
<ul>
|
||
<li>Tony Hoare "Null References: The Billion Dollar Mistake"</li>
|
||
</ul>
|
||
</blockquote>
|
||
<p>The problem with null values is that if you try to actually use a value that's
|
||
null as if it is a not-null value, you'll get an error of some kind. Because
|
||
this null or not-null property is pervasive, it's extremely easy to make this
|
||
kind of error.</p>
|
||
<p>The concept that null is trying to express is still a useful one, however: a
|
||
null is a value which is currently invalid or absent for some reason.</p>
|
||
<p>The problem isn't with the concept itself, but with the particular
|
||
implementation. As such, Rust does not have nulls, but it does have an enum
|
||
that can encode the concept of a value being present or absent. This enum is
|
||
<code>Option<T></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<T> {
|
||
Some(T),
|
||
None,
|
||
}
|
||
</code></pre>
|
||
<p>The <code>Option<T></code> enum is so useful that it's even included in the prelude; you
|
||
don't need to import it explicitly. Furthermore, so are its variants: you can
|
||
use <code>Some</code> and <code>None</code> directly, without prefixing them with <code>Option::</code>. This is
|
||
still just a regular enum, however, <code>Some(T)</code> and <code>None</code> are still values of
|
||
type <code>Option<T></code>.</p>
|
||
<!-- We haven't spoken about the prelude so far in the book, I think I made a
|
||
note of that in a previous chapter---we should tell the reader what it is
|
||
before mentioning it so they know what significance it has here -->
|
||
<!-- We did speak about the prelude previously, in chapter 2, the Processing a
|
||
Guess section. I don't have any comments from you about it there... /Carol -->
|
||
<p>The <code><T></code> syntax is a feature of Rust we haven't talked about yet. It's a
|
||
generic type parameter, and we'll cover generics in more detail in Chapter 10.
|
||
For now, all you need to know is that this means the <code>Some</code> variant of the
|
||
<code>Option</code> enum can hold one piece of data of any type. Here are some examples of
|
||
using <code>Option</code> values to hold number types and string types:</p>
|
||
<pre><code class="language-rust">let some_number = Some(5);
|
||
let some_string = Some("a string");
|
||
|
||
let absent_number: Option<i32> = 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<T></code> we have.</p>
|
||
<p>When we have a <code>Some</code> value, we know that there is a value present, and the
|
||
value is held within the <code>Some</code>. When we have a <code>None</code> value, in some sense,
|
||
that means the same thing that null does: we do not have a valid value. So why
|
||
is this any better than null?</p>
|
||
<p>In short, because <code>Option<T></code> and <code>T</code> (where <code>T</code> can be any type) are different
|
||
types from each other, so the compiler won't let us use an <code>Option</code> value as if
|
||
it was definitely a valid value. For example, this code won't compile because
|
||
it's trying to compare an <code>Option<i8></code> to an <code>i8</code>:</p>
|
||
<pre><code class="language-rust,ignore">let x: i8 = 5;
|
||
let y: Option<i8> = 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<std::option::Option<i8>>` is not satisfied
|
||
-->
|
||
|
|
||
7 | let sum = x + y;
|
||
| ^^^^^
|
||
|
|
||
</code></pre>
|
||
<p>Intense! What this error message is trying to say is that Rust does not
|
||
understand how to add an <code>Option<i8></code> and an <code>i8</code>, since they're different
|
||
types. When we have a value of a type like <code>i8</code> in Rust, the compiler will
|
||
ensure that we always have a valid value. We can proceed confidently without
|
||
having to check for null before using that value. Only when we have an
|
||
<code>Option<i8></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<T></code> to a <code>T</code> before you can do
|
||
<code>T</code> stuff with it. This helps catch one of the most common issues with null,
|
||
generally: assuming that something isn't null when it actually is.</p>
|
||
<p>This is pretty powerful: in order to have a value that can possibly be null,
|
||
you have to explicitly opt in by making the type of that value <code>Option<T></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<T></code>, you <em>can</em> safely assume that the value isn't null. This was a
|
||
deliberate design decision for Rust to limit null's pervasiveness and increase
|
||
the safety of Rust code.</p>
|
||
<!-- So does None count as an option<T>? I lost the None thread a bit here -->
|
||
<!-- Yes, since `Option<T>` is an enum and `None` is a variant of this enum,
|
||
`None`'s type is `Option<T>`. I hope with the clarifications I added in the
|
||
previous section that this will be clear by this point. /Carol -->
|
||
<p>So, how <em>do</em> you get the <code>T</code> value out of a <code>Some</code> variant when you have a
|
||
value of type <code>Option<T></code> so that you can use that value? The <code>Option<T></code> enum
|
||
has a large number of methods useful in a variety of situations that you can
|
||
check out in <a href="../std/option/enum.Option.html">its documentation</a><!-- ignore -->, and becoming familiar
|
||
with them will be extremely useful in your journey with Rust.</p>
|
||
<p>What we generally want to do in order to use an <code>Option<T></code> value is to have
|
||
code that will handle each variant. We want some code that will run only in the
|
||
case that we have a <code>Some(T)</code> value, and this code <em>is</em> allowed to use the
|
||
inner <code>T</code>. We want some <em>other</em> code to run if we have a <code>None</code> value, and that
|
||
code doesn't have a <code>T</code> value available. The <code>match</code> expression is a control
|
||
flow construct that does just this, when used with enums: it will run different
|
||
code depending on which variant of the enum it has, and that code can use the
|
||
data inside the matching value.</p>
|
||
<!-- I'm not sure about this connecting paragraph, it doesn't seem like match
|
||
and option are actually that much connected, at least not at first. That's
|
||
fine, this is all under the enum heading, but it might confuse if we imply
|
||
otherwise --- unless I'm just missing the connection -->
|
||
<!-- I've tried to make the connection more explicit, is this better? /Carol -->
|
||
<h2>Match</h2>
|
||
<p>Rust has an extremely powerful control-flow operator, <code>match</code>, that allows us to
|
||
compare a value against a series of patterns and then execute code based on
|
||
which pattern matches. The power comes from the expressiveness of the patterns
|
||
and the compiler checks that make sure all possible cases are handled.</p>
|
||
<p>Think of a <code>match</code> expression kind of like a coin sorting machine: coins slide
|
||
down a track with variously sized holes along it, and each coin falls
|
||
through the first hole it encounters that it fits into. In the same way, values
|
||
go through each pattern in a <code>match</code>, and at the first pattern the value
|
||
"fits", the value will fall into the associated code block to be used during
|
||
execution.</p>
|
||
<p>Since we're already talking about coins, let's use them for an example using
|
||
<code>match</code>! We can write a function that can take an unknown American coin and, in
|
||
a similar way as the counting machine, determine which coin it is and
|
||
return its value in cents, shown here in Listing 6-2:</p>
|
||
<figure>
|
||
<pre><code class="language-rust">enum Coin {
|
||
Penny,
|
||
Nickel,
|
||
Dime,
|
||
Quarter,
|
||
}
|
||
|
||
fn value_in_cents(coin: Coin) -> i32 {
|
||
match coin {
|
||
Coin::Penny => 1,
|
||
Coin::Nickel => 5,
|
||
Coin::Dime => 10,
|
||
Coin::Quarter => 25,
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 6-2: An enum and a <code>match</code> expression that has the variants of the enum
|
||
as its patterns.</p>
|
||
</figcaption>
|
||
</figure>
|
||
<!--- Flagging as a place to possibly put wingding numbers -- would it work to
|
||
put two arms in this example? I think that would illustrate the control flow
|
||
well -->
|
||
<!-- I think we're moving away from using generic examples like this and talking
|
||
about concrete examples instead. I've changed the text to reflect that, and I'm
|
||
happy to add wingdings once we're in libreoffice. /Carol -->
|
||
<p>Let's break down the <code>match</code> in the <code>value_in_cents</code> function. First, we list
|
||
the <code>match</code> keyword followed by an expression, which in this case is the value
|
||
<code>coin</code>. This feels very similar to an expression used with <code>if</code>, but there's a
|
||
big difference: with <code>if</code>, the expression needs to return a boolean value.
|
||
Here, it can be any type. The type of <code>coin</code> in this example is the <code>Coin</code> enum
|
||
that we have defined above.</p>
|
||
<p>Next, we have the <em>match arms</em>. An arm has two parts: a pattern and some code.
|
||
The first arm here has a pattern that is the value <code>Coin::Penny</code>, then the <code>=></code>
|
||
operator that separates the pattern and the code to run. The code in this case
|
||
is just the value <code>1</code>. Each arm is separated from the next with a comma.</p>
|
||
<p>When the <code>match</code> expression executes, it compares the resulting value against
|
||
the pattern of each arm, in order. If a pattern matches the value, the code
|
||
associated with that pattern is executed. If that pattern doesn't match the
|
||
value, execution continues to the next arm, much like a coin sorting machine.
|
||
We can have as many arms as we need: our <code>match</code> above has four arms.</p>
|
||
<p>The code associated with each arm is an expression, and the resulting value of
|
||
the expression in the matching arm is the value that gets returned for the
|
||
entire <code>match</code> expression.</p>
|
||
<p>Curly braces typically aren't used if the match arm code is short, as it is in
|
||
the above example where each arm just returns a value. If you wanted to run
|
||
multiple lines of code in a match arm, you can use curly braces. For example,
|
||
this code would print out "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) -> i32 {
|
||
match coin {
|
||
Coin::Penny => {
|
||
println!("Lucky penny!");
|
||
1
|
||
},
|
||
Coin::Nickel => 5,
|
||
Coin::Dime => 10,
|
||
Coin::Quarter => 25,
|
||
}
|
||
}
|
||
</code></pre>
|
||
<h3>Patterns that Bind to Values</h3>
|
||
<p>Another useful feature of match arms is that they can bind to parts of the
|
||
values that match the pattern. This is how we can extract values out of enum
|
||
variants.</p>
|
||
<p>As an example, let's change one of our enum variants to hold data inside it.
|
||
From 1999 through 2008, the U.S. printed quarters with different designs for
|
||
each of the 50 states on one side. No other coins got state designs, so only
|
||
quarters have this extra value. We can add this information to our <code>enum</code>
|
||
by changing the <code>Quarter</code> variant to include a <code>State</code> value stored inside it
|
||
as we've done here in Listing 6-3:</p>
|
||
<figure>
|
||
<pre><code class="language-rust">#[derive(Debug)] // So we can inspect the state in a minute
|
||
enum UsState {
|
||
Alabama,
|
||
Alaska,
|
||
// ... etc
|
||
}
|
||
|
||
enum Coin {
|
||
Penny,
|
||
Nickel,
|
||
Dime,
|
||
Quarter(UsState),
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 6-3: A <code>Coin</code> enum where the <code>Quarter</code> variant also holds a <code>UsState</code>
|
||
value</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Let's imagine that a friend of ours is trying to collect all 50 state quarters.
|
||
While we sort our loose change by coin type, we're also going to call out the
|
||
name of the state associated with each quarter so that if it's one our friend
|
||
doesn't have they can add it to their collection.</p>
|
||
<p>In the match expression for this, we add a variable, <code>state</code>, to the pattern
|
||
that matches values of the variant <code>Coin::Quarter</code>. When a <code>Coin::Quarter</code>
|
||
matches, the <code>state</code> variable will bind to the value of that quarter's state.
|
||
Then we can use <code>state</code> in the code for that arm like so:</p>
|
||
<pre><code class="language-rust"># #[derive(Debug)]
|
||
# enum UsState {
|
||
# Alabama,
|
||
# Alaska,
|
||
# }
|
||
#
|
||
# enum Coin {
|
||
# Penny,
|
||
# Nickel,
|
||
# Dime,
|
||
# Quarter(UsState),
|
||
# }
|
||
#
|
||
fn value_in_cents(coin: Coin) -> i32 {
|
||
match coin {
|
||
Coin::Penny => 1,
|
||
Coin::Nickel => 5,
|
||
Coin::Dime => 10,
|
||
Coin::Quarter(state) => {
|
||
println!("State quarter from {:?}!", state);
|
||
25
|
||
},
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>If we were to call <code>value_in_cents(Coin::Quarter(UsState::Alaska))</code>, <code>coin</code>
|
||
would be <code>Coin::Quarter(UsState::Alaska)</code>. When we compare that value with each
|
||
of the match arms, none of them match until we reach <code>Coin::Quarter(state)</code>. At
|
||
that point, the binding for <code>state</code> will be the value <code>UsState::Alaska</code>. We can
|
||
then use that binding in the <code>println!</code> expression, thus getting the inner
|
||
state value out of the <code>Coin</code> enum variant for <code>Quarter</code>.</p>
|
||
<h3>Matching with Option<T></h3>
|
||
<p>In the previous section we wanted to get the inner <code>T</code> value out of the <code>Some</code>
|
||
case when using <code>Option<T></code>; we can do this in a very similar way! Instead of
|
||
comparing coins we will be comparing the variants of <code>Option<T></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<i32></code> and if
|
||
there's a value inside, adds one to that value. If there isn't a value inside,
|
||
the function should return the <code>None</code> value and not attempt to perform any
|
||
operations.</p>
|
||
<p>This function is very easy to write, thanks to <code>match</code>, and will look like
|
||
Listing 6-4:</p>
|
||
<figure>
|
||
<pre><code class="language-rust">fn plus_one(x: Option<i32>) -> Option<i32> {
|
||
match x {
|
||
None => None,
|
||
Some(i) => Some(i + 1),
|
||
}
|
||
}
|
||
|
||
let five = Some(5);
|
||
let six = plus_one(five);
|
||
let none = plus_one(None);
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 6-4: A function that uses a <code>match</code> expression on an <code>Option<i32></code></p>
|
||
</figcaption>
|
||
</figure>
|
||
<!-- Flagging for wingding numbers -->
|
||
<h4>Matching <code>Some(T)</code></h4>
|
||
<p>Let's examine the first execution of <code>plus_one</code> in more detail. In the above
|
||
example when we call <code>plus_one(five)</code>, the variable <code>x</code> in the body of
|
||
<code>plus_one</code> will have the value <code>Some(5)</code>. We compare that against each match
|
||
arm:</p>
|
||
<pre><code class="language-rust,ignore">None => None,
|
||
</code></pre>
|
||
<p>The <code>Some(5)</code> value doesn't match the pattern <code>None</code>, so we continue.</p>
|
||
<pre><code class="language-rust,ignore">Some(i) => Some(i + 1),
|
||
</code></pre>
|
||
<p>Does <code>Some(5)</code> match <code>Some(i)</code>? Why yes it does! We have the same variant. The
|
||
<code>i</code> binds to the value contained in <code>Some</code>, so <code>i</code> takes the value <code>5</code>. The
|
||
code in the match arm is then executed, so we add one to the value of <code>i</code>
|
||
and create a new <code>Some</code> value with our total <code>6</code> inside.</p>
|
||
<h4>Matching <code>None</code></h4>
|
||
<p>Now let's consider the second call of <code>plus_one</code> where <code>x</code> is <code>None</code>. We
|
||
enter the <code>match</code>, and compare to the first arm:</p>
|
||
<pre><code class="language-rust,ignore">None => 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>=></code>. Since the first arm matched, no other
|
||
arms are compared.</p>
|
||
<p>Combining <code>match</code> and enums together is extremely powerful. You'll see this
|
||
pattern a lot in Rust code: <code>match</code> against an enum, bind a variable to the
|
||
data inside, then execute code based on it. It's a bit tricky at first, but
|
||
once you get used to it, you'll wish you had it in all languages. It's
|
||
consistently a user favorite.</p>
|
||
<h3>Matches are Exhaustive</h3>
|
||
<p>There's one other aspect of <code>match</code> we haven't discussed. Consider this version
|
||
of our <code>plus_one</code> function:</p>
|
||
<pre><code class="language-rust,ignore">fn plus_one(x: Option<i32>) -> Option<i32> {
|
||
match x {
|
||
Some(i) => Some(i + 1),
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We didn't handle the <code>None</code> case, so this will cause a bug. Luckily, it's a bug
|
||
Rust knows how to catch. If we try to compile this code, we'll get this error:</p>
|
||
<pre><code class="language-text">error[E0004]: non-exhaustive patterns: `None` not covered
|
||
-->
|
||
|
|
||
6 | match x {
|
||
| ^ pattern `None` not covered
|
||
</code></pre>
|
||
<p>Rust knows that we did not cover every possible option, and even knows which
|
||
pattern we forgot! Enums in Rust are <em>exhaustive</em>: we must exhaust every last
|
||
option possible in order to be valid. Especially in the case of <code>Option<T></code>,
|
||
when Rust prevents us from forgetting to explicitly handle the <code>None</code> case, it
|
||
protects us from assuming that we have a value when we might have null and thus
|
||
making the billion-dollar mistake discussed earlier.</p>
|
||
<h3>The _ Placeholder</h3>
|
||
<p>Rust also has a pattern we can use in situations when we don't want to list all
|
||
possible values. For example, a <code>u8</code> can have valid values of zero through 255.
|
||
If we only care about the values 1, 3, 5, and 7, we don't want to have to list
|
||
out 0, 2, 4, 6, 8, 9 all the way up to 255. Thankfully, we don't have to: we
|
||
can use the special pattern <code>_</code> instead.</p>
|
||
<pre><code class="language-rust">let some_u8_value = 0u8;
|
||
match some_u8_value {
|
||
1 => println!("one"),
|
||
3 => println!("three"),
|
||
5 => println!("five"),
|
||
7 => println!("seven"),
|
||
_ => (),
|
||
}
|
||
</code></pre>
|
||
<p>The <code>_</code> pattern will match any value. By putting it after our other arms, the
|
||
<code>_</code> will match all the possible cases that aren't specified before it. The <code>()</code>
|
||
is just the unit value, so nothing will happen in the <code>_</code> case. This way, we
|
||
can say that we want to do nothing for all of the possible values that we don't
|
||
list before the <code>_</code> placeholder.</p>
|
||
<p>The <code>match</code> expression can be a little wordy for the case where we only care
|
||
about <em>one</em> of the cases, though. For that case, Rust provides <code>if let</code>.</p>
|
||
<h2>Concise control flow with <code>if let</code></h2>
|
||
<p>The <code>if let</code> syntax lets you combine <code>if</code> and <code>let</code> into a less verbose way to
|
||
handle values that match one pattern and ignoring the rest. Take the following
|
||
program:</p>
|
||
<pre><code class="language-rust"># let some_option = Some(5);
|
||
match some_option {
|
||
Some(x) => {
|
||
// do something with x
|
||
},
|
||
None => (),
|
||
}
|
||
</code></pre>
|
||
<p>We want to do something with the <code>Some</code> match, but do nothing with the <code>None</code>
|
||
case. We can do this with an <code>Option</code>, but with a more complex enum,
|
||
adding <code>_ => ()</code> after processing just one variant is a lot of boilerplate code
|
||
that we have to add to satisfy the <code>match</code> expression.</p>
|
||
<p>Instead, we could write this in a shorter way with <code>if let</code>. This code behaves
|
||
exactly the same as the <code>match</code> above:</p>
|
||
<pre><code class="language-rust"># let some_option = Some(5);
|
||
if let Some(x) = some_option {
|
||
// do something with x
|
||
}
|
||
</code></pre>
|
||
<p><code>if let</code> takes a pattern and an expression separated by an <code>=</code>. It works
|
||
just like a <code>match</code>, where the expression is given to the <code>match</code> and the
|
||
pattern is its first arm.</p>
|
||
<p>Using <code>if let</code> means you have less to type, less indentation, and less
|
||
boilerplate. However, we've lost the exhaustiveness checking that <code>match</code>
|
||
enforces. Choosing between <code>match</code> and <code>if let</code> depends on what you're doing in
|
||
your particular case, and if gaining conciseness is an appropriate tradeoff for
|
||
losing exhaustiveness checking.</p>
|
||
<p>In other words, you can think of <code>if let</code> as syntax sugar for a <code>match</code> that
|
||
runs code when the value matches one pattern and then ignores all other values.</p>
|
||
<p>We can include an <code>else</code> that goes with an <code>if let</code>. The block of code that
|
||
goes with the <code>else</code> is the same as the block of code that would go with the
|
||
<code>_</code> case in the <code>match</code> expression that is equivalent to the <code>if let</code> and
|
||
<code>else</code>. Recall the <code>Coin</code> enum definition in Listing 6-3, where the <code>Quarter</code>
|
||
variant also held a <code>UsState</code> value. If we wanted to count all non-quarter
|
||
coins we see while also announcing the state of the quarters, we could do that
|
||
with a <code>match</code> expression like this:</p>
|
||
<pre><code class="language-rust"># #[derive(Debug)]
|
||
# enum UsState {
|
||
# Alabama,
|
||
# Alaska,
|
||
# }
|
||
#
|
||
# enum Coin {
|
||
# Penny,
|
||
# Nickel,
|
||
# Dime,
|
||
# Quarter(UsState),
|
||
# }
|
||
# let coin = Coin::Penny;
|
||
let mut count = 0;
|
||
match coin {
|
||
Coin::Quarter(state) => println!("State quarter from {:?}!", state),
|
||
_ => count += 1,
|
||
}
|
||
</code></pre>
|
||
<p>Or we could choose to use an <code>if let</code> and <code>else</code> expression like this:</p>
|
||
<pre><code class="language-rust"># #[derive(Debug)]
|
||
# enum UsState {
|
||
# Alabama,
|
||
# Alaska,
|
||
# }
|
||
#
|
||
# enum Coin {
|
||
# Penny,
|
||
# Nickel,
|
||
# Dime,
|
||
# Quarter(UsState),
|
||
# }
|
||
# let coin = Coin::Penny;
|
||
let mut count = 0;
|
||
if let Coin::Quarter(state) = coin {
|
||
println!("State quarter from {:?}!", state);
|
||
} else {
|
||
count += 1;
|
||
}
|
||
</code></pre>
|
||
<p>If you find yourself in a situation where your program has logic that is
|
||
verbose to express using a <code>match</code>, remember that <code>if let</code> is in your Rust
|
||
toolbox as well.</p>
|
||
<h2>Summary</h2>
|
||
<p>We've now covered how to use enums to create custom types that can be one of a
|
||
set of enumerated values. We've shown how the standard library's <code>Option<T></code>
|
||
type helps you use the type system to prevent errors. When enum values have data
|
||
inside them, you can use <code>match</code> or <code>if let</code> to extract and use those values,
|
||
depending on how many cases you need to handle.</p>
|
||
<p>Your Rust programs can now express concepts in your domain using structs and
|
||
enums. Creating custom types to use in your API ensures type safety: the
|
||
compiler will make certain your functions only get values of the type each
|
||
function expects.</p>
|
||
<p>In order to provide a well-organized API to your users that is straightforward
|
||
to use and only exposes exactly what your users will need, let's now turn to
|
||
Rust's <em>modules</em>.</p>
|
||
<h1>Modules</h1>
|
||
<p>When you start writing programs in Rust, your code might live solely in the
|
||
<code>main</code> function. As your code grows, you’ll eventually move functionality out
|
||
into other functions, both for re-use and for better organization. By splitting
|
||
your code up into smaller chunks, each chunk is easier to understand on its
|
||
own. But what happens if find yourself with too many functions? Rust has a
|
||
module system that handles the problem of wanting to to re-use code while
|
||
keeping your code organized.</p>
|
||
<p>In the same way that you extract lines of code into a function, you can extract
|
||
functions (and other code like structs and enums too) into different modules. A
|
||
<em>module</em> is a namespace that contains definitions of functions or types, and
|
||
you can choose whether those definitions are visible outside their module
|
||
(public) or not (private). Here’s an overview of how modules work:</p>
|
||
<ul>
|
||
<li>You declare a new module with the keyword <code>mod</code></li>
|
||
<li>By default, everything is set as private, but you can use the <code>pub</code> keyword
|
||
to make the module public, and therefore visible outside of the namespace.</li>
|
||
<li>The <code>use</code> keyword allows you to bring modules, or the definitions inside
|
||
modules, into scope so that it’s easier to refer to them.</li>
|
||
</ul>
|
||
<p>We’ll take a look at each of these parts and see how they fit into the whole.</p>
|
||
<h2><code>mod</code> and the Filesystem</h2>
|
||
<p>We’ll start our module example by making a new project with Cargo, but instead
|
||
of creating a binary crate, we’re going to make a library crate: a project that
|
||
other people can pull into their projects as a dependency. We saw this with the
|
||
<code>rand</code> crate in Chapter 2.</p>
|
||
<p>We’ll create a skeleton of a library that provides some general networking
|
||
functionality; we’re going to concentrate on the organization of the modules
|
||
and functions, but not worry about what code goes in the function bodies. We’ll
|
||
call our library <code>communicator</code>. By default, cargo will create a library unless
|
||
another type of project is specified, so if we leave off the <code>--bin</code> option
|
||
that we’ve been using so far our project will be a library:</p>
|
||
<pre><code class="language-text">$ cargo new communicator
|
||
$ cd communicator
|
||
</code></pre>
|
||
<p>Notice that Cargo generated <em>src/lib.rs</em> instead of <em>src/main.rs</em>. Inside
|
||
<em>src/lib.rs</em> we’ll find this:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Cargo creates an empty test to help us get our library started, rather
|
||
than the “Hello, world!” binary that we get with the <code>--bin</code> option. We’ll look
|
||
at the <code>#[]</code> and <code>mod tests</code> syntax a little later, but for now just make sure
|
||
to leave it in your <em>src/lib.rs</em>.</p>
|
||
<p>Since we don’t have a <em>src/main.rs</em>, there’s nothing for Cargo to execute with
|
||
the <code>cargo run</code> command. Therefore, we will be using the <code>cargo build</code> command
|
||
to only compile our library crate’s code.</p>
|
||
<p>We’re going to look at different options for organizing your library’s code
|
||
which will be suitable in a variety of situations, depending on the intentions
|
||
you have for your code.</p>
|
||
<h3>Module Definitions</h3>
|
||
<p>For our <code>communicator</code> networking library, we’re first going to define a module
|
||
named <code>network</code> that contains the definition of a function called <code>connect</code>.
|
||
Every module definition in Rust starts with the <code>mod</code> keyword. Add this code to
|
||
the beginning of the <em>lib.rs</em> file, above the test code:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">mod network {
|
||
fn connect() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>After the <code>mod</code> keyword, we put the name of the module, <code>network</code>, then a block
|
||
of code in curly braces. Everything inside this block is inside the namespace
|
||
<code>network</code>. In this case, we have a single function, <code>connect</code>. If we wanted to
|
||
call this function from a script outside the <code>network</code> module, we would need to
|
||
specify the module and use the namespace syntax <code>::</code>, like so:
|
||
<code>network::connect()</code>, rather than just <code>connect()</code>.</p>
|
||
<p>We can also have multiple modules, side-by-side, in the same <em>src/lib.rs</em> file.
|
||
For example, to have a <code>client</code> module too, that also has a function named
|
||
<code>connect</code>, we can add:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">mod network {
|
||
fn connect() {
|
||
}
|
||
}
|
||
|
||
mod client {
|
||
fn connect() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 7-1: The <code>network</code> module and the <code>client</code> module defined side-by-side
|
||
in <em>src/lib.rs</em></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Now we have a <code>network::connect</code> function and a <code>client::connect</code> function.
|
||
These can have completely different functionality, and the function names do
|
||
not conflict with each other since they’re in different modules.</p>
|
||
<p>While in this case, we’re building a library, there's nothing special about
|
||
<em>lib.rs</em>. We could also make use of submodules in a <em>main.rs</em> as well. In fact,
|
||
we can also put modules inside of modules. This can be useful as your modules
|
||
grow to keep related functionality organized together and separate
|
||
functionality apart. The choice of how you organize your code depends on how
|
||
you think about the relationship between the parts of your code. For instance,
|
||
the <code>client</code> code and its <code>connect</code> function might make more sense to users of
|
||
our library if it was inside the <code>network</code> namespace instead, like so:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">mod network {
|
||
fn connect() {
|
||
}
|
||
|
||
mod client {
|
||
fn connect() {
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 7-2: Moving the <code>client</code> module inside of the <code>network</code> module</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>In your <em>src/lib.rs</em> file, replace the existing <code>mod network</code> and <code>mod client</code>
|
||
definitions with this one that has the <code>client</code> module as an inner module of
|
||
<code>network</code>. Now we have the functions <code>network::connect</code> and
|
||
<code>network::client::connect</code>: again, the two functions named <code>connect</code> don’t
|
||
conflict with each other since they’re in different namespaces.</p>
|
||
<p>In this way, modules form a hierarchy. The contents of <em>src/lib.rs</em> are at the
|
||
topmost level, and the submodules are at lower levels. Here’s what the
|
||
organization of our example from Listing 7-1 looks like when thought of this
|
||
way:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── network
|
||
└── client
|
||
</code></pre>
|
||
<p>And here’s the example from Listing 7-2:</p>
|
||
<pre><code class="language-text">communicator
|
||
└── network
|
||
└── client
|
||
</code></pre>
|
||
<p>You can see that in Listing 7-2, <code>client</code> is a child of the <code>network</code> module,
|
||
rather than a sibling. More complicated projects can have a lot of modules, and
|
||
they’ll need to be organized logically in order to keep track of them. What
|
||
“logically” means in your project is up to you and depends on how you and users
|
||
of your library think about your project’s domain. Use the techniques we’ve
|
||
shown here to create side-by-side modules and nested modules in whatever
|
||
structure you would like.</p>
|
||
<h3>Moving Modules to Other Files</h3>
|
||
<p>Modules form a hierarchical structure, much like another structure in computing
|
||
that you’re used to: file systems! We can use Rust’s module system along with
|
||
multiple files to split Rust projects up so that not everything lives in
|
||
<em>src/lib.rs</em>. For this example, we will start with this code in <em>src/lib.rs</em>:</p>
|
||
<figure>
|
||
<span class="filename">File: src/lib.rs</span>
|
||
<pre><code class="language-rust">mod client {
|
||
fn connect() {
|
||
}
|
||
}
|
||
|
||
mod network {
|
||
fn connect() {
|
||
}
|
||
|
||
mod server {
|
||
fn connect() {
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 7-3: Three modules, <code>client</code>, <code>network</code>, and <code>network::server</code> all
|
||
defined in <em>src/lib.rs</em></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>which has this module hierarchy:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── client
|
||
└── network
|
||
└── server
|
||
</code></pre>
|
||
<p>If these modules had many functions, and each function was getting long, we
|
||
would have to scroll through this file to find the code we wanted to work with.
|
||
This would be a good reason to pull each of the <code>client</code>, <code>network</code>, and
|
||
<code>server</code> modules out of <em>src/lib.rs</em> and into their own files. Let’s start by
|
||
extracting the <code>client</code> module into another file. First, replace the <code>client</code>
|
||
module code in <em>src/lib.rs</em> with the following:</p>
|
||
<p><span class="filename">File: src/lib.rs</span></p>
|
||
<pre><code class="language-rust,ignore">mod client;
|
||
|
||
mod network {
|
||
fn connect() {
|
||
}
|
||
|
||
mod server {
|
||
fn connect() {
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<!-- I will add wingdings/ghosting in libreoffice /Carol -->
|
||
<p>We’re still <em>defining</em> the <code>client</code> module here, but by removing the curly
|
||
braces and definitions inside the <code>client</code> module and replacing them with a
|
||
semicolon, we’re letting Rust know to look in another location for the code
|
||
defined inside that module.</p>
|
||
<p>So now we need to create the external file with that module name. Create a
|
||
<em>client.rs</em> file in your <em>src/</em> directory, then open it up and enter the
|
||
following, which is the <code>connect</code> function in the <code>client</code> module that we
|
||
removed in the previous step:</p>
|
||
<p><span class="filename">File: src/client.rs</span></p>
|
||
<pre><code class="language-rust">fn connect() {
|
||
}
|
||
</code></pre>
|
||
<p>Note that we don’t need a <code>mod</code> declaration in this file; that’s because we
|
||
already declared the <code>client</code> module with <code>mod</code> in <em>src/lib.rs</em>. This file just
|
||
provides the <em>contents</em> of the <code>client</code> module. If we put a <code>mod client</code> here,
|
||
we’d be giving the <code>client</code> module its own submodule named <code>client</code>!</p>
|
||
<p>Rust only knows to look in <em>src/lib.rs</em> by default. If we want to add more
|
||
files to our project, we need to tell Rust in <em>src/lib.rs</em> to look in other
|
||
files; this is why <code>mod client</code> needs to be defined in <em>src/lib.rs</em> and can’t
|
||
be defined in <em>src/client.rs</em>.</p>
|
||
<p>Now, everything should compile successfully, though you’ll get a few warnings.
|
||
Remember to use <code>cargo build</code> instead of <code>cargo run</code> since we have a library
|
||
crate rather than a binary crate:</p>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/client.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/lib.rs:4:5
|
||
|
|
||
4 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/lib.rs:8:9
|
||
|
|
||
8 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>These warnings tell us that we have functions that are never used. Don’t worry
|
||
about those warnings for now; we’ll address them later in the chapter. The good
|
||
news is that they’re just warnings; our project was built successfully!</p>
|
||
<p>Let’s extract the <code>network</code> module into its own file next, using the same
|
||
pattern. In <em>src/lib.rs</em>, delete the body of the <code>network</code> module and add a
|
||
semicolon to the declaration, like so:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust,ignore">mod client;
|
||
|
||
mod network;
|
||
</code></pre>
|
||
<p>Then create a new <em>src/network.rs</em> file and enter the following:</p>
|
||
<p><span class="filename">Filename: src/network.rs</span></p>
|
||
<pre><code class="language-rust">fn connect() {
|
||
}
|
||
|
||
mod server {
|
||
fn connect() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Notice that we still have a <code>mod</code> declaration within this module file;
|
||
this is because we still want <code>server</code> to be a sub-module of <code>network</code>.</p>
|
||
<p>Now run <code>cargo build</code> again. Success! We have one more module to extract:
|
||
<code>server</code>. Because it’s a sub-module—that is, a module within a module—our
|
||
current tactic of extracting a module into a file named after that module won’t
|
||
work. We’re going to try anyway so that we can see the error. First change
|
||
<em>src/network.rs</em> to have <code>mod server;</code> instead of the <code>server</code> module’s
|
||
contents:</p>
|
||
<p><span class="filename">Filename: src/network.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn connect() {
|
||
}
|
||
|
||
mod server;
|
||
</code></pre>
|
||
<p>Then create a <em>src/server.rs</em> file and enter the contents of the <code>server</code>
|
||
module that we extracted:</p>
|
||
<p><span class="filename">Filename: src/server.rs</span></p>
|
||
<pre><code class="language-rust">fn connect() {
|
||
}
|
||
</code></pre>
|
||
<p>When we try to <code>cargo build</code>, we’ll get this error:</p>
|
||
<figure>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
error: cannot declare a new module at this location
|
||
--> src/network.rs:4:5
|
||
|
|
||
4 | mod server;
|
||
| ^^^^^^
|
||
|
|
||
note: maybe move this module `network` to its own directory via `network/mod.rs`
|
||
--> src/network.rs:4:5
|
||
|
|
||
4 | mod server;
|
||
| ^^^^^^
|
||
note: ... or maybe `use` the module `server` instead of possibly redeclaring it
|
||
--> src/network.rs:4:5
|
||
|
|
||
4 | mod server;
|
||
| ^^^^^^
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 7-4: Error when trying to extract the <code>server</code> submodule into
|
||
<em>src/server.rs</em></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>The error says we <code>cannot declare a new module at this location</code> and is
|
||
pointing to the <code>mod server;</code> line in <em>src/network.rs</em>. So <em>src/network.rs</em> is
|
||
different than <em>src/lib.rs</em> somehow; let’s keep reading to understand why.</p>
|
||
<p>The note in the middle of Listing 7-4 is actually pretty helpful, as it points
|
||
out something we haven’t yet talked about doing:</p>
|
||
<blockquote>
|
||
<p>note: maybe move this module <code>network</code> to its own directory via
|
||
<code>network/mod.rs</code></p>
|
||
</blockquote>
|
||
<p>Instead of continuing to follow the same file naming pattern we used
|
||
previously, we can do what the note suggests:</p>
|
||
<ol>
|
||
<li>Make a new <em>directory</em> named <em>network</em>, the parent module’s name</li>
|
||
<li>Move the <em>src/network.rs</em> file into the new <em>network</em> directory and rename
|
||
it so that it is now <em>src/network/mod.rs</em></li>
|
||
<li>Move the submodule file <em>src/server.rs</em> into the <em>network</em> directory</li>
|
||
</ol>
|
||
<p>Here are commands to carry out these steps:</p>
|
||
<pre><code class="language-text">$ mkdir src/network
|
||
$ mv src/network.rs src/network/mod.rs
|
||
$ mv src/server.rs src/network
|
||
</code></pre>
|
||
<p>Now if we try to <code>cargo build</code>, compilation will work (we’ll still have
|
||
warnings though). Our module layout still looks like this, which is exactly the
|
||
same as it did when we had all the code in <em>src/lib.rs</em> in Listing 7-3:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── client
|
||
└── network
|
||
└── server
|
||
</code></pre>
|
||
<p>The corresponding file layout now looks like this:</p>
|
||
<pre><code class="language-text">├── src
|
||
│ ├── client.rs
|
||
│ ├── lib.rs
|
||
│ └── network
|
||
│ ├── mod.rs
|
||
│ └── server.rs
|
||
</code></pre>
|
||
<p>So when we wanted to extract the <code>network::server</code> module, why did we have to
|
||
also change the <em>src/network.rs</em> file into the <em>src/network/mod.rs</em> file, and
|
||
also put the code for <code>network::server</code> in the <code>network</code> directory in
|
||
<em>src/network/server.rs</em>, instead of just being able to extract the
|
||
<code>network::server</code> into <em>src/server.rs</em>? The reason is that Rust wouldn’t be
|
||
able to tell that <code>server</code> was supposed to be a submodule of <code>network</code> if the
|
||
<em>server.rs</em> file was in the <em>src</em> directory. To make it clearer why Rust can’t
|
||
tell, let’s consider a different example where we have this module hierarchy
|
||
with all the definitions in <em>src/lib.rs</em>:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── client
|
||
└── network
|
||
└── client
|
||
</code></pre>
|
||
<p>In this example, we have three modules again, <code>client</code>, <code>network</code>, and
|
||
<code>network::client</code>. If we follow the same steps we originally did above for
|
||
extracting modules into files, for the <code>client</code> module we would create
|
||
<em>src/client.rs</em>. For the <code>network</code> module, we would create <em>src/network.rs</em>.
|
||
Then we wouldn’t be able to extract the <code>network::client</code> module into a
|
||
<em>src/client.rs</em> file, because that already exists for the top-level <code>client</code>
|
||
module! If we put the code in both the <code>client</code> and <code>network::client</code> modules
|
||
in the <em>src/client.rs</em> file, Rust would not have any way to know whether the
|
||
code was for <code>client</code> or for <code>network::client</code>.</p>
|
||
<p>Therefore, once we wanted to extract a file for the <code>network::client</code> submodule
|
||
of the <code>network</code> module, we needed to create a directory for the <code>network</code>
|
||
module instead of a <em>src/network.rs</em> file. The code that is in the <code>network</code>
|
||
module then goes into the <em>src/network/mod.rs</em> file, and the submodule
|
||
<code>network::client</code> can have its own <em>src/network/client.rs</em> file. Now the
|
||
top-level <em>src/client.rs</em> is unambiguously the code that belongs to the
|
||
<code>client</code> module.</p>
|
||
<h3>Rules of Module File Systems</h3>
|
||
<p>In summary, these are the rules of modules with regards to files:</p>
|
||
<ul>
|
||
<li>
|
||
<p>If a module named <code>foo</code> has no submodules, you should put the declarations
|
||
for <code>foo</code> in a file named <em>foo.rs</em>.</p>
|
||
</li>
|
||
<li>
|
||
<p>If a module named <code>foo</code> does have submodules, you should put the declarations
|
||
for <code>foo</code> in a file named <em>foo/mod.rs</em>.</p>
|
||
</li>
|
||
<li>
|
||
<p>The first two rules apply recursively, so that if a module named <code>foo</code> has a
|
||
submodule named <code>bar</code> and <code>bar</code> does not have submodules, you should have the
|
||
following files in your <em>src</em> directory:</p>
|
||
<pre><code class="language-text">├── foo
|
||
│ ├── bar.rs (contains the declarations in `foo::bar`)
|
||
│ └── mod.rs (contains the declarations in `foo`, including `mod bar`)
|
||
</code></pre>
|
||
</li>
|
||
<li>
|
||
<p>The modules themselves should be declared in their parent module’s file using
|
||
the <code>mod</code> keyword.</p>
|
||
</li>
|
||
</ul>
|
||
<p>Next, we’ll talk about the <code>pub</code> keyword, and get rid of those warnings!</p>
|
||
<h2>Controlling Visibility with <code>pub</code></h2>
|
||
<p>We resolved the error messages shown in Listing 7-4 by moving the <code>network</code> and
|
||
<code>network::server</code> code into the <em>src/network/mod.rs</em> and
|
||
<em>src/network/server.rs</em> files, respectively. At that point, <code>cargo build</code> was
|
||
able to build our project, but we still get some warning messages about the
|
||
<code>client::connect</code>, <code>network::connect</code>, and <code>network::server::connect</code> functions
|
||
not being used:</p>
|
||
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
src/client.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/mod.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>So why are we receiving these warnings? After all, we’re building a library
|
||
with functions that are intended to be used by our <em>users</em>, and not necessarily
|
||
by us within our own project, so it shouldn’t matter that these <code>connect</code>
|
||
functions go unused. The point of creating them is that they will be used by
|
||
another project and not our own.</p>
|
||
<p>To understand why this program invokes these warnings, let’s try using the
|
||
<code>connect</code> library as if we were another project, calling it externally. We can
|
||
do that by creating a binary crate in the same directory as our library crate,
|
||
by making a <em>src/main.rs</em> file containing this code:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">extern crate communicator;
|
||
|
||
fn main() {
|
||
communicator::client::connect();
|
||
}
|
||
</code></pre>
|
||
<p>We use the <code>extern crate</code> command to bring the <code>communicator</code> library crate
|
||
into scope, because our package actually now contains <em>two</em> crates. Cargo
|
||
treats <em>src/main.rs</em> as the root file of a binary crate, which is separate from
|
||
the existing library crate whose root file is <em>src/lib.rs</em>. This pattern is
|
||
quite common for executable projects: most functionality is in a library crate,
|
||
and the binary crate uses that library crate. This way, other programs can also
|
||
use the library crate, and it’s a nice separation of concerns.</p>
|
||
<p>Our binary crate right now just calls our library’s <code>connect</code> function from the
|
||
<code>client</code> module. However, invoking <code>cargo build</code> will now give us an error
|
||
after the warnings:</p>
|
||
<pre><code class="language-text">error: module `client` is private
|
||
--> src/main.rs:4:5
|
||
|
|
||
4 | communicator::client::connect();
|
||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||
</code></pre>
|
||
<p>Ah ha! This tells us that the <code>client</code> module is private, and this is the crux
|
||
of the warnings. It’s also the first time we’ve run into the concepts of
|
||
<em>public</em> and <em>private</em> in the context of Rust. The default state of all code in
|
||
Rust is private: no one else is allowed to use the code. If you don’t use a
|
||
private function within your own program, since your own program is the only
|
||
code allowed to use that function, Rust will warn you that the function has
|
||
gone unused.</p>
|
||
<p>Once we specify that a function like <code>client::connect</code> is public, not only will
|
||
our call to that function from our binary crate be allowed, the warning that
|
||
the function is unused will go away. Marking something public lets Rust know
|
||
that we intend for the function to be used by code outside of our program. Rust
|
||
considers the theoretical external usage that’s now possible as the function
|
||
“being used.” Thus, when something is marked as public, Rust will not require
|
||
that it’s used in our own program and will stop warning that the item is
|
||
unused.</p>
|
||
<h3>Making a Function Public</h3>
|
||
<p>To tell Rust to make something public, we add the <code>pub</code> keyword to the start of
|
||
the declaration of the item we want to make public. We’ll focus on fixing the
|
||
warning that tells us that <code>client::connect</code> has gone unused for now, as well
|
||
as the “module <code>client</code> is private” error from our binary crate. Modify
|
||
<em>src/lib.rs</em> to make the <code>client</code> module public, like so:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust,ignore">pub mod client;
|
||
|
||
mod network;
|
||
</code></pre>
|
||
<p>The <code>pub</code> goes right before <code>mod</code>. Let’s try building again:</p>
|
||
<pre><code class="language-text"><warnings>
|
||
error: function `connect` is private
|
||
--> src/main.rs:4:5
|
||
|
|
||
4 | communicator::client::connect();
|
||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||
</code></pre>
|
||
<p>Hooray! We have a different error! Yes, different error messages are a cause
|
||
for celebration. The new error says “function <code>connect</code> is private”, so let’s
|
||
edit <code>src/client.rs</code> to make <code>client::connect</code> public too:</p>
|
||
<p><span class="filename">Filename: src/client.rs</span></p>
|
||
<pre><code class="language-rust">pub fn connect() {
|
||
}
|
||
</code></pre>
|
||
<p>And run <code>cargo build</code> again:</p>
|
||
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/mod.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> 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
|
||
--> src/network/mod.rs:1:1
|
||
|
|
||
1 | pub fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Hmmm, we’re still getting an unused function warning even though
|
||
<code>network::connect</code> is set to <code>pub</code>. This is because the function is public
|
||
within the module, but the <code>network</code> module that the function resides in is not
|
||
public. We’re working from the interior of the library out this time, where
|
||
with <code>client::connect</code> we worked from the outside in. We need to change
|
||
<code>src/lib.rs</code> to make <code>network</code> public too:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust,ignore">pub mod client;
|
||
|
||
pub mod network;
|
||
</code></pre>
|
||
<p>Now if we compile, that warning is gone:</p>
|
||
<pre><code class="language-text">warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Only one warning left! Try to fix this one on your own!</p>
|
||
<h3>Privacy Rules</h3>
|
||
<p>Overall, these are the rules for item visibility:</p>
|
||
<ol>
|
||
<li>If an item is public, it can be accessed through any of its
|
||
parent modules.</li>
|
||
<li>If an item is private, it may be accessed only by the current module and its
|
||
child modules.</li>
|
||
</ol>
|
||
<h3>Privacy Examples</h3>
|
||
<p>Let’s look at a few more examples to get some practice. Create a new 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>
|
||
<h4>Looking at the Errors</h4>
|
||
<p>The <code>try_me</code> function is in the root module of our project. The module named
|
||
<code>outermost</code> is private, but the second privacy rule says the <code>try_me</code> function
|
||
is allowed to access the <code>outermost</code> module since <code>outermost</code> is in the current
|
||
(root) module, as is <code>try_me</code>.</p>
|
||
<p>The call to <code>outermost::middle_function</code> will work. This is because
|
||
<code>middle_function</code> is public, and <code>try_me</code> is accessing <code>middle_function</code>
|
||
through its parent module, <code>outermost</code> We determined in the previous paragraph
|
||
that this module is accessible.</p>
|
||
<p>The call to <code>outermost::middle_secret_function</code> will cause a compilation error.
|
||
<code>middle_secret_function</code> is private, so the second rule applies. The root
|
||
module is neither the current module of <code>middle_secret_function</code> (<code>outermost</code>
|
||
is), nor is it a child module of the current module of <code>middle_secret_function</code>.</p>
|
||
<p>The module named <code>inside</code> is private and has no child modules, so it can only
|
||
be accessed by its current module, <code>outermost</code>. That means the <code>try_me</code>
|
||
function is not allowed to call <code>outermost::inside::inner_function</code> or
|
||
<code>outermost::inside::secret_function</code> either.</p>
|
||
<h4>Fixing the Errors</h4>
|
||
<p>Here are some suggestions for changing the code in an attempt to fix the
|
||
errors. Before you try each one, make a guess as to whether it will fix the
|
||
errors, then compile to see if you’re right and use the privacy rules to
|
||
understand why.</p>
|
||
<ul>
|
||
<li>What if the <code>inside</code> module was public?</li>
|
||
<li>What if <code>outermost</code> was public and <code>inside</code> was private?</li>
|
||
<li>What if, in the body of <code>inner_function</code>, you called
|
||
<code>::outermost::middle_secret_function()</code>? (The two colons at the beginning
|
||
mean that we want to refer to the namespaces starting from the root
|
||
namespace.)</li>
|
||
</ul>
|
||
<p>Feel free to design more experiments and try them out!</p>
|
||
<p>Next, let’s talk about bringing items into a scope with the <code>use</code> keyword.</p>
|
||
<h2>Importing Names</h2>
|
||
<p>We’ve covered how to call functions defined within a module using the module
|
||
name as part of the call, as in the call to the <code>namespaces</code> function shown
|
||
here in Listing 7-6.</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">pub mod a {
|
||
pub mod series {
|
||
pub mod of {
|
||
pub fn namespaces() {}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
a::series::of::namespaces();
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 7-6: Calling a function by fully specifying its enclosing module’s
|
||
namespaces</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>As you can see, referring to the fully qualified name can get quite lengthy.
|
||
Luckily, Rust has a keyword to make these calls more concise.</p>
|
||
<h3>Concise Imports with <code>use</code></h3>
|
||
<p>Rust’s <code>use</code> keyword works to shorten lengthy function calls by bringing the
|
||
modules of the function you want to call into a scope. Here’s an example of
|
||
bringing the <code>a::series::of</code> namespace into a binary crate’s root scope:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">pub mod a {
|
||
pub mod series {
|
||
pub mod of {
|
||
pub fn namespaces() {}
|
||
}
|
||
}
|
||
}
|
||
|
||
use a::series::of;
|
||
|
||
fn main() {
|
||
of::namespaces();
|
||
}
|
||
</code></pre>
|
||
<p>The line <code>use a::series::of;</code> has made it so that anywhere in this scope that
|
||
we would want to refer to the <code>of</code> namespace, instead of having to say
|
||
<code>a::series::of</code>, we can replace that with <code>of</code>.</p>
|
||
<p>The <code>use</code> keyword brings only what we have specified into scope; it does not
|
||
bring children of modules into scope. That’s why we still have to say
|
||
<code>of::namespaces</code> when we want to call the <code>namespaces</code> function.</p>
|
||
<p>We could have chosen to bring the function itself into scope, by instead
|
||
specifying the function in the <code>use</code> as follows:</p>
|
||
<pre><code class="language-rust">pub mod a {
|
||
pub mod series {
|
||
pub mod of {
|
||
pub fn namespaces() {}
|
||
}
|
||
}
|
||
}
|
||
|
||
use a::series::of::namespaces;
|
||
|
||
fn main() {
|
||
namespaces();
|
||
}
|
||
</code></pre>
|
||
<p>This allows us to exclude any of the modules and just reference the function at
|
||
the callsite.</p>
|
||
<p>Since enums also form this kind of namespace, we can import an enum’s variants
|
||
with <code>use</code> as well. For any kind of <code>use</code> statement, if you’re importing
|
||
multiple items from one namespace, you can list them using curly braces and
|
||
commas in the last position, like so:</p>
|
||
<pre><code class="language-rust">enum TrafficLight {
|
||
Red,
|
||
Yellow,
|
||
Green,
|
||
}
|
||
|
||
use TrafficLight::{Red, Yellow};
|
||
|
||
fn main() {
|
||
let red = Red;
|
||
let yellow = Yellow;
|
||
let green = TrafficLight::Green; // because we didn’t `use` TrafficLight::Green
|
||
}
|
||
</code></pre>
|
||
<h3>Glob Imports with <code>*</code></h3>
|
||
<p>To import all the items in a namespace at once, we can use the <code>*</code> syntax. For
|
||
example:</p>
|
||
<pre><code class="language-rust">enum TrafficLight {
|
||
Red,
|
||
Yellow,
|
||
Green,
|
||
}
|
||
|
||
use TrafficLight::*;
|
||
|
||
fn main() {
|
||
let red = Red;
|
||
let yellow = Yellow;
|
||
let green = Green;
|
||
}
|
||
</code></pre>
|
||
<p>The <code>*</code> is called a <em>glob</em>, and it will import everything that’s visible inside
|
||
of the namespace. Globs should be used sparingly: they are convenient, but you
|
||
might also pull in more things than you expected and cause naming conflicts.</p>
|
||
<h3>Using <code>super</code> to Access a Parent Module</h3>
|
||
<p>As you now know, when you create a library crate, Cargo makes a <code>tests</code> module
|
||
for you. Let’s go into more detail about that now. In your <code>communicator</code>
|
||
project, open <em>src/lib.rs</em>.</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust,ignore">pub mod client;
|
||
|
||
pub mod network;
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We’ll explain more about testing in Chapter 12, but parts of this should make
|
||
sense now: we have a module named <code>tests</code> that lives next to our other modules
|
||
and contains one function named <code>it_works</code>. Even though there are special
|
||
annotations, the <code>tests</code> module is just another module! So our module hierarchy
|
||
looks like this:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── client
|
||
├── network
|
||
| └── client
|
||
└── tests
|
||
</code></pre>
|
||
<p>Tests are for exercising the code within our library, so let’s try to call
|
||
our <code>client::connect</code> function from this <code>it_works</code> function, even though
|
||
we’re not going to be checking any functionality right now:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
client::connect();
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Run the tests by invoking the <code>cargo test</code> command:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
error[E0433]: failed to resolve. Use of undeclared type or module `client`
|
||
--> 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
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>The compilation failed, but why? We don’t need to place <code>communicator::</code> in
|
||
front of the function like we did in <code>src/main.rs</code> because we are definitely
|
||
within the <code>communicator</code> library crate here. The reason is that paths are
|
||
always relative to the current module, which here is <code>tests</code>. The only
|
||
exception is in a <code>use</code> statement, where paths are relative to the crate root
|
||
by default. Our <code>tests</code> module needs the <code>client</code> module in its scope!</p>
|
||
<p>So how do we get back up one module in the module hierarchy to be able to call
|
||
the <code>client::connect</code> function in the <code>tests</code> module? In the <code>tests</code> module, we
|
||
can either use leading colons to let Rust know that we want to start from the
|
||
root and list the whole path:</p>
|
||
<pre><code class="language-rust,ignore">::client::connect();
|
||
</code></pre>
|
||
<p>Or we can use <code>super</code> to move up one module in the hierarchy from our current
|
||
module:</p>
|
||
<pre><code class="language-rust,ignore">super::client::connect();
|
||
</code></pre>
|
||
<p>These two options don’t look all that different in this example, but if you’re
|
||
deeper in a module hierarchy, starting from the root every time would get long.
|
||
In those cases, using <code>super</code> to get from the current module to sibling modules
|
||
is a good shortcut. Plus, if you’ve specified the path from the root in many
|
||
places in your code and then you rearrange your modules by moving a subtree to
|
||
another place, you’d end up needing to update the path in a lot of places,
|
||
which would be tedious.</p>
|
||
<p>It would also be annoying to have to type <code>super::</code> all the time in each test,
|
||
but you’ve already seen the tool for that solution: <code>use</code>! The <code>super::</code>
|
||
functionality changes the path you give to <code>use</code> so that it is relative to the
|
||
parent module instead of to the root module.</p>
|
||
<p>For these reasons, in the <code>tests</code> module especially, <code>use super::something</code> is
|
||
usually the way to go. So now our test looks like this:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
use super::client;
|
||
|
||
#[test]
|
||
fn it_works() {
|
||
client::connect();
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>If we run <code>cargo test</code> again, the test will pass and the first part of the test
|
||
result output will be:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
Running target/debug/communicator-92007ddb5330fa5a
|
||
|
||
running 1 test
|
||
test tests::it_works ... ok
|
||
|
||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
|
||
</code></pre>
|
||
<h2>Summary</h2>
|
||
<p>Now you know techniques for organizing your code! Use these to group related
|
||
functionality together, keep files from getting too long, and present a tidy
|
||
public API to users of your library.</p>
|
||
<p>Next, let’s look at some collection data structures in the standard library
|
||
that you can make use of in your nice, neat code!</p>
|
||
<h1>Fundamental Collections</h1>
|
||
<p>Rust's standard library includes a number of really useful data structures
|
||
called <em>collections</em>. Most other data types represent one specific value, but
|
||
collections can contain multiple values. Unlike the built-in array and tuple
|
||
types, the data these collections point to is stored on the heap, which means
|
||
the amount of data does not need to be known at compile time and can grow or
|
||
shrink as the program runs. Each kind of collection has different capabilities
|
||
and costs, and choosing an appropriate one for the situation you're in is a
|
||
skill you'll develop over time. In this chapter, we'll go over three
|
||
collections which are used very often in Rust programs:</p>
|
||
<ul>
|
||
<li>A <em>vector</em> allows us to store a variable number of values next to each other.</li>
|
||
<li>A <em>string</em> is a collection of characters. We've seen the <code>String</code> type
|
||
before, but we'll talk about it in depth now.</li>
|
||
<li>A <em>hash map</em> allows us to associate a value with a particular key.</li>
|
||
</ul>
|
||
<p>There are more specialized variants of each of these data structures for
|
||
particular situations, but these are the most fundamental and common. We're
|
||
going to discuss how to create and update each of the collections, as well as
|
||
what makes each special.</p>
|
||
<h2>Vectors</h2>
|
||
<p>The first type we'll look at is <code>Vec<T></code>, also known as a <em>vector</em>. Vectors
|
||
allow us to store more than one value in a single data structure that puts all
|
||
the values next to each other in memory. Vectors can only store values of the
|
||
same type. They are useful in situations where you have a list of items, such
|
||
as the lines of text in a file or the prices of items in a shopping cart.</p>
|
||
<h3>Creating a New Vector</h3>
|
||
<p>To create a new, empty vector, we can call the <code>Vec::new</code> function:</p>
|
||
<pre><code class="language-rust">let v: Vec<i32> = 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<i32></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<i32></code>, and the type annotation isn't necessary. Let's look at how to
|
||
modify a vector next.</p>
|
||
<h3>Updating a Vector</h3>
|
||
<p>To create a vector then add elements to it, we can use the <code>push</code> method:</p>
|
||
<pre><code class="language-rust">let mut v = Vec::new();
|
||
|
||
v.push(5);
|
||
v.push(6);
|
||
v.push(7);
|
||
v.push(8);
|
||
</code></pre>
|
||
<p>As with any variable as we discussed in Chapter 3, if we want to be able to
|
||
change its value, we need to make it mutable with the <code>mut</code> keyword. The
|
||
numbers we place inside are all <code>i32</code>s, and Rust infers this from the data, so
|
||
we don't need the <code>Vec<i32></code> annotation.</p>
|
||
<h3>Dropping a Vector Drops its Elements</h3>
|
||
<p>Like any other <code>struct</code>, a vector will be freed when it goes out of scope:</p>
|
||
<pre><code class="language-rust">{
|
||
let v = vec![1, 2, 3, 4];
|
||
|
||
// do stuff with v
|
||
|
||
} // <- v goes out of scope and is freed here
|
||
</code></pre>
|
||
<p>When the vector gets dropped, all of its contents will also be dropped, meaning
|
||
those integers it holds will be cleaned up. This may seem like a
|
||
straightforward point, but can get a little more complicated once we start to
|
||
introduce references to the elements of the vector. Let's tackle that next!</p>
|
||
<h3>Reading Elements of Vectors</h3>
|
||
<p>Now that you know how to create, update, and destroy vectors, knowing how to
|
||
read their contents is a good next step. There are two ways to reference a
|
||
value stored in a vector. In the examples, we've annotated the types of the
|
||
values that are returned from these functions for extra clarity.</p>
|
||
<p>This example shows both methods of accessing a value in a vector either with
|
||
indexing syntax or the <code>get</code> method:</p>
|
||
<pre><code class="language-rust">let v = vec![1, 2, 3, 4, 5];
|
||
|
||
let third: &i32 = &v[2];
|
||
let third: Option<&i32> = 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>&</code> and
|
||
<code>[]</code>s, which gives us a reference, or using the <code>get</code> method with the index
|
||
passed as an argument, which gives us an <code>Option<&T></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 = &v[100];
|
||
let does_not_exist = v.get(100);
|
||
</code></pre>
|
||
<p>When you run this, you will find that with the first <code>[]</code> method, Rust will
|
||
cause a <code>panic!</code> when a non-existent element is referenced. This method would
|
||
be preferable if you want your program to consider an attempt to access an
|
||
element past the end of the vector to be a fatal error that should crash the
|
||
program.</p>
|
||
<p>When the <code>get</code> method is passed an index that is outside the array, it will
|
||
return <code>None</code> without <code>panic!</code>ing. You would use this if accessing an element
|
||
beyond the range of the vector will happen occasionally under normal
|
||
circumstances. Your code can then have logic to handle having either
|
||
<code>Some(&element)</code> or <code>None</code>, as we discussed in Chapter 6. For example, the
|
||
index could be coming from a person entering a number. If they accidentally
|
||
enter a number that's too large and your program gets a <code>None</code> value, you could
|
||
tell the user how many items are in the current <code>Vec</code> and give them another
|
||
chance to enter a valid value. That would be more user-friendly than crashing
|
||
the program for a typo!</p>
|
||
<h4>Invalid References</h4>
|
||
<p>Once the program has a valid reference, the borrow checker will enforce the
|
||
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
|
||
any other references to the contents of the vector stay valid. Recall the rule
|
||
that says we can't have mutable and immutable references in the same scope.
|
||
That rule applies in this example, where we hold an immutable reference to the
|
||
first element in a vector and try to add an element to the end:</p>
|
||
<pre><code class="language-rust,ignore">let mut v = vec![1, 2, 3, 4, 5];
|
||
|
||
let first = &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 = &v[0];
|
||
| - immutable borrow occurs here
|
||
5 |
|
||
6 | v.push(6);
|
||
| ^ mutable borrow occurs here
|
||
7 | }
|
||
| - immutable borrow ends here
|
||
</code></pre>
|
||
<p>This code might look like it should work: why should a reference to the first
|
||
element care about what changes about the end of the vector? The reason why
|
||
this code isn't allowed is due to the way vectors work. Adding a new element
|
||
onto the end of the vector might require allocating new memory and copying the
|
||
old elements over to the new space, in the circumstance that there isn't enough
|
||
room to put all the elements next to each other where the vector was. In that
|
||
case, the reference to the first element would be pointing to deallocated
|
||
memory. The borrowing rules prevent programs from ending up in that situation.</p>
|
||
<blockquote>
|
||
<p>Note: For more on this, see <a href="https://doc.rust-lang.org/stable/nomicon/vec.html">The Nomicon</a>.</p>
|
||
</blockquote>
|
||
<h3>Using an Enum to Store Multiple Types</h3>
|
||
<p>At the beginning of this chapter, we said that vectors can only store values
|
||
that are all the same type. This can be inconvenient; there are definitely use
|
||
cases for needing to store a list of things of different types. Luckily, the
|
||
variants of an enum are all defined under the same enum type. When we need to
|
||
store elements of a different type in a vector this scenario, we can define and
|
||
use an enum!</p>
|
||
<p>For example, let's say we want to get values from a row in a spreadsheet, where
|
||
some of the columns in the row contain integers, some floating point numbers,
|
||
and some strings. We can define an enum whose variants will hold the different
|
||
value types, and then all of the enum variants will be considered the same
|
||
type, that of the enum. Then we can create a vector that holds that enum and
|
||
so, ultimately, holds different types:</p>
|
||
<pre><code class="language-rust">enum SpreadsheetCell {
|
||
Int(i32),
|
||
Float(f64),
|
||
Text(String),
|
||
}
|
||
|
||
let row = vec![
|
||
SpreadsheetCell::Int(3),
|
||
SpreadsheetCell::Text(String::from("blue")),
|
||
SpreadsheetCell::Float(10.12),
|
||
];
|
||
</code></pre>
|
||
<p>The reason Rust needs to know exactly what types will be in the vector at
|
||
compile time is so that it knows exactly how much memory on the heap will be
|
||
needed to store each element. A secondary advantage to this is that we can be
|
||
explicit about what types are allowed in this vector. If Rust allowed a vector
|
||
to hold any type, there would be a chance that one or more of the types would
|
||
cause errors with the operations performed on the elements of the vector. Using
|
||
an enum plus a <code>match</code> means that Rust will ensure at compile time that we
|
||
always handle every possible case, as we discussed in Chapter 6.</p>
|
||
<!-- Can you briefly explain what the match is doing here, as a recap? How does
|
||
it mean we always handle every possible case? I'm not sure it's totally clear.
|
||
-->
|
||
<!-- Because this is a focus of chapter 6 rather than this chapter's focus, we
|
||
don't think we should repeat it here as well, but we added a reference. /Carol
|
||
-->
|
||
<p>If you don't know at the time that you're writing a program the exhaustive set
|
||
of types the program will get at runtime to store in a vector, the enum
|
||
technique won't work. Instead, you can use a trait object, which we'll cover in
|
||
Chapter 13.</p>
|
||
<p>Now that we've gone over some of the most common ways to use vectors, be sure
|
||
to take a look at the API documentation for all of the many useful methods
|
||
defined on <code>Vec</code> by the standard library. For example, in addition to <code>push</code>
|
||
there's a <code>pop</code> method that will remove and return the last element. Let's move
|
||
on to the next collection type: <code>String</code>!</p>
|
||
<!-- Do you mean the Rust online documentation here? Are you not including it
|
||
in the book for space reasons? We might want to justify sending them out of the
|
||
book if we don't want to cover it here -->
|
||
<!-- Yes, there are many, many methods on Vec: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html
|
||
Also there are occasionally new methods available with new versions of the
|
||
language, so there's no way we can be comprehensive here. We want the reader to
|
||
use the API documentation in these situations since the purpose of the online
|
||
docs is to be comprehensive and up to date. I personally wouldn't expect a book
|
||
like this to duplicate the info that's in the API docs, so I don't think a
|
||
justification is necessary here. /Carol -->
|
||
<h2>Strings</h2>
|
||
<p>We've already talked about strings a bunch in Chapter 4, but let's take a more
|
||
in-depth look at them now. Strings are an area that new Rustaceans commonly get
|
||
stuck on. This is due to a combination of three things: Rust's propensity for
|
||
making sure to expose possible errors, strings being a more complicated data
|
||
structure than many programmers give them credit for, and UTF-8. These things
|
||
combine in a way that can seem difficult when coming from other languages.</p>
|
||
<p>The reason Strings are in the collections chapter is that strings are
|
||
implemented as a collection of bytes plus some methods to provide useful
|
||
functionality when those bytes are interpreted as text. In this section, we'll
|
||
talk about the operations on <code>String</code> that every collection type has, like
|
||
creating, updating, and reading. We'll also discuss the ways in which <code>String</code>
|
||
is different than the other collections, namely how indexing into a <code>String</code> is
|
||
complicated by the differences in which people and computers interpret <code>String</code>
|
||
data.</p>
|
||
<h3>What is a String?</h3>
|
||
<p>Before we can dig into those aspects, we need to talk about what exactly we
|
||
mean by the term 'string'. Rust actually only has one string type in the core
|
||
language itself: <code>str</code>, the string slice, which is usually seen in its borrowed
|
||
form, <code>&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>&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>&str</code>.
|
||
These string types may store different encodings or be represented in memory in
|
||
a different way, for example. We won't be talking about these other string
|
||
types in this chapter; see their API documentation for more about how to use
|
||
them and when each is appropriate.</p>
|
||
<h3>Creating a New String</h3>
|
||
<p>Many of the same operations available with <code>Vec</code> are available with <code>String</code> as
|
||
well, starting with the <code>new</code> function to create a string, like so:</p>
|
||
<pre><code class="language-rust">let s = String::new();
|
||
</code></pre>
|
||
<p>This creates a new empty string called <code>s</code> that we can then load data into.</p>
|
||
<p>Often, we'll have some initial data that we'd like to start the string off
|
||
with. For that, we use the <code>to_string</code> method, which is available on any type
|
||
that implements the <code>Display</code> trait, which string literals do:</p>
|
||
<pre><code class="language-rust">let data = "initial contents";
|
||
|
||
let s = data.to_string();
|
||
|
||
// the method also works on a literal directly:
|
||
let s = "initial contents".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("initial contents");
|
||
</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 = "السلام عليكم";
|
||
let hello = "Dobrý den";
|
||
let hello = "Hello";
|
||
let hello = "שָׁלוֹם";
|
||
let hello = "नमस्ते";
|
||
let hello = "こんにちは";
|
||
let hello = "안녕하세요";
|
||
let hello = "你好";
|
||
let hello = "Olá";
|
||
let hello = "Здравствуйте";
|
||
let hello = "Hola";
|
||
</code></pre>
|
||
<h3>Updating a String</h3>
|
||
<p>A <code>String</code> can can grow in size and its contents can change just like the
|
||
contents of a <code>Vec</code>, by pushing more data into it. In addition, <code>String</code> has
|
||
concatenation operations implemented with the <code>+</code> operator for convenience.</p>
|
||
<h4>Appending to a String with Push</h4>
|
||
<p>We can grow a <code>String</code> by using the <code>push_str</code> method to append a string slice:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("foo");
|
||
s.push_str("bar");
|
||
</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
|
||
argument. For example, it would be unfortunate if we weren't able to use <code>s2</code>
|
||
after appending its contents to <code>s1</code>:</p>
|
||
<pre><code class="language-rust">let mut s1 = String::from("foo");
|
||
let s2 = String::from("bar");
|
||
s1.push_str(&s2);
|
||
</code></pre>
|
||
<p>The <code>push</code> method is defined to take a single character as an argument and add
|
||
it to the <code>String</code>:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("lo");
|
||
s.push('l');
|
||
</code></pre>
|
||
<p>After this, <code>s</code> will contain "lol".</p>
|
||
<h4>Concatenation with the + Operator or the <code>format!</code> Macro</h4>
|
||
<p>Often, we'll want to combine two existing strings together. One way is to use
|
||
the <code>+</code> operator like this:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("Hello, ");
|
||
let s2 = String::from("world!");
|
||
let s3 = s1 + &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: &str) -> String {
|
||
</code></pre>
|
||
<p>This isn't the exact signature that's in the standard library; there <code>add</code> is
|
||
defined using generics. Here, we're looking at the signature of <code>add</code> with
|
||
concrete types substituted for the generic ones, which is what happens when we
|
||
call this method with <code>String</code> values. This signature gives us the clues we
|
||
need to understand the tricky bits of the <code>+</code> operator.</p>
|
||
<p>First of all, <code>s2</code> has an <code>&</code>, meaning that we are adding a <em>reference</em> of the
|
||
second string to the first string. This is because of the <code>s</code> argument in the
|
||
<code>add</code> function: we can only add a <code>&str</code> to a <code>String</code>, we can't add two
|
||
<code>String</code>s together. Remember back in Chapter 4 when we talked about how
|
||
<code>&String</code> will coerce to <code>&str</code>: we write <code>&s2</code> so that the <code>String</code> will
|
||
coerce to the proper type, <code>&str</code>. Because this method does not take ownership
|
||
of the argument, <code>s2</code> will still be valid after this operation.</p>
|
||
<p>Second, we can see in the signature that <code>add</code> takes ownership of <code>self</code>,
|
||
because <code>self</code> does <em>not</em> have an <code>&</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 + &s2;</code> looks like it will copy both strings and create a new one,
|
||
this statement actually takes ownership of <code>s1</code>, appends a copy of <code>s2</code>'s
|
||
contents, then returns ownership of the result. In other words, it looks like
|
||
it's making a lot of copies, but isn't: the implementation is more efficient
|
||
than copying.</p>
|
||
<p>If we need to concatenate multiple strings, the behavior of <code>+</code> gets unwieldy:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("tic");
|
||
let s2 = String::from("tac");
|
||
let s3 = String::from("toe");
|
||
|
||
let s = s1 + "-" + &s2 + "-" + &s3;
|
||
</code></pre>
|
||
<p><code>s</code> will be "tic-tac-toe" at this point. With all of the <code>+</code> and <code>"</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("tic");
|
||
let s2 = String::from("tac");
|
||
let s3 = String::from("toe");
|
||
|
||
let s = format!("{}-{}-{}", s1, s2, s3);
|
||
</code></pre>
|
||
<!-- Are we going to discuss the format macro elsewhere at all? If not, some
|
||
more info here might be good, this seems like a really useful tool. Is it only
|
||
used on strings? -->
|
||
<!-- No, we weren't planning on it. We thought it would be sufficient to
|
||
mention that it works the same way as `println!` since we've covered how
|
||
`println!` works in Ch 2, "Printing Values with `println!` Placeholders" and Ch
|
||
5, Ch 5, "Adding Useful Functionality with Derived Traits". `format!` can be
|
||
used on anything that `println!` can; using `{}` in the format string works
|
||
with anything that implements the `Display` trait and `{:?}` works with
|
||
anything that implements the `Debug` trait. Do you have any thoughts on how we
|
||
could make the similarities with `format!` and `println!` clearer than what we
|
||
have in the next paragraph without repeating the `println!` content too much?
|
||
/Carol -->
|
||
<p>This code will also set <code>s</code> to "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 arguments.</p>
|
||
<h3>Indexing into Strings</h3>
|
||
<p>In many other languages, accessing individual characters in a string by
|
||
referencing them by index is a valid and common operation. In Rust, however, if
|
||
we try to access parts of a <code>String</code> using indexing syntax, we'll get an error.
|
||
That is, this code:</p>
|
||
<pre><code class="language-rust,ignore">let s1 = String::from("hello");
|
||
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<_>` is not
|
||
satisfied [--explain E0277]
|
||
|>
|
||
|> let h = s1[0];
|
||
|> ^^^^^
|
||
note: the type `std::string::String` cannot be indexed by `_`
|
||
</code></pre>
|
||
<p>The error and the note tell the story: Rust strings don't support indexing. So
|
||
the follow-up question is, why not? In order to answer that, we have to talk a
|
||
bit about how Rust stores strings in memory.</p>
|
||
<h4>Internal Representation</h4>
|
||
<p>A <code>String</code> is a wrapper over a <code>Vec<u8></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 = "Hola".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 = "Здравствуйте".len();
|
||
</code></pre>
|
||
<p>A person asked how long the string is might say 12. However, Rust's answer
|
||
is 24. This is the number of bytes that it takes to encode "Здравствуйте" in
|
||
UTF-8, since each character takes two bytes of storage. Therefore, an index
|
||
into the string's bytes will not always correlate to a valid character.</p>
|
||
<p>To demonstrate, consider this invalid Rust code:</p>
|
||
<pre><code class="language-rust,ignore">let hello = "Здравствуйте";
|
||
let answer = &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>&"hello"[0]</code> would return <code>104</code>, not <code>h</code>. To avoid
|
||
returning an unexpected value and causing bugs that might not be discovered
|
||
immediately, Rust chooses to not compile this code at all and prevent
|
||
misunderstandings earlier.</p>
|
||
<h4>Bytes and Scalar Values and Grapheme Clusters! Oh my!</h4>
|
||
<p>This leads to another point about UTF-8: there are really three relevant ways
|
||
to look at strings, from Rust's perspective: as bytes, scalar values, and
|
||
grapheme clusters (the closest thing to what people would call 'letters').</p>
|
||
<p>If we look at the Hindi word "नमस्ते" 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">["न", "म", "स्", "ते"]
|
||
</code></pre>
|
||
<p>Rust provides different ways of interpreting the raw string data that computers
|
||
store so that each program can choose the interpretation it needs, no matter
|
||
what human language the data is in.</p>
|
||
<p>A final reason Rust does not allow you to index into a <code>String</code> to get a
|
||
character is that indexing operations are expected to always take constant time
|
||
(O(1)). It isn't possible to guarantee that performance with a <code>String</code>,
|
||
though, since Rust would have to walk through the contents from the beginning
|
||
to the index to determine how many valid characters there were.</p>
|
||
<p>All of these problems mean that Rust does not implement <code>[]</code> for <code>String</code>, so
|
||
we cannot directly do this.</p>
|
||
<h3>Slicing Strings</h3>
|
||
<p>However, indexing the <em>bytes</em> of a string is very useful, and is not expected
|
||
to be fast. While we can't use <code>[]</code> with a single number, we <em>can</em> use <code>[]</code>
|
||
with a range to create a string slice containing particular bytes:</p>
|
||
<pre><code class="language-rust">let hello = "Здравствуйте";
|
||
|
||
let s = &hello[0..4];
|
||
</code></pre>
|
||
<p>Here, <code>s</code> will be a <code>&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>&hello[0..1]</code>? The answer: it will panic at
|
||
runtime, in the same way that accessing an invalid index in a vector does:</p>
|
||
<pre><code class="language-text">thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not lie on
|
||
character boundary', ../src/libcore/str/mod.rs:1694
|
||
</code></pre>
|
||
<p>You should use this with caution, since it can cause your program to crash.</p>
|
||
<h3>Methods for Iterating Over Strings</h3>
|
||
<p>Luckily, there are other ways we can access elements in a String.</p>
|
||
<p>If we need to perform operations on individual characters, the best way to do
|
||
so is to use the <code>chars</code> method. Calling <code>chars</code> on "नमस्ते" 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 "नमस्ते".chars() {
|
||
println!("{}", 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 "नमस्ते".bytes() {
|
||
println!("{}", b);
|
||
}
|
||
</code></pre>
|
||
<p>This code will print the 18 bytes that make up this <code>String</code>, starting with:</p>
|
||
<pre><code class="language-text">224
|
||
164
|
||
168
|
||
224
|
||
// ... etc
|
||
</code></pre>
|
||
<p>But make sure to remember that valid UTF-8 characters may be made up of more
|
||
than one byte.</p>
|
||
<p>Getting grapheme clusters from <code>String</code>s is complex, so this functionality is
|
||
not provided by the standard library. There are crates available on crates.io
|
||
if this is the functionality you need.</p>
|
||
<!-- Can you recommend some, or maybe just say why we aren't outlining the
|
||
method here, ie it's complicated and therefore best to use a crate? -->
|
||
<!-- We're trying not to mention too many crates in the book. Most crates are
|
||
provided by the community, so we don't want to mention some and not others and
|
||
seem biased towards certain crates, plus crates can change more quickly (and
|
||
new crates can be created) than the language and this book will. /Carol -->
|
||
<h3>Strings are Not so Simple</h3>
|
||
<p>To summarize, strings are complicated. Different programming languages make
|
||
different choices about how to present this complexity to the programmer. Rust
|
||
has chosen to make the correct handling of <code>String</code> data the default behavior
|
||
for all Rust programs, which does mean programmers have to put more thought
|
||
into handling UTF-8 data upfront. This tradeoff exposes more of the complexity
|
||
of strings than other programming languages do, but this will prevent you from
|
||
having to handle errors involving non-ASCII characters later in your
|
||
development lifecycle.</p>
|
||
<p>Let's switch to something a bit less complex: hash map!</p>
|
||
<h2>Hash Maps</h2>
|
||
<p>The last of our fundamental collections is the <em>hash map</em>. The type <code>HashMap<K, V></code> stores a mapping of keys of type <code>K</code> to values of type <code>V</code>. It does this
|
||
via a <em>hashing function</em>, which determines how it places these keys and values
|
||
into memory. Many different programming languages support this kind of data
|
||
structure, but often with a different name: hash, map, object, hash table, or
|
||
associative array, just to name a few.</p>
|
||
<p>Hash maps are useful for when you want to be able to look up data not by an
|
||
index, as you can with vectors, but by using a key that can be of any type. For
|
||
example, in a game, you could keep track of each team's score in a hash map
|
||
where each key is a team's name and the values are each team's score. Given a
|
||
team name, you can retrieve their score.</p>
|
||
<p>We'll go over the basic API of hash maps in this chapter, but there are many
|
||
more goodies hiding in the functions defined on <code>HashMap</code> by the standard
|
||
library. As always, check the standard library documentation for more
|
||
information.</p>
|
||
<h3>Creating a New Hash Map</h3>
|
||
<p>We can create an empty <code>HashMap</code> with <code>new</code>, and add elements with <code>insert</code>.
|
||
Here we're keeping track of the scores of two teams whose names are Blue and
|
||
Yellow. The Blue team will start with 10 points and the Yellow team starts with
|
||
50:</p>
|
||
<pre><code class="language-rust">use std::collections::HashMap;
|
||
|
||
let mut scores = HashMap::new();
|
||
|
||
scores.insert(String::from("Blue"), 10);
|
||
scores.insert(String::from("Yellow"), 50);
|
||
</code></pre>
|
||
<p>Note that we need to first <code>use</code> the <code>HashMap</code> from the collections portion of
|
||
the standard library. Of our three fundamental collections, this one is the
|
||
least often used, so it's not included in the features imported automatically
|
||
in the prelude. Hash maps also have less support from the standard library;
|
||
there's no built-in macro to construct them, for example.</p>
|
||
<p>Just like vectors, hash maps store their data on the heap. This <code>HashMap</code> has
|
||
keys of type <code>&str</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("Blue"), String::from("Yellow")];
|
||
let initial_scores = vec![10, 50];
|
||
|
||
let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect();
|
||
</code></pre>
|
||
<p>The type annotation <code>HashMap<_, _></code> is needed here because it's possible to
|
||
<code>collect</code> into many different data structures, and Rust doesn't know which you
|
||
want unless you specify. For the type parameters for the key and value types,
|
||
however, we use underscores and Rust can infer the types that the hash map
|
||
contains based on the types of the data in the vector.</p>
|
||
<h3>Hash Maps and Ownership</h3>
|
||
<p>For types that implement the <code>Copy</code> trait, like <code>i32</code>, the values are copied
|
||
into the hash map. For owned values like <code>String</code>, the values will be moved and
|
||
the hash map will be the owner of those values:</p>
|
||
<pre><code class="language-rust">use std::collections::HashMap;
|
||
|
||
let field_name = String::from("Favorite color");
|
||
let field_value = String::from("Blue");
|
||
|
||
let mut map = HashMap::new();
|
||
map.insert(field_name, field_value);
|
||
// field_name and field_value are invalid at this point
|
||
</code></pre>
|
||
<p>We would not be able to use the bindings <code>field_name</code> and <code>field_value</code> after
|
||
they have been moved into the hash map with the call to <code>insert</code>.</p>
|
||
<p>If we insert references to values into the hash map, the values themselves will
|
||
not be moved into the hash map. The values that the references point to must be
|
||
valid for at least as long as the hash map is valid, though. We will talk more
|
||
about these issues in the Lifetimes section of Chapter 10.</p>
|
||
<h3>Accessing Values in a Hash Map</h3>
|
||
<p>We can get a value out of the hash map by providing its key to the <code>get</code> method:</p>
|
||
<pre><code class="language-rust">use std::collections::HashMap;
|
||
|
||
let mut scores = HashMap::new();
|
||
|
||
scores.insert(String::from("Blue"), 10);
|
||
scores.insert(String::from("Yellow"), 50);
|
||
|
||
let team_name = String::from("Blue");
|
||
let score = scores.get(&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<V></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("Blue"), 10);
|
||
scores.insert(String::from("Yellow"), 50);
|
||
|
||
for (key, value) in &scores {
|
||
println!("{}: {}", key, value);
|
||
}
|
||
</code></pre>
|
||
<p>This will print each pair, in an arbitrary order:</p>
|
||
<pre><code class="language-text">Yellow: 50
|
||
Blue: 10
|
||
</code></pre>
|
||
<h3>Updating a Hash Map</h3>
|
||
<!-- So the quantity of keys must be defined up front, that's not growable?
|
||
That could be worthy saying -->
|
||
<!-- No, the number of keys is growable, it's just that for EACH individual
|
||
key, there can only be one value. I've tried to clarify. /Carol -->
|
||
<p>While the number of keys and values is growable, each individual key can only
|
||
have one value associated with it at a time. When we want to change the data in
|
||
a hash map, we have to decide how to handle the case when a key already has a
|
||
value assigned. We could choose to replace the old value with the new value,
|
||
completely disregarding the old value. We could choose to keep the old value
|
||
and ignore the new value, and only add the new value if the key <em>doesn't</em>
|
||
already have a value. Or we could combine the old value and the new value.
|
||
Let's look at how to do each of these!</p>
|
||
<h4>Overwriting a Value</h4>
|
||
<p>If we insert a key and a value into a 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("Blue"), 10);
|
||
scores.insert(String::from("Blue"), 25);
|
||
|
||
println!("{:?}", scores);
|
||
</code></pre>
|
||
<p>This will print <code>{"Blue": 25}</code>. The original value of 10 has been overwritten.</p>
|
||
<h4>Only Insert If the Key Has No Value</h4>
|
||
<p>It's common to want to check if a particular key has a value and, if it does
|
||
not, insert a value for it. Hash maps have a special API for this, called
|
||
<code>entry</code>, that takes the key we want to check as an argument. The return value
|
||
of the <code>entry</code> function is an enum, <code>Entry</code>, that represents a value that might
|
||
or might not exist. Let's say that we want to check if the key for the Yellow
|
||
team has a value associated with it. If it doesn't, we want to insert the value
|
||
50, and the same for the Blue team. With the entry API, the code for this
|
||
looks like:</p>
|
||
<pre><code class="language-rust">use std::collections::HashMap;
|
||
|
||
let mut scores = HashMap::new();
|
||
scores.insert(String::from("Blue"), 10);
|
||
|
||
scores.entry(String::from("Yellow")).or_insert(50);
|
||
scores.entry(String::from("Blue")).or_insert(50);
|
||
|
||
println!("{:?}", scores);
|
||
</code></pre>
|
||
<p>The <code>or_insert</code> method on <code>Entry</code> returns the value for the <code>Entry</code>'s key if it
|
||
exists, and if not, inserts its argument as the new value for the <code>Entry</code>'s key
|
||
and returns that. This is much cleaner than writing the logic ourselves, and in
|
||
addition, plays more nicely with the borrow checker.</p>
|
||
<p>This code will print <code>{"Yellow": 50, "Blue": 10}</code>. The first call to <code>entry</code>
|
||
will insert the key for the Yellow team with the value 50, since the Yellow
|
||
team doesn't have a value already. The second call to <code>entry</code> will not change
|
||
the hash map since the Blue team already has the value 10.</p>
|
||
<h4>Update a Value Based on the Old Value</h4>
|
||
<p>Another common use case for hash maps is to look up a key's value then update
|
||
it, based on the old value. For instance, if we wanted to count how many times
|
||
each word appeared in some text, we could use a hash map with the words as keys
|
||
and increment the value to keep track of how many times we've seen that word.
|
||
If this is the first time we've seen a word, we'll first insert the value <code>0</code>.</p>
|
||
<pre><code class="language-rust">use std::collections::HashMap;
|
||
|
||
let text = "hello world wonderful world";
|
||
|
||
let mut map = HashMap::new();
|
||
|
||
for word in text.split_whitespace() {
|
||
let count = map.entry(word).or_insert(0);
|
||
*count += 1;
|
||
}
|
||
|
||
println!("{:?}", map);
|
||
</code></pre>
|
||
<p>This will print <code>{"world": 2, "hello": 1, "wonderful": 1}</code>. The <code>or_insert</code>
|
||
method actually returns a mutable reference (<code>&mut V</code>) to the value for this
|
||
key. Here we store that mutable reference in the <code>count</code> variable, so in order
|
||
to assign to that value we must first dereference <code>count</code> using the asterisk
|
||
(<code>*</code>). The mutable reference goes out of scope at the end of the <code>for</code> loop, so
|
||
all of these changes are safe and allowed by the borrowing rules.</p>
|
||
<h3>Hashing Function</h3>
|
||
<p>By default, <code>HashMap</code> uses a cryptographically secure hashing function that can
|
||
provide resistance to Denial of Service (DoS) attacks. This is not the fastest
|
||
hashing algorithm out there, but the tradeoff for better security that comes
|
||
with the drop in performance is worth it. If you profile your code and find
|
||
that the default hash function is too slow for your purposes, you can switch to
|
||
another function by specifying a different <em>hasher</em>. A hasher is a type that
|
||
implements the <code>BuildHasher</code> trait. We'll be talking about traits and how to
|
||
implement them in Chapter 10.</p>
|
||
<h2>Summary</h2>
|
||
<p>Vectors, strings, and hash maps will take you far in programs where you need to
|
||
store, access, and modify data. Here are some exercises you should now be
|
||
equipped to solve:</p>
|
||
<ol>
|
||
<li>Given a list of integers, use a vector and return the mean (average), median
|
||
(when sorted, the value in the middle position), and mode (the value that
|
||
occurs most often; a hash map will be helpful here) of the list.</li>
|
||
<li>Convert strings to Pig Latin, where the first consonant of each word is
|
||
moved to the end of the word with an added "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>
|
||
</ol>
|
||
<p>The standard library API documentation describes methods these types have that
|
||
will be helpful for these exercises!</p>
|
||
<p>We're getting into more complex programs where operations can fail, which means
|
||
it's a perfect time to go over error handling next!</p>
|
||
<h1>Error Handling</h1>
|
||
<p>Rust's 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<T, E></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<T, E></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>
|
||
<h2>Unrecoverable Errors with <code>panic!</code></h2>
|
||
<p>Sometimes, bad things happen, and there's nothing that you can do about it. For
|
||
these cases, Rust has 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>
|
||
<!-- PROD: START BOX -->
|
||
<blockquote>
|
||
<h4>Unwinding</h4>
|
||
<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 <code>abort</code>, 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 program 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 <code>Cargo.toml</code>. 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>
|
||
<!-- PROD: END BOX -->
|
||
<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!("crash and burn");
|
||
}
|
||
</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: <code>src/main.rs:2</code> indicates that it's the second like of our
|
||
<em>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>
|
||
<h3>Using a <code>panic!</code> Backtrace</h3>
|
||
<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', ../src/libcollections/vec.rs:1265
|
||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
|
||
</code></pre>
|
||
<p>This points at a file we didn't write, <em>../src/libcollections/vec.rs</em>. That's
|
||
the implementation of <code>Vec<T></code> in the standard library. The code that gets run
|
||
when we use <code>[]</code> on our vector <code>v</code> is in <em>../src/libcollections/vec.rs</em>, and
|
||
that is where the <code>panic!</code> is actually happening.</p>
|
||
<p>The next <code>note</code> 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', ../src/libcollections/vec.rs:1265
|
||
stack backtrace:
|
||
1: 0x560956150ae9 -
|
||
std::sys::backtrace::tracing::imp::write::h482d45d91246faa2
|
||
2: 0x56095615345c -
|
||
std::panicking::default_hook::_{{closure}}::h89158f66286b674e
|
||
3: 0x56095615291e - std::panicking::default_hook::h9e30d428ee3b0c43
|
||
4: 0x560956152f88 -
|
||
std::panicking::rust_panic_with_hook::h2224f33fb7bf2f4c
|
||
5: 0x560956152e22 - std::panicking::begin_panic::hcb11a4dc6d779ae5
|
||
6: 0x560956152d50 - std::panicking::begin_panic_fmt::h310416c62f3935b3
|
||
7: 0x560956152cd1 - rust_begin_unwind
|
||
8: 0x560956188a2f - core::panicking::panic_fmt::hc5789f4e80194729
|
||
9: 0x5609561889d3 -
|
||
core::panicking::panic_bounds_check::hb2d969c3cc11ed08
|
||
10: 0x56095614c075 - _<collections..vec..Vec<T> as
|
||
core..ops..Index<usize>>::index::hb9f10d3dadbe8101
|
||
at ../src/libcollections/vec.rs:1265
|
||
11: 0x56095614c134 - panic::main::h2d7d3751fb8705e2
|
||
at /projects/panic/src/main.rs:4
|
||
12: 0x56095615af46 - __rust_maybe_catch_panic
|
||
13: 0x560956152082 - std::rt::lang_start::h352a66f5026f54bd
|
||
14: 0x56095614c1b3 - main
|
||
15: 0x7f75b88ed72f - __libc_start_main
|
||
16: 0x56095614b3c8 - _start
|
||
17: 0x0 - <unknown>
|
||
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 9-1: The backtrace generated by a call to <code>panic!</code> displayed when
|
||
the environment variable <code>RUST_BACKTRACE</code> is set</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>That's a lot of output! Line 11 of the backtrace points to the line in our
|
||
project causing the problem: <code>src/main.rs</code>, 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>
|
||
<h2>Recoverable Errors with <code>Result</code></h2>
|
||
<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 "Handling Potential Failure with the
|
||
<code>Result</code> Type" 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<T, E> {
|
||
Ok(T),
|
||
Err(E),
|
||
}
|
||
</code></pre>
|
||
<!-- Would it make sense for this to be something like:
|
||
<pre><code>enum Result<T, E> {
|
||
Ok(T) => successful_result,
|
||
Err(E) => error,
|
||
}
|
||
</code></pre>
|
||
<p>instead? Then you could concretely explain the returned result.
|
||
--></p>
|
||
<!-- This notation looks similar to a `match`, but it's not a `match`, so we
|
||
think this would be confusing. We've tried to clarify better in the text.
|
||
/Carol -->
|
||
<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("hello.txt");
|
||
}
|
||
</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. 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("hello.txt");
|
||
</code></pre>
|
||
<p>Attempting to compile now gives us:</p>
|
||
<pre><code class="language-text">error[E0308]: mismatched types
|
||
--> src/main.rs:4:18
|
||
|
|
||
4 | let f: u32 = File::open("hello.txt");
|
||
| ^^^^^^^^^^^^^^^^^^^^^^^ expected u32, found enum `std::result::Result`
|
||
|
|
||
= note: expected type `u32`
|
||
= note: found type `std::result::Result<std::fs::File, std::io::Error>`
|
||
</code></pre>
|
||
<p>This tells us the return type of the <code>File::open</code> function is a <code>Result<T, E></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>
|
||
<!--Can you say explicitly why there being many ways things can fail means we
|
||
use the result type? Also, are we importing the File type from the standard
|
||
crate here? That seems worth mentioning. -->
|
||
<!-- We think it would be repetitive to point out every example that imports a
|
||
type from the standard library. We're past the Modules Chapter 7 "Importing
|
||
Names With Use" section that explains the concept in depth, as well as multiple
|
||
examples in the Hash maps section of Chapter 8 that show how and why to import
|
||
types from the standard library. /Carol -->
|
||
<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>
|
||
<!-- I'll ghost everything except the match statement lines in the libreoffice
|
||
file /Carol -->
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,should_panic">use std::fs::File;
|
||
|
||
fn main() {
|
||
let f = File::open("hello.txt");
|
||
|
||
let f = match f {
|
||
Ok(file) => file,
|
||
Err(error) => panic!("There was a problem opening the file: {:?}",
|
||
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>
|
||
<!-- So we don't need the Result keyword in this code example? And what is the
|
||
{:?} syntax, can you include a line about that? -->
|
||
<!-- We've added an explanation that Result is like Option in that it's
|
||
imported into the prelude, which the reader should be familiar with. We
|
||
explained the {:?} syntax in Structs, chapter 5, in the section "Adding Useful
|
||
Functionality with Derived Traits". It's the debug format. Having to re-explain
|
||
multiple concepts that are not the primary focus of this example really
|
||
obscures the point of the section. /Carol -->
|
||
<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 <code>hello.txt</code> 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: "No such file or directory" } }', src/main.rs:8
|
||
</code></pre>
|
||
<!-- Do we have to manually print the error message, or does it show when we
|
||
run the program? -->
|
||
<!-- No, the `panic!` macro prints what we give to it, which we covered in the
|
||
section previous to this one. /Carol -->
|
||
<h3>Matching on Different Errors</h3>
|
||
<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("hello.txt");
|
||
|
||
let f = match f {
|
||
Ok(file) => file,
|
||
Err(ref error) if error.kind() == ErrorKind::NotFound => {
|
||
match File::create("hello.txt") {
|
||
Ok(fc) => fc,
|
||
Err(e) => panic!("Tried to create file but there was a problem: {:?}", e),
|
||
}
|
||
},
|
||
Err(error) => panic!("There was a problem opening the file: {:?}",
|
||
error),
|
||
};
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 9-4: Handling different kinds of errors in different ways</p>
|
||
</figcaption>
|
||
</figure>
|
||
<!-- I will add ghosting and wingdings here in libreoffice /Carol -->
|
||
<p>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 the <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>&</code> will be covered in detail
|
||
in Chapter XX. In short, in the context of a pattern, <code>&</code> matches a reference
|
||
and give 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 'File::create'. 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>
|
||
<h3>Shortcuts for Panic on Error: <code>unwrap</code> and <code>expect</code></h3>
|
||
<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<T, E></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>
|
||
<!-- Can you explain a bit more what unwrap() does---you mean every time we
|
||
cause a panic it calls the unwrap method? -->
|
||
<!-- I'm not sure how the conclusion "every time we cause a panic it calls the
|
||
unwrap method" follows from the text that was here, but I've tried to reword.
|
||
Please let us know what part of the text specifically is implying that here so
|
||
that we can be sure that we've fixed it. /Carol -->
|
||
<!-- I'll ghost everything except `unwrap()` in the libreoffice file /Carol -->
|
||
<pre><code class="language-rust,should_panic">use std::fs::File;
|
||
|
||
fn main() {
|
||
let f = File::open("hello.txt").unwrap();
|
||
}
|
||
</code></pre>
|
||
<!-- Can you talk ore about the syntax here, how it differs? It looks like
|
||
there aren't generics here for T and E. How is this still related to Result? -->
|
||
<!-- I'm not sure how to make this clearer. We're chaining the method call onto
|
||
the return value of the `File::open` function, which hasn't changed. The reader
|
||
should understand method calls by now. T and E are part of the *definition* of
|
||
the Result type, since Listing 9-2 we've been talking about *using* a Result
|
||
instance. Listings 9-2, 9-3, and 9-4 don't contain T and E either, so I'm not
|
||
sure why it's confusing that this code doesn't contain T and E. /Carol -->
|
||
<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: "No such file or directory" } }',
|
||
../src/libcore/result.rs:837
|
||
</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>
|
||
<!-- I'll ghost everything except `expect(...)` in the libreoffice file /Carol -->
|
||
<pre><code class="language-rust,should_panic">use std::fs::File;
|
||
|
||
fn main() {
|
||
let f = File::open("hello.txt").expect("Failed to open hello.txt");
|
||
}
|
||
</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: "No such file or directory" } }', ../src/libcore/result.rs:837
|
||
</code></pre>
|
||
<!-- I added the above paragraph, can you review it and correct it as
|
||
necessary? So this is like what we did in Listing 9-3?-->
|
||
<!-- Yes, the implementations for both `unwrap` and `expect` are similar to 9-3,
|
||
which we want to show so that the reader knows they don't have to write out all
|
||
of 9-3 every time they have a `Result` value. Does this comment mean your
|
||
earlier comments in this section are moot? /Carol -->
|
||
<!-- Is panic used for both types of errors? The introduction makes it seem as
|
||
though it's only for unrecoverable errors -->
|
||
<!-- When you call panic, you are causing the program to crash and therefore
|
||
creating an unrecoverable error. You can choose to do that at any time, even
|
||
when there are *no* errors. There's nothing that prevents you from calling
|
||
`panic!` inappropriately, which is why the "to panic or not to panic" section
|
||
goes over the criteria the reader should use to decide if they're in a
|
||
situation that's recoverable or not. I've actually moved the text that was here
|
||
into that section to keep that whole discussion together. /Carol
|
||
-->
|
||
<h3>Propagating Errors</h3>
|
||
<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>
|
||
<!-- What's the benefit/result of returning the error to the code that called
|
||
the function, besides putting off handling it---can you lay that out? -->
|
||
<!-- We're giving control/decision making ability to the code that's calling
|
||
our code. I've tried to be more explicit here; please let me know what could be
|
||
improved if it's still not clear. /Carol -->
|
||
<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::fs::File;
|
||
|
||
fn read_username_from_file() -> Result<String, io::Error> {
|
||
let f = File::open("hello.txt");
|
||
|
||
let mut f = match f {
|
||
Ok(file) => file,
|
||
Err(e) => return Err(e),
|
||
};
|
||
|
||
let mut s = String::new();
|
||
|
||
match f.read_to_string(&mut s) {
|
||
Ok(_) => Ok(s),
|
||
Err(e) => 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<String, io::Error></code>. This means that the function is returning a value of the type
|
||
<code>Result<T, E></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>
|
||
<h3>A Shortcut for Propagating Errors: <code>?</code></h3>
|
||
<!-- The `?` ended up stabilizing in 1.13 and is quickly becoming preferred over
|
||
`try!`, so we decided to only cover `?`. /Carol -->
|
||
<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:</p>
|
||
<!-- I'll ghost everything except the question mark in libreoffice. /Carol -->
|
||
<figure>
|
||
<pre><code class="language-rust">use std::io;
|
||
use std::fs::File;
|
||
|
||
fn read_username_from_file() -> Result<String, io::Error> {
|
||
let mut f = File::open("hello.txt")?;
|
||
let mut s = String::new();
|
||
f.read_to_string(&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>
|
||
<!-- Below, are we talking about what just the ? operator does, or what the
|
||
program with the ? operator does? -->
|
||
<!-- I'm not sure what the difference is. We're talking about what the ? does
|
||
in the context of this program... /Carol -->
|
||
<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 binding <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() -> Result<String, io::Error> {
|
||
let mut s = String::new();
|
||
|
||
File::open("hello.txt")?.read_to_string(&mut s)?;
|
||
|
||
Ok(s)
|
||
}
|
||
</code></pre>
|
||
<!-- Can you explain what is happening in this code and how it differs? -->
|
||
<!-- I've tried to make it even clearer that the functionality does NOT differ
|
||
/Carol -->
|
||
<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("hello.txt")?</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>
|
||
<h4><code>?</code> Can Only Be Used in Functions That Return <code>Result</code></h4>
|
||
<!-- I think we need a new heading here, could you suggest something? I'm sure
|
||
there's a better way to phrase this!-->
|
||
<!-- I've tried, but I'm not really sure how to say it any more succinctly than
|
||
this, I'm not sure if it's better than what you suggested /Carol -->
|
||
<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>
|
||
<!-- Which functions return a Result and how would the reader know? I'm also not
|
||
sure what you mean by "expand", that they have the same functionality (but
|
||
condensed!)? -->
|
||
<!-- You can tell what any function returns by looking at the return type
|
||
defined in the function signature, I'm not sure what part of Chapter 3 wasn't
|
||
clear enough to convey that. The reader should be comfortable with function
|
||
signatures by this point, and could also use the API docs to tell what a
|
||
function returns.
|
||
<p>I've reworded to remove the word expand, but yes, we meant "functionally
|
||
equivalent to replacing it with the longer code"</p>
|
||
<p>/Carol
|
||
--></p>
|
||
<p>Let's look at what happens if use <code>try!</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">fn main() {
|
||
let f = File::open("hello.txt")?;
|
||
}
|
||
</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 --></p>
|
||
<p>When we compile this, we get the following error message:</p>
|
||
<pre><code class="language-text">error[E0308]: mismatched types
|
||
-->
|
||
|
|
||
3 | let f = File::open("hello.txt")?;
|
||
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected (), found enum `std::result::Result`
|
||
|
|
||
= note: expected type `()`
|
||
= note: found type `std::result::Result<_, _>`
|
||
</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>
|
||
<h2>To <code>panic!</code> or Not To <code>panic!</code></h2>
|
||
<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>
|
||
<h3>Examples, Prototype Code, and Tests: Perfectly Fine to Panic</h3>
|
||
<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>
|
||
<h3>Cases When You Have More Information Than The Compiler</h3>
|
||
<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>
|
||
<!-- If we know that there won't be an error, why do we still need to use
|
||
unwrap()? Can you clarify that in the text? -->
|
||
<!-- Because you still have to extract the value from the `Ok`; knowing there
|
||
won't be an error doesn't change the types. I've tried to clarify in the
|
||
paragraph above and again below. /Carol-->
|
||
<pre><code class="language-rust">use std::net::IpAddr;
|
||
|
||
let home = "127.0.0.1".parse::<IpAddr>().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>
|
||
<h3>Guidelines for Error Handling</h3>
|
||
<p>It's advisable to have your code <code>panic!</code> when it's possible that you could end
|
||
up in a <em>bad state</em>---in this context, <em>bad state</em> 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 <code>panic</code>, should be explained in the API documentation
|
||
for the function.</p>
|
||
<p>Having lots of error checks in all of your functions would be verbose and
|
||
annoying, though. Luckily, 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
|
||
takes a particular type as an argument, you can proceed with your code's logic
|
||
knowing that the compiler has already ensured you have a valid value. For
|
||
example, if you have a type rather than an <code>Option</code>, 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
|
||
argument value is never negative.</p>
|
||
<!-- Can you go into more detail explaining this last sentence? Why is a type
|
||
better to use than an Option?-->
|
||
<!-- I tried to reword, but I'm not sure if I made it any clearer. You don't
|
||
have to have extra checks, so your code is simpler; I'm not sure why it's not
|
||
clear that simpler is better. /Carol -->
|
||
<h3>Creating Custom Types for Validation</h3>
|
||
<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) => num,
|
||
Err(_) => continue,
|
||
};
|
||
|
||
if guess < 1 || guess > 100 {
|
||
println!("The secret number will be between 1 and 100.");
|
||
continue;
|
||
}
|
||
|
||
match guess.cmp(&secret_number) {
|
||
// snip
|
||
}
|
||
</code></pre>
|
||
<!-- I'll add wingding numbers in the libreoffice file /Carol -->
|
||
<p>The <code>if</code> expression checks to see if our value is out of range, tells the user
|
||
about the problem, and calls <code>continue</code> to start the next iteration of the loop
|
||
and ask for another guess. After the <code>if</code> expression, we can proceed with the
|
||
comparisons between <code>guess</code> and the secret number knowing that guess is between
|
||
1 and 100.</p>
|
||
<p>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 the type's
|
||
constructor rather than repeating them. 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) -> Guess {
|
||
if value < 1 || value > 100 {
|
||
panic!("Guess value must be between 1 and 100, got {}.", value);
|
||
}
|
||
|
||
Guess {
|
||
value: value,
|
||
}
|
||
}
|
||
|
||
pub fn value(&self) -> 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>
|
||
<!-- I'll add wingding numbers in the libreoffice file /Carol -->
|
||
<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 is a
|
||
constructor of <code>Guess</code> values. The <code>new</code> function takes one argument named
|
||
<code>value</code> of type <code>u32</code> and returns a <code>Guess</code>. The code in the body of the <code>new</code>
|
||
function tests the <code>value</code> argument 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>
|
||
argument, and return the <code>Guess</code>.</p>
|
||
<!-- I'm not sure if you mean the function that creates the guess type (so
|
||
listing 9-8) or the function that uses the guess type, below. You mean the
|
||
wider function needs a way to signal that there's a bug leading to contract
|
||
violation? -->
|
||
<!-- I'm not sure what part is confusing, and I'm not sure what you mean by
|
||
"wider function". I hope the slower explanation of the code has cleared
|
||
this up; please provide more detail on what's confusing if not. /Carol -->
|
||
<p>Next, we implement a method named <code>value</code> that borrows <code>self</code>, doesn't take any
|
||
other arguments, 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> constructor 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 constructor.</p>
|
||
<p>A function that takes as an argument or returns only numbers between 1 and 100
|
||
could then declare in its signature that it takes a <code>Guess</code> rather than a
|
||
<code>u32</code>, and wouldn't need to do any additional checks in its body.</p>
|
||
<h2>Summary</h2>
|
||
<p>Rust's error handling features are designed to help you write more robust code.
|
||
The <code>panic!</code> macro signals that your program is in a state it can't handle, and
|
||
lets you tell the process to stop instead of trying to proceed with invalid or
|
||
incorrect values. The <code>Result</code> enum uses Rust's type system 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>
|
||
<h1>Generics</h1>
|
||
<p>One of the core tools a programming language gives you is the ability to deal
|
||
effectively with duplication of code. It's important to minimize the amount of
|
||
code that is duplicated throughout a program to make maintenance easier and
|
||
minimize logic errors. Maintenance will be easier if there's only one place
|
||
that you need to change the code if you change your mind about how the program
|
||
should work, rather than multiple places in the code. If your program's logic
|
||
is duplicated in different places and those places don't match, you'll get
|
||
errors or unexpected and undesired behavior from your program that could be
|
||
hard to track down. Rust has the concept of <em>generics</em> as one way to eliminate
|
||
duplicate code. Generics come in the form of generic types, traits that those
|
||
generic types have, and generic lifetimes. We'll cover how to use all of these
|
||
in this chapter.</p>
|
||
<h2>Removing Duplication by Extracting a Function</h2>
|
||
<p>Let's first go through a technique for dealing with duplication that you're
|
||
probably familiar with: extracting a function. Consider a small program that
|
||
finds the largest number in a list, shown in Listing 10-1:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">fn main() {
|
||
let numbers = vec![34, 50, 25, 100, 65];
|
||
|
||
let mut largest = numbers[0];
|
||
|
||
for number in numbers {
|
||
if number > largest {
|
||
largest = number;
|
||
}
|
||
}
|
||
|
||
println!("The largest number is {}", largest);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-1: Code to find the largest number in a list of numbers</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>If we needed to find the largest number in two different lists of numbers, we
|
||
could duplicate the code in Listing 10-1 and have the same logic exist in two
|
||
places in the program:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let numbers = vec![34, 50, 25, 100, 65];
|
||
|
||
let mut largest = numbers[0];
|
||
|
||
for number in numbers {
|
||
if number > largest {
|
||
largest = number;
|
||
}
|
||
}
|
||
|
||
println!("The largest number is {}", largest);
|
||
|
||
let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];
|
||
|
||
let mut largest = numbers[0];
|
||
|
||
for number in numbers {
|
||
if number > largest {
|
||
largest = number;
|
||
}
|
||
}
|
||
|
||
println!("The largest number is {}", largest);
|
||
}
|
||
</code></pre>
|
||
<p>Copying code is tedious and error-prone, plus now we have two places to update
|
||
the logic if we need it to change. Rust, like many languages, gives us a way to
|
||
deal with this duplication by creating an abstraction, and in this case the
|
||
abstraction we'll use is a function. Here's a program where we've extracted the
|
||
code in Listing 10-1 that finds the largest number into a function named
|
||
<code>largest</code>. This program can find the largest number in two different lists of
|
||
numbers, but the code from Listing 10-1 only exists in one spot:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn largest(numbers: Vec<i32>) {
|
||
let mut largest = numbers[0];
|
||
|
||
for number in numbers {
|
||
if number > largest {
|
||
largest = number;
|
||
}
|
||
}
|
||
|
||
println!("The largest number is {}", largest);
|
||
}
|
||
|
||
fn main() {
|
||
let numbers = vec![34, 50, 25, 100, 65];
|
||
|
||
largest(numbers);
|
||
|
||
let numbers = vec![102, 34, 6000, 89, 54, 2, 43, 8];
|
||
|
||
largest(numbers);
|
||
}
|
||
</code></pre>
|
||
<p>The function takes an argument, <code>numbers</code>, which represents any concrete
|
||
<code>Vec<i32></code> that we might pass into the function. The code in the function
|
||
definition operates on the <code>numbers</code> representation of any <code>Vec<i32></code>. When
|
||
we call the <code>largest</code> function, the code actually runs on the specific values
|
||
that we pass in.</p>
|
||
<p>Functions aren't the only way to eliminate duplication. For example, our
|
||
<code>largest</code> function only works for vectors of <code>i32</code>. What if we wanted to find
|
||
the largest number in a list of floats? Or the largest value in some sort of
|
||
custom <code>struct</code> or <code>enum</code>? We can't solve those kinds of duplication with
|
||
regular functions.</p>
|
||
<p>To solve these kinds of problems, Rust provides a feature called <em>generics</em>. In
|
||
the same way that functions allow us to abstract over common code, generics
|
||
allow us to abstract over types. This ability gives us tremendous power to
|
||
write code that works in a large number of situations. First, we'll examine the
|
||
syntax of generics. Then, we'll talk about another feature that's used to
|
||
augment generics: traits. Finally, we'll discuss one of Rust's most unique uses
|
||
of generics: lifetimes.</p>
|
||
<h2>Generics Syntax</h2>
|
||
<p>We've already hinted at the idea of generics in previous chapters, but we
|
||
never dug into what exactly they are or how to use them. In places where we
|
||
specify a type, like function signatures or structs, instead we can use
|
||
<em>generics</em>. Generics are stand-ins that represent an abstract set instead of something concrete. In this section, we're going to cover generic <em>data types</em>.</p>
|
||
<p>You can recognize when any kind of generics are used by the way that they fit
|
||
into Rust's syntax: any time you see angle brackets, <code><></code>, you're dealing with
|
||
generics. Types we've seen before, like in Chapter 8 where we discussed vectors
|
||
with types like <code>Vec<i32></code>, employ generics. The type that the standard library
|
||
defines for vectors is <code>Vec<T></code>. That <code>T</code> is called a <em>type parameter</em>, and it
|
||
serves a similar function as parameters to functions: you fill in the parameter
|
||
with a concrete type, and that determines how the overall type works. In the
|
||
same way that a function like <code>foo(x: i32)</code> can be called with a specific value
|
||
such as <code>foo(5)</code>, a <code>Vec<T></code> can be created with a specific type, like
|
||
<code>Vec<i32></code>.</p>
|
||
<h3>Duplicated Enum Definitions</h3>
|
||
<p>Let's dive into generic data types in more detail. We learned about how to use
|
||
the <code>Option<T></code> enum in Chapter 6, but we never examined its definition. Let's
|
||
try to imagine how we'd write it! We'll start from duplicated code like we did
|
||
in the "Removing Duplication by Extracting a Function" section. This time,
|
||
we'll remove the duplication by extracting a generic data type instead of
|
||
extracting a function, but the mechanics of doing the extraction will be
|
||
similar. First, let's consider an <code>Option</code> enum with a <code>Some</code> variant that can
|
||
only hold an <code>i32</code>. We'll call this enum <code>OptionalNumber</code>:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">enum OptionalNumber {
|
||
Some(i32),
|
||
None,
|
||
}
|
||
|
||
fn main() {
|
||
let number = OptionalNumber::Some(5);
|
||
let no_number = OptionalNumber::None;
|
||
}
|
||
</code></pre>
|
||
<p>This works just fine for <code>i32</code>s. But what if we also wanted to store <code>f64</code>s? We
|
||
would have to duplicate code to define a separate <code>Option</code> enum type for each
|
||
type we wanted to be able to hold in the <code>Some</code> variants. For example, here is
|
||
how we could define and use <code>OptionalFloatingPointNumber</code>:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">enum OptionalFloatingPointNumber {
|
||
Some(f64),
|
||
None,
|
||
}
|
||
|
||
fn main() {
|
||
let number = OptionalFloatingPointNumber::Some(5.0);
|
||
let no_number = OptionalFloatingPointNumber::None;
|
||
}
|
||
</code></pre>
|
||
<p>We've made the enum's name a bit long in order to drive the point home. With
|
||
what we currently know how to do in Rust, we would have to write a unique type
|
||
for every single kind of value we wanted to have either <code>Some</code> or <code>None</code> of. In
|
||
other words, the idea of "an optional value" is a more abstract concept than one
|
||
specific type. We want it to work for any type at all.</p>
|
||
<h3>Removing Duplication by Extracting a Generic Data Type</h3>
|
||
<p>Let's see how to get from duplicated types to the generic type. Here are the
|
||
definitions of our two enums side-by-side:</p>
|
||
<pre><code class="language-text">enum OptionalNumber { enum OptionalFloatingPointNumber {
|
||
Some(i32), Some(f64),
|
||
None, None,
|
||
} }
|
||
</code></pre>
|
||
<p>Aside from the names, we have one line where the two definitions are very
|
||
close, but still different: the line with the <code>Some</code> definitions. The only
|
||
difference is the type of the data in that variant, <code>i32</code> and <code>f64</code>.</p>
|
||
<p>Just like we can parameterize arguments to a function by choosing a name, we
|
||
can parameterize the type by choosing a name. In this case, we've chosen the
|
||
name <code>T</code>. We could choose any identifier here, but Rust style has type
|
||
parameters follow the same style as types themselves: CamelCase. In addition,
|
||
they tend to be short, often one letter. <code>T</code> is the traditional default choice,
|
||
short for 'type'. Let's use that name in our <code>Some</code> variant definitions where
|
||
the <code>i32</code> and <code>f64</code> types were:</p>
|
||
<pre><code class="language-text">enum OptionalNumber { enum OptionalFloatingPointNumber {
|
||
Some(T), Some(T),
|
||
None, None,
|
||
} }
|
||
</code></pre>
|
||
<p>There's one problem, though: we've <em>used</em> <code>T</code>, but not defined it. This would
|
||
be similar to using an argument to a function in the body without declaring it
|
||
in the signature. We need to tell Rust that we've introduced a generic
|
||
parameter. The syntax to do that is the angle brackets, like this:</p>
|
||
<pre><code class="language-text">enum OptionalNumber<T> { enum OptionalFloatingPointNumber<T> {
|
||
Some(T), Some(T),
|
||
None, None,
|
||
} }
|
||
</code></pre>
|
||
<p>The <code><></code>s after the enum name indicate a list of type parameters, just like
|
||
<code>()</code> after a function name indicates a list of value parameters. Now the only
|
||
difference between our two <code>enum</code>s is the name. Since we've made them generic,
|
||
they're not specific to integers or floating point numbers anymore, so they can
|
||
have the same name:</p>
|
||
<pre><code class="language-text">enum Option<T> { enum Option<T> {
|
||
Some(T), Some(T),
|
||
None, None,
|
||
} }
|
||
</code></pre>
|
||
<p>Now they're identical! We've made our type fully generic. This definition is
|
||
also how <code>Option</code> is defined in the standard library. If we were to read this
|
||
definition aloud, we'd say, "<code>Option</code> is an <code>enum</code> with one type parameter,
|
||
<code>T</code>. It has two variants: <code>Some</code>, which has a value with type <code>T</code>, and <code>None</code>,
|
||
which has no value." We can now use the same <code>Option</code> type whether we're holding an <code>i32</code> or an <code>f64</code>:</p>
|
||
<pre><code class="language-rust">let integer = Option::Some(5);
|
||
let float = Option::Some(5.0);
|
||
</code></pre>
|
||
<p>We've left in the <code>Option::</code> namespace for consistency with the previous
|
||
examples, but since <code>use Option::*</code> is in the prelude, it's not needed. Usually
|
||
using <code>Option</code> looks like this:</p>
|
||
<pre><code class="language-rust">let integer = Some(5);
|
||
let float = Some(5.0);
|
||
</code></pre>
|
||
<p>When you recognize situations with almost-duplicate types like this in your
|
||
code, you can follow this process to reduce duplication using generics.</p>
|
||
<h3>Monomorphization at Compile Time</h3>
|
||
<p>Understanding this refactoring process is also useful in understanding how
|
||
generics work behind the scenes: the compiler does the exact opposite of this
|
||
process when compiling your code. <em>Monomorphization</em> means taking code that
|
||
uses generic type parameters and generating code that is specific for each
|
||
concrete type that is used with the generic code. Monomorphization is why
|
||
Rust's generics are extremely efficient at runtime. Consider this code that
|
||
uses the standard library's <code>Option</code>:</p>
|
||
<pre><code class="language-rust">let integer = Some(5);
|
||
let float = Some(5.0);
|
||
</code></pre>
|
||
<p>When Rust compiles this code, it will perform monomorphization. What this means
|
||
is the compiler will see that we've used two kinds of <code>Option<T></code>: one where
|
||
<code>T</code> is <code>i32</code>, and one where <code>T</code> is <code>f64</code>. As such, it will expand the generic
|
||
definition of <code>Option<T></code> into <code>Option_i32</code> and <code>Option_f64</code>, thereby replacing
|
||
the generic definition with the specific ones. The more specific version looks
|
||
like the duplicated code we started with at the beginning of this section:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">enum Option_i32 {
|
||
Some(i32),
|
||
None,
|
||
}
|
||
|
||
enum Option_f64 {
|
||
Some(f64),
|
||
None,
|
||
}
|
||
|
||
fn main() {
|
||
let integer = Option_i32::Some(5);
|
||
let float = Option_f64::Some(5.0);
|
||
}
|
||
</code></pre>
|
||
<p>In other words, we can write the non-duplicated form that uses generics in our
|
||
code, but Rust will compile that into code that acts as though we wrote the
|
||
specific type out in each instance. This means we pay no runtime cost for using
|
||
generics; it's just like we duplicated each particular definition.</p>
|
||
<h3>Generic Structs</h3>
|
||
<p>In a similar fashion as we did with enums, we can use <code><></code>s with structs as
|
||
well in order to define structs that have a generic type parameter in one or
|
||
more of their fields. Generic structs also get monomorphized into specialized
|
||
types at compile time. Listing 10-2 shows the definition and use of a <code>Point</code>
|
||
struct that could hold <code>x</code> and <code>y</code> coordinate values that are any type:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">struct Point<T> {
|
||
x: T,
|
||
y: T,
|
||
}
|
||
|
||
fn main() {
|
||
let integer = Point { x: 5, y: 10 };
|
||
let float = Point { x: 1.0, y: 4.0 };
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-2: A <code>Point</code> struct that holds <code>x</code> and <code>y</code> values of type <code>T</code></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>The syntax is the same with structs: add a <code><T></code> after the name of the struct,
|
||
then use <code>T</code> in the definition where you want to use that generic type instead
|
||
of a specific type.</p>
|
||
<h3>Multiple Type Parameters</h3>
|
||
<p>Note that in the <code>Point</code> definition in Listing 10-2, we've used the same <code>T</code>
|
||
parameter for both fields. This means <code>x</code> and <code>y</code> must always be values of the
|
||
same type. Trying to instantiate a <code>Point</code> that uses an <code>i32</code> for <code>x</code> and an
|
||
<code>f64</code> for <code>y</code>, like this:</p>
|
||
<pre><code class="language-rust,ignore">let p = Point { x: 5, y: 20.0 };
|
||
</code></pre>
|
||
<p>results in a compile-time error that indicates the type of <code>y</code> must match the
|
||
type of <code>x</code>:</p>
|
||
<pre><code class="language-text">error[E0308]: mismatched types
|
||
|
|
||
7 | let p = Point { x: 5, y: 20.0 };
|
||
| ^^^^ expected integral variable, found floating-point variable
|
||
|
|
||
= note: expected type `{integer}`
|
||
= note: found type `{float}`
|
||
</code></pre>
|
||
<p>If we need to be able to have fields with generic but different types, we can
|
||
declare multiple type parameters within the angle brackets, separated by a
|
||
comma. Listing 10-3 shows how to define a <code>Point</code> that can have different types
|
||
for <code>x</code> and <code>y</code>:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust">struct Point<X, Y> {
|
||
x: X,
|
||
y: Y,
|
||
}
|
||
|
||
fn main() {
|
||
let integer = Point { x: 5, y: 10 };
|
||
let float = Point { x: 1.0, y: 4.0 };
|
||
let p = Point { x: 5, y: 20.0 };
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-3: A <code>Point</code> struct that holds an <code>x</code> value of type <code>X</code> and a <code>y</code>
|
||
value of type <code>Y</code></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Now <code>x</code> will have the type of <code>X</code>, and <code>y</code> will have the type of <code>Y</code>, and we
|
||
can instantiate a <code>Point</code> with an <code>i32</code> for <code>x</code> and an <code>f64</code> for <code>y</code>.</p>
|
||
<p>We can make <code>enum</code>s with multiple type parameters as well. Recall the enum
|
||
<code>Result<T, E></code> from Chapter 9 that we used for recoverable errors. Here's its
|
||
definition:</p>
|
||
<pre><code class="language-rust">enum Result<T, E> {
|
||
Ok(T),
|
||
Err(E),
|
||
}
|
||
</code></pre>
|
||
<p>Each variant stores a different kind of information, and they're both generic.</p>
|
||
<p>You can have as many type parameters as you'd like. Similarly to parameters of
|
||
values in function signatures, if you have a lot of parameters, the code can
|
||
get quite confusing, so try to keep the number of parameters defined in any one
|
||
type small if you can.</p>
|
||
<h3>Generic Functions and Methods</h3>
|
||
<p>In a similar way to data structures, we can use the <code><></code> syntax in function or
|
||
method definitions. The angle brackets for type parameters go after the
|
||
function or method name and before the argument list in parentheses:</p>
|
||
<pre><code class="language-rust">fn generic_function<T>(value: T) {
|
||
// code goes here
|
||
}
|
||
</code></pre>
|
||
<p>We can use the same process that we used to refactor duplicated type
|
||
definitions using generics to refactor duplicated function definitions using
|
||
generics. Consider these two side-by-side function signatures that differ in
|
||
the type of <code>value</code>:</p>
|
||
<pre><code class="language-text">fn takes_integer(value: i32) { fn takes_float(value: f64) {
|
||
// code goes here // code goes here
|
||
} }
|
||
</code></pre>
|
||
<p>We can add a type parameter list that declares the generic type <code>T</code> after the
|
||
function names, then use <code>T</code> where the specific <code>i32</code> and <code>f64</code> types were:</p>
|
||
<pre><code class="language-text">fn takes_integer<T>(value: T) { fn takes_float<T>(value: T) {
|
||
// code goes here // code goes here
|
||
} }
|
||
</code></pre>
|
||
<p>At this point, only the names differ, so we could unify the two functions into
|
||
one:</p>
|
||
<pre><code class="language-rust,ignore">fn takes<T>(value: T) {
|
||
// code goes here
|
||
}
|
||
</code></pre>
|
||
<p>There's one problem though. We've got some function <em>definitions</em> that work,
|
||
but if we try to use <code>value</code> in code in the function body, we'll get an
|
||
error. For example, the function definition in Listing 10-4 tries to print out
|
||
<code>value</code> in its body:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust,ignore">fn show_anything<T>(value: T) {
|
||
println!("I have something to show you!");
|
||
println!("It's: {}", value);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-4: A <code>show_anything</code> function definition that does not yet compile</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Compiling this definition results in an error:</p>
|
||
<pre><code class="language-text"> error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
|
||
--> <anon>:3:37
|
||
|
|
||
3 | println!("It's: {}", value);
|
||
| ^^^^^ trait `T: std::fmt::Display` not satisfied
|
||
|
|
||
= help: consider adding a `where T: std::fmt::Display` bound
|
||
= note: required by `std::fmt::Display::fmt`
|
||
|
||
error: aborting due to previous error(s)
|
||
</code></pre>
|
||
<p>This error mentions something we haven't learned about yet: traits. In the next
|
||
section, we'll learn how to make this compile.</p>
|
||
<h2>Traits</h2>
|
||
<p><em>Traits</em> are similar to a feature often called 'interfaces' in other languages,
|
||
but are also different. Traits let us do another kind of abstraction: they let
|
||
us abstract over <em>behavior</em> that types can have in common.</p>
|
||
<p>When we use a generic type parameter, we are telling Rust that any type is
|
||
valid in that location. When other code <em>uses</em> a value that could be of any
|
||
type, we need to also tell Rust that the type has the functionality that we
|
||
need. Traits let us specify that, for example, we need any type <code>T</code> that has
|
||
methods defined on it that allow us to print a value of that type. This is
|
||
powerful because we can still leave our definitions generic to allow use of
|
||
many different types, but we can constrain the type at compile-time to types
|
||
that have the behavior we need to be able to use.</p>
|
||
<p>Listing 10-5 has an example definition of a trait named <code>Printable</code> with a
|
||
method named <code>print</code>:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">trait Printable {
|
||
fn print(&self);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-5: A <code>Printable</code> trait definition with one method, <code>print</code></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>We declare a trait with the <code>trait</code> keyword, then the trait's name. In this
|
||
case, our trait will describe types which can be printed. Inside of curly
|
||
braces, we declare a method signature, but instead of providing an
|
||
implementation inside curly braces, we put a semicolon after the signature. A
|
||
trait can have multiple methods in its body, with the method signatures listed
|
||
one per line and each line ending in a semicolon.</p>
|
||
<p>Implementing a trait for a particular type looks similar to implementing
|
||
methods on a type since it's also done with the <code>impl</code> keyword, but we specify
|
||
the trait name as well. Inside the <code>impl</code> block, we specify definitions for the
|
||
trait's methods in the context of the specific type. Listing 10-6 has an
|
||
example of implementing the <code>Printable</code> trait from Listing 10-5 (that only has
|
||
the <code>print</code> method) for a <code>Temperature</code> enum:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust"># trait Printable {
|
||
# fn print(&self);
|
||
# }
|
||
#
|
||
enum Temperature {
|
||
Celsius(i32),
|
||
Fahrenheit(i32),
|
||
}
|
||
|
||
impl Printable for Temperature {
|
||
fn print(&self) {
|
||
match *self {
|
||
Temperature::Celsius(val) => println!("{}°C", val),
|
||
Temperature::Fahrenheit(val) => println!("{}°F", val),
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-6: Implementing the <code>Printable</code> trait on a <code>Temperature</code> enum</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>In the same way <code>impl</code> lets us define methods, we've used it to define methods
|
||
that pertain to our trait. We can call methods that our trait has defined just
|
||
like we can call other methods:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust"># trait Printable {
|
||
# fn print(&self);
|
||
# }
|
||
#
|
||
# enum Temperature {
|
||
# Celsius(i32),
|
||
# Fahrenheit(i32),
|
||
# }
|
||
#
|
||
# impl Printable for Temperature {
|
||
# fn print(&self) {
|
||
# match *self {
|
||
# Temperature::Celsius(val) => println!("{}°C", val),
|
||
# Temperature::Fahrenheit(val) => println!("{}°F", val),
|
||
# }
|
||
# }
|
||
# }
|
||
#
|
||
fn main() {
|
||
let t = Temperature::Celsius(37);
|
||
|
||
t.print();
|
||
}
|
||
</code></pre>
|
||
<p>Note that in order to use a trait's methods, the trait itself must be in scope.
|
||
If the definition of <code>Printable</code> was in a module, the definition would need to
|
||
be defined as <code>pub</code> and we would need to <code>use</code> the trait in the scope where we
|
||
wanted to call the <code>print</code> method. This is because it's possible to have two
|
||
traits that both define a method named <code>print</code>, and our <code>Temperature</code> enum might
|
||
implement both. Rust wouldn't know which <code>print</code> method we wanted unless we
|
||
brought the trait we wanted into our current scope with <code>use</code>.</p>
|
||
<h3>Trait Bounds</h3>
|
||
<p>Defining traits with methods and implementing the trait methods on a particular
|
||
type gives Rust more information than just defining methods on a type directly.
|
||
The information Rust gets is that the type that implements the trait can be
|
||
used in places where the code specifies that it needs some type that implements
|
||
a trait. To illustrate this, Listing 10-7 has a <code>print_anything</code> function
|
||
definition. This is similar to the <code>show_anything</code> function from Listing 10-4,
|
||
but this function has a <em>trait bound</em> on the generic type <code>T</code> and uses the
|
||
<code>print</code> function from the trait. A trait bound constrains the generic type to
|
||
be any type that implements the trait specified, instead of any type at all.
|
||
With the trait bound, we're then allowed to use the trait method <code>print</code> in the
|
||
function body:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</figure>
|
||
<pre><code class="language-rust"># trait Printable {
|
||
# fn print(&self);
|
||
# }
|
||
#
|
||
fn print_anything<T: Printable>(value: T) {
|
||
println!("I have something to print for you!");
|
||
value.print();
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-7: A <code>print_anything</code> function that uses the trait bound <code>Printable</code>
|
||
on type <code>T</code></p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Trait bounds are specified in the type name declarations within the angle
|
||
brackets. After the name of the type that you want to apply the bound to, add a
|
||
colon (<code>:</code>) and then specify the name of the trait. This function now specifies
|
||
that it takes a <code>value</code> parameter that can be of any type, as long as that type
|
||
implements the trait <code>Printable</code>. We need to specify the <code>Printable</code> trait in
|
||
the type name declarations because we want to be able to call the <code>print</code>
|
||
method that is part of the <code>Printable</code> trait.</p>
|
||
<p>Now we are able to call the <code>print_anything</code> function from Listing 10-7 and
|
||
pass it a <code>Temperature</code> instance as the <code>value</code> parameter, since we implemented
|
||
the trait <code>Printable</code> on <code>Temperature</code> in Listing 10-6:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust"># trait Printable {
|
||
# fn print(&self);
|
||
# }
|
||
#
|
||
# enum Temperature {
|
||
# Celsius(i32),
|
||
# Fahrenheit(i32),
|
||
# }
|
||
#
|
||
# impl Printable for Temperature {
|
||
# fn print(&self) {
|
||
# match *self {
|
||
# Temperature::Celsius(val) => println!("{}°C", val),
|
||
# Temperature::Fahrenheit(val) => println!("{}°F", val),
|
||
# }
|
||
# }
|
||
# }
|
||
#
|
||
# fn print_anything<T: Printable>(value: T) {
|
||
# println!("I have something to print for you!");
|
||
# value.print();
|
||
# }
|
||
#
|
||
fn main() {
|
||
let temperature = Temperature::Fahrenheit(98);
|
||
print_anything(temperature);
|
||
}
|
||
</code></pre>
|
||
<p>If we implement the <code>Printable</code> trait on other types, we can use them with the
|
||
<code>print_anything</code> method too. If we try to call <code>print_anything</code> with an <code>i32</code>,
|
||
which does <em>not</em> implement the <code>Printable</code> trait, we get a compile-time error
|
||
that looks like this:</p>
|
||
<pre><code class="language-text">error[E0277]: the trait bound `{integer}: Printable` is not satisfied
|
||
|
|
||
29 | print_anything(3);
|
||
| ^^^^^^^^^^^^^^ trait `{integer}: Printable` not satisfied
|
||
|
|
||
= help: the following implementations were found:
|
||
= help: <Point as Printable>
|
||
= note: required by `print_anything`
|
||
</code></pre>
|
||
<p>Traits are an extremely useful feature of Rust. You'll almost never see generic
|
||
functions without an accompanying trait bound. There are many traits in the
|
||
standard library, and they're used for many, many different things. For
|
||
example, our <code>Printable</code> trait is similar to one of those traits, <code>Display</code>.
|
||
And in fact, that's how <code>println!</code> decides how to format things with <code>{}</code>. The
|
||
<code>Display</code> trait has a <code>fmt</code> method that determines how to format something.</p>
|
||
<p>Listing 10-8 shows our original example from Listing 10-3, but this time using
|
||
the standard library's <code>Display</code> trait in the trait bound on the generic type
|
||
in the <code>show_anything</code> function:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">use std::fmt::Display;
|
||
|
||
fn show_anything<T: Display>(value: T) {
|
||
println!("I have something to show you!");
|
||
println!("It's: {}", value);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-8: The <code>show_anything</code> function with trait bounds</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Now that this function specifies that <code>T</code> can be any type as long as that type
|
||
implements the <code>Display</code> trait, this code will compile.</p>
|
||
<h3>Multiple Trait Bounds and <code>where</code> Syntax</h3>
|
||
<p>Each generic type can have its own trait bounds. The signature for a function
|
||
that takes a type <code>T</code> that implements <code>Display</code> and a type <code>U</code> that implements
|
||
<code>Printable</code> looks like:</p>
|
||
<pre><code class="language-rust,ignore">fn some_function<T: Display, U: Printable>(value: T, other_value: U) {
|
||
</code></pre>
|
||
<p>To specify multiple trait bounds on one type, list the trait bounds in a list
|
||
with a <code>+</code> between each trait. For example, here's the signature of a function
|
||
that takes a type <code>T</code> that implements <code>Display</code> and <code>Clone</code> (which is another
|
||
standard library trait we have mentioned):</p>
|
||
<pre><code class="language-rust,ignore">fn some_function<T: Display + Clone>(value: T) {
|
||
</code></pre>
|
||
<p>When trait bounds start getting complicated, there is another syntax that's a
|
||
bit cleaner: <code>where</code>. And in fact, the error we got when we ran the code from
|
||
Listing 10-3 referred to it:</p>
|
||
<pre><code class="language-text">help: consider adding a `where T: std::fmt::Display` bound
|
||
</code></pre>
|
||
<p>The <code>where</code> syntax moves the trait bounds after the function arguments list.
|
||
This definition of <code>show_anything</code> means the exact same thing as the definition
|
||
in Listing 10-8, just said a different way:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">use std::fmt::Display;
|
||
|
||
fn show_anything<T>(value: T) where T: Display {
|
||
println!("I have something to show you!");
|
||
println!("It's: {}", value);
|
||
}
|
||
</code></pre>
|
||
<p>Instead of <code>T: Display</code> going inside the angle brackets, they go after the
|
||
<code>where</code> keyword at the end of the function signature. This can make complex
|
||
signatures easier to read. The <code>where</code> clause and its parts can also go on new
|
||
lines. Here's the signature of a function that takes three generic type
|
||
parameters that each have multiple trait bounds:</p>
|
||
<pre><code class="language-rust,ignore">fn some_function<T, U, V>(t: T, u: U, v: V)
|
||
where T: Display + Clone,
|
||
U: Printable + Debug,
|
||
V: Clone + Printable
|
||
{
|
||
</code></pre>
|
||
<p>Generic type parameters and trait bounds are part of Rust's rich type system.
|
||
Another important kind of generic in Rust interacts with Rust's ownership and
|
||
references features, and they're called <em>lifetimes</em>.</p>
|
||
<h2>Lifetime Syntax</h2>
|
||
<p>Generic type parameters let us abstract over types, and traits let us abstract
|
||
over behavior. There's one more way that Rust allows us to do something
|
||
similar: <em>lifetimes</em> allow us to be generic over scopes of code.</p>
|
||
<p>Scopes of code? Yes, it's a bit unusual. Lifetimes are, in some ways, Rust's
|
||
most distinctive feature. They are a bit different than the tools you have used
|
||
in other programming languages. Lifetimes are a big topic, so we're not going
|
||
to cover everything about them in this chapter. What we <em>are</em> going to do is
|
||
talk about the very basics of lifetimes, so that when you see the syntax in
|
||
documentation or other places, you'll be familiar with the concepts. Chapter 20
|
||
will contain more advanced information about everything lifetimes can do.</p>
|
||
<h3>Core Syntax</h3>
|
||
<p>We talked about references in Chapter 4, but we left out an important detail.
|
||
As it turns out, every reference in Rust has a <em>lifetime</em>, which is the scope
|
||
for which that reference is valid. Most of the time, lifetimes are implicit,
|
||
but just like we can choose to annotate types everywhere, we can choose to
|
||
annotate lifetimes.</p>
|
||
<p>Lifetimes have a slightly unusual syntax:</p>
|
||
<pre><code class="language-rust,ignore">&i32 // a reference
|
||
&'a i32 // a reference with an explicit lifetime
|
||
</code></pre>
|
||
<p>The <code>'a</code> there is a <em>lifetime</em> with the name <code>a</code>. A single apostrophe indicates
|
||
that this name is for a lifetime. Lifetime names need to be declared before
|
||
they're used. Here's a function signature with lifetime declarations and
|
||
annotations:</p>
|
||
<pre><code class="language-rust,ignore">fn some_function<'a>(argument: &'a i32) {
|
||
</code></pre>
|
||
<p>Notice anything? In the same way that generic type declarations go inside angle
|
||
brackets after the function name, lifetime declarations also go inside those
|
||
same angle brackets. We can even write functions that take both a lifetime
|
||
declaration and a generic type declaration:</p>
|
||
<pre><code class="language-rust,ignore">fn some_function<'a, T>(argument: &'a T) {
|
||
</code></pre>
|
||
<p>This function takes one argument, a reference to some type, <code>T</code>, and the
|
||
reference has the lifetime <code>'a</code>. In the same way that we parameterize functions
|
||
that take generic types, we parameterize references with lifetimes.</p>
|
||
<p>So, that's the syntax, but <em>why</em>? What does a lifetime do, anyway?</p>
|
||
<h3>Lifetimes Prevent Dangling References</h3>
|
||
<p>Consider the program in listing 10-8. There's an outer scope and an inner
|
||
scope. The outer scope declares a variable named <code>r</code> with no initial value, and
|
||
the inner scope declares a variable named <code>x</code> with the initial value of 5.
|
||
Inside the inner scope, we attempt to set the value of <code>r</code> to a reference to
|
||
<code>x</code>. Then the inner scope ends and we attempt to print out the value in <code>r</code>:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust,ignore">{
|
||
let r;
|
||
|
||
{
|
||
let x = 5;
|
||
r = &x;
|
||
}
|
||
|
||
println!("r: {}", r);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-8: An attempt to use a reference whose value has gone out of scope</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>If we compile this code, we get an error:</p>
|
||
<pre><code class="language-text"> error: `x` does not live long enough
|
||
--> <anon>:6:10
|
||
|
|
||
6 | r = &x;
|
||
| ^ does not live long enough
|
||
7 | }
|
||
| - borrowed value only lives until here
|
||
...
|
||
10 | }
|
||
| - borrowed value needs to live until here
|
||
</code></pre>
|
||
<p>The variable <code>x</code> doesn't "live long enough." 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 "lives longer." If Rust allowed this code to work, <code>r</code> would be
|
||
referencing memory that was deallocated when <code>x</code> went out of scope. That'd be
|
||
bad! Once it's deallocated, it's meaningless.</p>
|
||
<p>So how does Rust determine that this code should not be allowed? Part of the
|
||
compiler called the <em>borrow checker</em> compares scopes to determine that all
|
||
borrows are valid. Here's the same example from Listing 10-8 with some
|
||
annotations:</p>
|
||
<pre><code class="language-rust,ignore">{
|
||
let r; // -------+-- 'a
|
||
// |
|
||
{ // |
|
||
let x = 5; // -+-----+-- 'b
|
||
r = &x; // | |
|
||
} // -+ |
|
||
// |
|
||
println!("r: {}", r); // |
|
||
// |
|
||
// -------+
|
||
}
|
||
</code></pre>
|
||
<p>Here, we've annotated the lifetime of <code>r</code> with <code>'a</code> and the lifetime of <code>x</code>
|
||
with <code>'b</code>. Rust looks at these lifetimes and sees that <code>r</code> has a lifetime of
|
||
<code>'a</code>, but that it refers to something with a lifetime of <code>'b</code>. It rejects the
|
||
program because the lifetime <code>'b</code> is shorter than the lifetime of <code>'a</code>-- the
|
||
value that the reference is referring to does not live as long as the reference
|
||
does.</p>
|
||
<p>Let's look at a different example that compiles because it does not try to make
|
||
a dangling reference, and see what the lifetimes look like:</p>
|
||
<pre><code class="language-rust">{
|
||
let x = 5; // -----+-- 'b
|
||
// |
|
||
let r = &x; // --+--+-- 'a
|
||
// | |
|
||
println!("r: {}", r); // | |
|
||
// --+ |
|
||
// -----+
|
||
}
|
||
</code></pre>
|
||
<p>Here, <code>x</code> lives for <code>'b</code>, which in this case is larger than <code>'a</code>. This is
|
||
allowed: Rust knows that the reference in <code>r</code> will always be valid, as it has a
|
||
smaller scope than <code>x</code>, the value it refers to.</p>
|
||
<p>Note that we didn't have to name any lifetimes in the code itself; Rust figured
|
||
it out for us. One situation in which Rust can't figure out the lifetimes is
|
||
for a function or method when one of the arguments or return values is a
|
||
reference, except for a few scenarios we'll discuss in the lifetime elision
|
||
section.</p>
|
||
<h3>Lifetime Annotations in Struct Definitions</h3>
|
||
<p>Another time that Rust can't figure out the lifetimes is when structs have a
|
||
field that holds a reference. In that case, naming the lifetimes looks like
|
||
this:</p>
|
||
<pre><code class="language-rust">struct Ref<'a> {
|
||
x: &'a i32,
|
||
}
|
||
</code></pre>
|
||
<p>Again, the lifetime names are declared in the angle brackets where generic type
|
||
parameters are declared, and this is because lifetimes are a form of generics.
|
||
In the examples above, <code>'a</code> and <code>'b</code> were concrete lifetimes: we knew about <code>r</code>
|
||
and <code>x</code> and how long they would live exactly. However, when we write a
|
||
function, we can't know beforehand exactly all of the arguments that it could
|
||
be called with and how long they will be valid for. We have to explain to Rust
|
||
what we expect the lifetime of the argument to be (we'll learn about how
|
||
to know what you expect the lifetime to be in a bit). This is similar to
|
||
writing a function that has an argument of a generic type: we don't know what
|
||
type the arguments will actually end up being when the function gets called.
|
||
Lifetimes are the same idea, but they are generic over the scope of a
|
||
reference, rather than a type.</p>
|
||
<h3>Lifetime Annotations in Function Signatures</h3>
|
||
<p>Lifetime annotations for functions go on the function signature, but we don't
|
||
have to annotate any of the code in the function body with lifetimes. That's
|
||
because Rust can analyze the specific code inside the function without any
|
||
help. When a function interacts with references that come from or go to code
|
||
outside that function, however, the lifetimes of those arguments or return
|
||
values will potentially be different each time that function gets called. Rust
|
||
would have to analyze every place the function is called to determine that
|
||
there were no dangling references. That would be impossible because a library
|
||
that you provide to someone else might be called in code that hasn't been
|
||
written yet, at the time that you're compiling your library.</p>
|
||
<p>Lifetime parameters specify generic lifetimes that will apply to any specific
|
||
lifetimes the function gets called with. The annotation of lifetime parameters
|
||
tell Rust what it needs to know in order to be able to analyze a function
|
||
without knowing about all possible calling code. Lifetime annotations do not
|
||
change how long any of the references involved live. In the same way that
|
||
functions can accept any type when the signature specifies a generic type
|
||
parameter, functions can accept references with any lifetime when the signature
|
||
specifies a generic lifetime parameter.</p>
|
||
<p>To understand lifetime annotations in context, let's write a function that will
|
||
return the longest of two string slices. The way we want to be able to call
|
||
this function is by passing two string slices, and we want to get back a string
|
||
slice. The code in Listing 10-9 should print <code>The longest string is abcd</code> once
|
||
we've implemented the <code>longest</code> function:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust"># fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
|
||
# if x.len() > y.len() {
|
||
# x
|
||
# } else {
|
||
# y
|
||
# }
|
||
# }
|
||
#
|
||
fn main() {
|
||
let a = String::from("abcd");
|
||
let b = "xyz";
|
||
|
||
let c = longest(a.as_str(), b);
|
||
println!("The longest string is {}", c);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 10-9: A <code>main</code> function that demonstrates how we'd like to use the
|
||
<code>longest</code> function</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Note that we want the function to take string slices because we don't want the
|
||
<code>longest</code> function to take ownership of its arguments, and we want the function
|
||
to be able to accept slices of a <code>String</code> (like <code>a</code>) is as well as string
|
||
literals (<code>b</code>). Refer back to the "String Slices as Arguments" section of
|
||
Chapter 4 for more discussion about why these are the arguments we want.</p>
|
||
<p>Here's the start of an implementation of the <code>longest</code> function that won't
|
||
compile yet:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn longest(x: &str, y: &str) -> &str {
|
||
if x.len() > y.len() {
|
||
x
|
||
} else {
|
||
y
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>If we try to compile this, we get an error that talks about lifetimes:</p>
|
||
<pre><code class="language-text">error[E0106]: missing lifetime specifier
|
||
|
|
||
1 | fn longest(x: &str, y: &str) -> &str {
|
||
| ^ expected lifetime parameter
|
||
|
|
||
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
|
||
</code></pre>
|
||
<p>The help text is telling us that the return type needs a generic lifetime
|
||
parameter on it because this function is returning a reference and Rust can't
|
||
tell if the reference being returned refers to <code>x</code> or <code>y</code>. Actually, we don't
|
||
know either, since in the <code>if</code> block in the body of this function returns a
|
||
reference to <code>x</code> and the <code>else</code> block returns a reference to <code>y</code>! The way to
|
||
specify the lifetime parameters in this case is to have the same lifetime for
|
||
all of the input parameters and the return type:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
|
||
if x.len() > y.len() {
|
||
x
|
||
} else {
|
||
y
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>This will compile and will produce the result we want with the <code>main</code> function
|
||
in Listing 10-9. This function signature is now saying that for some lifetime
|
||
named <code>'a</code>, it will get two arguments, both which are string slices that live
|
||
at least as long as the lifetime <code>'a</code>. The function will return a string slice
|
||
that also will last at least as long as the lifetime <code>'a</code>. This is the contract
|
||
we are telling Rust we want it to enforce. By specifying the lifetime
|
||
parameters in this function signature, we are not changing the lifetimes of any
|
||
values passed in or returned, but we are saying that any values that do not
|
||
adhere to this contract should be rejected by the borrow checker. This function
|
||
does not know (or need to know) exactly how long <code>x</code> and <code>y</code> will live since it
|
||
knows that there is some scope that can be substituted for <code>'a</code> that will
|
||
satisfy this signature.</p>
|
||
<p>The exact way to specify lifetime parameters depends on what your function is
|
||
doing. If the function didn't actually return the longest string slice but
|
||
instead always returned the first argument, we wouldn't need to specify a
|
||
lifetime on <code>y</code>. This code compiles:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn longest<'a>(x: &'a str, y: &str) -> &'a str {
|
||
x
|
||
}
|
||
</code></pre>
|
||
<p>The lifetime parameter for the return type needs to be specified and needs to
|
||
match one of the arguments' lifetime parameters. If the reference returned does
|
||
<em>not</em> refer to one of the arguments, the only other possibility is that it
|
||
refers to a value created within this function, and that would be a dangling
|
||
reference since the value will go out of scope at the end of the function.
|
||
Consider this attempted implementation of <code>longest</code>:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">fn longest<'a>(x: &str, y: &str) -> &'a str {
|
||
let result = String::from("really long string");
|
||
result.as_str()
|
||
}
|
||
</code></pre>
|
||
<p>Even though we've specified a lifetime for the return type, this function fails
|
||
to compile with the following error message:</p>
|
||
<pre><code class="language-text">error: `result` does not live long enough
|
||
|
|
||
3 | result.as_str()
|
||
| ^^^^^^ does not live long enough
|
||
4 | }
|
||
| - borrowed value only lives until here
|
||
|
|
||
note: borrowed value must be valid for the lifetime 'a as defined on the block at 1:44...
|
||
|
|
||
1 | fn longest<'a>(x: &str, y: &str) -> &'a str {
|
||
| ^
|
||
</code></pre>
|
||
<p>The problem is that <code>result</code> will go out of scope and get cleaned up at the end
|
||
of the <code>longest</code> function, and we're trying to return a reference to <code>result</code>
|
||
from the function. There's no way we can specify lifetime parameters that would
|
||
change the dangling reference, and Rust won't let us create a dangling
|
||
reference. In this case, the best fix would be to return an owned data type
|
||
rather than a reference so that the calling function is then responsible for
|
||
cleaning up the value.</p>
|
||
<p>Ultimately, lifetime syntax is about connecting the lifetimes of various
|
||
arguments and return values of functions. Once they're connected, Rust has
|
||
enough information to allow memory-safe operations and disallow operations that
|
||
would create dangling pointers or otherwise violate memory safety.</p>
|
||
<h3>Lifetime Elision</h3>
|
||
<p>If every reference has a lifetime, and we need to provide them for functions
|
||
that use references as arguments or return values, then why did this function
|
||
from the "String Slices" section of Chapter 4 compile? We haven't annotated any
|
||
lifetimes here, yet Rust happily compiles this function:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">fn first_word(s: &str) -> &str {
|
||
let bytes = s.as_bytes();
|
||
|
||
for (i, &item) in bytes.iter().enumerate() {
|
||
if item == b' ' {
|
||
return &s[0..i];
|
||
}
|
||
}
|
||
|
||
&s[..]
|
||
}
|
||
</code></pre>
|
||
<p>The answer is historical: in early versions of pre-1.0 Rust, this would not
|
||
have compiled. Every reference needed an explicit lifetime. At that time, the
|
||
function signature would have been written like this:</p>
|
||
<pre><code class="language-rust,ignore">fn first_word<'a>(s: &'a str) -> &'a str {
|
||
</code></pre>
|
||
<p>After writing a lot of Rust code, some patterns developed. The Rust team
|
||
noticed that the vast majority of code followed the pattern, and being forced
|
||
to use explicit lifetime syntax on every reference wasn't a very great
|
||
developer experience.</p>
|
||
<p>To make it so that lifetime annotations weren't needed as often, they added
|
||
<em>lifetime elision rules</em> to Rust's analysis of references. This feature isn't
|
||
full inference: Rust doesn't try to guess what you meant in places where there
|
||
could be ambiguity. The rules are a very basic set of particular cases, and if
|
||
your code fits one of those cases, you don't need to write the lifetimes
|
||
explicitly. Here are the rules:</p>
|
||
<p>Lifetimes on function arguments are called <em>input lifetimes</em>, and lifetimes on
|
||
return values are called <em>output lifetimes</em>. There's one rule related to how
|
||
Rust infers input lifetimes in the absence of explicit annotations:</p>
|
||
<ol>
|
||
<li>Each argument that is a reference and therefore needs a lifetime parameter
|
||
gets its own. In other words, a function with one argument gets one lifetime
|
||
parameter: <code>fn foo<'a>(x: &'a i32)</code>, a function with two arguments gets two
|
||
separate lifetime parameters: <code>fn foo<'a, 'b>(x: &'a i32, y: &'b i32)</code>, and
|
||
so on.</li>
|
||
</ol>
|
||
<p>And two rules related to output lifetimes:</p>
|
||
<ol start="2">
|
||
<li>If there is exactly one input lifetime parameter, that lifetime is assigned
|
||
to all output lifetime parameters: <code>fn foo<'a>(x: &'a i32) -> &'a i32</code>.</li>
|
||
<li>If there are multiple input lifetime parameters, but one of them is <code>&self</code>
|
||
or <code>&mut self</code>, then the lifetime of <code>self</code> is the lifetime assigned to all
|
||
output lifetime parameters. This makes writing methods much nicer.</li>
|
||
</ol>
|
||
<p>If none of these three rules apply, then you must explicitly annotate input and
|
||
output lifetimes. These rules do apply in the <code>first_word</code> function, which is
|
||
why we didn't have to specify any lifetimes.</p>
|
||
<p>These rules cover the vast majority of cases, allowing you to write a lot of
|
||
code without needing to specify explicit lifetimes. However, Rust is always
|
||
checking these rules and the lifetimes in your program, and cases in which the
|
||
lifetime elision rules do not apply are cases where you'll need to add lifetime
|
||
parameters to help Rust understand the contracts of your code.</p>
|
||
<h3>Lifetime Annotations in Method Definitions</h3>
|
||
<p>Now that we've gone over the lifetime elision rules, defining methods on
|
||
structs that hold references will make more sense. The lifetime name needs to
|
||
be declared after the <code>impl</code> keyword and then used after the struct's name,
|
||
since the lifetime is part of the struct's type. The lifetimes can be elided in
|
||
any methods where the output type's lifetime is the same as that of the
|
||
struct's because of the third elision rule. Here's a struct called <code>App</code> that
|
||
holds a reference to another struct, <code>Config</code>, defined elsewhere. The
|
||
<code>append_to_name</code> method does not need lifetime annotations even though the
|
||
method has a reference as an argument and is returning a reference; the
|
||
lifetime of the return value will be the lifetime of <code>self</code>:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust"># struct Config {}
|
||
#
|
||
struct App<'a> {
|
||
name: String,
|
||
config: &'a Config,
|
||
}
|
||
|
||
impl<'a> App<'a> {
|
||
fn append_to_name(&mut self, suffix: &str) -> &str {
|
||
self.name.push_str(suffix);
|
||
self.name.as_str()
|
||
}
|
||
}
|
||
</code></pre>
|
||
<h3>The Static Lifetime</h3>
|
||
<p>There is <em>one</em> special lifetime that Rust knows about: <code>'static</code>. The <code>'static</code>
|
||
lifetime is the entire duration of the program. All string literals have the
|
||
<code>'static</code> lifetime:</p>
|
||
<pre><code class="language-rust">let s: &'static str = "I have a static lifetime.";
|
||
</code></pre>
|
||
<p>The text of this string is stored directly in the binary of your program and
|
||
the binary of your program is always available. Therefore, the lifetime of all
|
||
string literals is <code>'static</code>. You may see suggestions to use the <code>'static</code>
|
||
lifetime in error message help text, but before adding it, think about whether
|
||
the reference you have is one that actually lives the entire lifetime of your
|
||
program or not (or even if you want it to live that long, if it could). Most of
|
||
the time, the problem in the code is an attempt to create a dangling reference
|
||
or a mismatch of the available lifetimes, and the solution is fixing those
|
||
problems, not specifying the <code>'static</code> lifetime.</p>
|
||
<h2>Summary</h2>
|
||
<p>We've covered the basics of Rust's system of generics. Generics are the core to
|
||
building good abstractions, and can be used in a number of ways. There's more
|
||
to learn about them, particularly lifetimes, but we'll cover those in later
|
||
chapters. Let's move on to testing.</p>
|
||
<h1>Testing</h1>
|
||
<blockquote>
|
||
<p>Program testing can be a very effective way to show the presence of bugs, but
|
||
it is hopelessly inadequate for showing their absence.</p>
|
||
<p>Edsger W. Dijkstra, "The Humble Programmer" (1972)</p>
|
||
</blockquote>
|
||
<p>Rust is a programming language that cares a lot about correctness, but
|
||
correctness is a complex topic and isn't easy to prove. Rust places a lot of
|
||
weight on its type system to help ensure that our programs do what we intend,
|
||
but it cannot help with everything. As such, Rust also includes support for
|
||
writing software tests in the language itself.</p>
|
||
<p>For example, we can write a function called <code>add_two</code> with a signature that
|
||
accepts an integer as an argument and returns an integer as a result. We can
|
||
implement and compile that function, and Rust can do all the type checking and
|
||
borrow checking that we've seen it's capable of doing. What Rust <em>can't</em> check
|
||
for us is that we've implemented this function to return the argument plus two
|
||
and not the argument plus 10 or the argument minus 50! That's where tests come
|
||
in. We can write tests that, for example, pass <code>3</code> to the <code>add_two</code> function
|
||
and check that we get <code>5</code> back. We can run the tests whenever we make changes
|
||
to our code to make sure we didn't change any existing behavior from what the
|
||
tests specify it should be.</p>
|
||
<p>Testing is a skill, and we cannot hope to cover everything about how to write
|
||
good tests in one chapter of a book. What we can discuss, however, are the
|
||
mechanics of Rust's testing facilities. We'll talk about the annotations and
|
||
macros available to you when writing your tests, the default behavior and
|
||
options provided for running your tests, and how to organize tests into unit
|
||
tests and integration tests.</p>
|
||
<h2>Writing Tests</h2>
|
||
<p>Tests are Rust functions that use particular features and are written in such a
|
||
way as to verify that non-test code is functioning in the expected manner.
|
||
Everything we've discussed about Rust code applies to Rust tests as well! Let's
|
||
look at the features Rust provides specifically for writing tests: the <code>test</code>
|
||
attribute, a few macros, and the <code>should_panic</code> attribute.</p>
|
||
<h3>The <code>test</code> attribute</h3>
|
||
<p>At its simplest, a test in Rust is a function that's annotated with the <code>test</code>
|
||
attribute. Let's make a new library project with Cargo called <code>adder</code>:</p>
|
||
<pre><code class="language-text">$ cargo new adder
|
||
Created library `adder` project
|
||
$ cd adder
|
||
</code></pre>
|
||
<p>Cargo will automatically generate a simple test when you make a new library
|
||
project. Here's the contents of <code>src/lib.rs</code>:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>For now, let's ignore the <code>tests</code> module and the <code>#[cfg(test)]</code> annotation in
|
||
order to focus on just the function. Note the <code>#[test]</code> before it: this
|
||
attribute indicates this is a test function. The function currently has no
|
||
body; that's good enough to pass! We can run the tests with <code>cargo test</code>:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Compiling adder v0.1.0 (file:///projects/adder)
|
||
Finished debug [unoptimized + debuginfo] target(s) in 0.22 secs
|
||
Running target/debug/deps/adder-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>
|
||
<h3>The <code>assert!</code> macro</h3>
|
||
<p>The empty test function passes because any test which doesn't <code>panic!</code> passes,
|
||
and any test that does <code>panic!</code> fails. Let's make the test fail by using the
|
||
<code>assert!</code> macro:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[test]
|
||
fn it_works() {
|
||
assert!(false);
|
||
}
|
||
</code></pre>
|
||
<p>The <code>assert!</code> macro is provided by the standard library, and it takes one
|
||
argument. If the argument is <code>true</code>, nothing happens. If the argument is
|
||
<code>false</code>, the macro will <code>panic!</code>. Let's run our tests again:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Compiling adder v0.1.0 (file:///projects/adder)
|
||
Finished debug [unoptimized + debuginfo] target(s) in 0.22 secs
|
||
Running target/debug/deps/adder-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>
|
||
<h3>Testing equality with the <code>assert_eq!</code> and <code>assert_ne!</code> macros</h3>
|
||
<p>A common way to test functionality is to compare the result of the code under
|
||
test to the value you expect it to be, and check that they're equal. You can do
|
||
this using the <code>assert!</code> macro by passing it an expression using the <code>==</code>
|
||
macro. This is so common, though, that the standard library provides a pair of
|
||
macros to do this for convenience: <code>assert_eq!</code> and <code>assert_ne!</code>. These macros
|
||
compare two arguments for equality or inequality, respectively. The other
|
||
advantage of using these macros is they will print out what the two values
|
||
actually are if the assertion fails so that it's easier to see <em>why</em> the test
|
||
failed, whereas the <code>assert!</code> macro would just print out that it got a <code>false</code>
|
||
value for the <code>==</code> expression.</p>
|
||
<p>Here's an example test that uses each of these macros and will pass:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[test]
|
||
fn it_works() {
|
||
assert_eq!("Hello", "Hello");
|
||
|
||
assert_ne!("Hello", "world");
|
||
}
|
||
</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!(
|
||
"assertion failed: `(left == right)` (left: `{:?}`, right: `{:?}`): {}"
|
||
left_val,
|
||
right_val,
|
||
optional_custom_message
|
||
)
|
||
}
|
||
|
||
// assert_ne! - panic if the values are equal
|
||
if left_val == right_val {
|
||
panic!(
|
||
"assertion failed: `(left != right)` (left: `{:?}`, right: `{:?}`): {}"
|
||
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 = "hello"; // this value would come from running your code
|
||
assert_eq!(result, "world", "greeting operation failed");
|
||
}
|
||
</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: `"hello"`, right: `"world"`): greeting operation failed',
|
||
src/main.rs:4
|
||
</code></pre>
|
||
<p>The two arguments to <code>assert_eq!</code> are named "left" and "right" rather than
|
||
"expected" and "actual"; the order of the value that comes from your code and
|
||
the value hardcoded into your test isn't important.</p>
|
||
<p>Since these macros use the operators <code>==</code> and <code>!=</code> and print the values using
|
||
debug formatting, the values being compared must implement the <code>PartialEq</code> and
|
||
<code>Debug</code> traits. Types provided by Rust implement these traits, but for structs
|
||
and enums that you define, you'll need to add <code>PartialEq</code> in order to be able
|
||
to assert that values of those types are equal or not equal and <code>Debug</code> in
|
||
order to be able to print out the values in the case that the assertion fails.
|
||
Because both of these traits are derivable traits that we mentioned in Chapter
|
||
5, usually this is as straightforward as adding the <code>#[derive(PartialEq, Debug)]</code> annotation to your struct or enum definition. See Appendix C for more
|
||
details about these and other derivable traits.</p>
|
||
<h2>Test for failure with <code>should_panic</code></h2>
|
||
<p>We can invert our test's failure with another attribute: <code>should_panic</code>. This
|
||
is useful when we want to test that calling a particular function will cause an
|
||
error. For example, let's test something that we know will panic from Chapter
|
||
8: attempting to create a slice using range syntax with byte indices that
|
||
aren't on character boundaries. Add the <code>#[should_panic]</code> attribute before the
|
||
function like the <code>#[test]</code> attribute, as shown in Listing 11-1:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">#[test]
|
||
#[should_panic]
|
||
fn slice_not_on_char_boundaries() {
|
||
let s = "Здравствуйте";
|
||
&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 = "do not lie on character boundary")]
|
||
fn slice_not_on_char_boundaries() {
|
||
let s = "Здравствуйте";
|
||
&s[0..1];
|
||
}
|
||
</code></pre>
|
||
<!-- I will add ghosting in libreoffice /Carol -->
|
||
<figcaption>
|
||
<p>Listing 11-2: A test expecting a <code>panic!</code> with a particular message</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Try on your own to see what happens when a <code>should_panic</code> test panics but
|
||
doesn't match the expected message: cause a <code>panic!</code> that happens for a
|
||
different reason in this test, or change the expected panic message to
|
||
something that doesn't match the character boundary panic message.</p>
|
||
<h2>Running tests</h2>
|
||
<p>Just like <code>cargo run</code> compiles your code and then runs the resulting binary,
|
||
<code>cargo test</code> compiles your code in test mode and runs the resulting test
|
||
binary. The default behavior of the binary that <code>cargo test</code> produces is to run
|
||
all the tests in parallel and to capture output generated during test runs so
|
||
that it's easier to read the output about the test results.</p>
|
||
<p>The default behavior of running tests can be changed by specifying command line
|
||
options. Some of these options can be passed to <code>cargo test</code>, and some need to
|
||
be passed instead to the resulting test binary. The way to separate these
|
||
arguments is with <code>--</code>: after <code>cargo test</code>, list the arguments that go to
|
||
<code>cargo test</code>, then the separator <code>--</code>, and then the arguments that go to the
|
||
test binary.</p>
|
||
<h3>Tests Run in Parallel</h3>
|
||
<p>Tests are run in parallel using threads. For this reason, you should take care
|
||
that your tests are written in such a way as to not depend on each other or on
|
||
any shared state. Shared state can also include the environment, such as the
|
||
current working directory or environment variables.</p>
|
||
<p>If you don't want this behavior, or if you want more fine-grained control over
|
||
the number of threads used, you can send the <code>--test-threads</code> flag and the
|
||
number of threads to the test binary. Setting the number of test threads to 1
|
||
means to not use any parallelism:</p>
|
||
<pre><code class="language-text">$ cargo test -- --test-threads=1
|
||
</code></pre>
|
||
<h3>Tests Capture Output</h3>
|
||
<p>By default, Rust's test library captures and discards output to standard out
|
||
and standard error, unless the test fails. For example, if you call <code>println!</code>
|
||
in a test and the test passes, you won't see the <code>println!</code> output in your
|
||
terminal. This behavior can be disabled by sending the <code>--nocapture</code> flag to
|
||
the test binary:</p>
|
||
<pre><code class="language-text">$ cargo test -- --nocapture
|
||
</code></pre>
|
||
<h3>Running a Subset of Tests by Name</h3>
|
||
<p>Sometimes, running a full test suite can take a long time. If you're only
|
||
working on code in a particular area, you might want to only run the tests
|
||
having to do with that code. <code>cargo test</code> takes an argument that allows you to
|
||
only run certain tests, specified by name.</p>
|
||
<p>Let's create three tests with the following names as shown in Listing 11-3:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">#[test]
|
||
fn add_two_and_two() {
|
||
assert_eq!(4, 2 + 2);
|
||
}
|
||
|
||
#[test]
|
||
fn add_three_and_two() {
|
||
assert_eq!(5, 3 + 2);
|
||
}
|
||
|
||
#[test]
|
||
fn one_hundred() {
|
||
assert_eq!(102, 100 + 2);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 11-3: Three tests with a variety of names</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Running with different arguments will run different subsets of the tests. No
|
||
arguments, as we've already seen, runs all the tests:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
|
||
Running target/debug/deps/adder-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>
|
||
<h3>Ignore Some Tests Unless Specifically Requested</h3>
|
||
<p>Sometimes a few specific tests can be very time-consuming to execute, so during
|
||
most runs of <code>cargo test</code>, we'd like to exclude them. Instead of having to
|
||
construct an argument to <code>cargo test</code> to run all tests except these and
|
||
remember to use that argument every time, we can annotate these tests with the
|
||
<code>ignore</code> attribute:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[test]
|
||
fn it_works() {
|
||
assert!(true);
|
||
}
|
||
|
||
#[test]
|
||
#[ignore]
|
||
fn expensive_test() {
|
||
// code that takes an hour to run
|
||
}
|
||
</code></pre>
|
||
<p>Now if we run our tests, we'll see <code>it_works</code> is run, but <code>expensive_test</code> is
|
||
not:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Compiling adder v0.1.0 (file:///projects/adder)
|
||
Finished debug [unoptimized + debuginfo] target(s) in 0.24 secs
|
||
Running target/debug/deps/adder-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>
|
||
<h2>Test Organization</h2>
|
||
<p>As mentioned before, testing is a large discipline, and different people
|
||
sometimes use different terminology and organization. The Rust community tends
|
||
to think about tests in terms of two main categories: <em>unit tests</em> and
|
||
<em>integration tests</em>. Unit tests tend to be smaller and more focused, testing
|
||
one module in isolation at a time. They can also test private interfaces.
|
||
Integration tests are entirely external to your library. They use your code in
|
||
the same way any other code would, using only the public interface and
|
||
exercising multiple modules per test. Both kinds of tests are important to
|
||
ensure that the pieces of your library are doing what you expect them to
|
||
separately and together.</p>
|
||
<h3>Unit Tests</h3>
|
||
<p>The purpose of unit tests is to test each unit of code in isolation from the
|
||
rest of the code, in order to be able to quickly pinpoint where code is working
|
||
as expected or not. Unit tests live in the <em>src</em> directory, in the same files
|
||
as the code they are testing. They are separated into their own <code>tests</code> module
|
||
in each file.</p>
|
||
<h4>The Tests Module and <code>cfg(test)</code></h4>
|
||
<p>By placing tests in their own module and using the <code>cfg</code> annotation on the
|
||
module, we can tell Rust to only compile and run the test code when we run
|
||
<code>cargo test</code>. This saves compile time when we only want to build the library
|
||
code with <code>cargo build</code>, and saves space in the resulting compiled artifact
|
||
since the tests are not included.</p>
|
||
<p>Remember when we generated the new <code>adder</code> project in the last section? Cargo
|
||
generated this code for us:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We ignored the module stuff so we could concentrate on the mechanics of the
|
||
test code inside the module, but now let's focus on the code surrounding our
|
||
tests.</p>
|
||
<p>First of all, there's a new attribute, <code>cfg</code>. The <code>cfg</code> attribute lets us
|
||
declare that something should only be included given a certain <em>configuration</em>.
|
||
Rust provides the <code>test</code> configuration for compiling and running tests. By
|
||
using this attribute, Cargo only compiles our test code if we're currently
|
||
trying to run the tests.</p>
|
||
<p>Next, the <code>tests</code> module holds all of our test functions, while our code is
|
||
outside of the <code>tests</code> module. The name of the <code>tests</code> module is a convention;
|
||
otherwise this is a regular module that follows the usual visibility rules we
|
||
covered in Chapter 7. Because we're in an inner module, we need to bring the
|
||
code under test into scope. This can be annoying if you have a large module, so
|
||
this is a common use of globs.</p>
|
||
<p>Up until now in this chapter, we've been writing tests in our <code>adder</code> project
|
||
that don't actually call any code we've written. Let's change that now! In
|
||
<em>src/lib.rs</em>, place this <code>add_two</code> function and <code>tests</code> module that has a test
|
||
function to exercise the code, as shown in Listing 11-5:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">pub fn add_two(a: i32) -> 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`
|
||
--> src/lib.rs:9:23
|
||
|
|
||
9 | assert_eq!(4, add_two(2));
|
||
| ^^^^^^^ unresolved name
|
||
</code></pre>
|
||
<p>If this module contained lots of code we wanted to test, it would be annoying
|
||
to list everything in the <code>use</code> statement in the tests. It's common instead to
|
||
put <code>use super::*;</code> within a module's <code>test</code> submodule in order to bring
|
||
everything into the <code>test</code> module scope at once.</p>
|
||
<h4>Testing Private Functions</h4>
|
||
<p>There's controversy within the testing community about whether you should write
|
||
unit tests for private functions or not. Regardless of which testing ideology
|
||
you adhere to, Rust does allow you to test private functions due to the way
|
||
that the privacy rules work. Consider the code in Listing 11-6 with the private
|
||
function <code>internal_adder</code>:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/lib.rs</span>
|
||
<pre><code class="language-rust">pub fn add_two(a: i32) -> i32 {
|
||
internal_adder(a, 2)
|
||
}
|
||
|
||
fn internal_adder(a: i32, b: i32) -> i32 {
|
||
a + b
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use internal_adder;
|
||
|
||
#[test]
|
||
fn internal() {
|
||
assert_eq!(4, internal_adder(2, 2));
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 11-6: Testing a private function</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>Because tests are just Rust code and the <code>tests</code> module is just another module,
|
||
we can import and call <code>internal_adder</code> in a test just fine. If you don't think
|
||
private functions should be tested, there's nothing in Rust that will compel
|
||
you to do so.</p>
|
||
<h3>Integration Tests</h3>
|
||
<p>In Rust, integration tests are tests that are entirely external to your
|
||
library. They use your library in the same way any other code would. Their
|
||
purpose is to test that many parts of your library work correctly together.
|
||
Units of code that work correctly by themselves could have problems when
|
||
integrated, so test coverage of the integrated code is important as well.</p>
|
||
<h4>The <em>tests</em> Directory</h4>
|
||
<p>Cargo has support for integration tests in the <em>tests</em> directory. If you make
|
||
one and put Rust files inside, Cargo will compile each of the files as an
|
||
individual crate. Let's give it a try!</p>
|
||
<p>First, make a <em>tests</em> directory at the top level of your project directory,
|
||
next to <em>src</em>. Then, make a new file, <em>tests/integration_test.rs</em>, and put the
|
||
code in Listing 11-7 inside:</p>
|
||
<figure>
|
||
<span class="filename">Filename: tests/integration_test.rs</span>
|
||
<pre><code class="language-rust,ignore">extern crate adder;
|
||
|
||
#[test]
|
||
fn it_adds_two() {
|
||
assert_eq!(4, adder::add_two(2));
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 11-7: An integration test of a function in the <code>adder</code> crate</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>We now have <code>extern crate adder</code> at the top, which we didn't need in the unit
|
||
tests. Each test in the <code>tests</code> directory is an entirely separate crate, so we
|
||
need to import our library into each of them. This is also why <code>tests</code> is a
|
||
suitable place to write integration-style tests: they use the library like any
|
||
other consumer of it would, by importing the crate and using only the public
|
||
API.</p>
|
||
<p>We also don't need a <code>tests</code> module in this file. The whole directory won't be
|
||
compiled unless we're running the tests, so we don't need to annotate any part
|
||
of it with <code>#[cfg(test)]</code>. Also, each test file is already isolated into its
|
||
own crate, so we don't need to separate the test code further.</p>
|
||
<p>Let's run the integration tests, which also get run when we run <code>cargo test</code>:</p>
|
||
<pre><code class="language-text">$ cargo test
|
||
Compiling adder v0.1.0 (file:///projects/adder)
|
||
Running target/debug/deps/adder-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>
|
||
<h4>Submodules in Integration Tests</h4>
|
||
<p>As you add more integration tests, you may want to make more than one file in
|
||
the <code>tests</code> directory in order to group the test functions by the functionality
|
||
they're testing, for example. As we mentioned before, that will work fine,
|
||
given that Cargo treats every file as its own crate.</p>
|
||
<p>Eventually, you may have a set of helper functions that are common to all
|
||
integration tests, for example, functions that set up common scenarios. If you
|
||
extract these into a file in the <em>tests</em> directory, like <em>tests/common.rs</em> for
|
||
example, this file will be compiled into a separate crate just like the Rust
|
||
files in this directory that contain test functions are. There will be a
|
||
separate section in the test output for this file. Since this is probably not
|
||
what you want, it's recommended to instead use a <em>mod.rs</em> file in a
|
||
subdirectory, like <em>tests/common/mod.rs</em>, for helper functions. Files in
|
||
subdirectories of the <em>tests</em> directory do not get compiled as separate crates
|
||
or have sections in the test output.</p>
|
||
<h4>Integration Tests for Binary Crates</h4>
|
||
<p>If your project is a binary crate that only contains a <em>src/main.rs</em> and does
|
||
not have a <em>src/lib.rs</em>, it is not possible to create integration tests in the
|
||
<em>tests</em> directory and use <code>extern crate</code> to import the functions in
|
||
<em>src/main.rs</em>. This is one of the reasons Rust projects that provide a binary
|
||
have a straightforward <em>src/main.rs</em> that calls logic that lives in
|
||
<em>src/lib.rs</em>. With that structure, integration tests <em>can</em> test the library
|
||
crate by using <code>extern crate</code> to cover the important functionality, and if that
|
||
works, the small amount of code in <em>src/main.rs</em> will work as well and does not
|
||
need to be tested.</p>
|
||
<h2>Summary</h2>
|
||
<p>Rust's testing features provide a way to specify how code should function to
|
||
ensure the code continues to work in the specified ways even as we make
|
||
changes. Unit tests exercise different parts of a library separately and can
|
||
test private implementation details. Integration tests cover the use of many
|
||
parts of the library working together, and use the library's public API to test
|
||
the code in the same way other code will use it. Rust's type system and
|
||
ownership rules help prevent some kinds of bugs, but tests are an important
|
||
part of reducing logic bugs having to do with how your code is expected to
|
||
behave.</p>
|
||
<p>Let's put together the knowledge from this chapter and other previous chapters
|
||
and work on a project in the next chapter!</p>
|
||
<h1>An I/O Project</h1>
|
||
<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 "Globally search a Regular Expression and Print." In the
|
||
simplest use case, it does this:</p>
|
||
<ul>
|
||
<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>
|
||
</ul>
|
||
<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>
|
||
<h2>Accepting Command Line Arguments</h2>
|
||
<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 16 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<String> = env::args().collect();
|
||
println!("{:?}", 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
|
||
["target/debug/greprs"]
|
||
|
||
$ cargo run needle haystack
|
||
...snip...
|
||
["target/debug/greprs", "needle", "haystack"]
|
||
</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<String> = env::args().collect();
|
||
|
||
let search = &args[1];
|
||
let filename = &args[2];
|
||
|
||
println!("Searching for {}", search);
|
||
println!("In file {}", 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>
|
||
<h2>Reading a File</h2>
|
||
<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<String> = env::args().collect();
|
||
|
||
let search = &args[1];
|
||
let filename = &args[2];
|
||
|
||
println!("Searching for {}", search);
|
||
println!("In file {}", filename);
|
||
|
||
let mut f = File::open(filename).expect("file not found");
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
|
||
println!("With text:\n{}", 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>
|
||
<h2>Improving Error Handling and Modularity</h2>
|
||
<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 "file
|
||
not found". 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>
|
||
<h3>Separation of Concerns for Binary Projects</h3>
|
||
<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<String> = env::args().collect();
|
||
|
||
let (search, filename) = parse_config(&args);
|
||
|
||
println!("Searching for {}", search);
|
||
println!("In file {}", filename);
|
||
|
||
// ...snip...
|
||
#
|
||
# let mut f = File::open(filename).expect("file not found");
|
||
#
|
||
# let mut contents = String::new();
|
||
# f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
#
|
||
# println!("With text:\n{}", contents);
|
||
}
|
||
|
||
fn parse_config(args: &[String]) -> (&str, &str) {
|
||
let search = &args[1];
|
||
let filename = &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>
|
||
<h3>Grouping Configuration Values</h3>
|
||
<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<String> = env::args().collect();
|
||
|
||
let config = parse_config(&args);
|
||
|
||
println!("Searching for {}", config.search);
|
||
println!("In file {}", config.filename);
|
||
|
||
let mut f = File::open(config.filename).expect("file not found");
|
||
|
||
// ...snip...
|
||
# let mut contents = String::new();
|
||
# f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
#
|
||
# println!("With text:\n{}", contents);
|
||
}
|
||
|
||
struct Config {
|
||
search: String,
|
||
filename: String,
|
||
}
|
||
|
||
fn parse_config(args: &[String]) -> 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>
|
||
<h4>The Tradeoffs of Using <code>clone</code></h4>
|
||
<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>
|
||
<h3>Creating a Constructor for <code>Config</code></h3>
|
||
<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<String> = env::args().collect();
|
||
|
||
let config = Config::new(&args);
|
||
|
||
println!("Searching for {}", config.search);
|
||
println!("In file {}", config.filename);
|
||
|
||
// ...snip...
|
||
|
||
# let mut f = File::open(config.filename).expect("file not found");
|
||
#
|
||
# let mut contents = String::new();
|
||
# f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
#
|
||
# println!("With text:\n{}", contents);
|
||
|
||
}
|
||
|
||
# struct Config {
|
||
# search: String,
|
||
# filename: String,
|
||
# }
|
||
#
|
||
// ...snip...
|
||
|
||
impl Config {
|
||
fn new(args: &[String]) -> 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>
|
||
<h3>Returning a <code>Result</code> from the Constructor</h3>
|
||
<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<String> = env::args().collect();
|
||
#
|
||
# let config = Config::new(&args);
|
||
#
|
||
# println!("Searching for {}", config.search);
|
||
# println!("In file {}", config.filename);
|
||
#
|
||
# let mut f = File::open(config.filename).expect("file not found");
|
||
#
|
||
# let mut contents = String::new();
|
||
# f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
#
|
||
# println!("With text:\n{}", contents);
|
||
# }
|
||
#
|
||
# struct Config {
|
||
# search: String,
|
||
# filename: String,
|
||
# }
|
||
#
|
||
# impl Config {
|
||
// ...snip...
|
||
fn new(args: &[String]) -> Config {
|
||
if args.len() < 3 {
|
||
panic!("not enough arguments");
|
||
}
|
||
|
||
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<String> = env::args().collect();
|
||
#
|
||
# let config = Config::new(&args).unwrap_or_else(|err| {
|
||
# println!("Problem parsing arguments: {}", err);
|
||
# process::exit(1);
|
||
# });
|
||
#
|
||
# println!("Searching for {}", config.search);
|
||
# println!("In file {}", config.filename);
|
||
#
|
||
# let mut f = File::open(config.filename).expect("file not found");
|
||
#
|
||
# let mut contents = String::new();
|
||
# f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
#
|
||
# println!("With text:\n{}", contents);
|
||
# }
|
||
# struct Config {
|
||
# search: String,
|
||
# filename: String,
|
||
# }
|
||
#
|
||
impl Config {
|
||
fn new(args: &[String]) -> Result<Config, &'static str> {
|
||
if args.len() < 3 {
|
||
return Err("not enough arguments");
|
||
}
|
||
|
||
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>&'static str</code> when an error happens. Recall from "The
|
||
Static Lifetime" section in Chapter 10 <code>&'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>
|
||
<h3>Calling <code>Config::new</code> and Handling Errors</h3>
|
||
<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<String> = env::args().collect();
|
||
|
||
let config = Config::new(&args).unwrap_or_else(|err| {
|
||
println!("Problem parsing arguments: {}", err);
|
||
process::exit(1);
|
||
});
|
||
|
||
println!("Searching for {}", config.search);
|
||
println!("In file {}", config.filename);
|
||
|
||
// ...snip...
|
||
#
|
||
# let mut f = File::open(config.filename).expect("file not found");
|
||
#
|
||
# let mut contents = String::new();
|
||
# f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
#
|
||
# println!("With text:\n{}", contents);
|
||
# }
|
||
#
|
||
# struct Config {
|
||
# search: String,
|
||
# filename: String,
|
||
# }
|
||
#
|
||
# impl Config {
|
||
# fn new(args: &[String]) -> Result<Config, &'static str> {
|
||
# if args.len() < 3 {
|
||
# return Err("not enough arguments");
|
||
# }
|
||
#
|
||
# 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<T, E></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 argument <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>
|
||
<h3>Handling Errors from the <code>run</code> Function</h3>
|
||
<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<String> = env::args().collect();
|
||
#
|
||
# let config = Config::new(&args).unwrap_or_else(|err| {
|
||
# println!("Problem parsing arguments: {}", err);
|
||
# process::exit(1);
|
||
# });
|
||
// ...snip...
|
||
|
||
println!("Searching for {}", config.search);
|
||
println!("In file {}", config.filename);
|
||
|
||
run(config);
|
||
}
|
||
|
||
fn run(config: Config) {
|
||
let mut f = File::open(config.filename).expect("file not found");
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents).expect("something went wrong reading the file");
|
||
|
||
println!("With text:\n{}", contents);
|
||
}
|
||
|
||
// ...snip...
|
||
#
|
||
# struct Config {
|
||
# search: String,
|
||
# filename: String,
|
||
# }
|
||
#
|
||
# impl Config {
|
||
# fn new(args: &[String]) -> Result<Config, &'static str> {
|
||
# if args.len() < 3 {
|
||
# return Err("not enough arguments");
|
||
# }
|
||
#
|
||
# 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<T, E></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<String> = env::args().collect();
|
||
#
|
||
# let config = Config::new(&args).unwrap_or_else(|err| {
|
||
# println!("Problem parsing arguments: {}", err);
|
||
# process::exit(1);
|
||
# });
|
||
#
|
||
# println!("Searching for {}", config.search);
|
||
# println!("In file {}", config.filename);
|
||
#
|
||
# run(config);
|
||
#
|
||
# }
|
||
|
||
fn run(config: Config) -> Result<(), Box<Error>> {
|
||
let mut f = File::open(config.filename)?;
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents)?;
|
||
|
||
println!("With text:\n{}", contents);
|
||
|
||
Ok(())
|
||
}
|
||
#
|
||
# struct Config {
|
||
# search: String,
|
||
# filename: String,
|
||
# }
|
||
#
|
||
# impl Config {
|
||
# fn new(args: &[String]) -> Result<Config, &'static str> {
|
||
# if args.len() < 3 {
|
||
# return Err("not enough arguments");
|
||
# }
|
||
#
|
||
# 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<(), Box<Error>></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<Error></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<Error></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
|
||
--> 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!("Searching for {}", config.search);
|
||
println!("In file {}", config.filename);
|
||
|
||
if let Err(e) = run(config) {
|
||
println!("Application error: {}", e);
|
||
|
||
process::exit(1);
|
||
}
|
||
}
|
||
|
||
fn run(config: Config) -> Result<(), Box<Error>> {
|
||
let mut f = File::open(config.filename)?;
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents)?;
|
||
|
||
println!("With text:\n{}", 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>
|
||
<h3>Split Code into a Library Crate</h3>
|
||
<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: &[String]) -> Result<Config, &'static str> {
|
||
if args.len() < 3 {
|
||
return Err("not enough arguments");
|
||
}
|
||
|
||
let search = args[1].clone();
|
||
let filename = args[2].clone();
|
||
|
||
Ok(Config {
|
||
search: search,
|
||
filename: filename,
|
||
})
|
||
}
|
||
}
|
||
|
||
pub fn run(config: Config) -> Result<(), Box<Error>>{
|
||
let mut f = File::open(config.filename)?;
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents)?;
|
||
|
||
println!("With text:\n{}", 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<String> = env::args().collect();
|
||
|
||
let config = Config::new(&args).unwrap_or_else(|err| {
|
||
println!("Problem parsing arguments: {}", err);
|
||
process::exit(1);
|
||
});
|
||
|
||
println!("Searching for {}", config.search);
|
||
println!("In file {}", config.filename);
|
||
|
||
if let Err(e) = greprs::run(config) {
|
||
println!("Application error: {}", 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>
|
||
<h2>Testing the Library's Functionality</h2>
|
||
<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<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
|
||
vec![]
|
||
}
|
||
|
||
pub fn run(config: Config) -> Result<(), Box<Error>>{
|
||
let mut f = File::open(config.filename)?;
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents)?;
|
||
|
||
grep(&config.search, &contents);
|
||
|
||
Ok(())
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod test {
|
||
use grep;
|
||
|
||
#[test]
|
||
fn one_result() {
|
||
let search = "duct";
|
||
let contents = "\
|
||
Rust:
|
||
safe, fast, productive.
|
||
Pick three.";
|
||
|
||
assert_eq!(
|
||
vec!["safe, fast, productive."],
|
||
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> argument and the return value. Remember,
|
||
lifetime parameters are used to specify which arguments' 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 argument <code>contents</code>, as opposed to referencing slices of the argument
|
||
<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> argument. 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
|
||
--> src\lib.rs:37:46
|
||
|
|
||
37 | fn grep(search: &str, contents: &str) -> Vec<&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 `search` or
|
||
`contents`
|
||
</code></pre>
|
||
<p>Rust can't possibly know which of the two arguments we need, so it needs us to
|
||
tell it. Because <code>contents</code> is the argument 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
|
||
argument that should be connected to the return value using the lifetime syntax.</p>
|
||
<p>Connecting arguments 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: `["safe, fast, productive."]`, 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<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
|
||
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<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
|
||
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:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
|
||
let mut results = Vec::new();
|
||
|
||
for line in contents.lines() {
|
||
if line.contains(search) {
|
||
results.push(line);
|
||
}
|
||
}
|
||
|
||
results
|
||
}
|
||
</code></pre>
|
||
<!-- 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) -> Result<(), Box<Error>> {
|
||
let mut f = File::open(config.filename)?;
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents)?;
|
||
|
||
for line in grep(&config.search, &contents) {
|
||
println!("{}", 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>
|
||
<h2>Working with Environment Variables</h2>
|
||
<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>
|
||
<h3>Implement and Test a Case-Insensitive <code>grep</code> Function</h3>
|
||
<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 = "duct";
|
||
let contents = "\
|
||
Rust:
|
||
safe, fast, productive.
|
||
Pick three.
|
||
Duct tape.";
|
||
|
||
assert_eq!(
|
||
vec!["safe, fast, productive."],
|
||
grep(search, contents)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn case_insensitive() {
|
||
let search = "rust";
|
||
let contents = "\
|
||
Rust:
|
||
safe, fast, productive.
|
||
Pick three.
|
||
Trust me.";
|
||
|
||
assert_eq!(
|
||
vec!["Rust:", "Trust me."],
|
||
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:</p>
|
||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||
<pre><code class="language-rust">fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
|
||
let search = search.to_lowercase();
|
||
let mut results = Vec::new();
|
||
|
||
for line in contents.lines() {
|
||
if line.to_lowercase().contains(&search) {
|
||
results.push(line);
|
||
}
|
||
}
|
||
|
||
results
|
||
}
|
||
</code></pre>
|
||
<!-- 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) -> Result<(), Box<Error>>{
|
||
let mut f = File::open(config.filename)?;
|
||
|
||
let mut contents = String::new();
|
||
f.read_to_string(&mut contents)?;
|
||
|
||
let results = if config.case_sensitive {
|
||
grep(&config.search, &contents)
|
||
} else {
|
||
grep_case_insensitive(&config.search, &contents)
|
||
};
|
||
|
||
for line in results {
|
||
println!("{}", 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: &[String]) -> Result<Config, &'static str> {
|
||
if args.len() < 3 {
|
||
return Err("not enough arguments");
|
||
}
|
||
|
||
let search = args[1].clone();
|
||
let filename = args[2].clone();
|
||
|
||
let mut case_sensitive = true;
|
||
|
||
for (name, _) in env::vars() {
|
||
if name == "CASE_INSENSITIVE" {
|
||
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>
|
||
<h2>Write to <code>stderr</code> Instead of <code>stdout</code></h2>
|
||
<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: "standard out" is
|
||
used for most information, but "standard error" is used for error messages. This
|
||
makes it easier to do things like "Print error messages to my terminal, but
|
||
write other output to a file."</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>></code> on the command line, and running our program
|
||
without any arguments, which causes an error:</p>
|
||
<pre><code class="language-text">$ cargo run > output.txt
|
||
</code></pre>
|
||
<p>The <code>></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-15:</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<String> = env::args().collect();
|
||
|
||
let config = Config::new(&args).unwrap_or_else(|err| {
|
||
writeln!(
|
||
&mut stderr,
|
||
"Problem parsing arguments: {}",
|
||
err
|
||
).expect("Could not write to stderr");
|
||
|
||
process::exit(1);
|
||
});
|
||
|
||
if let Err(e) = greprs::run(config) {
|
||
|
||
writeln!(
|
||
&mut stderr,
|
||
"Application error: {}",
|
||
e
|
||
).expect("Could not write to stderr");
|
||
|
||
process::exit(1);
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 12-15: 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>></code>:</p>
|
||
<pre><code class="language-text">$ cargo run > 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 > 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>
|
||
<h2>Summary</h2>
|
||
<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>
|
||
<h1>Functional Language features in Rust - Iterators and Closures</h1>
|
||
<h2>Closures</h2>
|
||
<h3>What is a closure</h3>
|
||
<p>How are they diff from fns</p>
|
||
<h3><code>Fn</code> traits</h3>
|
||
<h2>Iterators</h2>
|
||
<h3>Iterator & for loop</h3>
|
||
<p>.into_iter()</p>
|
||
<h3>Iterators are Lazy</h3>
|
||
<p>Difference between adapter and consumer - another iterator or consuming?</p>
|
||
<h3>Implementing the Iterator trait</h3>
|
||
<p>Talk about using Associated Types here, foreshadow to advanced type systems
|
||
chapter about why this is a different thing than normal</p>
|
||
<h2>??? How does this improve the I/O project from Chapter 12</h2>
|
||
<p>Does this get woven into the above sections?</p>
|
||
<h2>Summary: Performance</h2>
|
||
<h3>Iterators compile down to ASM == for loop</h3>
|
||
<p>Most complicated chain of iterator functions that compile down to the same ASM as a for loop</p>
|
||
<h3>Representation: Closures are a Struct</h3>
|
||
<p>Closures don't have any further performance penalty over regular fn calls</p>
|
||
<h1>More about Cargo and Crates.io</h1>
|
||
<h2>Getting your project ready to be published on Crates.io</h2>
|
||
<p>(and publish itself)</p>
|
||
<h3>Metadata in your Cargo.toml</h3>
|
||
<h3>Versions</h3>
|
||
<ul>
|
||
<li>yank</li>
|
||
</ul>
|
||
<h3><code>pub use</code></h3>
|
||
<h3>Doc Comments</h3>
|
||
<h2>Release profiles</h2>
|
||
<h2>Cargo Workspaces</h2>
|
||
<h2><code>cargo install</code> and Cargo Extensions</h2>
|
||
<h1>Smart Pointers</h1>
|
||
<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>
|
||
<h2><code>Box<T></code></h2>
|
||
<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>
|
||
<h2><code>Rc<T></code></h2>
|
||
<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<T> {
|
||
data: Box<T>,
|
||
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>
|
||
<h3>Rc Cycles</h3>
|
||
<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>
|
||
<h4>Solution: turn an Rc into a <code>Weak<T></code></h4>
|
||
<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.</p>
|
||
<p>Why is the weak count needed then????</p>
|
||
<h2><code>RefCell<T></code></h2>
|
||
<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>
|
||
<h3><code>borrow</code> and <code>borrow_mut</code> methods</h3>
|
||
<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>
|
||
<h2><code>Cell<T></code></h2>
|
||
<p>Same thing as RefCell but for types that are Copy. No borrow checking rules here
|
||
anyway. So just reason #2 above.</p>
|
||
<h2>Is this really safe? Yes!</h2>
|
||
<p>RefCell is still doing the checks, just at runtime
|
||
Cell is safe bc Copy types don't need the ownership rules anyway</p>
|
||
<h3>The Interior Mutability Pattern</h3>
|
||
<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<T></code> maybe. Affects optimizations since &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>
|
||
<h2>Summary</h2>
|
||
<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>
|
||
<h1>Fearless Concurrency</h1>
|
||
<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 "shared" aspect) enable fearless concurrency: the
|
||
compiler is making sure you don't shoot yourself in your foot.</p>
|
||
<h2>What are threads</h2>
|
||
<h2>Rust's concurrency tradeoffs</h2>
|
||
<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>
|
||
<h2>Let's get a thread: <code>thread::spawn</code></h2>
|
||
<p>Code examples - just print stuff, no data sharing</p>
|
||
<h2>Communicating between threads</h2>
|
||
<h3><code>Channels</code></h3>
|
||
<p>Look up examples of cases where channels are useful</p>
|
||
<p>Can match modeling of certain problems</p>
|
||
<h4><code>Send</code></h4>
|
||
<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>
|
||
<h2>Sharing data between threads</h2>
|
||
<p>Try to share data and get an error about which trait it doesn't implement</p>
|
||
<h3><code>Sync</code></h3>
|
||
<p>It's ok to access a thing from multiple threads at once</p>
|
||
<p>Immutable things can be sync easily.</p>
|
||
<h3><code>Arc<T></code></h3>
|
||
<p>Atomic Reference Counting. Inner data still has to be immutable.</p>
|
||
<p>Steve knows the motivating code that goes here.</p>
|
||
<h3><code>Mutex<T></code></h3>
|
||
<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>
|
||
<h2>Maybe make the I/O project concurrent?</h2>
|
||
<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>. "that paper" 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>
|
||
<h2>Arc</h2>
|
||
<p>Check out <a href="http://stackoverflow.com/a/40985661/51683">this awesome explanation of <code>Arc</code></a>.</p>
|
||
<h1>Is Rust OOP?</h1>
|
||
<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>
|
||
<h2>Command pattern</h2>
|
||
<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 "we want a thing that has a run function"? 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>
|
||
<h2>Supertraits</h2>
|
||
<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>
|
||
<h2>Trait objects</h2>
|
||
<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>
|
||
<h3>Implementation details</h3>
|
||
<ul>
|
||
<li>Like how other languages implement oo.</li>
|
||
</ul>
|
||
<h3>How to use it</h3>
|
||
<ul>
|
||
<li>Statically checked duck typing</li>
|
||
</ul>
|
||
<h2>Builder pattern</h2>
|
||
<p>When you don't know how many arguments you're going to have</p>
|
||
<h2>Delegation</h2>
|
||
<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>
|
||
<h2>How do you share data?</h2>
|
||
<p>Answer: get and set methods, this is awkward and might get better someday.</p>
|
||
<h1>Patterns</h1>
|
||
<p>We've actually used patterns a few times so far: they're used in <code>let</code>
|
||
statements, in function arguments, and in the <code>match</code> expression. Patterns have
|
||
a lot more abilities than we have demonstrated so far, so we'll cover some of
|
||
the most commonly used ones in this section. Any of these abilities work in any
|
||
place where a pattern is used.</p>
|
||
<h2><code>let</code> statements</h2>
|
||
<p>A basic <code>let</code> statement has this form:</p>
|
||
<pre><code class="language-text">let PATTERN = EXPRESSION;
|
||
</code></pre>
|
||
<p>We've seen statements like <code>let x = 5;</code> with a variable name in the <code>PATTERN</code>
|
||
slot; a variable name is just a particularly humble form of pattern.</p>
|
||
<p>Let’s try a more complex pattern. Change our example program to this:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let (x, y) = (5, 6);
|
||
|
||
println!("The value of x is: {}", x);
|
||
println!("The value of y is: {}", 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>
|
||
<h2>Type annotations</h2>
|
||
<p>Most of the time, Rust uses <em>type inference</em>, meaning that it attempts to infer
|
||
the types of your variables rather than you having to declare them explicitly
|
||
even though Rust is a statically typed language. Occasionally, Rust won't have
|
||
enough information to infer the type of your value, and you will need to add a
|
||
type annotation in with the pattern.</p>
|
||
<p>Here’s what a <code>let</code> statement with a <em>type annotation</em> looks like:</p>
|
||
<pre><code class="language-rust">let x: i32 = 5;
|
||
</code></pre>
|
||
<p>We can add a colon, followed by the type name. Here’s the structure of a <code>let</code>
|
||
statement with a type annotation:</p>
|
||
<pre><code class="language-text">let PATTERN: TYPE = VALUE;
|
||
</code></pre>
|
||
<p>Note that the colon and the <code>TYPE</code> go <em>after</em> the <code>PATTERN</code>, not in the pattern
|
||
itself. As an example, here’s our more complex pattern with two variables:</p>
|
||
<pre><code class="language-rust">let (x, y): (i32, i32) = (5, 6);
|
||
</code></pre>
|
||
<p>Just like we match up the <code>VALUE</code> with the <code>PATTERN</code>, we match up the <code>TYPE</code>
|
||
with the <code>PATTERN</code>.</p>
|
||
<h2>Literals & _</h2>
|
||
<p>You can match against literals directly, and <code>_</code> acts as an any case:</p>
|
||
<pre><code class="language-rust">let x = 1;
|
||
|
||
match x {
|
||
1 => println!("one"),
|
||
2 => println!("two"),
|
||
3 => println!("three"),
|
||
_ => println!("anything"),
|
||
}
|
||
</code></pre>
|
||
<p>This prints <code>one</code>.</p>
|
||
<h1>Multiple patterns</h1>
|
||
<p>You can match multiple patterns with <code>|</code>:</p>
|
||
<pre><code class="language-rust">let x = 1;
|
||
|
||
match x {
|
||
1 | 2 => println!("one or two"),
|
||
3 => println!("three"),
|
||
_ => println!("anything"),
|
||
}
|
||
</code></pre>
|
||
<p>This prints <code>one or two</code>.</p>
|
||
<h2>ref and ref mut</h2>
|
||
<p>Usually, when you match against a pattern, variables are bound to a value.
|
||
This means you'll end up moving the value into the <code>match</code>:</p>
|
||
<pre><code class="language-rust,ignore">let name = Some(String::from("Bors"));
|
||
|
||
match name {
|
||
Some(name) => println!("Found a name: {}", name),
|
||
None => (),
|
||
}
|
||
|
||
// name is moved here. This line will fail to compile:
|
||
println!("name is: {:?}", 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("Bors"));
|
||
|
||
match name {
|
||
Some(ref name) => println!("Found a name: {}", name),
|
||
None => (),
|
||
}
|
||
|
||
// name is not moved here; the match only took a reference to its data rather
|
||
// than moving it. This will work:
|
||
println!("name is: {:?}", 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("Bors"));
|
||
|
||
match name {
|
||
Some(ref mut name) => *name = String::from("Another name"),
|
||
None => (),
|
||
}
|
||
|
||
// name is not moved here; the match only took a reference to its data rather
|
||
// than moving it
|
||
println!("name is: {:?}", name);
|
||
</code></pre>
|
||
<h2>Destructuring</h2>
|
||
<p>Patterns can be used to destructure structs and enums:</p>
|
||
<pre><code class="language-rust">struct Point {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
|
||
let origin = Point { x: 0, y: 0 };
|
||
|
||
let Point { x, y } = origin;
|
||
</code></pre>
|
||
<p>This brings <code>x</code> and <code>y</code> variables into scope, matching the <code>x</code> and <code>y</code> of
|
||
<code>origin</code>. While it can be unusual in <code>let</code>, this is the same principle of
|
||
patterns in <code>match</code>:</p>
|
||
<pre><code class="language-rust">struct Point {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
|
||
let origin = Point { x: 0, y: 0 };
|
||
|
||
match origin {
|
||
Point { x, y } => { }, // variables x and y are created here
|
||
}
|
||
</code></pre>
|
||
<h2>Shadowing</h2>
|
||
<p>As with all variables, those declared by a pattern will shadow variables
|
||
outside of the <code>match</code> construct:</p>
|
||
<pre><code class="language-rust">let x = Some(5);
|
||
|
||
match x {
|
||
Some(x) => { }, // x is an i32 here, not an Option<i32>
|
||
None => (),
|
||
}
|
||
</code></pre>
|
||
<h2>Ignoring values</h2>
|
||
<p>We discussed using <code>_</code> as a whole pattern to ignore it above, but you can
|
||
also use <code>_</code> inside of another pattern to ignore just part of it:</p>
|
||
<pre><code class="language-rust">let x = Some(5);
|
||
|
||
match x {
|
||
Some(_) => println!("got a Some and I don't care what's inside"),
|
||
None => (),
|
||
}
|
||
</code></pre>
|
||
<p>Or like this:</p>
|
||
<pre><code class="language-rust">let numbers = (2, 4, 8, 16, 32);
|
||
|
||
match numbers {
|
||
(first, _, third, _, fifth) => println!("Some numbers: {}, {}, {}", 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, .. } => { }, // y and z are ignored
|
||
}
|
||
</code></pre>
|
||
<h2>Ranges</h2>
|
||
<p>You can match a range of values with <code>...</code>:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
|
||
match x {
|
||
1 ... 5 => println!("one through five"),
|
||
_ => println!("something else"),
|
||
}
|
||
</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' => println!("early ASCII letter"),
|
||
'k' ... 'z' => println!("late ASCII letter"),
|
||
_ => println!("something else"),
|
||
}
|
||
</code></pre>
|
||
<h2>Guards</h2>
|
||
<p>You can introduce match guards with <code>if</code>:</p>
|
||
<pre><code class="language-rust">let x = Some(5);
|
||
|
||
match x {
|
||
Some(x) if x < 5 => println!("less than five: {}", x),
|
||
Some(x) => println!("{}", x),
|
||
None => (),
|
||
}
|
||
</code></pre>
|
||
<p>If youre 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 => println!("yes"),
|
||
_ => println!("no"),
|
||
}
|
||
</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 => ...
|
||
</code></pre>
|
||
<p>not this:</p>
|
||
<pre><code class="language-text">4 | (5 if y) => ...
|
||
</code></pre>
|
||
<h2>Bindings</h2>
|
||
<p>You can bind values to names with <code>@</code>:</p>
|
||
<h1>More Lifetimes</h1>
|
||
<h2>Lifetimes that depend on other lifetimes</h2>
|
||
<p>'a: 'b stuff: subtyping</p>
|
||
<h2>Higher ranked trait bounds</h2>
|
||
<p>for<'a></p>
|
||
<p>Needed for closures</p>
|
||
<h1>Advanced Type System Features</h1>
|
||
<h2>Unsafe Rust</h2>
|
||
<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>
|
||
<h3>Raw Pointers</h3>
|
||
<h3>Unsafe Functions</h3>
|
||
<h4><code>transmute</code></h4>
|
||
<p>never ever. don't. stop.</p>
|
||
<h4><code>extern fn</code></h4>
|
||
<p>You have to write unsafe code to FFI</p>
|
||
<h3><code>static</code></h3>
|
||
<h3>Unsafe Traits</h3>
|
||
<h2>Associated Types</h2>
|
||
<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>
|
||
<h2>The Thing Formerly Known as UFCS</h2>
|
||
<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>
|
||
<h2>Coherence</h2>
|
||
<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>
|
||
<h1>Appendix</h1>
|
||
<p>The following sections contain reference material you may find useful in your
|
||
Rust journey.</p>
|
||
<h2>Keywords</h2>
|
||
<p>The following keywords are reserved by the Rust language and may not be used as
|
||
names of functions, variables, macros, modules, crates, constants, static
|
||
values, attributes, struct fields, or arguments.</p>
|
||
<ul>
|
||
<li><code>abstract</code></li>
|
||
<li><code>alignof</code></li>
|
||
<li><code>as</code></li>
|
||
<li><code>become</code></li>
|
||
<li><code>box</code></li>
|
||
<li><code>break</code></li>
|
||
<li><code>const</code></li>
|
||
<li><code>continue</code></li>
|
||
<li><code>crate</code></li>
|
||
<li><code>do</code></li>
|
||
<li><code>else</code></li>
|
||
<li><code>enum</code></li>
|
||
<li><code>extern</code></li>
|
||
<li><code>false</code></li>
|
||
<li><code>final</code></li>
|
||
<li><code>fn</code></li>
|
||
<li><code>for</code></li>
|
||
<li><code>if</code></li>
|
||
<li><code>impl</code></li>
|
||
<li><code>in</code></li>
|
||
<li><code>let</code></li>
|
||
<li><code>loop</code></li>
|
||
<li><code>macro</code></li>
|
||
<li><code>match</code></li>
|
||
<li><code>mod</code></li>
|
||
<li><code>move</code></li>
|
||
<li><code>mut</code></li>
|
||
<li><code>offsetof</code></li>
|
||
<li><code>override</code></li>
|
||
<li><code>priv</code></li>
|
||
<li><code>proc</code></li>
|
||
<li><code>pub</code></li>
|
||
<li><code>pure</code></li>
|
||
<li><code>ref</code></li>
|
||
<li><code>return</code></li>
|
||
<li><code>Self</code></li>
|
||
<li><code>self</code></li>
|
||
<li><code>sizeof</code></li>
|
||
<li><code>static</code></li>
|
||
<li><code>struct</code></li>
|
||
<li><code>super</code></li>
|
||
<li><code>trait</code></li>
|
||
<li><code>true</code></li>
|
||
<li><code>type</code></li>
|
||
<li><code>typeof</code></li>
|
||
<li><code>unsafe</code></li>
|
||
<li><code>unsized</code></li>
|
||
<li><code>use</code></li>
|
||
<li><code>virtual</code></li>
|
||
<li><code>where</code></li>
|
||
<li><code>while</code></li>
|
||
<li><code>yield</code></li>
|
||
</ul>
|
||
<h2>Operators</h2>
|
||
<h3>Unary operator expressions</h3>
|
||
<p>Rust defines the following unary operators. They are all written as prefix
|
||
operators, before the expression they apply to.</p>
|
||
<ul>
|
||
<li><code>-</code>
|
||
: Negation. Signed integer types and floating-point types support negation. It
|
||
is an error to apply negation to unsigned types; for example, the compiler
|
||
rejects <code>-1u32</code>.</li>
|
||
<li><code>*</code>
|
||
: Dereference. When applied to a pointer, it denotes the pointed-to location.
|
||
For pointers to mutable locations, the resulting value can be assigned to.
|
||
On non-pointer types, it calls the <code>deref</code> method of the <code>std::ops::Deref</code>
|
||
trait, or the <code>deref_mut</code> method of the <code>std::ops::DerefMut</code> trait (if
|
||
implemented by the type and required for an outer expression that will or
|
||
could mutate the dereference), and produces the result of dereferencing the
|
||
<code>&</code> or <code>&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>&</code> and <code>&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>&</code>), this implies that the value may not be mutated, but
|
||
it may be read or shared again. For a mutable borrow (<code>&mut</code>), the
|
||
value may not be accessed in any way until the borrow expires.</li>
|
||
</ul>
|
||
<h3>Binary operator expressions</h3>
|
||
<p>Binary operators expressions are given in order of operator precedence.</p>
|
||
<h4>Arithmetic operators</h4>
|
||
<p>Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
|
||
defined in the <code>std::ops</code> module of the <code>std</code> library. This means arithmetic
|
||
operators can be overridden for user-defined types. The default meaning of the
|
||
operators on standard types is given here.</p>
|
||
<ul>
|
||
<li><code>+</code>
|
||
: Addition and array/string concatenation.
|
||
Calls the <code>add</code> method on the <code>std::ops::Add</code> trait.</li>
|
||
<li><code>-</code>
|
||
: Subtraction.
|
||
Calls the <code>sub</code> method on the <code>std::ops::Sub</code> trait.</li>
|
||
<li><code>*</code>
|
||
: Multiplication.
|
||
Calls the <code>mul</code> method on the <code>std::ops::Mul</code> trait.</li>
|
||
<li><code>/</code>
|
||
: Quotient.
|
||
Calls the <code>div</code> method on the <code>std::ops::Div</code> trait.</li>
|
||
<li><code>%</code>
|
||
: Remainder.
|
||
Calls the <code>rem</code> method on the <code>std::ops::Rem</code> trait.</li>
|
||
</ul>
|
||
<p>Note that Rust does not have a built-in operator for exponential (power)
|
||
calculation; see the <code>pow</code> method on the numeric types.</p>
|
||
<h4>Bitwise operators</h4>
|
||
<p>Like the arithmetic operators, bitwise operators are syntactic sugar for calls
|
||
to methods of built-in traits. This means bitwise operators can be overridden
|
||
for user-defined types. The default meaning of the operators on standard types
|
||
is given here. Bitwise <code>&</code>, <code>|</code> and <code>^</code> applied to boolean arguments are
|
||
equivalent to logical <code>&&</code>, <code>||</code> and <code>!=</code> evaluated in non-lazy fashion.</p>
|
||
<ul>
|
||
<li><code>&</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><<</code>
|
||
: Left shift.
|
||
Calls the <code>shl</code> method of the <code>std::ops::Shl</code> trait.</li>
|
||
<li><code>>></code>
|
||
: Right shift (arithmetic).
|
||
Calls the <code>shr</code> method of the <code>std::ops::Shr</code> trait.</li>
|
||
</ul>
|
||
<h4>Lazy boolean operators</h4>
|
||
<p>The operators <code>||</code> and <code>&&</code> may be applied to operands of boolean type. The
|
||
<code>||</code> operator denotes logical 'or', and the <code>&&</code> operator denotes logical
|
||
'and'. They differ from <code>|</code> and <code>&</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>&&</code> only when it evaluates to
|
||
<code>true</code>.</p>
|
||
<h4>Comparison operators</h4>
|
||
<p>Comparison operators are, like the arithmetic operators and bitwise operators,
|
||
syntactic sugar for calls to built-in traits. This means that comparison
|
||
operators can be overridden for user-defined types. The default meaning of the
|
||
operators on standard types is given here.</p>
|
||
<ul>
|
||
<li><code>==</code>
|
||
: Equal to.
|
||
Calls the <code>eq</code> method on the <code>std::cmp::PartialEq</code> trait.</li>
|
||
<li><code>!=</code>
|
||
: Unequal to.
|
||
Calls the <code>ne</code> method on the <code>std::cmp::PartialEq</code> trait.</li>
|
||
<li><code><</code>
|
||
: Less than.
|
||
Calls the <code>lt</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
|
||
<li><code>></code>
|
||
: Greater than.
|
||
Calls the <code>gt</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
|
||
<li><code><=</code>
|
||
: Less than or equal.
|
||
Calls the <code>le</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
|
||
<li><code>>=</code>
|
||
: Greater than or equal.
|
||
Calls the <code>ge</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
|
||
</ul>
|
||
<h4>Type cast expressions</h4>
|
||
<p>A type cast expression is denoted with the binary operator <code>as</code>.</p>
|
||
<p>Executing an <code>as</code> expression casts the value on the left-hand side to the type
|
||
on the right-hand side.</p>
|
||
<p>An example of an <code>as</code> expression:</p>
|
||
<pre><code class="language-rust"># fn sum(values: &[f64]) -> f64 { 0.0 }
|
||
# fn len(values: &[f64]) -> i32 { 0 }
|
||
|
||
fn average(values: &[f64]) -> 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 "harmless" conversions that
|
||
do not lose information and which have minimal or no risk of
|
||
surprising side-effects on the dynamic execution semantics.</p>
|
||
<h4>Assignment expressions</h4>
|
||
<p>An <em>assignment expression</em> consists of a pattern followed by an equals
|
||
sign (<code>=</code>) and an expression.</p>
|
||
<p>Evaluating an assignment expression either copies or
|
||
moves its right-hand operand to its left-hand
|
||
operand.</p>
|
||
<pre><code># let mut x = 0;
|
||
# let y = 0;
|
||
x = y;
|
||
</code></pre>
|
||
<h4>Compound assignment expressions</h4>
|
||
<p>The <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>&</code>, <code>|</code>, <code>^</code>, <code><<</code>, and <code>>></code> operators may be
|
||
composed with the <code>=</code> operator. The expression <code>lval OP= val</code> is equivalent to
|
||
<code>lval = lval OP val</code>. For example, <code>x = x + 1</code> may be written as <code>x += 1</code>.</p>
|
||
<p>Any such expression always has the <code>unit</code> type.</p>
|
||
<h4>Operator precedence</h4>
|
||
<p>The precedence of Rust binary operators is ordered as follows, going from
|
||
strong to weak:</p>
|
||
<pre><code class="language-text">as :
|
||
* / %
|
||
+ -
|
||
<< >>
|
||
&
|
||
^
|
||
|
|
||
== != < > <= >=
|
||
&&
|
||
||
|
||
.. ...
|
||
<-
|
||
=
|
||
</code></pre>
|
||
<p>Operators at the same precedence level are evaluated left-to-right. Unary
|
||
operators have the same precedence level and are stronger than any of the
|
||
binary operators.</p>
|
||
<h2>Derivable Traits</h2>
|
||
<h1>Nightly Rust</h1>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
|
||
|
||
|
||
</div>
|
||
|
||
|
||
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<!-- Local fallback for Font Awesome -->
|
||
<script>
|
||
if ($(".fa").css("font-family") !== "FontAwesome") {
|
||
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
||
}
|
||
</script>
|
||
|
||
<!-- Livereload script (if served using the cli tool) -->
|
||
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|