Files
book/print.html
T

5946 lines
299 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Rust Programming Language</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="favicon.png">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<!-- MathJax -->
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<!-- Fetch JQuery from CDN but have a local fallback -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
}
</script>
</head>
<body class="light">
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme = localStorage.getItem('theme');
if (theme == null) { theme = 'light'; }
$('body').removeClass().addClass(theme);
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var sidebar = localStorage.getItem('sidebar');
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
</script>
<div id="sidebar" class="sidebar">
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts-in-rust.html"><strong>3.</strong> Common Programming Concepts in Rust</a></li><li><ul class="section"><li><a href="ch03-01-variable-bindings-and-mutability.html"><strong>3.1.</strong> Variable Bindings 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-ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums</a></li><li><ul class="section"><li><a href="ch06-01-option.html"><strong>6.1.</strong> Option</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> Match</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-fundamental-collections.html"><strong>8.</strong> Fundamental Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><strong>9.</strong> Error Handling</li><li><strong>10.</strong> Generics</li><li><strong>11.</strong> Iterators</li><li><strong>12.</strong> I/O</li><li><ul class="section"><li><strong>12.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>12.2.</strong> <code>std::fs</code></li><li><strong>12.3.</strong> <code>std::path</code></li><li><strong>12.4.</strong> <code>std::env</code></li></ul></li><li><a href="chXX-patterns.html"><strong>13.</strong> Patterns</a></li><li><strong>14.</strong> Testing</li><li><strong>15.</strong> Debugging</li><li><strong>16.</strong> Composition</li><li><strong>17.</strong> Closures</li><li><strong>18.</strong> Zero-cost Abstractions</li><li><ul class="section"><li><strong>18.1.</strong> Iterators as a Case Study</li></ul></li><li><strong>19.</strong> Creating a Library</li><li><ul class="section"><li><strong>19.1.</strong> Cargo</li><li><strong>19.2.</strong> Crates.io</li><li><a href="chYY-YY-public-api.html"><strong>19.3.</strong> Organizing your Public API</a></li><li><a href="chYY-YY-documentation.html"><strong>19.4.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>19.5.</strong> Workspaces and Multiple Related Crates</a></li></ul></li><li><strong>20.</strong> Smart Pointers</li><li><ul class="section"><li><strong>20.1.</strong> <code>Deref</code></li><li><strong>20.2.</strong> <code>Deref</code> Coercions</li><li><strong>20.3.</strong> <code>Box&lt;T&gt;</code></li><li><strong>20.4.</strong> <code>Rc&lt;T&gt;</code></li></ul></li><li><strong>21.</strong> Concurrency</li><li><ul class="section"><li><strong>21.1.</strong> Threads</li><li><strong>21.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>21.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>21.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>21.5.</strong> <code>Channels</code></li></ul></li><li><strong>22.</strong> More Lifetimes</li><li><strong>23.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>23.1.</strong> Raw Pointers</li><li><strong>23.2.</strong> <code>transmute</code></li></ul></li><li><strong>24.</strong> FFI</li><li><ul class="section"><li><strong>24.1.</strong> Conditional Compilation</li><li><strong>24.2.</strong> Bindings to C</li><li><strong>24.3.</strong> Using Rust from Other Languages</li><li><strong>24.4.</strong> <code>static</code></li></ul></li><li><strong>25.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>25.1.</strong> Associated Types</li><li><strong>25.2.</strong> Trait Objects</li><li><strong>25.3.</strong> UFCS</li><li><strong>25.4.</strong> Coherence</li></ul></li><li><strong>26.</strong> Interior Mutability</li><li><ul class="section"><li><strong>26.1.</strong> <code>Cell&lt;T&gt;</code></li><li><strong>26.2.</strong> <code>RefCell&lt;T&gt;</code></li></ul></li><li><strong>27.</strong> Macros</li><li><strong>28.</strong> Nightly Rust</li><li><a href="appendix-00.html"><strong>29.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>29.1.</strong> Keywords</a></li><li><a href="appendix-02-derivable-traits.html"><strong>29.2.</strong> Derivable Traits</a></li></ul></li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar" class="menu-bar">
<div class="left-buttons">
<i id="sidebar-toggle" class="fa fa-bars"></i>
<i id="theme-toggle" class="fa fa-paint-brush"></i>
</div>
<h1 class="menu-title">The Rust Programming Language</h1>
<div class="right-buttons">
<i id="print-button" class="fa fa-print" title="Print this book"></i>
</div>
</div>
<div id="content" class="content">
<h1>Introduction</h1>
<p>Welcome to “The Rust Programming Language”, an introductory book about Rust.
Rust is a programming language that’s focused on safety, speed, and
concurrency. Its design lets you create programs that have the performance and
control of a low-level language, but with helpful abstractions that feel like a
high-level language. The Rust community welcomes all programmers who have their
experience in languages like C and are looking for a safer alternative, as well
as programmers from languages like Python who are looking for ways to write more
performant code without losing expressiveness.</p>
<p>Rust provides the majority of its safety checks at compile time and without a
garbage collector so that your program's runtime isn't impacted. This makes it
useful in a number of use cases that other languages aren’t good at: embedding
in other languages, programs with specific space and time requirements, and
writing low-level code, like device drivers and operating systems. It'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-bash">$ 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-bash">Rust is installed now. Great!
</code></pre>
<h3>Installing on Windows</h3>
<p>On Windows, go to <a href="https://rustup.rs/">https://rustup.rs</a><!-- ignore --> and
follow the instructions to download rustup-init.exe. Run that and follow the
rest of the instructions it gives you.</p>
<p>The rest of the Windows-specific commands in the book will assume that you are
using <code>cmd</code> as your shell. If you use a different shell, you may be able to run
the same commands that Linux and Mac users do. If neither work, consult the
documentation for the shell you are using.</p>
<h3>Custom installations</h3>
<p>If you have reasons for preferring not to use rustup.rs, please see <a href="https://www.rust-lang.org/install.html">the Rust
installation page</a> for other options.</p>
<h3>Uninstalling</h3>
<p>Uninstalling Rust is as easy as installing it. From your shell, run
the uninstall script:</p>
<pre><code class="language-bash">$ 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-bash">$ 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-bash">rustc x.y.z (abcabcabc yyyy-mm-dd)
</code></pre>
<p>If you see this, Rust has been installed successfully!
Congrats!</p>
<p>If you don't and you're on Windows, check that Rust is in your <code>%PATH%</code> system
variable.</p>
<p>If it still isn't working, there are a number of places where you can get help.
The easiest is <a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a><!-- ignore -->,
which you can access through <a href="http://chat.mibbit.com/?server=irc.mozilla.org&amp;channel=%23rust">Mibbit</a>. Go to that address, and you'll
be chatting with other Rustaceans (a silly nickname we call ourselves) who can
help you out. Other great resources include <a href="https://users.rust-lang.org/">the user’s forum</a> and
<a href="http://stackoverflow.com/questions/tagged/rust">Stack Overflow</a>.</p>
<h3>Local documentation</h3>
<p>The installer also includes a copy of the documentation locally, so you can
read it offline. Run <code>rustup doc</code> to open the local documentation in your
browser.</p>
<p>Any time there's a type or function provided by the standard library and you're
not sure what it does, use the API documentation to find out!</p>
<h2>Hello, World!</h2>
<p>Now that you have Rust installed, let’s write your first Rust program. It's
traditional when learning a new language to write a little program to print the
text “Hello, world!” to the screen, and in this section, we'll follow that
tradition.</p>
<blockquote>
<p>Note: This book assumes basic familiarity with the command line. Rust itself
makes no specific demands about your editing, tooling, or where your code
lives, so if you prefer an IDE to the command line, feel free to use your
favorite IDE.</p>
</blockquote>
<h3>Creating a Project File</h3>
<p>First, make a file to put your Rust code in. Rust doesn't care where your code
lives, but for this book, we'd suggest making a <em>projects</em> directory in your
home directory and keeping all your projects there. Open a terminal and enter
the following commands to make a directory for this particular project:</p>
<p>Linux and Mac:</p>
<pre><code class="language-bash">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<p>Windows:</p>
<pre><code class="language-cmd">&gt; mkdir %USERPROFILE%\projects
&gt; cd %USERPROFILE%\projects
&gt; mkdir hello_world
&gt; cd hello_world
</code></pre>
<h3>Writing and Running a Rust Program</h3>
<p>Next, make a new source file and call it <code>main.rs</code>. Rust files always end with
the <code>.rs</code> extension. If you’re using more than one word in your filename, use
an underscore to separate them. For example, you'd use <code>hello_world.rs</code> rather
than <code>helloworld.rs</code>.</p>
<p>Now open the <code>main.rs</code> file you just created, and type the following code:</p>
<p>Filename: main.rs</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Save the file, and go back to your terminal window. On Linux or OSX, enter the
following commands:</p>
<pre><code class="language-bash">$ rustc main.rs
$ ./main
Hello, world!
</code></pre>
<p>On Windows, just replace <code>./main</code> with <code>.\main.exe</code>. Regardless of your
operating system, you should see the string <code>Hello, world!</code> print to the
terminal. If you did, then congratulations! You've officially written a Rust
program. That makes you a Rust programmer! Welcome.</p>
<h3>Anatomy of a Rust Program</h3>
<p>Now, let’s go over what just happened in your &quot;Hello, world!&quot; program in
detail. Here's the first piece of the puzzle:</p>
<pre><code class="language-rust">fn main() {
}
</code></pre>
<p>These lines define a <em>function</em> in Rust. The <code>main</code> function is special: it's
the first thing that is run for every executable Rust program. The first line
says, “I’m declaring a function named <code>main</code> that takes no arguments and
returns nothing.” If there were arguments, they would go inside the parentheses,
<code>(</code> and <code>)</code>.</p>
<p>Also note that the function body is wrapped in curly braces, <code>{</code> and <code>}</code>. Rust
requires these around all function bodies. It's considered good style to put
the opening curly brace on the same line as the function declaration, with one
space in between.</p>
<p>Inside the <code>main</code> function:</p>
<pre><code class="language-rust"> println!(&quot;Hello, world!&quot;);
</code></pre>
<p>This line does all of the work in this little program: it prints text to the
screen. There are a number of details that are important here. The first is
that it’s indented 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 XX, but for now you just need to know
that when you see a <code>!</code> that means that you’re calling a macro instead of a
normal function.</p>
<p>Next is <code>&quot;Hello, world!&quot;</code> which is a <em>string</em>. We pass this string as an
argument to <code>println!</code>, which prints the string to the screen. Easy enough!</p>
<p>The line ends with a semicolon (<code>;</code>). The <code>;</code> indicates that this expression is
over, and the next one is ready to begin. Most lines of Rust code end with a
<code>;</code>.</p>
<h3>Compiling and Running Are Separate Steps</h3>
<p>In &quot;Writing and Running a Rust Program&quot;, we showed you how to run a newly
created program. We'll break that process down and examine each step now.</p>
<p>Before running a Rust program, you have to compile it. You can use the Rust
compiler by entering the <code>rustc</code> command and passing it the name of your source
file, like this:</p>
<pre><code class="language-bash">$ rustc main.rs
</code></pre>
<p>If you come from a C or C++ background, you'll notice that this is similar to
<code>gcc</code> or <code>clang</code>. After compiling successfully, Rust should output a binary
executable, which you can see on Linux or OSX by entering the <code>ls</code> command in
your shell as follows:</p>
<pre><code class="language-bash">$ ls
main main.rs
</code></pre>
<p>On Windows, you'd enter:</p>
<pre><code class="language-cmd">&gt; dir /B %= the /B option says to only show the file names =%
main.exe
main.rs
</code></pre>
<p>This shows we have two files: the source code, with the <code>.rs</code> extension, and the
executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else). All that's left to
do from here is run the <code>main</code> or <code>main.exe</code> file, like this:</p>
<pre><code class="language-bash">$ ./main # or .\main.exe on Windows
</code></pre>
<p>If <code>main.rs</code> were your &quot;Hello, world!&quot; program, this would print <code>Hello, world!</code> to your terminal.</p>
<p>If you come from a dynamic language like Ruby, Python, or JavaScript, you may
not be used to compiling and running a program being separate steps. Rust is an
<em>ahead-of-time compiled</em> language, which means that you can compile a program,
give it to someone else, and they can run it even without having Rust
installed. If you give someone a <code>.rb</code>, <code>.py</code>, or <code>.js</code> file, on the other
hand, they need to have a Ruby, Python, or JavaScript implementation installed
(respectively), but you only need one command to both compile and run your
program. Everything is a tradeoff in language design.</p>
<p>Just compiling with <code>rustc</code> is fine for simple programs, but as your project
grows, you'll want to be able to manage all of the options your project has
and make it easy to share your code with other people and projects. Next, we'll
introduce you to a tool called Cargo, which will help you write real-world Rust
programs.</p>
<h2>Hello, Cargo!</h2>
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
manage their Rust projects because it makes a lot of tasks easier. For example,
Cargo takes care of building your code, downloading the libraries your code
depends on, and building those libraries. We call libraries your code needs
<em>dependencies</em>.</p>
<p>The simplest Rust programs, like the one we've written so far, don’t have any
dependencies, so right now, you'd only be using the part of Cargo that can take
care of building your code. As you write more complex Rust programs, you’ll
want to add dependencies, and if you start off using Cargo, that will be a lot
easier to do.</p>
<p>As the vast, vast majority of Rust projects use Cargo, we will assume that
you’re using it for the rest of the book. Cargo comes installed with Rust
itself, if you used the official installers as covered in the Installation
chapter. If you installed Rust through some other means, you can check if you
have Cargo installed by typing the following into your terminal:</p>
<pre><code class="language-bash">$ 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-bash">$ cd ~/projects
</code></pre>
<p>Windows:</p>
<pre><code class="language-cmd">&gt; cd %USERPROFILE%\projects
</code></pre>
<p>And then on any operating system run:</p>
<pre><code class="language-bash">$ 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 <code>hello_cargo</code> directory, we can see that Cargo has
generated two files and one directory for us: a <code>Cargo.toml</code> and a <code>src</code>
directory with a <code>main.rs</code> file inside. It has also initialized a new <code>git</code>
repository in the <code>hello_cargo</code> directory for us, along with a <code>.gitignore</code>
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 <code>Cargo.toml</code> in your text editor of choice. It should look something
like this:</p>
<p>Filename: Cargo.toml</p>
<pre><code class="language-toml">[package]
name = &quot;hello_cargo&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]
[dependencies]
</code></pre>
<p>This file is in the <a href="https://github.com/toml-lang/toml"><em>TOML</em></a><!-- ignore --> (Tom's Obvious, Minimal
Language) format. TOML is similar to INI but has some extra goodies and is used
as Cargo’s configuration format.</p>
<p>The first line, <code>[package]</code>, is a section heading that indicates that the
following statements are configuring a package. As we add more information to
this file, we’ll add other sections.</p>
<p>The next three lines set the three bits of configuration that Cargo needs to
see in order to know that it should compile your program: its name, what
version it is, and who wrote it. Cargo gets your name and email information
from your environment. If it’s not correct, go ahead and fix that and save the
file.</p>
<p>The last line, <code>[dependencies]</code>, is the start of a section for you to list any
<em>crates</em> (which is what we call packages of Rust code) that your project will
depend on so that Cargo knows to download and compile those too. We won't need
any other crates for this project, but we will in the guessing game tutorial in
the next chapter.</p>
<p>Now let's look at <code>src/main.rs</code>:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Cargo has generated a &quot;Hello World!&quot; for you, just like the one we wrote
earlier! So that part is the same. The differences between our previous project
and the project generated by Cargo that we've seen so far are:</p>
<ul>
<li>Our code goes in the <code>src</code> directory</li>
<li>The top level contains a <code>Cargo.toml</code> configuration file</li>
</ul>
<p>Cargo expects your source files to live inside the <code>src</code> 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 <code>hello_world</code> directory, you can convert it to a project that does use
Cargo by moving your code into the <code>src</code> directory and creating an appropriate
<code>Cargo.toml</code>.</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-bash">$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
</code></pre>
<p>This should have created an executable file in <code>target/debug/hello_cargo</code> (or
<code>target\debug\hello_cargo.exe</code> on Windows), which you can run with this command:</p>
<pre><code class="language-bash">$ ./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 <code>Cargo.lock</code>, which looks like this:</p>
<p>Filename: Cargo.lock</p>
<pre><code class="language-toml">[root]
name = &quot;hello_cargo&quot;
version = &quot;0.1.0&quot;
</code></pre>
<p>Cargo uses the <code>Cargo.lock</code> file 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-bash">$ 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-bash">$ 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 <code>target/debug</code> 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 <code>target/release</code> instead of <code>target/debug</code>. 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 <code>target/release</code>.</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-bash">$ 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 with a hands-on project! This chapter will introduce you to
a few common Rust concepts by showing how you would use them in a real program.
You'll learn about <code>let</code>, <code>match</code>, methods, associated functions, using
external crates, and more! Following chapters will explore these ideas in more
detail; this chapter will get you practicing the fundamentals.</p>
<p>We’re going to implement a classic beginner programming problem: the guessing
game. Here’s how it works: Our program will generate a random integer between
one and a hundred. It will then prompt us to enter a guess. Upon entering our
guess, it will tell us if we’re too low or too high. Once we guess correctly,
it will congratulate us.</p>
<h2>Setting Up a New Project</h2>
<p>Let’s set up a new project. Go to your projects directory from the previous
chapter, and create a new project using Cargo, like so:</p>
<pre><code class="language-bash">$ cargo new guessing_game --bin
$ cd guessing_game
</code></pre>
<p>We pass the name of our project to <code>cargo new</code> and pass the <code>--bin</code> flag, since
we’re going to be making another binary like in Chapter 1.</p>
<p>Take a look at the generated <code>Cargo.toml</code>:</p>
<p>Filename: Cargo.toml</p>
<pre><code class="language-toml">[package]
name = &quot;guessing_game&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]
[dependencies]
</code></pre>
<p>If the author information that Cargo got from your environment is not correct,
go ahead and fix that in the file and save it again.</p>
<p>As we saw in the last chapter, cargo new generates a “Hello, world!” program
for us. Check out src/main.rs:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Let’s try compiling what Cargo gave us and running it in the same step, using
the <code>cargo run</code> command:</p>
<pre><code class="language-bash">$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Running `target/debug/guessing_game`
Hello, world!
</code></pre>
<p>Great! The <code>run</code> command comes in handy when you need to rapidly iterate on a
project. Our game is such a project: we want to quickly test each
iteration before moving on to the next one.</p>
<p>Now open up your <code>src/main.rs</code> again. We’ll be writing all of our code in this
file.</p>
<h2>Processing a Guess</h2>
<p>Let’s get to it! We'll split the development of this game up into parts. This
first part will ask for input from a user and process the input, checking that
the input is in the form we expect. First we need to allow our player to input
a guess. Enter this in your <code>src/main.rs</code>:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">use std::io;
fn main() {
println!(&quot;Guess the number!&quot;);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
println!(&quot;You guessed: {}&quot;, guess);
}
</code></pre>
<p>There’s a lot here! Let’s go over it, bit by bit.</p>
<pre><code class="language-rust,ignore">use std::io;
</code></pre>
<p>We’ll need to take user input and then print the result as output, and for that
functionality we need to import the <code>io</code> (input/output) library from the
standard library (which is known as <code>std</code>).</p>
<p>By default, Rust only imports a few things into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
<em>prelude</em></a><!-- ignore -->. If it’s not in the prelude, you’ll have to
import it into your program explicitly with a <code>use</code> statement. Using the
<code>std::io</code> library gets you a number of useful <code>io</code>-related things, including
the functionality to accept user input.</p>
<pre><code class="language-rust,ignore">fn main() {
</code></pre>
<p>As you’ve seen in Chapter 1, the <code>main</code> function is the entry point into the
program. The <code>fn</code> syntax declares a new function, the <code>()</code>s indicate that
there are no arguments, and <code>{</code> starts the body of the function.</p>
<pre><code class="language-rust,ignore">println!(&quot;Guess the number!&quot;);
println!(&quot;Please input your guess.&quot;);
</code></pre>
<p>As we learned in Chapter 1, <code>println!</code> is a macro that prints a string to the
screen. This is just a prompt stating what the game is and requesting input from
the user.</p>
<h3>Storing Values with Variable Bindings</h3>
<p>Next we need to store the user input.</p>
<pre><code class="language-rust,ignore">let mut guess = String::new();
</code></pre>
<p>Now we’re getting interesting! There’s a lot going on in this little line.
The first thing to notice is that this is a <code>let</code> statement, which is
used to create <em>variable bindings</em>. Here's another example:</p>
<pre><code class="language-rust,ignore">let foo = bar;
</code></pre>
<p>This will create a new binding named <code>foo</code>, and bind it to the value <code>bar</code>. In
many languages, this is called a <em>variable</em>, but Rust’s variable bindings have
a few differences.</p>
<p>For example, they’re immutable by default. To make our binding mutable, our
example uses <code>mut</code> before the binding name.</p>
<pre><code class="language-rust">let foo = 5; // immutable.
let mut bar = 5; // mutable
</code></pre>
<blockquote>
<p>Note: The <code>//</code> syntax will start a comment that continues until the end of the
line. Rust ignores everything in comments.</p>
</blockquote>
<p>So now we know that <code>let mut guess</code> will introduce a mutable binding named
<code>guess</code>, but we have to look at the other side of the <code>=</code> for the value it’s
bound to: <code>String::new</code>. <code>String</code> is a string type, provided by the standard
library. A <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> 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 a particular type. An associated function is a function that is
associated with a type, in this case <code>String</code>, rather than 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, as it’s a common name for making
a new value of some kind.</p>
<p>So to summarize, the <code>let mut guess = String::new();</code> line has created a
mutable binding that is currently bound to a new, empty instance of a <code>String</code>.
Whew!</p>
<p>Let’s move forward:</p>
<pre><code class="language-rust,ignore">io::stdin().read_line(&amp;mut guess)
.expect(&quot;Failed to read line&quot;);
</code></pre>
<p>We included the input/output functionality from the standard library with use
std::io; on the first line of the program. We are now calling an associated
function, stdin(), on io. If we didn’t have the use std::io line at the
beginning of the program, we could have written this function call as
std::io::stdin(). The stdin() function returns an instance of std::io::Stdin,
which is a type that represents a handle to the standard input for your
terminal.</p>
<p>The next part, <code>.read_line(&amp;mut guess)</code>, calls the
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle
to get input from the user. We’re also passing one argument to <code>read_line</code>:
<code>&amp;mut guess</code>.</p>
<p>The job of <code>read_line</code> is to take whatever the user types into standard input
and place that into a string, so it takes that string as an argument. The
string argument needs to be mutable so that the method can change the string's
content by adding the user input.</p>
<p>The <code>&amp;</code> indicates that this argument is a <em>reference</em>, which gives you a way to
let multiple parts of your code access one piece of data without needing to
copy that data into memory multiple times. References are a complex feature,
and one of Rust’s major advantages is how safe and easy it is to use
references. We don’t need to know a lot of those details to finish our program
right now, though; Chapter XX will cover references in more detail. For now,
all we need to know is that like <code>let</code> bindings, references are immutable by
default. Hence, we need to write <code>&amp;mut guess</code>, rather than <code>&amp;guess</code>, to make it
mutable.</p>
<p>We’re not quite done with this line of code. While it’s a single line of text,
it’s only the first part of the single logical line of code. The second part is
this method:</p>
<pre><code class="language-rust,ignore">.expect(&quot;Failed to read line&quot;);
</code></pre>
<p>When you call a method with the <code>.foo()</code> syntax, it's often wise to introduce a
newline and other whitespace. This helps you split up long lines. We could have
written this code as:</p>
<pre><code class="language-rust,ignore">io::stdin().read_line(&amp;mut guess).expect(&quot;failed to read line&quot;);
</code></pre>
<p>But that gets hard to read. So we’ve split it up, two lines for two method
calls. Now let's see what this line does.</p>
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
<p>We mentioned that <code>read_line</code> puts what the user types into the string we
pass 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 -->,
and then specific versions for sub-libraries, like <code>io::Result</code>.</p>
<p>The <code>Result</code> types are <a href="ch06-00-enums.html">enums</a><!-- ignore -->, which is short for
<em>enumerations</em>. An enumeration is a type that can have a fixed set of values,
which are called the enum's <em>variants</em>. We will be covering enums in more
detail in Chapter XX.</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 the <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.
<code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that we can call.
If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will cause our
program to crash and display the message that we 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 us so that we 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>, our program will compile, but we’ll get a warning:</p>
<pre><code class="language-bash">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
src/main.rs:10:5: 10:39 warning: unused result which must be used,
#[warn(unused_must_use)] on by default
src/main.rs:10 io::stdin().read_line(&amp;mut guess);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<p>Rust warns that we haven’t used the <code>Result</code> value, telling us that we
haven’t handled a possible error. The right way to suppress the warning is to
actually write error handling, but if we just want to crash the program when a
problem occurs, we can use <code>expect</code>. We’ll save recovering from errors for a
future project.</p>
<h3>Printing Values with <code>println!</code> Placeholders</h3>
<p>There’s only one line of this first example left, aside from the closing curly
brace:</p>
<pre><code class="language-rust,ignore"> println!(&quot;You guessed: {}&quot;, guess);
</code></pre>
<p>This prints out the string we saved our input in. The <code>{}</code>s are a placeholder:
think of <code>{}</code> as little crab pincers, holding a value in place. You can print
more than one value this way: the first <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 then look like this:</p>
<pre><code class="language-rust">let x = 5;
let y = 10;
println!(&quot;x = {} and y = {}&quot;, x, y);
</code></pre>
<p>Which would print out &quot;x = 5 and y = 10&quot;.</p>
<h3>Testing the First Part</h3>
<p>Back to our guessing game, let's test what we have so far. We can run it with
<code>cargo run</code>:</p>
<pre><code class="language-bash">$ 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>All right! Our first part is done: we can get input from the keyboard and then
print it back out.</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 that the game is fun to play
more than once, and we'd like to have a random number between 1 and 100 so the
game isn’t too difficult. Rust does not yet include random number functionality
in its standard library. The Rust team does, however, 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 <em>crate</em> is what we call 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
the code using <code>rand</code>, we need to modify our <code>Cargo.toml</code> to include the <code>rand</code>
crate as a dependency. Open it up, and add this line at the bottom beneath the
<code>[dependencies]</code> section header that Cargo created for you:</p>
<p>Filename: Cargo.toml</p>
<pre><code class="language-toml">[dependencies]
rand = &quot;0.3.14&quot;
</code></pre>
<p>In the <code>Cargo.toml</code> file, everything that follows a header is part of a section
that goes until another section starts. Cargo uses the <code>[dependencies]</code> section
to know what external crates your project depends on and what versions of those
crates you require. In this case, we’ve specified 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. A bare number like above is actually
shorthand for <code>^0.3.14</code>, which means &quot;any version that has a public API
compatible with version 0.3.14&quot;.</p>
<p>Now, without changing any of our code, let’s build our project:</p>
<pre><code class="language-bash">$ 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>
<p>You may see different version numbers (but they will all be compatible with
your code, thanks to semver!) and the lines may be in a different order.</p>
<p>Lots of new output! 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 our <code>[dependencies]</code> and downloads
any we don’t have yet. In this case, while we only listed <code>rand</code> as a
dependency, we’ve 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
our project with our dependencies available.</p>
<p>If we immediately run <code>cargo build</code> again without making any changes, we won't
get any output. Cargo knows it has already downloaded and compiled our
dependencies, and we haven't changed anything about them in our <code>Cargo.toml</code>
file. Cargo also knows that we haven't changed anything about our code, so it
doesn't recompile that either. With nothing to do, it simply exits. If we open
up <code>src/main.rs</code>, make a trivial change, then save it again, we’ll only see one
line:</p>
<pre><code class="language-bash">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
</code></pre>
<p>This just updates the build with your tiny change to the <code>main.rs</code> file. Our
dependencies haven't changed, so Cargo knows it can reuse what it has already
downloaded and compiled for those. It just rebuilds our part of the code.</p>
<h4>The Cargo.lock File that Ensures Reproducible Builds</h4>
<p>Cargo has a mechanism to make sure we can rebuild the exact same artifact every
time we or anyone else builds our code: Cargo will only use the versions of the
dependencies you specified until you say otherwise. For example, what happens
if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out, containing an
important bugfix, but that also contains a regression that will break our code?</p>
<p>The answer to this problem is the <code>Cargo.lock</code> file created the first time we
ran <code>cargo build</code> that is now in your project directory. When you build your
project for the first time, Cargo figures out all of the versions of your
dependencies that fit your criteria then writes them to the <code>Cargo.lock</code> file.
When you build your project in the future, Cargo will see that the <code>Cargo.lock</code>
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, our project will stay at <code>0.3.14</code> until we
explicitly upgrade, thanks to the lock file.</p>
<h4>Updating a Crate to Get a New Version</h4>
<p>When we <em>do</em> want to update a crate, Cargo has another command,
<code>update</code>, which will:</p>
<ul>
<li>Ignore the <code>Cargo.lock</code> file and figure out all the latest versions that fit
our specifications in <code>Cargo.toml</code>.</li>
<li>If that works, write those versions out to the lock file.</li>
</ul>
<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>, this is what we would see if we ran <code>cargo update</code>:</p>
<pre><code class="language-bash">$ cargo update
Updating registry `https://github.com/rust-lang/crates.io-index`
Updating rand v0.3.14 -&gt; v0.3.15
</code></pre>
<p>At this point, you would also notice a change in your <code>Cargo.lock</code> file noting
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</p>
<p>If we wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
series, we’d have to update what is in the <code>Cargo.toml</code> file to look like this
instead:</p>
<pre><code class="language-toml">[dependencies]
rand = &quot;0.4.0&quot;
</code></pre>
<p>The next time we <code>cargo build</code>, assuming that the <code>rand</code> crate version <code>0.4.0</code>
has been released, Cargo will update the crates index and re-evaluate our
<code>rand</code> requirements according to the new version we have 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 we will get into in Chapter XX, but
for now, that’s all we need to know. Cargo makes it really easy to re-use
libraries, so Rustaceans are able to write smaller projects which are assembled
out of a number of sub-packages.</p>
<h3>Generating a Random Number</h3>
<p>Let’s get on to actually <em>using</em> <code>rand</code>. Our next step is to update our
<code>main.rs</code> code as follows:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;failed to read line&quot;);
println!(&quot;You guessed: {}&quot;, guess);
}
</code></pre>
<p>First we've added a line to the top, <code>extern crate rand</code>, that lets Rust know
we’ll be making use of that external dependency. This also does the equivalent
of calling <code>use rand</code>, so we can now call anything in the <code>rand</code> crate by
prefixing it with <code>rand::</code>.</p>
<p>Next, we added 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. We'll cover traits in detail in the
Traits section in Chapter XX.</p>
<p>We also added two more lines in the middle:</p>
<pre><code class="language-rust,ignore">let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
</code></pre>
<p>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 our current thread of
execution and seeded by the operating system. Next, we call the <code>gen_range</code>
method on our 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 above. 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 <code>1</code> and <code>101</code> to ask for a number ranging from one to a
hundred.</p>
<p>Knowing what traits to import and what 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 to build documentation provided by all
of your dependencies locally and then 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> then click on &quot;rand&quot; in the sidebar on the left.</p>
<p>The second line that we added to our code prints out the secret number. This is
useful while we’re developing our program to let us easily test it out, but
we’ll be deleting it for the final version. It’s not much of a game if it
prints out the answer when you start it up!</p>
<p>Try running our new program a few times:</p>
<pre><code class="language-bash">$ 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 Our Guesses</h2>
<p>Now that we’ve got user input, let’s compare our guess to the secret number.
Here’s that part of our next step:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;failed to read line&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
}
</code></pre>
<p>There are a few new bits here. The first is another <code>use</code>, bringing a type
called <code>std::cmp::Ordering</code> into scope from the standard crate. <code>Ordering</code> is
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
<code>Greater</code>, and <code>Equal</code>. These are the three outcomes that are possible when you
compare two values.</p>
<p>Then we add five new lines at the bottom that use the <code>Ordering</code> type:</p>
<pre><code class="language-rust,ignore">match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
</code></pre>
<p>The <code>cmp</code> method compares two values, and can be called on anything that can
be compared. It takes a reference to whatever you want to compare with, so here
it's comparing our <code>guess</code> to our <code>secret_number</code>. <code>cmp</code> returns a variant of
the <code>Ordering</code> enum we imported with the <code>use</code> statement earlier. We use a
<a href="match.html"><code>match</code></a><!-- ignore --> statement to decide what to do next based on
which variant of <code>Ordering</code> we got back from our call to <code>cmp</code> with the values
in <code>guess</code> and <code>secret_number</code>.</p>
<p><code>match</code> statements are made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
the code that we should run if the value given to the beginning of the <code>match</code>
statement 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 will be covered in detail in Chapter XX and
Chapter XX, respectively.</p>
<p>Let's walk through an example of what would happen with our <code>match</code>. Say that
the user has guessed 50, and the randomly-generated secret number this time
is 38. So when we compare 50 to 38, the <code>cmp</code> method will return
<code>Ordering::Greater</code>, since 50 is greater than 38. <code>Ordering::Greater</code> is the
value that the <code>match</code> statement gets. It looks at the first arm's pattern,
<code>Ordering::Less</code>, and says nope, the value we have (<code>Ordering::Greater</code>) does
not match <code>Ordering::Less</code>. So it ignores the code in that arm and moves on to
the next arm. The next arm's pattern, <code>Ordering::Greater</code>, <strong>does</strong> match
<code>Ordering::Greater</code>! The associated code in that arm will get executed, which
prints &quot;Too big!&quot; to the screen. Then we're done with the <code>match</code> statement; we
don't look at the last arm at all in this particular scenario.</p>
<p>However, this code won’t quite compile yet. Let’s try it:</p>
<pre><code class="language-bash">$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
src/main.rs:23:21: 23:35 error: mismatched types [E0308]
src/main.rs:23 match guess.cmp(&amp;secret_number) {
^~~~~~~~~~~~~~
src/main.rs:23:21: 23:35 help: run `rustc --explain E0308` to see a detailed explanation
src/main.rs:23:21: 23:35 note: expected type `&amp;std::string::String`
src/main.rs:23:21: 23:35 note: found type `&amp;_`
error: aborting due to previous error
Could not compile `guessing_game`.
</code></pre>
<p>Whew! This is a big error. The core of the error says that we have <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 out. Our
<code>secret_number</code> on the other hand is a number type. There are a few number
types which can have a value between one and a hundred: <code>i32</code>, a thirty-two-bit
number; <code>u32</code>, an unsigned thirty-two-bit number; <code>i64</code>, a sixty-four-bit
number; or others. Rust defaults to an <code>i32</code>, so that's the type of
<code>secret_number</code> unless we add type information elsewhere that would cause Rust
to infer a different numerical type. The error is because Rust will not compare
a string and a number type.</p>
<p>Ultimately, we want to convert the <code>String</code> we read as input into a real number
type so that we can compare it to the guess numerically. We can do that with
two more lines; to your <code>main</code> function body, add the following two lines:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;failed to read line&quot;);
let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
}
</code></pre>
<p>The two new lines are:</p>
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
</code></pre>
<p>We create a variable binding <code>guess</code>. But wait a minute, don't we already have
a variable binding named <code>guess</code>? We do, but Rust allows us to <em>shadow</em> the
previous value of <code>guess</code> with a new one. This is often used in this exact
situation, where we want to convert a value from one type into another type.
Shadowing lets us re-use the <code>guess</code> variable name rather than forcing us to
come up with two unique bindings, like <code>guess_str</code> and <code>guess</code> or something
(we'll cover shadowing in more detail in Chapter 3).</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 our input in
it. The <code>trim</code> method on <code>String</code>s will eliminate any whitespace at the
beginning and end. Our <code>u32</code> can only contain numerical characters, but we have
to press the return key to satisfy <code>read_line</code>. When we press the return
key, it introduces a newline character. For example, if we type <code>5</code> and hit
return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents &quot;newline&quot;, the
return key. The <code>trim</code> method gets rid of this, leaving our string with only
the <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. Since this method can parse a variety of number types, we
need to tell Rust the exact type of number we want with <code>let guess: u32</code>. The
colon (<code>:</code>) after <code>guess</code> tells Rust we’re going to annotate its type. Rust has
a few built-in number types, but we’ve chosen <code>u32</code>, an unsigned, thirty-two
bit integer. It’s a good default choice for a small positive number. You'll see
the other number types in Chapter XX. Additionally, our <code>u32</code> annotation here
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>Our call to <code>parse</code> could quite easily cause an error. If, for example, our
string contained <code>A👍%</code>, there’d 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 that we discussed earlier. We're going to 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 could not 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 turn the string into 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 that it will take out of the <code>Ok</code> value for us.</p>
<p>Let’s try our program out!</p>
<pre><code class="language-bash">$ 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! You can see we even added spaces before our guess, and it still figured
out that we 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>Now we’ve got most of the game working, but we can only make 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. We'll add that in to give us more
chances at guessing the number:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
loop {
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;failed to read line&quot;);
let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; println!(&quot;You win!&quot;),
}
}
}
</code></pre>
<p>As you can see, we've moved everything from the guess input onwards into a
loop. Make sure to indent those lines another four spaces each, and try it out.
You'll notice we have 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 we can quit!</p>
<p>We could always halt the program by using the keyboard shortcut <code>control-c</code>.
There's another way to escape the insatiable monster we've created, though,
that can be found in our discussion about <code>parse</code>: if we give a non-number
answer, the program will crash. We can use that to quit! Observe:</p>
<pre><code class="language-bash">$ 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>This method means that typing <code>quit</code> actually quits the game, but so does any
other non-number input. This is suboptimal, to say the least. We want the game
to automatically stop when the correct number is guessed.</p>
<h4>Quitting When you Win</h4>
<p>Let’s program the game to quit when you win by adding a <code>break</code> in that case:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
println!(&quot;The secret number is: {}&quot;, secret_number);
loop {
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;failed to read line&quot;);
let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; {
println!(&quot;You win!&quot;);
break;
}
}
}
}
</code></pre>
<p>By adding the <code>break</code> line after <code>You win!</code>, we’ll exit the loop when we guess
the secret number correctly. Exiting the loop also means exiting the program,
since the loop is the last thing in <code>main</code>.</p>
<h4>Handling Invalid Input</h4>
<p>For our final refinement of the game's behavior, rather than crashing the
program when someone inputs a non-number, we want the game to ignore it so we
can continue guessing. We can do that by altering the line where we convert
<code>guess</code> from a <code>String</code> to a <code>u32</code>:</p>
<pre><code class="language-rust,ignore">let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
</code></pre>
<p>This is how you generally move from &quot;crash on error&quot; to &quot;actually handle the
error&quot;: by switching from an <code>expect</code> statement to a <code>match</code> statement.
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 going to use a <code>match</code> statement 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 match statement 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> binding 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 match arm, but it does match
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catch-all value; we're
saying we want to match all <code>Err</code> values, no matter what information they have
inside them. So we execute the second arm's code, <code>continue</code>: this means to go
to the next iteration of the <code>loop</code> and ask for another guess. So we have
effectively ignored all errors that <code>parse</code> might hit!</p>
<p>Now everything in our program should work as we expect it to! Let’s try it:</p>
<pre><code class="language-bash">$ 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 last tweak, we can finish the guessing game: we're still
printing out the secret number. That was good for testing, but it kind of ruins
the game. Let's delete the <code>println!</code> that outputs the secret number. Here’s our
full, final code:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!(&quot;Guess the number!&quot;);
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!(&quot;Please input your guess.&quot;);
let mut guess = String::new();
io::stdin().read_line(&amp;mut guess)
.expect(&quot;failed to read line&quot;);
let guess: u32 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; {
println!(&quot;You win!&quot;);
break;
}
}
}
}
</code></pre>
<h2>Complete!</h2>
<p>At this point, you have successfully built the Guessing Game! Congratulations!</p>
<p>This project was a hands-on way to introduce you to a lot of new Rust concepts:
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
In the next few chapters, we will go through these concepts in more detail.
Chapter 3 covers concepts that most programming languages have, like variables,
data types, and functions, and shows how to use them in Rust. Chapter 4 gets
into ownership, which is the feature of Rust 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 in Rust</h1>
<p>Let's first look at concepts that appear in almost every programming language
and see 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 Rust’s particular syntax and conventions concerning
these common concepts.</p>
<p>Specifically, we’ll be talking about variable bindings, 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 -->
<p>Keep in mind as we get into variables and functions that 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. This means you cannot use these words as names of
variables or functions, for example. Most of these have special meaning and we
will be using them to do various things in our Rust programs; a few have no
current functionality associated but have been reserved for functionality that
might be in the Rust language in the future. You can find a list of the
keywords in Appendix XX.</p>
<!-- PROD: END BOX -->
<h2>Variable Bindings and Mutability</h2>
<p>We mentioned in Chapter 2 that by default, variable bindings are <em>immutable</em>.
This is one of many nudges in Rust that encourages us to write our code in a
way that gets the most of the safety and easy concurrency that Rust has to
offer. We still have the option to make our bindings mutable, though. Let's
explore how and why Rust encourages us to favor immutability, and why we might
want to opt out of that.</p>
<p>Variable bindings being immutable means that once a value is bound, you can't
change that value. To illustrate this, let's generate a new project in your
projects directory called <code>bindings</code> by using <code>cargo new --bin bindings</code>.</p>
<p>Then, in your new <code>bindings</code> directory, open <code>src/main.rs</code> and replace its code
with the following:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let x = 5;
println!(&quot;The value of x is: {}&quot;, x);
x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Save and run the program using <code>cargo run</code>, and you should receive an error
message, as in this output:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.0.1 (file:///projects/bindings)
error: re-assignment of immutable variable `x` [--explain E0384]
--&gt; src/main.rs:4:5
4 |&gt; x = 6;
|&gt; ^^^^^
note: prior assignment occurs here
--&gt; src/main.rs:2:9
2 |&gt; let x = 5;
|&gt; ^
</code></pre>
<p>This is our first example of the compiler helping us find an error in our
program! Compiler errors can be frustrating. Keep in mind that 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 Rust compiler is trying to help your program be the very best.</p>
<!-- PROD: START BOX -->
###### Extended Error Explanations
<p>Now that you've seen a Rust error, let's take a moment to look at one
particularly useful aspect of errors. Rust encourages you to seek further
information on the kind of error you've received with output like this:</p>
<pre><code class="language-bash">error: re-assignment of immutable variable `x` [--explain E0384]
</code></pre>
<p>This tells us that if we pass the <code>--explain</code> flag to <code>rustc</code> with the provided
error code, we can see an extended explanation which will try to explain common
causes of and solutions to that kind of error. Not every error has a longer
explanation, but many do. Here’s a portion of the explanation for the <code>E0384</code>
error we received:</p>
<pre><code class="language-bash">$ rustc --explain E0384
This error occurs when an attempt is made to reassign an immutable variable.
For example:
```
fn main(){
let x = 3;
x = 5; // error, reassignment of immutable variable
}
```
</code></pre>
<p>These explanations can really help if you’re stuck on an error, so don't
hesitate to look up the error code. The compiler is your friend, and it's there
to help.</p>
<!-- PROD: END BOX -->
<p>The error tells us 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 said was immutable because this very situation can
lead to bugs. If one part of our code operates on an 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 only changes the value <em>sometimes</em>.</p>
<p>In Rust, we can trust that a value we say won't change really won't change,
because the compiler is enforcing that guarantee for us. When reading and
writing code, we don't have to keep track in our head how and where a value
might change. This can make code easier to reason about.</p>
<p>Mutability can be really useful, though! Bindings are immutable only by
default; you can make them mutable by adding <code>mut</code> in front of the variable
name. In addition to allowing this value to be changed, it conveys intent to
future readers of the code by indicating that other parts of the code will be
changing this value.</p>
<p>For example, change the program you just wrote to the following:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let mut x = 5;
println!(&quot;The value of x is: {}&quot;, x);
x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Running this, we get:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 5
The value of x is: 6
</code></pre>
<p>Using <code>mut</code>, we are 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 binding mutable because it makes the
code easier to understand than an implementation that only uses immutable
bindings. In cases where you're using large data structures, mutating an
instance in place may be faster than copying and returning newly allocated
instances. It all depends on the tradeoffs you want to make in your situation.</p>
<h3>Shadowing</h3>
<p>As we saw in the guessing game tutorial, we can declare new bindings with the
same name as a previous binding, and the new binding <em>shadows</em> the previous
binding. We say that the first binding is <em>shadowed</em> by the second, which means
that the second binding's value is what you will see when you use the variable.
We can shadow a binding by using the same binding's name and repeating the use
of the <code>let</code> keyword as follows:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>This program first binds <code>x</code> to a value of <code>5</code>. Then, it shadows <code>x</code> by
repeating <code>let x =</code>, taking the original value and adding <code>1</code> so that 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>. If
you run this, it will output:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 12
</code></pre>
<p>This is different from marking a binding 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 binding. We can perform a few transformations on a value, but
have the binding be immutable after those transformations have been completed.</p>
<p>The other difference between <code>mut</code> and shadowing is that, since we're
effectively creating a new binding when we use the <code>let</code> keyword again, we can
change the type of the value we're binding to but reuse the same name. For
example, say we ask a user to show us how many spaces they want between some
text by sending us space characters, but we really want to store that as a
number:</p>
<pre><code class="language-rust">let spaces = &quot; &quot;;
let spaces = spaces.len();
</code></pre>
<p>This is allowed: the first <code>spaces</code> binding is a string type, and the second
<code>spaces</code> binding, which is a brand new binding that happens to have the same
name as the first one, is a number type. Shadowing thus saves us from having to
come up with different names like <code>spaces_str</code> and <code>spaces_num</code>; we can reuse
the simpler <code>spaces</code> name. If we try to use <code>mut</code> for this, however, like this:</p>
<pre><code class="language-rust,ignore">let mut spaces = &quot; &quot;;
spaces = spaces.len();
</code></pre>
<p>We will get a compile-time error because we are not allowed to mutate a
binding's type:</p>
<pre><code class="language-bash">error: mismatched types [--explain E0308]
--&gt;
|&gt;
4 |&gt; spaces = spaces.len();
|&gt; ^^^^^^^^^^^^ expected &amp;-ptr, found usize
note: expected type `&amp;str`
note: found type `usize`
error: aborting due to previous error
</code></pre>
<p>Now that we've explored how variable bindings work, let's look at some more
data types of values that we can bind variables to.</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 given so it knows how to work with that data. In this section, we'll
look at a number of types built into the language itself split into two subsets:
scalar and compound.</p>
<p>Something to keep in mind throughout this section: Rust is a <em>statically typed</em>
language, which means that it must know the types of all bindings at compile
time. The compiler can usually infer what type we want to use based on the
value and how we use it. In cases when many types are possible, such as when we
converted a <code>String</code> to a numeric type using <code>parse</code> in Chapter 2, we must
add a type annotation, like this:</p>
<pre><code class="language-rust">let guess: u32 = &quot;42&quot;.parse().unwrap();
</code></pre>
<p>If we don't put the type annotation here, Rust will give us this error that
means the compiler needs more information from us to know which possible type
we want:</p>
<pre><code class="language-bash">error: unable to infer enough type information about `_`; type annotations or
generic parameter binding required [--explain E0282]
--&gt;
|&gt;
3 |&gt; let guess = &quot;42&quot;.parse().unwrap();
|&gt; ^^^^^
</code></pre>
<p>You will see some type annotations as we discuss the various data types.</p>
<h3>Scalar Types</h3>
<p>A <em>scalar</em> type represents a single value. There are four primary scalar
types in Rust: 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've used one integer
type already 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. There are a number of
built-in integer types in Rust, shown in Table 3-1.</p>
<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>
<p><em>Table 3-1: Integer types in Rust. Each variant in the signed and unsigned
columns (for example, <code>i32</code>) can be used to declare the type of an integer
value.</em></p>
<p>Each variant can be either signed or unsigned and has an explicit size. Signed
and unsigned merely refers to whether it is possible for the number to be
either 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 minus
sign, but 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 text).</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 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 from 0 to 2<sup>8</sup> - 1, which equals 0 to 255.</p>
<p>Finally, 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 for 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>
<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>
<p><em>Table 3-2: Integer literals in Rust.</em></p>
<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>,
as it’s roughly the same speed as <code>f32</code>, but has a larger precision. It is
possible to use an <code>f64</code> on 32 bit systems, but it will be slower than using an
<code>f32</code> 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 case. See
Chapter XX for how to run benchmarks.</p>
<p>Here's an example showing floating-point numbers in action:</p>
<p>Filename: src/main.rs</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, while <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
these number types: addition, subtraction, multiplication, division, and
remainder. This code shows how you'd use each one in a <code>let</code> statement:</p>
<p>Filename: src/main.rs</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.</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 with <code>bool</code>.
For example:</p>
<p>Filename: src/main.rs</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 like an <code>if</code>
statement. We’ll cover how <code>if</code> statements work in Rust in the &quot;Control Flow&quot;
section of this chapter.</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 this code
shows one way to use it:</p>
<p>Filename: src/main.rs</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> represents a Unicode Scalar Value, which means that 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>s 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. A &quot;character&quot; isn’t really a concept in Unicode, however, so your
human intuition for what a &quot;character&quot; is may not match up with what a <code>char</code>
is in Rust. We'll discuss this in detail in the Strings section of 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
distinct 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 distinct type, and the types of
the different values in the tuple do not have to be the same. We've added
optional type annotations in this example:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
</code></pre>
<p>Note that the single name <code>tup</code> binds to the entire tuple, emphasizing the fact
that 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>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let tup = (500, 6.4, 1);
let (x, y, z) = tup;
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>In this program, we first create a tuple and bind it to the name <code>tup</code>. We then
use a pattern with <code>let</code> to take <code>tup</code> and turn it into three separate
bindings, <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, we print the value of <code>y</code>, which is
<code>6.4</code>.</p>
<h4>Tuple Indexing</h4>
<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>Filename: src/main.rs</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 bindings to each element
by using their index. As with most programming languages, the first index in a
tuple is 0.</p>
<h3>Arrays</h3>
<p>Another way to bind a name to 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>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
}
</code></pre>
<p>While arrays can be useful since they are a primitive type so using them can be
very fast, they aren't as flexible as the vector type. 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 go with a vector, and we'll discuss them in more detail in
Chapter 8.</p>
<p>An example of when we might want to use an array is storing the months of the
year. It's very unlikely that our program will need to add or remove months, so
we can use an array since we know we will always have 12 items:</p>
<pre><code class="language-rust">let months = [&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;,
&quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;];
</code></pre>
<h4>Accessing Array Elements</h4>
<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>Filename: src/main.rs</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 binding named <code>first</code> will get the value <code>1</code>, since that
is the value at index <code>[0]</code> in the array. The binding named <code>second</code> will get
the value <code>2</code> from index <code>[1]</code> in the array.</p>
<h4>Invalid Array Element Access</h4>
<p>What happens if you try to access an element of an array past the end of the
array? Say we changed our program to:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let a = [1, 2, 3, 4, 5];
let element = a[10];
println!(&quot;The value of element is: {}&quot;, element);
}
</code></pre>
<p>Running this code with <code>cargo run</code> produces:</p>
<pre><code class="language-bash">$ cargo run
Compiling arrays v0.1.0 (file:///projects/arrays)
Running `target/debug/arrays`
thread '&lt;main&gt;' panicked at 'index out of bounds: the len is 5 but the index is
10', src/main.rs:4
note: Run with `RUST_BACKTRACE=1` for a backtrace.
error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
</code></pre>
<p>We can see that the compilation did not give us any errors, but we got a
<em>runtime</em> error and our program didn't exit successfully. When we attempt to
access an element using indexing, Rust will check that the index we've
specified is less than the array length. If the index is greater than the
length, it will &quot;panic&quot;, which is what it's called when a Rust program exits
with an error.</p>
<p>This is our 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 us against this
kind of error by immediately exiting instead of allowing the memory access and
continuing. We'll discuss more of Rust’s error handling in Chapter XX.</p>
<h2>How Functions Work</h2>
<p>Functions are pervasive in Rust code. We’ve already seen one of the most
important functions in the language: the <code>main</code> function that’s the entry
point of many programs. We've also seen the <code>fn</code> keyword, which allows us 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 lower case, and there are underscores
separating words. Here's a program containing an example function definition:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
another_function();
}
fn another_function() {
println!(&quot;Another function.&quot;);
}
</code></pre>
<p>Function definitions in Rust start with <code>fn</code> and have a set of parentheses
after the function name. The curly braces tell the compiler where the function
body begins and ends.</p>
<p>We can call any function we’ve defined by entering its name followed by a pair
of parentheses. Since <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 our source code; we could
have defined it before as well. Rust doesn’t care where you define your
functions, only that they are defined somewhere.</p>
<p>Let’s start a new binary project named <code>functions</code> so that we can explore
further. Place the <code>another_function</code> example in <code>src/main.rs</code> and run it.
You should see the following output:</p>
<pre><code class="language-bash">$ 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 they appear in the <code>main</code> function. First, our
“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>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Try running this program, and you should get this output:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p>In the declaration of <code>another_function</code>, we place one argument named <code>x</code>. We
specify the type of <code>x</code> as <code>i32</code>. When we pass <code>5</code> 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, we <em>must</em> declare the type. This is a deliberate
decision in the design of Rust; requiring type annotations in function
definitions means the compiler almost never needs you to use them elsewhere in
the code in order to figure out what you mean.</p>
<p>When you want a function to have multiple arguments, just separate them inside
the function signature with commas, like this:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
another_function(5, 6);
}
fn another_function(x: i32, y: i32) {
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>In this example, we make a function with two arguments, both of which are
<code>i32</code>s. If your function has multiple arguments, they don’t need to be the same
type, but they just happen to be in this example. Our function then prints out
the values of both of its arguments.</p>
<p>Let’s try out this code. Replace the program currently in your <code>function</code>
project's <code>main.rs</code> file with the example above, and run it as follows:</p>
<pre><code class="language-bash">$ 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>Since <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 seen functions without an ending expression, but
we have seen expressions as parts of statements. Since 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>
<h4>Statements and Expressions</h4>
<p>We've already been using both 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 binding and assigning a value to it with the <code>let</code> keyword
is a statement. In this example, <code>let y = 6;</code> is a statement:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let y = 6;
}
</code></pre>
<p>Function definitions are also statements; the entire previous example is a
statement in itself.</p>
<p>Statements do not return values themselves. Therefore, you can’t assign a <code>let</code>
binding to another binding, as this code tries to do:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let x = (let y = 6);
}
</code></pre>
<p>If we were to run this program, we’d get an error like this:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found statement (`let`)
--&gt; src/main.rs:2:14
2 |&gt; let x = (let y = 6);
|&gt; ^^^
note: variable declaration using `let` is a statement
error: aborting due to previous error
error: Could not compile `functions`.
</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 like C and Ruby where
the assignment returns the value of the assignment. In those languages, we 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 are code that evaluate to something, and make up most of the rest
of the code that you will write in Rust. Consider a simple math operation, like
this:</p>
<pre><code class="language-rust,ignore">5 + 6
</code></pre>
<p>This is an expression, and evaluating it results in the value <code>11</code>. Expressions
can be part of statements-- in the previous example 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>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = {
let x = 3;
x + 1
};
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<!-- If we use wingding numbers to call out code, we might delete the
repetition here and just use those numbers--that can help the flow of the text.
I'm flagging this as a reminder for when we transfer to libreoffice -->
<p>The 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>, and then gets bound to
<code>y</code> as part of the <code>let</code> statement.</p>
<p>Note that the line containing <code>x + 1</code> does not have a semicolon at the end,
unlike most of the lines we've seen up until now. This is the most important
distinction between expressions and statements to remember: statements end in
semicolons while expressions do not. If you add a semicolon to the end of an
expression, that will turn it into a statement, which will then not return a
value. Keep this in mind as we explore function return values and expressions.</p>
<h3>Functions with Return Values</h3>
<p>Functions can return values back to the code that calls them. We don’t name
return values, but we do declare their type, after an arrow (<code>-&gt;</code>). In Rust,
the &quot;return value of the function” is synonymous with the &quot;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>Filename: src/main.rs</p>
<pre><code class="language-rust">fn five() -&gt; i32 {
5
}
fn main() {
let x = five();
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>There are no function calls, macros, or even <code>let</code> statements in the <code>five</code>
function: just the number <code>5</code> by itself. That's a perfectly valid function in
Rust. Note the function's return type is specified, too, as <code>-&gt; i32</code>. Try
running this code, and the output should look like this:</p>
<pre><code class="language-bash">$ 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 us using the return value of a function
to initialize a binding.</p>
<p>Because the function <code>five</code> returns a <code>5</code>, that line is the same as saying:</p>
<pre><code class="language-rust">let x = 5;
</code></pre>
<p>The second interesting bit is the <code>five</code> function itself. It 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 is an expression whose
value we want to return. Let's look at another example:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let x = plus_one(5);
println!(&quot;The value of x is: {}&quot;, x);
}
fn plus_one(x: i32) -&gt; i32 {
x + 1
}
</code></pre>
<p>Running this code will print <code>The value of x is: 6</code>. What happens if we put a
semicolon at the end of the line containing <code>x + 1</code>, changing it from an
expression to a statement?</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let x = plus_one(5);
println!(&quot;The value of x is: {}&quot;, x);
}
fn plus_one(x: i32) -&gt; i32 {
x + 1;
}
</code></pre>
<p>Running this code gives an error, as follows:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: not all control paths return a value [--explain E0269]
--&gt; src/main.rs:7:1
7 |&gt; fn plus_one(x: i32) -&gt; i32 {
|&gt; ^
help: consider removing this semicolon:
--&gt; src/main.rs:8:10
8 |&gt; x + 1;
|&gt; ^
error: aborting due to previous error
error: Could not compile `functions`.
</code></pre>
<p>The main error message, &quot;not all control paths return a value&quot;, reveals the
core of the 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 gives an option to rectify this: 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, we leave notes in our source
code that the compiler will ignore but people reading the source code may find
useful. These notes are called <em>comments</em>.</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 will last 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 of code:</p>
<p>Filename: src/main.rs</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 above, like so:</p>
<p>Filename: src/main.rs</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 it. Comments are not particularly complicated.</p>
<h2>Control Flow</h2>
<p>Decisions on 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 us control the flow of execution of our 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 say, &quot;If this condition is met, run this
block of code. If the condition is not met, do not run this block of code.&quot;</p>
<p>Let’s make a new project to explore <code>if</code>, called <code>branches</code>. In <code>src/main.rs</code>,
put:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let number = 3;
if number &lt; 5 {
println!(&quot;condition was true&quot;);
} else {
println!(&quot;condition was false&quot;);
}
}
</code></pre>
<p>All <code>if</code> expressions start with the keyword <code>if</code>, which is followed by a
condition. In this case, our condition is checking if our variable binding
<code>number</code> has a value that is less than 5. The block of code we want to execute
if the condition is true goes immediately after the condition, inside curly
braces. These blocks are sometimes called <em>arms</em>. We can optionally also
include an <code>else</code> expression, which we have chosen to do here. This gives the
program an alternative block of code to execute should the condition evaluate
to false. If you don't give 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, and you should see output like this:</p>
<pre><code class="language-bash">$ 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-bash">$ 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 here <em>must</em> be a <code>bool</code>. To see what
happens if the condition isn't a <code>bool</code>, try running this code:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let number = 3;
if number {
println!(&quot;number was three&quot;);
}
}
</code></pre>
<p>The <code>if</code> condition evaluates to a value of <code>3</code> this time, and Rust will
complain about it:</p>
<pre><code class="language-bash"> Compiling branches v0.1.0 (file:///projects/branches)
error: mismatched types [--explain E0308]
--&gt; src/main.rs:4:8
4 |&gt; if number {
|&gt; ^^^^^^ expected bool, found integral variable
note: expected type `bool`
note: found type `_`
error: aborting due to previous error
Could not compile `branches`.
</code></pre>
<p>The error tells us that Rust expected a <code>bool</code>, but got an integer. Rust will
not automatically try to convert non-boolean types to a boolean here, unlike
languages like Ruby or JavaScript. We must be explicit and always give <code>if</code> a
<code>boolean</code> as its condition. If you wanted your <code>if</code> code block to run only when
a number is not equal to <code>0</code>, for example, we would change the <code>if</code> expression
to read:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let number = 3;
if number != 0 {
println!(&quot;number was something other than zero&quot;);
}
}
</code></pre>
<p>Running this 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>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let number = 6;
if number % 4 == 0 {
println!(&quot;number is divisible by 4&quot;);
} else if number % 3 == 0 {
println!(&quot;number is divisible by 3&quot;);
} else if number % 2 == 0 {
println!(&quot;number is divisible by 2&quot;);
} else {
println!(&quot;number is not divisible by 4, 3, or 2&quot;);
}
}
</code></pre>
<p>This program has four possible paths it can take. If you try running it, you
should see output like this:</p>
<pre><code class="language-bash">$ 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 will check each <code>if</code> expression in turn and
execute the first body for which the condition holds true. Note that even
though 6 is divisible by 2, we did not see the output <code>number is divisible by 2</code>, nor did we see the <code>number is not divisible by 4, 3, or 2</code> text from the
<code>else</code> block. That's because 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 find
yourself with more than one, you may want to look at refactoring your code. In
Chapter 6, we'll talk about a powerful Rust branching construct called <code>match</code>
for these cases.</p>
<h4>Using <code>if</code> in a Binding</h4>
<p>The last detail you need to know about <code>if</code> is that it’s an expression. That
means that we can use it on the right hand side of a <code>let</code> binding, for
instance:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!(&quot;The value of number is: {}&quot;, number);
}
</code></pre>
<p>The <code>number</code> variable will be bound to a value based on the outcome of the <code>if</code>
expression. Let’s run this to see what happens:</p>
<pre><code class="language-bash">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
The value of number is: 5
</code></pre>
<p>Remember, 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 value that
results from both arms of the <code>if</code> must be the same type; in the previous
example, they were both <code>i32</code> integers. But what happens if the types are
mismatched, as in the following example?</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let condition = true;
let number = if condition {
5
} else {
&quot;six&quot;
};
println!(&quot;The value of number is: {}&quot;, number);
}
</code></pre>
<p>If we try to run this, we’ll get an error. The <code>if</code> and <code>else</code> arms have value
types that are incompatible, and Rust tells us exactly where to find the
problem in our program:</p>
<pre><code class="language-bash"> Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: if and else have incompatible types
--&gt; src/main.rs:4:18
|
4 | let number = if condition {
| ^ expected integral variable, found reference
|
= note: expected type `{integer}`
= note: found type `&amp;'static str`
error: aborting due to previous error
error: Could not compile `branches`.
</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 can’t work, because variable
bindings must have a single type. Rust needs to know at compile time what type
the <code>number</code> binding is, definitively, so that 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 be able to make fewer guarantees about our code if it had
to keep track of multiple hypothetical types for any variable binding.</p>
<h3>Repetition with Loops</h3>
<p>It’s often useful to be able to execute a block of code more than one time. For
this, Rust has 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 try out
loops, let’s make a new project called <code>loops</code>.</p>
<p>There are three kinds of loops in Rust: <code>loop</code>, <code>while</code>, and <code>for</code>. Let’s dig
in.</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 we explicitly tell it to stop.</p>
<p>For an example, change the <code>src/main.rs</code> file in your <em>loops</em> directory to look
like this:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
loop {
println!(&quot;again!&quot;);
}
}
</code></pre>
<p>If 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,
<code>control-c</code>, to halt a program stuck in a continual loop. Give it a try:</p>
<pre><code class="language-bash">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!
</code></pre>
<p>That <code>^C</code> there is where we hit <code>control-c</code>. You may or may not see &quot;again!&quot;
printed after the <code>^C</code>, depending on where the code was in the loop when it
received the signal to halt.</p>
<p>Fortunately, Rust provides another, more reliable way to break out of a loop.
We 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
Chapter 2 to exit the program when the user won the game by guessing the number
correctly.</p>
<h4>Conditional Loops With <code>while</code></h4>
<p>It's often useful for a program to have a condition that can be evaluated
within a loop. While the condition is true, the loop runs. When the condition
ceases to be true, we call <code>break</code>, stopping the loop. This could be
implemented with 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>But this pattern is so common that Rust has a more efficient language construct
for it, called a <code>while</code> loop. Here's an example using <code>while</code>: this program
loops three times, counting down each time. Finally, after the loop, it prints
another message, then exits:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let mut number = 3;
while number != 0 {
println!(&quot;{}!&quot;, number);
number = number - 1;
}
println!(&quot;LIFTOFF!!!&quot;);
}
</code></pre>
<p>This gets rid of a lot of nesting that would be necessary if we used <code>loop</code>,
<code>if</code>, <code>else</code>, and <code>break</code>, and it's more clear. While a condition holds, run
this code; otherwise, exit the loop.</p>
<h4>Looping Through a Collection with <code>for</code></h4>
<p>We could use this <code>while</code> construct to loop over the elements of a collection,
like an array. For example:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index &lt; 5 {
println!(&quot;the value is: {}&quot;, a[index]);
index = index + 1;
}
}
</code></pre>
<p>Here, we're counting up through the elements in the array. We start at index 0,
then loop until we hit the final index of our array (that is, when <code>index &lt; 5</code>
is no longer true). Running this will print out every element of the array:</p>
<pre><code class="language-bash">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
</code></pre>
<p>All five array values appear in the terminal, as expected. Even though <code>index</code>
will reach a value of <code>6</code> at some point, the loop stops executing before trying
to fetch a sixth value from the array.</p>
<p>This approach is error-prone, though; we could cause our program to panic by
getting the index length incorrect. It's also slow, as the compiler needs to
perform the conditional check on every element on every iteration through the
loop.</p>
<p>As a more efficient alternative, we 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>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!(&quot;the value is: {}&quot;, element);
}
}
</code></pre>
<p>If we run this, we'll see the same output as the previous example. Importantly,
though, we've now increased the safety of our 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 previous code that uses the <code>while</code> loop, if we removed an
item from the <code>a</code> array but forgot to update the condition to <code>while index &lt; 4</code>, our code would panic. Using the <code>for</code> loop means we would not need to
remember to change any other code if we changed the number of values in the
array.</p>
<p>If you're wondering about the <code>iter</code> code in this example, keep reading! We
will cover method syntax generally in Chapter XX and iterators specifically in
Chapter XX.</p>
<p>The safety and conciseness of <code>for</code> loops make them the most commonly used loop
construct in Rust. Even in situations where you want to run some code a certain
number of times, like our countdown example that used a <code>while</code> loop, 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 with a for loop, and using another
method we haven't yet talked about, <code>rev</code>, to reverse the range:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
for number in (1..4).rev() {
println!(&quot;{}!&quot;, number);
}
println!(&quot;LIFTOFF!!!&quot;);
}
</code></pre>
<p>That's a bit nicer, isn't it?</p>
<h2>Summary</h2>
<p>You made it! That was a big chapter: we covered variable bindings, scalar and
compound data types, functions, comments, <code>if</code> expressions, and loops! If you'd
like to get some practice with the concepts in this chapter, try building
programs to do things like:</p>
<ul>
<li>Converting temperatures between Fahrenheit and Celsius.</li>
<li>Generate the nth Fibonacci number.</li>
<li>Print the lyrics to the Christmas carol <em>The Twelve Days of Christmas</em>,
taking advantage of the repetition in the song.</li>
</ul>
<p>When you're ready to move on, we'll talk about a concept in Rust that <em>doesn't</em>
commonly exist in other programming languages: ownership.</p>
<h1>Understanding Ownership</h1>
<p>Ownership is Rust's most unique feature, and enables Rust to make memory safety
guarantees without needing a garbage collector. It's therefore important to
understand how ownership works in Rust. In this chapter we'll talk about
ownership as well as several related features: borrowing, slices, and how Rust
lays things out in memory.</p>
<h2>Ownership</h2>
<p>Rust’s central feature is <em>ownership</em>. It is a feature that is straightforward
to explain, but has deep implications for the rest of the language.</p>
<p>All programs have to manage the way they use a computer's memory while running.
Some languages have garbage collection, while in others, the programmer has to
explicitly allocate and free the memory. Rust takes a third approach: memory is
managed through a system of ownership with a set of rules that the compiler
checks at compile-time. You do not pay any run-time cost for any of these
features.</p>
<p>Since ownership is a new concept for many programmers, it does take
some time to get used to. There is good news, though: the more experienced you
become with Rust and the rules of the ownership system, the more you'll be
able to naturally develop code that is both safe and efficient. Keep at it!</p>
<p>Once you understand ownership, you have a good foundation for understanding the
features that make Rust unique. In this chapter, we'll learn ownership by going
through some examples, focusing on a very common data structure: strings.</p>
<!-- PROD: START BOX -->
<h6>The Stack and the Heap</h6>
<p>In many programming languages, we don't have to think about the stack and the
heap very often. But in a systems programming language like Rust, whether a
value is on the stack or the heap has more of an effect on how the language
behaves and why we have to make certain decisions. We're going to be describing
parts of ownership in relation to the stack and the heap, so here is a brief
explanation.</p>
<p>Both the stack and the heap are parts of memory that is available to your code
to use at runtime, but they are structured in different ways. The stack stores
values in the order it gets them and removes the values in the opposite order.
This is referred to as <em>last in, first out</em>. Think of a stack of plates: when
you add more plates, you put them on top of the pile, and when you need a
plate, you take one off the top. Adding or removing plates from the middle or
bottom wouldn't work as well! Adding data is called <em>pushing onto the stack</em>
and removing data is called <em>popping off the stack</em>.</p>
<p>The stack is fast because of the way it accesses the data: it never has to look
around for a place to put new data or a place to get data from; that place is
always the top. Another property that makes the stack fast is that all data on
the stack must take up a known, fixed size.</p>
<p>For data with a size unknown to us at compile time, or a size that might
change, we can store data on the heap instead. The heap is less organized: when
we put data on the heap, we ask for some amount of space. The operating system
finds an empty spot somewhere in the heap that is big enough, marks it as being
in use, and returns to us a pointer to that location. This process is called
<em>allocating on the heap</em>, and sometimes we just say &quot;allocating&quot; for short.
Pushing values onto the stack is not considered allocating. Since the pointer
is a known, fixed size, we can store the pointer on the stack, but when we want
the actual data, we have to follow the pointer.</p>
<p>Think of being seated at a restaurant. When you enter, you say how many people
are in your group, and the staff finds an empty table that would fit everyone
and leads you there. If someone in your group comes late, they can ask where
you have been seated to find you.</p>
<p>Accessing data in the heap is slower because we have to follow a pointer to
get there. Allocating a large amount of space can also take time.</p>
<p>When our code calls a function, the values passed into the function (including,
potentially, pointers to data on the heap) and the function's local variables
get pushed onto the stack. When the function is over, those values get popped
off the stack.</p>
<p>Keeping track of what parts of code are using what data on the heap, minimizing
the amount of duplicate data on the heap, and cleaning up unused data on the
heap so that we don't run out of space 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>
<!-- PROD: END BOX -->
<h3>Ownership Rules</h3>
<p>First, let's take a look at the rules. Keep these in mind as we go through the
examples that will illustrate the rules:</p>
<blockquote>
<ol>
<li>Each value in Rust has a variable binding 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 Binding Scope</h3>
<p>We've walked through an example of a Rust program already in the tutorial
chapter. Now that we’re past basic syntax, we won’t include all of the <code>fn main() {</code> stuff in examples, so if you’re following along, you will have to put
the following examples inside of a <code>main</code> function yourself. This lets our
examples be a bit more concise, letting us focus on the actual details rather
than boilerplate.</p>
<p>As a first example of ownership, we'll look at the <em>scope</em> of some variable
bindings. A scope is the range within a program for which an item is valid.
Let's say we have a variable binding that looks like this:</p>
<pre><code class="language-rust">let s = &quot;hello&quot;;
</code></pre>
<p>The variable binding <code>s</code> refers to a string literal, where the value of the
string is hard coded into the text of our program. The binding is valid from
the point at which it’s declared until the end of the current <em>scope</em>. That is:</p>
<pre><code class="language-rust">{ // s is not valid here, it’s not yet declared
let s = &quot;hello&quot;; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>In other words, there are two important points in time here:</p>
<ul>
<li>When <code>s</code> comes <em>into scope</em>, it is valid.</li>
<li>It remains so until it <em>goes out of scope</em>.</li>
</ul>
<p>At this point, things are similar to other programming languages. Now let’s
build on top of this understanding by introducing the <code>String</code> type.</p>
<h3>The <code>String</code> Type</h3>
<p>In order to illustrate the rules of ownership, we need a data type that is more
complex than the ones we covered in Chapter 3. All of the data types we've
looked at previously are stored on the stack and popped off the stack when
their scope is over, but we want to look at data that is stored on the heap and
explore how Rust knows when to clean that data up.</p>
<p>We're going to use <code>String</code> as the example here and concentrate on the parts of
<code>String</code> that relate to ownership. These aspects also apply to other complex
data types provided by the standard library and that you create. We'll go into
more depth about <code>String</code> specifically in Chapter XX.</p>
<p>We've already seen string literals, where a string value is hard-coded into our
program. String literals are convenient, but they aren’t always suitable for
every situation you want to use text. For one thing, they’re immutable. For
another, not every string value can be known when we write our code: what if we
want to take user input and store it?</p>
<p>For things like this, Rust has a second string type, <code>String</code>. This type is
allocated on the heap, and as such, is able to store an amount of text that is
unknown to us at compile time. You can create a <code>String</code> from a string literal
using the <code>from</code> function, like so:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
</code></pre>
<p>The double colon (<code>::</code>) is an operator that allows us to namespace this
particular <code>from</code> function under the <code>String</code> type itself, rather than using
some sort of name like <code>string_from</code>. We’ll discuss this syntax more in the
“Method Syntax” and “Modules” chapters.</p>
<p>This kind of string <em>can</em> be mutated:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
s.push_str(&quot;, world!&quot;); // push_str() appends a literal to a String
println!(&quot;{}&quot;, s); // This will print `hello, world!`
</code></pre>
<p>So, what’s the difference here? Why can <code>String</code> be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.</p>
<h3>Memory and Allocation</h3>
<p>In the case of a string literal, because we know the contents at compile time,
the text is hard-coded directly into the final executable. This makes string
literals quite fast and efficient. But these properties only come from its
immutability. Unfortunately, we can’t put a blob of memory into the binary for
each piece of text whose size is unknown at compile time and whose size might
change over the course of running the program.</p>
<p>With the <code>String</code> type, in order to support a mutable, growable piece of text,
we need to allocate an amount of memory on the heap, unknown at compile time,
to hold the contents. This means two things:</p>
<ol>
<li>The memory must be requested from the operating system at runtime.</li>
<li>We need a way of giving this memory back to the operating system when we’re
done with our <code>String</code>.</li>
</ol>
<p>That first part is done by us: when we call <code>String::from</code>, its
implementation requests the memory it needs. This is pretty much universal in
programming languages.</p>
<p>The second case, however, is different. In languages with a <em>garbage collector</em>
(GC), the GC will keep track and clean up memory that isn't being used anymore,
and we, as the programmer, don’t need to think about it. Without GC, it’s the
programmer's responsibility to identify when memory is no longer being used and
call code to explicitly return it, just as we did to request it. Doing this
correctly has historically been a difficult problem in programming. If we
forget, we will waste memory. If we do it too early, we will have an invalid
variable. If we do it twice, that’s a bug too. We need to pair exactly one
<code>allocate</code> with exactly one <code>free</code>.</p>
<p>Rust takes a different path: the memory is automatically returned once the
binding to it goes out of scope. Here’s a version of our scope example from
earlier using <code>String</code>:</p>
<pre><code class="language-rust">{
let s = String::from(&quot;hello&quot;); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>There is a natural point at which we can return the memory our <code>String</code> needs
back to the operating system: when <code>s</code> goes out of scope. When a variable
binding goes out of scope, Rust calls a special function for us. This function
is called <code>drop</code>, and it is where the author of <code>String</code> can put the code to
return the memory. Rust calls <code>drop</code> automatically at the closing <code>}</code>.</p>
<blockquote>
<p>Note: This pattern is sometimes called *Resource Acquisition Is
Initialization* in C++, or RAII for short. While they are very similar,
Rust’s take on this concept has a number of differences, so we don’t tend
to use the same term. If you’re familiar with this idea, keep in mind that it
is <em>roughly</em> similar in Rust, but not identical.</p>
</blockquote>
<p>This pattern has a profound impact on the way that Rust code is written. It may
seem simple right now, but things can get tricky in more advanced situations
when we want to have multiple variable bindings use the data that we have
allocated on the heap. Let’s go over some of those situations now.</p>
<h4>Ways Bindings and Data Interact: Move</h4>
<p>There are different ways that multiple bindings can interact with the same data
in Rust. Let's take an example using an integer:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
</code></pre>
<p>We can probably guess what this is doing based on our experience with other
languages: “Bind the value <code>5</code> to <code>x</code>, then make a copy of the value in <code>x</code> and
bind it to <code>y</code>.” We now have two bindings, <code>x</code> and <code>y</code>, and both equal <code>5</code>.
This is indeed what is happening since integers are simple values with a known,
fixed size, and these two <code>5</code> values are pushed onto the stack.</p>
<p>Now let’s look at the <code>String</code> version:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
</code></pre>
<p>This looks very similar to the previous code, so we might assume that the way
it works would be the same: that the second line would make a copy of the value
in <code>s1</code> and bind it to <code>s2</code>. This isn't quite what happens.</p>
<p>To explain this more thoroughly, let’s take a look at what <code>String</code> looks like
under the covers in Figure 4-1. A <code>String</code> is made up of three parts, shown on
the left: a pointer to the memory that holds the contents of the string, a
length, and a capacity. This group of data is stored on the stack. On the right
is the memory that holds the contents, and this is on the heap.</p>
<p><img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" /></p>
<p>Figure 4-1: Representation in memory of a <code>String</code> holding the value &quot;hello&quot;
bound to <code>s1</code></p>
<p>The length is how much memory, in bytes, the contents of the <code>String</code> is
currently using. The capacity is the total amount of memory, in bytes, that the
<code>String</code> has gotten from the operating system. The difference between length
and capacity matters but not in this context, so for now, it's fine to ignore
the capacity.</p>
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> data itself is copied, meaning we
copy the pointer, the length, and the capacity that are on the stack. We do not
copy the data on the heap that the <code>String</code>'s pointer refers to. In other
words, it looks like figure 4-2.</p>
<p><img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" /></p>
<p>Figure 4-2: Representation in memory of the binding <code>s2</code> that has a copy of
<code>s1</code>'s pointer, length and capacity</p>
<p>And <em>not</em> Figure 4-3, which is what memory would look like if Rust instead
copied the heap data as well. If Rust did this, the operation <code>s2 = s1</code> could
potentially be very expensive if the data on the heap was large.</p>
<p><img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" /></p>
<p>Figure 4-3: Another possibility for what <code>s2 = s1</code> might do, if Rust chose to
copy heap data as well.</p>
<p>Earlier, we said that when a binding goes out of scope, Rust will automatically
call the <code>drop</code> function and clean up the heap memory for that binding. But
in figure 4-2, we see both data pointers pointing to the same location. This is
a problem: when <code>s2</code> and <code>s1</code> go out of scope, they will both try to free the
same memory. This is known as a <em>double free</em> error and is one of the memory
safety bugs we mentioned before. Freeing memory twice can lead to memory
corruption, which can potentially lead to security vulnerabilities.</p>
<p>In order to ensure memory safety, there's one more detail to what happens in
this situation in Rust. Instead of trying to copy the allocated memory, Rust
says that <code>s1</code> is no longer valid and, therefore, doesn’t need to free anything
when it goes out of scope. Check out what happens when you try to use <code>s1</code>
after <code>s2</code> is created:</p>
<pre><code class="language-rust,ignore">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
println!(&quot;{}&quot;, s1);
</code></pre>
<p>You’ll get an error like this:</p>
<pre><code class="language-bash">5:22 error: use of moved value: `s1` [E0382]
println!(&quot;{}&quot;, s1);
^~
5:24 note: in this expansion of println! (defined in &lt;std macros&gt;)
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default
let s2 = s1;
^~
</code></pre>
<p>If you have heard the terms &quot;shallow copy&quot; and &quot;deep copy&quot; 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 binding, instead of calling this a shallow copy,
it's known as a <em>move</em>. Here we would read this by saying that <code>s1</code> was <em>moved</em>
into <code>s2</code>. So what actually happens looks like Figure 4-4.</p>
<p><img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" /></p>
<p>Figure 4-4: Representation in memory after <code>s1</code> has been invalidated</p>
<p>That solves our problem! With only <code>s2</code> valid, when it goes out of scope, it
alone will free the memory, and we’re done.</p>
<p>Furthermore, there’s a design choice that’s implied by this: Rust will never
automatically create &quot;deep&quot; copies of your data. Therefore, any <em>automatic</em>
copying can be assumed to be inexpensive.</p>
<h4>Ways Bindings and Data Interact: Clone</h4>
<p>If we <em>do</em> want to deeply copy the <code>String</code>’s data and not just the <code>String</code>
itself, there’s a common method for that: <code>clone</code>. We will discuss methods in
the section on <a href="ch05-01-structs.html"><code>structs</code> in Chapter XX</a><!-- ignore -->, but they’re a
common enough feature in many programming languages that you have probably seen
them before.</p>
<p>Here’s an example of the <code>clone</code> method in action:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1.clone();
println!(&quot;s1 = {}, s2 = {}&quot;, s1, s2);
</code></pre>
<p>This will work just fine, and this is how you can explicitly get the behavior
we showed in Figure 4-3, where the heap data <em>does</em> get copied.</p>
<p>When you see a call to <code>clone</code>, you know that some arbitrary code is being
executed, and that code may be expensive. It’s a visual indicator that something
different is going on here.</p>
<h4>Stack-only Data: Copy</h4>
<p>There’s another wrinkle we haven’t talked about yet. This code, that we showed
earlier, works and is valid:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!(&quot;x = {}, y = {}&quot;, x, y);
</code></pre>
<p>This seems to contradict what we just learned: we don't have a call to
<code>clone</code>, but <code>x</code> is still valid, and wasn't moved into <code>y</code>.</p>
<p>This is because types like integers that have a known size at compile time are
stored entirely on the stack, so copies of the actual values are quick to make.
That means there's no reason we would want to prevent <code>x</code> from being valid
after we create the binding <code>y</code>. In other words, there’s no difference between
deep and shallow copying here, so calling <code>clone</code> wouldn’t do anything
differently from the usual shallow copying and we can leave it out.</p>
<p>Rust has a special annotation called the <code>Copy</code> trait that we can place on
types like these (we'll talk more about traits in Chapter XX). If a type has
the <code>Copy</code> trait, an older binding is still usable after assignment. Rust will
not let us annotate a type with the <code>Copy</code> trait if the type, or any of its
parts, has implemented <code>drop</code>. If the type needs something special to happen
when the value goes out of scope and we add the <code>Copy</code> annotation to that type,
we will get a compile-time error.</p>
<p>So what types are <code>Copy</code>? You can check the documentation for the given type to
be sure, but as a rule of thumb, any group of simple scalar values can be Copy,
and nothing that requires allocation or is some form of resource is <code>Copy</code>.
Here’s some of the types that are <code>Copy</code>:</p>
<ul>
<li>All of the integer types, like <code>u32</code>.</li>
<li>The booleans, <code>true</code> and <code>false</code>.</li>
<li>All of the floating point types, like <code>f64</code>.</li>
<li>Tuples, but only if they contain types which are also <code>Copy</code>. <code>(i32, i32)</code>
is <code>Copy</code>, but <code>(i32, String)</code> is not.</li>
</ul>
<h3>Ownership and Functions</h3>
<p>The semantics for passing a value to a function are similar to assigning a
value to a binding. Passing a binding to a function will move or copy, just
like assignment. Here’s an example, with some annotations showing where bindings
go into and out of scope:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;); // s comes into scope.
takes_ownership(s); // s's value moves into the function...
// ... and so is no longer valid here.
let x = 5; // x comes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so it’s okay to still
// use x afterward.
} // Here, x goes out of scope, then s. But since s's value was moved, nothing
// special happens.
fn takes_ownership(some_string: String) { // some_string comes into scope.
println!(&quot;{}&quot;, some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope.
println!(&quot;{}&quot;, some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
</code></pre>
<p>If we tried to use <code>s</code> after the call to <code>takes_ownership</code>, Rust
would throw a compile-time error. These static checks protect us from mistakes.
Try adding code to <code>main</code> that uses <code>s</code> and <code>x</code> to see where you can use them
and where the ownership rules prevent you from doing so.</p>
<h3>Return Values and Scope</h3>
<p>Returning values can also transfer ownership. Here's an example with similar annotations:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1.
let s2 = String::from(&quot;hello&quot;); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3.
} // Here, s3 goes out of scope, and is dropped. s2 goes out of scope, but was
// moved, so nothing happens. s1 goes out of scope, and is dropped.
fn gives_ownership() -&gt; String { // gives_ownership will move its
// return value into the function
// that calls it.
let some_string = String::from(&quot;hello&quot;); // some_string comes into scope.
some_string // some_string is returned, and
// moves out to the calling
// function.
}
// takes_and_gives_back will both take a String and return one
fn takes_and_gives_back(a_string: String) -&gt; String { // a_string comes into scope
a_string // a_string is returned, and moves out to the calling function
}
</code></pre>
<p>It’s the same pattern, every time: assigning a value to another binding moves
it, and when heap data values' bindings go out of scope, if the data hasn’t
been moved to be owned by another binding, the value will be cleaned up by
<code>drop</code>.</p>
<p>Taking ownership then returning ownership with every function is a bit tedious.
What if we want to let a function use a value but not take ownership? It’s
quite annoying that anything we pass in also needs to be passed back if we want
to use it again, in addition to any data resulting from the body of the
function that we might want to return as well.</p>
<p>It is possible to return multiple values using a tuple, like this:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let (s2, len) = calculate_length(s1);
println!(&quot;The length of '{}' is {}.&quot;, s2, len);
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
</code></pre>
<p>But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for this concept: references.</p>
<h2>References and Borrowing</h2>
<p>The issue with the tuple code at the end of the last section is that we have to
return the <code>String</code> back to the calling function so that we can still use the
<code>String</code> after the call to <code>calculate_length</code>, since the <code>String</code> was moved
into <code>calculate_length</code>.</p>
<p>Here is how you would use a function without taking ownership of it using
<em>references:</em></p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let len = calculate_length(&amp;s1);
println!(&quot;The length of '{}' is {}.&quot;, s1, len);
}
fn calculate_length(s: &amp;String) -&gt; usize {
let length = s.len();
length
}
</code></pre>
<p>First, you’ll notice all of the tuple stuff in the binding declaration and the
function return value is gone. Next, note that we pass <code>&amp;s1</code> into
<code>calculate_length</code>, and in its definition, we take <code>&amp;String</code> rather than
<code>String</code>.</p>
<p>These <code>&amp;</code>s are <em>references</em>, and they allow you to refer to some value
without taking ownership of it. Figure 4-5 shows a diagram of this.</p>
<p><img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" /></p>
<p>Figure 4-5: <code>&amp;String s</code> pointing at <code>String s1</code></p>
<p>Let’s take a closer look at the function call here:</p>
<pre><code class="language-rust"># fn calculate_length(s: &amp;String) -&gt; usize {
# let length = s.len();
#
# length
# }
let s1 = String::from(&quot;hello&quot;);
let len = calculate_length(&amp;s1);
</code></pre>
<p>The <code>&amp;s1</code> syntax lets us create a reference which <em>refers</em> to the value of <code>s1</code>
but does not own it. Because it does not own it, the value it points to will
not be dropped when the reference goes out of scope.</p>
<p>Likewise, the signature of the function uses <code>&amp;</code> to indicate that it takes
a reference as an argument. Let’s add some explanatory annotations:</p>
<pre><code class="language-rust">fn calculate_length(s: &amp;String) -&gt; usize { // s is a reference to a String
let length = s.len();
length
} // Here, s goes out of scope. But since it does not have ownership of what
// it refers to, nothing happens.
</code></pre>
<p>It’s the same process as before, but we don’t drop what the reference points to
when it goes out of scope because we don't have ownership. This lets us write
functions which take references as arguments instead of the values themselves,
so that we won’t need to return them to give back ownership.</p>
<p>We call this process <em>borrowing</em>. Just like with real life, if a person owns
something, you can borrow it from them, and when you’re done, you have to give
it back.</p>
<p>So what happens if we try to modify something we're borrowing? Try this code
out. Spoiler alert: it doesn’t work!</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let s = String::from(&quot;hello&quot;);
change(&amp;s);
}
fn change(some_string: &amp;String) {
some_string.push_str(&quot;, world&quot;);
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-bash">error: cannot borrow immutable borrowed content `*some_string` as mutable
--&gt; error.rs:8:5
|
8 | some_string.push_str(&quot;, world&quot;);
| ^^^^^^^^^^^
</code></pre>
<p>Just as bindings are immutable by default, so are references. We’re not allowed
to modify something we have a reference to.</p>
<h3>Mutable References</h3>
<p>We can fix this error with just a small tweak:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let mut s = String::from(&quot;hello&quot;);
change(&amp;mut s);
}
fn change(some_string: &amp;mut String) {
some_string.push_str(&quot;, world&quot;);
}
</code></pre>
<p>First, we had to change <code>s</code> to be <code>mut</code>. Then we had to create a mutable
reference with <code>&amp;mut s</code> and accept a mutable reference with <code>some_string: &amp;mut String</code>.</p>
<p>Mutable references have one big restriction, though: you can only have one
mutable reference to a particular piece of data in a particular scope. This
code will fail:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">let mut s = String::from(&quot;hello&quot;);
let r1 = &amp;mut s;
let r2 = &amp;mut s;
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-bash">error[E0499]: cannot borrow `s` as mutable more than once at a time
--&gt; borrow_twice.rs:5:19
|
4 | let r1 = &amp;mut s;
| - first mutable borrow occurs here
5 | let r2 = &amp;mut s;
| ^ second mutable borrow occurs here
6 | }
| - first borrow ends here
</code></pre>
<p>This restriction allows for mutation but in a very controlled fashion. It is
something that new Rustaceans struggle with, because most languages let you
mutate whenever you’d like. The benefit of having this restriction is that Rust
can prevent data races at compile time. A <em>data race</em> is a particular type of
race condition where two or more pointers access the same data at the same
time, at least one of the pointers is being used to write to the data, and
there's no mechanism being used to synchronize access to the data. Data races
cause undefined behavior and can be difficult to diagnose and fix when trying
to track them down at runtime; Rust prevents this problem from happening since
it won't even compile code with data races!</p>
<p>As always, we can use <code>{}</code>s to create a new scope, allowing for multiple mutable
references, just not <em>simultaneous</em> ones:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
{
let r1 = &amp;mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &amp;mut s;
</code></pre>
<p>There is a similar rule for combining mutable and immutable references. This
code errors:</p>
<pre><code class="language-rust,ignore">let mut s = String::from(&quot;hello&quot;);
let r1 = &amp;s; // no problem
let r2 = &amp;s; // no problem
let r3 = &amp;mut s; // BIG PROBLEM
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-bash">error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--&gt; borrow_thrice.rs:6:19
|
4 | let r1 = &amp;s; // no problem
| - immutable borrow occurs here
5 | let r2 = &amp;s; // no problem
6 | let r3 = &amp;mut s; // BIG PROBLEM
| ^ mutable borrow occurs here
7 | }
| - immutable borrow ends here
</code></pre>
<p>Whew! We <em>also</em> cannot have a mutable reference while we have an immutable one.
Users of an immutable reference don’t expect the values to suddenly change out
from under them! Multiple immutable references are okay, however, since no one
who is just reading the data has the ability to affect anyone else's reading of
the data.</p>
<p>Even though these errors may be frustrating at times, remember that it's the
Rust compiler pointing out a potential bug earlier (at compile time rather than
at runtime) and showing you exactly where the problem is instead of you having
to track down why sometimes your data isn't what you thought it should be.</p>
<h3>Dangling References</h3>
<p>In languages with pointers, it's easy to make the error of creating a <em>dangling
pointer</em>, a pointer referencing a location in memory that may have been given
to someone else, by freeing some memory while keeping around a pointer to that
memory. In Rust, by contrast, the compiler guarantees that references will
never be dangling: if we have a reference to some data, the compiler will
ensure that the data will not go out of scope before the reference to the data
does.</p>
<p>Let’s try to create a dangling reference:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -&gt; &amp;String {
let s = String::from(&quot;hello&quot;);
&amp;s
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-bash">error[E0106]: missing lifetime specifier
--&gt; dangle.rs:5:16
|
5 | fn dangle() -&gt; &amp;String {
| ^^^^^^^
|
= help: this function's return type contains a borrowed value, but there is no
value for it to be borrowed from
= help: consider giving it a 'static lifetime
error: aborting due to previous error
</code></pre>
<p>This error message refers to a feature we haven’t learned about yet:
<em>lifetimes</em>. We'll discuss lifetimes in detail in Chapter XX, but, disregarding
the parts about lifetimes, the message does contain the key to why this code is
a problem: <code>this function’s return type contains a borrowed value, but there is no value for it to be borrowed from</code>.</p>
<p>Let’s have a closer look at exactly what's happening at each stage of our
<code>dangle</code> code:</p>
<pre><code class="language-rust,ignore">fn dangle() -&gt; &amp;String { // dangle returns a reference to a String
let s = String::from(&quot;hello&quot;); // s is a new String
&amp;s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
// Danger!
</code></pre>
<p>Because <code>s</code> is created inside of <code>dangle</code>, when the code of <code>dangle</code> is
finished, it will be deallocated. But we tried to return a reference to it.
That means this reference would be pointing to an invalid <code>String</code>! That’s
no good. Rust won’t let us do this.</p>
<p>The correct code here is to return the <code>String</code> directly:</p>
<pre><code class="language-rust">fn no_dangle() -&gt; String {
let s = String::from(&quot;hello&quot;);
s
}
</code></pre>
<p>This works, no problem. Ownership is moved out, nothing is deallocated.</p>
<h3>The Rules of References</h3>
<p>Here’s a recap of what we’ve talked about:</p>
<ol>
<li>At any given time, you may have <em>either</em>, but not both of:
<ol>
<li>One mutable reference.</li>
<li>Any number of immutable references.</li>
</ol>
</li>
<li>References must always be valid.</li>
</ol>
<p>Next, let's look at a different kind of reference: slices.</p>
<h2>Slices</h2>
<p>There is another data type which does not have ownership: slices. Slices let
you reference a contiguous sequence of elements in a collection rather than the
whole collection itself.</p>
<p>Here’s a small programming problem: write a function which takes a string and
returns the first word it finds in that string. If it doesn’t find a space in
the string, it means the whole string is one word, so the whole thing should be
returned.</p>
<p>Let’s think about the signature of this function:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; ?
</code></pre>
<p>This function, <code>first_word</code>, takes a <code>&amp;String</code> as an argument. We don’t want
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about <em>part</em> of a string. We could return the index of the end of
the word, though. Let’s try that:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; usize {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
</code></pre>
<p>Let’s break that down a bit:</p>
<pre><code class="language-rust,ignore">let bytes = s.as_bytes();
</code></pre>
<p>Since we need to go through the String element by element and
check if a value is a space, we will convert our String to an
array of bytes using the <code>as_bytes</code> method.</p>
<pre><code class="language-rust,ignore">for (i, &amp;item) in bytes.iter().enumerate() {
</code></pre>
<p>We will be discussing iterators in more detail in Chapter XX, but for now, know
that <code>iter</code> is a method that returns each element in a collection, and
<code>enumerate</code> modifies the result of <code>iter</code> and returns each element as part
of a tuple instead, where the first element of the tuple is the index, and the
second element is a reference to the element itself. This is a bit nicer than
calculating the index ourselves.</p>
<p>Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we
match against the tuple with <code>i</code> for the index and <code>&amp;item</code> for a single byte.
Since we get a reference from <code>.iter().enumerate()</code>, we use <code>&amp;</code> in the pattern.</p>
<pre><code class="language-rust,ignore"> if item == b' ' {
return i;
}
}
s.len()
</code></pre>
<p>We search for the byte that represents the space, using the byte literal
syntax. If we find a space, we return the position. Otherwise, we return the
length of the string, using <code>s.len()</code>.</p>
<p>We now have a way to find out the index of the end of the first word in the
string, but there’s a problem. We’re returning a <code>usize</code> on its own, but it’s
only a meaningful number in the context of the <code>&amp;String</code>. In other words,
because it’s a separate value from the <code>String</code>, there’s no guarantee that it
will still be valid in the future. Consider this program that uses this
<code>first_word</code> function:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust"># fn first_word(s: &amp;String) -&gt; usize {
# let bytes = s.as_bytes();
#
# for (i, &amp;item) in bytes.iter().enumerate() {
# if item == b' ' {
# return i;
# }
# }
#
# s.len()
# }
#
fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s); // word will get the value 5.
s.clear(); // This empties the String, making it equal to &quot;&quot;.
// word still has the value 5 here, but there's no more string that
// we could meaningfully use the value 5 with. word is now totally invalid!
}
</code></pre>
<p>This program compiles without any errors, and also would if we used <code>word</code>
after calling <code>s.clear()</code>. <code>word</code> isn't connected to the state of <code>s</code> at all,
so <code>word</code> still contains the value <code>5</code>. We could use that <code>5</code> with <code>s</code> to try
to extract the first word out, but this would be a bug since the contents of
<code>s</code> have changed since we saved <code>5</code> in <code>word</code>.</p>
<p>This is bad! It’s even worse if we wanted to write a <code>second_word</code>
function. Its signature would have to look like this:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; (usize, usize) {
</code></pre>
<p>Now we’re tracking both a start <em>and</em> an ending index, and we have even more
values that were calculated from data in a particular state but aren't tied to
that state at all. We now have three unrelated variable bindings floating
around which need to be kept in sync.</p>
<p>Luckily, Rust has a solution to this problem: string slices.</p>
<h3>String Slices</h3>
<p>A string slice is a reference to part of a <code>String</code>, and looks like this:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello world&quot;);
let hello = &amp;s[0..5];
let world = &amp;s[6..11];
</code></pre>
<p>This is similar to taking a reference to the whole <code>String</code>, but with the
extra <code>[0..5]</code> bit. Rather than a reference to the entire <code>String</code>, it’s a
reference to an internal position in the <code>String</code> and the number of elements
that it refers to.</p>
<p>We create slices with a range of <code>[starting_index..ending_index]</code>, but the
slice data structure actually stores the starting position and the length of the
slice. So in the case of <code>let world = &amp;s[6..11];</code>, <code>world</code> would be a slice that
contains a pointer to the 6th byte of <code>s</code> and a length value of 5.</p>
<p>Figure 4-6 shows this in a diagram:</p>
<p><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%;" /></p>
<p>Figure 4-6: String slice referring to part of a <code>String</code></p>
<p>With Rust’s <code>..</code> range syntax, if you want to start at the first index (zero),
you can drop the value before the <code>..</code>. In other words, these are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let slice = &amp;s[0..2];
let slice = &amp;s[..2];
</code></pre>
<p>By the same token, if your slice should include the last byte of the
<code>String</code>, you can drop the trailing number. That means these are
equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let len = s.len();
let slice = &amp;s[3..len];
let slice = &amp;s[3..];
</code></pre>
<p>You can also drop both values to take a slice of the entire string. So these
are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let len = s.len();
let slice = &amp;s[0..len];
let slice = &amp;s[..];
</code></pre>
<p>With this in mind, let’s re-write <code>first_word</code> to return a slice. The type
that signifies &quot;string slice&quot; is written as <code>&amp;str</code>:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;item) in bytes.iter().enumerate() {
if item == b' ' {
return &amp;s[0..i];
}
}
&amp;s[..]
}
</code></pre>
<p>We get the index for the end of the word in the same way as before, by looking
for the first occurrence of a space. When we find a space, we return a string
slice using the start of the string and the index of the space as the starting
and ending indices.</p>
<p>Now when we call <code>first_word</code>, we get back a single value that is tied to the
underlying data. The value is made up of a reference to the starting point of
the slice and the number of elements in the slice.</p>
<p>Returning a slice would also work for a <code>second_word</code> function:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>We now have a straightforward API that’s much harder to mess up. Remember our
bug from before, when we got the first word but then cleared the string so that
our first word was invalid? That code was logically incorrect but didn't show
any immediate errors. The problems would show up later, if we kept trying to
use the first word index with an emptied string. Slices make this bug
impossible, and let us know we have a problem with our code much sooner. Using
the slice version of <code>first_word</code> will throw a compile time error:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s);
s.clear(); // Error!
}
</code></pre>
<p>Here’s the compiler error:</p>
<pre><code class="language-bash">17:6 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
s.clear(); // Error!
^
15:29 note: previous borrow of `s` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `s` until the borrow ends
let word = first_word(&amp;s);
^
18:2 note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>Remember from the borrowing rules that if we have an immutable reference to
something, we cannot also take a mutable reference. Since <code>clear</code> needs to
truncate the <code>String</code>, it tries to take a mutable reference, which fails. Not
only has Rust made our API easier to use, but it’s also eliminated an entire
class of errors at compile time!</p>
<h4>String Literals are Slices</h4>
<p>Remember how we talked about string literals being stored inside of the binary
itself? Now that we know about slices, we can now properly understand string
literals.</p>
<pre><code class="language-rust">let s = &quot;Hello, world!&quot;;
</code></pre>
<p>The type of <code>s</code> here is <code>&amp;str</code>: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; <code>&amp;str</code> is an
immutable reference.</p>
<h4>String Slices as Arguments</h4>
<p>Knowing that you can take slices of both literals and <code>String</code>s leads us to
one more improvement on <code>first_word</code>, and that’s its signature:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>A more experienced Rustacean would write this one instead because it allows us
to use the same function on both <code>String</code>s and <code>&amp;str</code>s:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>If we have a string slice, we can pass that as the argument directly. If we
have a <code>String</code>, we can pass a slice of the entire <code>String</code>. This makes our API
more general and useful without losing any functionality:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust"># fn first_word(s: &amp;str) -&gt; &amp;str {
# let bytes = s.as_bytes();
#
# for (i, &amp;item) in bytes.iter().enumerate() {
# if item == b' ' {
# return &amp;s[0..i];
# }
# }
#
# &amp;s[..]
# }
fn main() {
let my_string = String::from(&quot;hello world&quot;);
// first_word works on slices of `String`s
let word = first_word(&amp;my_string[..]);
let my_string_literal = &quot;hello world&quot;;
// first_word works on slices of string literals
let word = first_word(&amp;my_string_literal[..]);
// since string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
}
</code></pre>
<h3>Other Slices</h3>
<p>String slices, as you might imagine, are specific to strings. But there’s a more
general slice type, too. Consider this array:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
</code></pre>
<p>Just like we may want to refer to a part of a string, we may want to refer to
part of an array, and would do so like this:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
let slice = &amp;a[1..3];
</code></pre>
<p>This slice has the type <code>&amp;[i32]</code>. It works the exact same way as string slices
do, by storing a reference to the first element and a length. You’ll use this
kind of slice for all sorts of other collections. We’ll discuss these in detail
when we talk about vectors in Chapter XX.</p>
<h2>Summary</h2>
<p>The concepts of ownership, borrowing, and slices are what ensure memory safety
in Rust programs at compile time. Rust is a language that gives you control
over your memory usage like other systems programming languages, but having the
owner of data automatically clean up that data when the owner goes out of scope
means you don't have to write and debug extra code to get this control.</p>
<p>Ownership affects how lots of other parts of Rust work, so we will be talking
about these concepts further throughout the rest of the book. Let's move on to
the next chapter where we'll look at grouping pieces of data together in a
<code>struct</code>.</p>
<h1>Structs</h1>
<p>A <code>struct</code>, short for <em>structure</em>, is a custom data type that lets us name and
package together multiple related values that make up a meaningful group. If
you come from an object-oriented language, a <code>struct</code> is like an object's data
attributes. In the next section of this chapter, we'll talk about how to define
methods on our structs; methods are how you specify the <em>behavior</em> that goes
along with a struct's data. The <code>struct</code> and <code>enum</code> (that we will talk about in
Chapter 6) concepts are the building blocks for creating new types in your
program's domain in order to take full advantage of Rust's compile-time type
checking.</p>
<p>One way of thinking about structs is that they are similar to tuples that 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, a struct to store information about a user account might look like:</p>
<pre><code class="language-rust">struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
</code></pre>
<p>To use a struct, we create an <em>instance</em> of that struct by specifying concrete
values for each of the fields. Creating an instance is done by declaring a
binding with <code>let</code>, stating the name of the struct, then curly braces with
<code>key: value</code> pairs inside it where the keys are the names of the fields and the
values are the data we want to store in those fields. The fields don't have to
be specified in the same order in which the struct declared them. In other
words, the struct definition is like a general template for the type, and
instances fill in that template with particular data to create values of the
type. For example, we can declare a particular user like this:</p>
<pre><code class="language-rust"># struct User {
# username: String,
# email: String,
# sign_in_count: u64,
# active: bool,
# }
#
let user1 = User {
email: String::from(&quot;someone@example.com&quot;),
username: String::from(&quot;someusername123&quot;),
active: true,
sign_in_count: 1,
};
</code></pre>
<p>To get a particular value out of a struct, we can use dot notation. If we
wanted just this user's email address, we can say <code>user1.email</code>.</p>
<h2>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 variable
bindings, then refactor our program until we're using <code>struct</code>s 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. Here’s a short program that has one way of doing just
that to put into our project's <code>src/main.rs</code>:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let length1 = 50;
let width1 = 30;
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(length1, width1)
);
}
fn area(length: u32, width: u32) -&gt; u32 {
length * width
}
</code></pre>
<p>Let's try running this program with <code>cargo run</code>:</p>
<pre><code class="language-bash">The area of the rectangle is 1500 square pixels.
</code></pre>
<h3>Refactoring with Tuples</h3>
<p>Our little program works okay; it figures out the area of the rectangle by
calling the <code>area</code> function with each dimension. But we can do better. The
length and the width are related to each other since together they describe one
rectangle.</p>
<p>The issue with this method is evident in the signature of <code>area</code>:</p>
<pre><code class="language-rust,ignore">fn area(length: u32, width: u32) -&gt; u32 {
</code></pre>
<p>The area 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. Here’s a
version of our program which uses tuples:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let rect1 = (50, 30);
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(rect1)
);
}
fn area(dimensions: (u32, u32)) -&gt; u32 {
dimensions.0 * dimensions.1
}
</code></pre>
<!-- 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 <code>struct</code>s. We can transform our tuple into a data
type with a name for the whole as well as names for the parts:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
area(&amp;rect1)
);
}
fn area(rectangle: &amp;Rectangle) -&gt; u32 {
rectangle.length * rectangle.width
}
</code></pre>
<!-- Will add ghosting & wingdings once we're in libreoffice /Carol -->
<p>Here we've defined a <code>struct</code> and given it the name <code>Rectangle</code>. Inside the
<code>{}</code> we defined the fields to be <code>length</code> and <code>width</code>, both of which have type
<code>u32</code>. Then in <code>main</code>, we create a particular instance of a <code>Rectangle</code> that
has a length of 50 and a width of 30.</p>
<p>Our <code>area</code> function now takes one argument that we've named <code>rectangle</code> whose
type is an immutable borrow of a struct <code>Rectangle</code> instance. As we covered in
Chapter 4, we want to borrow the struct rather than take ownership of it so
that <code>main</code> keeps its ownership and can continue using <code>rect1</code>, so that's why
we have the <code>&amp;</code> in the function signature and at the call site.</p>
<p>The <code>area</code> function accesses the <code>length</code> and <code>width</code> fields of the <code>Rectangle</code>
instance it got as an argument. Our function signature for <code>area</code> now says
exactly what we mean: calculate the area of a <code>Rectangle</code>, using its <code>length</code>
and <code>width</code> fields. This conveys that the length and width are related to each
other, and gives descriptive names to the values rather than using the tuple
index values of <code>0</code> and <code>1</code>. This is a win for clarity.</p>
<h3>Adding Useful Functionality with Derived Traits</h3>
<p>It'd be nice to be able to print out an instance of our <code>Rectangle</code> while we're
debugging our program and see the values for all its fields. Let's try using
the <code>println!</code> macro as we have been and see what happens:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(&quot;rect1 is {}&quot;, rect1);
}
</code></pre>
<p>If we run this, we get an error with this core message:</p>
<pre><code class="language-bash">error: 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-bash">note: `Rectangle` cannot be formatted with the default formatter; try using
`:?` instead if you are using a format string
</code></pre>
<p>Let's try it! The <code>println!</code> will now look like
<code>println!(&quot;rect1 is {:?}&quot;, rect1);</code>. Putting the specifier <code>:?</code> inside
the <code>{}</code> tells <code>println!</code> we want to use an output format called <code>Debug</code>.
<code>Debug</code> is a trait that enables us to print out our struct in a way that is
useful for developers so that we can see its value while we are debugging our
code.</p>
<p>Let's try running with this change and... drat. We still get an error:</p>
<pre><code class="language-bash">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-bash">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. Now our program looks like this:</p>
<pre><code class="language-rust">#[derive(Debug)]
struct Rectangle {
length: u32,
width: u32,
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(&quot;rect1 is {:?}&quot;, rect1);
}
</code></pre>
<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-bash">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.</p>
<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 XX. 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 XX 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:</p>
<pre><code class="language-rust">#[derive(Debug)]
struct Rectangle {
length: u32,
width: u32,
}
impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.length * self.width
}
}
fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
println!(
&quot;The area of the rectangle is {} square pixels.&quot;,
rect1.area()
);
}
</code></pre>
<!-- 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.</p>
<p>In the signature for <code>area</code>, we get to use <code>&amp;self</code> instead of <code>rectangle: &amp;Rectangle</code> because Rust knows the type of <code>self</code> is <code>Rectangle</code> due to this
method being inside the <code>impl Rectangle</code> context. Note we still need to have
the <code>&amp;</code> before <code>self</code>, just like we had <code>&amp;Rectangle</code>. Methods can choose to
take ownership of <code>self</code>, borrow <code>self</code> immutably as we've done here, or borrow
<code>self</code> mutably, just like any other argument.</p>
<p>We've chosen <code>&amp;self</code> here for the same reason we used <code>&amp;Rectangle</code> in the
function version: we don't want to take ownership, and we just want to be able
to read the data in the struct, not write to it. If we wanted to be able to
change the instance that we've called the method on as part of what the method
does, we'd put <code>&amp;mut self</code> as the first argument instead. Having a method that
takes ownership of the instance by having just <code>self</code> as the first argument is
rarer; this is usually used when the method transforms <code>self</code> into something
else and we want to prevent the caller from using the original instance after
the transformation.</p>
<p>The main benefit of using methods over functions, in addition to getting to use
method syntax and not having to repeat the type of <code>self</code> in every method's
signature, is for organization. We've put all the things we can do with an
instance of a type together in one <code>impl</code> block, rather than make future users
of our code search for capabilities of <code>Rectangle</code> all over the place.</p>
<!-- PROD: START BOX -->
<h4>Where's the <code>-&gt;</code> operator?</h4>
<p>In languages like C++, there are two different operators for calling methods:
<code>.</code> if you're calling a method on the object directly, and <code>-&gt;</code> if you're
calling the method on a pointer to the object and thus need to dereference the
pointer first. In other words, if <code>object</code> is a pointer, <code>object-&gt;something()</code>
is like <code>(*object).something()</code>.</p>
<p>Rust doesn't have an equivalent to the <code>-&gt;</code> operator; instead, Rust has a
feature called <em>automatic referencing and dereferencing</em>. Calling methods is
one of the few places in Rust that has behavior like this.</p>
<p>Here’s how it works: when you call a method with <code>object.something()</code>, Rust
will automatically add in <code>&amp;</code>, <code>&amp;mut</code>, or <code>*</code> so that <code>object</code> matches the
signature of the method. In other words, these are the same:</p>
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
# struct Point {
# x: f64,
# y: f64,
# }
#
# impl Point {
# fn distance(&amp;self, other: &amp;Point) -&gt; f64 {
# let x_squared = f64::powi(other.x - self.x, 2);
# let y_squared = f64::powi(other.y - self.y, 2);
#
# f64::sqrt(x_squared + y_squared)
# }
# }
# let p1 = Point { x: 0.0, y: 0.0 };
# let p2 = Point { x: 5.0, y: 6.5 };
p1.distance(&amp;p2);
(&amp;p1).distance(&amp;p2);
</code></pre>
<p>The first one looks much, much cleaner. This automatic referencing behavior
works because methods have a clear receiver — the type of <code>self</code>. Given the
receiver and name of a method, Rust can figure out definitively whether the
method is just reading (so needs <code>&amp;self</code>), mutating (so <code>&amp;mut self</code>), or
consuming (so <code>self</code>). The fact that Rust makes borrowing implicit for method
receivers is a big part of making ownership ergonomic in practice.</p>
<!-- 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
this code:</p>
<pre><code class="language-rust,ignore">fn main() {
let rect1 = Rectangle { length: 50, width: 30 };
let rect2 = Rectangle { length: 40, width: 10 };
let rect3 = Rectangle { length: 45, width: 60 };
println!(&quot;Can rect1 hold rect2? {}&quot;, rect1.can_hold(&amp;rect2));
println!(&quot;Can rect1 hold rect3? {}&quot;, rect1.can_hold(&amp;rect3));
}
</code></pre>
<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-bash">Can rect1 hold rect2? true
Can rect1 hold rect3? false
</code></pre>
<p>We know we want to define a method, so it will be within the <code>impl Rectangle</code>
block. The method name will be <code>can_hold</code>, and it will take an immutable borrow
of another <code>Rectangle</code> as an argument. We can tell what the type of the
argument will be by looking at a call site: <code>rect1.can_hold(&amp;rect2)</code> passes in
<code>&amp;rect2</code>, which is an immutable borrow to <code>rect2</code>, an instance of <code>Rectangle</code>.
This makes sense, since we only need to read <code>rect2</code> (rather than write, which
would mean we'd need a mutable borrow) and we want <code>main</code> to keep ownership of
<code>rect2</code> so that we could use it again after calling this method. The return
value of <code>can_hold</code> will be a boolean, and the implementation will check to see
if <code>self</code>'s length and width are both greater than the length and width of the
other <code>Rectangle</code>, respectively. Let's write that code!</p>
<pre><code># #[derive(Debug)]
# struct Rectangle {
# length: u32,
# width: u32,
# }
#
impl Rectangle {
fn area(&amp;self) -&gt; u32 {
self.length * self.width
}
fn can_hold(&amp;self, other: &amp;Rectangle) -&gt; bool {
self.length &gt; other.length &amp;&amp; self.width &gt; other.width
}
}
</code></pre>
<!-- Will add ghosting here in libreoffice /Carol -->
<p>If we run this with the <code>main</code> from earlier, 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>
<pre><code class="language-rust"># #[derive(Debug)]
# struct Rectangle {
# length: u32,
# width: u32,
# }
#
impl Rectangle {
fn square(size: u32) -&gt; Rectangle {
Rectangle { length: size, width: size }
}
}
</code></pre>
<p>To call this associated function, we use the <code>::</code> syntax with the struct name:
<code>let sq = Rectange::square(3);</code>, for example. It's kind of 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>
<h1>Enums</h1>
<p>Next, let’s look at <em>enumerations</em>, which allow you to define a type by
enumerating its possible values. Commonly called &quot;enums&quot;, these unlock a lot of
power in Rust when combined with pattern matching. Enums are a feature that are
in many languages, but what they can do is different per-language. Rust’s enums
are most similar to &quot;algebraic data types&quot; in functional languages like F#,
OCaml, or Haskell.</p>
<p>Here’s an example of an enum definition:</p>
<pre><code class="language-rust">enum IpAddrKind {
V4,
V6,
}
</code></pre>
<p>This enum represents the kind of an IP address. There are two major standards
used for IP addresses: version four and version six. Any IP address can be
either a version four address or a version six address, but it cannot be both
kinds at the same time. This is where enums get their name: they allow us to
enumerate all of the possible kinds that our value can have.</p>
<p>We can create values 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 name, and we use
the double colon to separate the two.</p>
<p>Enums have more tricks up their sleeves, however. Thinking more about our IP
address type, we don’t have a way to store the actual data of the IP address;
we only know what kind it is. Given that you just learned about structs, you
might tackle this problem like this:</p>
<pre><code class="language-rust">enum IpAddrKind {
V4,
V6,
}
struct IpAddr {
kind: IpAddrKind,
address: String,
}
let home = IpAddr {
kind: IpAddrKind::V4,
address: String::from(&quot;127.0.0.1&quot;),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from(&quot;::1&quot;),
};
</code></pre>
<p>We’ve used a struct to bundle the two values together: now we keep the kind
with the value itself. We can represent the same thing in a different way with
just an enum:</p>
<pre><code class="language-rust">enum IpAddr {
V4(String),
V6(String),
}
let home = IpAddr::V4(String::from(&quot;127.0.0.1&quot;));
let loopback = IpAddr::V6(String::from(&quot;::1&quot;));
</code></pre>
<p>We can attach data to each variant of the enum directly. No need for an extra
struct. But beyond that, this approach is better than using a struct alongside
our enum because we can attach different kinds of data to each variant.
Imagine that instead of a <code>String</code>, we would prefer to store a <code>V4</code> as its four
individual components while leaving the <code>V6</code> variant as a <code>String</code>. With our
struct, we’d be stuck. But enums deal with this case with ease:</p>
<pre><code class="language-rust">enum IpAddr {
V4(u8, u8, u8, u8),
V6(String),
}
let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from(&quot;::1&quot;));
</code></pre>
<p>You can put any kind of data inside of an enum variant, including another enum!
The <code>IpAddr</code> enum is <a href="../std/net/enum.IpAddr.html">in the standard library</a><!-- ignore -->, but it
embeds two different structs inside of its variants:</p>
<pre><code class="language-rust">struct Ipv4Addr {
// details elided
}
struct Ipv6Addr {
// details elided
}
enum IpAddr {
V4(Ipv4Addr),
V6(Ipv6Addr),
}
</code></pre>
<p>Here’s an enum with a 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>
<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 might seem overwhelming, but another way to look at the different enum
possibilities is that they are just like different kinds of struct definitions
that you already know, except without the <code>struct</code> keyword and they are grouped
together under the <code>Message</code> type. These structs could hold the same data that
these enum variants hold:</p>
<pre><code class="language-rust">struct QuitMessage; // unit struct
struct MoveMessage {
x: i32,
y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple struct
</code></pre>
<p>Let's look at another enum in the standard library that is very common and
useful: <code>Option</code>.</p>
<h2>Option</h2>
<p>Now that we have had an introduction to enums, let's combine them with a
feature that we talked a little bit about in the previous chapter: generics.</p>
<p>Programming language design is often thought of as which features you include,
but it's also about which features you leave out. Rust does not have a feature
that is in many other languages: <em>null</em>. In languages with this feature,
variables can have two states: null or not-null.</p>
<p>The inventor of this concept has this to say:</p>
<blockquote>
<p>I call it my billion-dollar mistake. At that time, I was designing the first
comprehensive type system for references in an object-oriented language. My
goal was to ensure that all use of references should be absolutely safe, with
checking performed automatically by the compiler. But I couldn't resist the
temptation to put in a null reference, simply because it was so easy to
implement. This has led to innumerable errors, vulnerabilities, and system
crashes, which have probably caused a billion dollars of pain and damage in
the last forty years.</p>
<ul>
<li>Tony Hoare &quot;Null References: The Billion Dollar Mistake&quot;</li>
</ul>
</blockquote>
<p>The problem with null values is twofold: first, a value can be null or not, at
any time. The second is that if you try to use a value that's null, you'll get
an error of some kind, depending on the language. Because this property is
pervasive, it's extremely easy to make this kind of error.</p>
<p>Even with these problems, the concept that null is trying to express is still a
useful one: this is a value which is currently invalid or not present for some
reason. The problem isn't with the concept itself, but with the particular
implementation. As such, Rust does not have the concept of null, but we do have
an enum which can encode the concept of a value being present or not present. We
call this enum <code>Option&lt;T&gt;</code>, and it looks like this:</p>
<pre><code class="language-rust">enum Option&lt;T&gt; {
Some(T),
None,
}
</code></pre>
<p>This enum is <a href="../std/option/enum.Option.html">provided by the standard library</a><!-- ignore -->, and is
so useful that it's even in the prelude; you don't need to import it
explicitly. Furthermore, so are its variants: you can say <code>Some</code> and <code>None</code>
directly, without prefixing them with <code>Option::</code>.</p>
<p>Here's an example of using <code>Option&lt;T&gt;</code>:</p>
<pre><code class="language-rust">let some_number = Some(5);
let some_string = Some(&quot;a string&quot;);
// If we only say None, we need to tell Rust what type of Option&lt;T&gt; we have.
let absent_number: Option&lt;i32&gt; = None;
</code></pre>
<p>Let's dig in. First, you'll notice that we used the <code>&lt;T&gt;</code> syntax when defining
<code>Option&lt;T&gt;</code>: it's a generic enum. <code>Option&lt;T&gt;</code> has two variants: <code>Some</code>, which
contains a <code>T</code>, and <code>None</code>, which has no data associated with it. In some
sense, <code>None</code> means &quot;null&quot;, and <code>Some</code> means &quot;not null&quot;. So why is this any
better than null?</p>
<p>In short, because <code>Option&lt;T&gt;</code> and <code>T</code> are different types. That's a bit too
short though. Here's an example:</p>
<pre><code class="language-rust,ignore">let x: i8 = 5;
let y: Option&lt;i8&gt; = Some(5);
let sum = x + y;
</code></pre>
<p>This will not compile. We get an error message like this:</p>
<pre><code class="language-bash">error: the trait bound `i8: std::ops::Add&lt;std::option::Option&lt;i8&gt;&gt;` is not
satisfied [E0277]
let sum = x + y;
^~~~~
</code></pre>
<p>Intense! What this error message is trying to say is that Rust does not
understand how to add an <code>Option&lt;T&gt;</code> and a <code>T</code>. They're different types! This
shows one of the big advantages of an <code>Option&lt;T&gt;</code>: if you have a value that
may or may not exist, you have to deal with that fact before you can assume it
exists. In other words, you have to convert an <code>Option&lt;T&gt;</code> to a <code>T</code> before you
can do <code>T</code> stuff with it. This helps catch one of the most common issues with
null, generally: assuming that something isn't null when it actually is.</p>
<p>This is pretty powerful: in order to have a value that can possibly be null,
you have to explicitly opt in by making the type of that value an <code>Option&lt;T&gt;</code>.
Then, when you use that value, you are required to explicitly handle the case
when the value is null. Everywhere that a value has a type that isn't an
<code>Option&lt;T&gt;</code>, you <em>can</em> safely assume that the value isn't null. This was a
deliberate design decision for Rust to limit null's pervasiveness and increase
the safety of Rust code.</p>
<p>So, how <em>do</em> you get a <code>T</code> from an <code>Option&lt;T&gt;</code>? The <code>Option&lt;T&gt;</code> enum has a
large number of methods 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>But we want a deeper understanding than that. If we didn't have those methods
defined for us already, what would we do? And more generally, how do we get
the inner values out of any enum variant? We need a new feature: <code>match</code>.</p>
<h2>Match</h2>
<p>Rust has an extremely powerful control-flow operator: <code>match</code>. It allows us to
compare a value against a series of patterns and then execute code based on
how they compare.</p>
<p>Think of a <code>match</code> expression kind of like a coin sorting machine. Coins slide
down a track that has 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 for the first pattern that the value
&quot;fits&quot;, the value will fall into the associated code block to be used during
execution.</p>
<p>Since we're already talking about coins, let's use them for an example using
<code>match</code>. We can write a function that can take an unknown American coin and, in
a similar way as the coin counting machine, determine which coin it is and
return its value in cents:</p>
<pre><code class="language-rust">enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -&gt; i32 {
match coin {
Coin::Penny =&gt; 1,
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter =&gt; 25,
}
}
</code></pre>
<p>Let's break down the <code>match</code>! At a high-level, using <code>match</code> looks like this:</p>
<pre><code class="language-text">match expression {
pattern =&gt; code,
}
</code></pre>
<p>First, we have the <code>match</code> keyword. Next, we have an expression. This feels
very similar to an expression used with <code>if</code>, but there's a big difference:
with <code>if</code>, the condition needs to return a boolean value. Here, it can be any
type.</p>
<p>Next, we have a &quot;match arm&quot;. That's the part that looks like <code>pattern =&gt; code,</code>. We can have as many arms as we need to: our <code>match</code> above has four
arms. An arm has two parts: a pattern and some code. 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.</p>
<p>The code associated with each arm is an expression, and the resulting value of
the code with the matching arm that gets executed 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 we wanted to run
multiple lines of code in a match arm, we can use curly braces. This code would
print out &quot;Lucky penny!&quot; every time the method was called with a <code>Coin::Penny</code>,
but would still return the last value of the block, <code>1</code>:</p>
<pre><code class="language-rust"># enum Coin {
# Penny,
# Nickel,
# Dime,
# Quarter,
# }
#
fn value_in_cents(coin: Coin) -&gt; i32 {
match coin {
Coin::Penny =&gt; {
println!(&quot;Lucky penny!&quot;);
1
},
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter =&gt; 25,
}
}
</code></pre>
<p>Another useful feature of match arms is that they can create bindings to parts
of the values that match the pattern. From 1999 through 2008, the U.S. printed
quarters with different designs for each of the 50 states on one side. The other
coins did not get state designs, so only quarters have this extra attribute. We
can add this information to our <code>enum</code> by changing the <code>Quarter</code> variant to have
a <code>State</code> value:</p>
<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>
<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 in order to count it, we're going
to call out the name of the state so that if it's one our friend doesn't have
yet, they can add it to their collection.</p>
<p>In the match statement to do this, the quarter case now has a binding, <code>state</code>,
that contains the value of the state of that quarter. The binding will only get
created if the coin matches the <code>Quarter</code> pattern. Then we can use the binding
in the code for that arm:</p>
<pre><code class="language-rust"># #[derive(Debug)]
# enum UsState {
# Alabama,
# Alaska,
# }
#
# enum Coin {
# Penny,
# Nickel,
# Dime,
# Quarter(UsState),
# }
#
fn value_in_cents(coin: Coin) -&gt; i32 {
match coin {
Coin::Penny =&gt; 1,
Coin::Nickel =&gt; 5,
Coin::Dime =&gt; 10,
Coin::Quarter(state) =&gt; {
println!(&quot;State quarter from {:?}!&quot;, state);
25
},
}
}
</code></pre>
<p>If we were to call <code>value_in_cents(Coin::Quarter(UsState::Alaska))</code>, <code>coin</code> will
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>, thus getting the inner state value out of
the <code>Coin</code> enum variant for <code>Quarter</code> and enabling us to print &quot;State quarter
from Alaska!&quot;.</p>
<p>Remember the <code>Option&lt;T&gt;</code> type from the previous section, and that we wanted to
be able to get the inner <code>T</code> value out of the <code>Some</code> case? This will be very
similar! Instead of coins, we will be comparing to other patterns, but the way
that the <code>match</code> expression works remains the same as a coin sorting machine in
the way that we look for the first pattern that fits the value.</p>
<p>Let's say that we want to write a function that takes an <code>Option&lt;i32&gt;</code>, and
if there's a value inside, add one to it. If there isn't a value inside, we
want to return the <code>None</code> value and not attempt to add.</p>
<p>This function is very easy to write, thanks to <code>match</code>. It looks like this:</p>
<pre><code class="language-rust">fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
match x {
None =&gt; None,
Some(i) =&gt; Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
</code></pre>
<p>Let's examine the first execution of <code>plus_one()</code> in more detail. In the above
example, <code>x</code> will be <code>Some(5)</code>. Let's compare that against each arm:</p>
<pre><code class="language-text">None =&gt; None,
</code></pre>
<p>Does <code>Some(5)</code> match <code>None</code>? No, it's the wrong variant. So let's continue.</p>
<pre><code class="language-text">Some(i) =&gt; Some(i + 1),
</code></pre>
<p>Does <code>Some(5)</code> match <code>Some(i)</code>? Why yes it does! We have the same variant. The
<code>i</code> binds to the value inside of the <code>Some</code>, so <code>i</code> has the value <code>5</code>. Then we
execute the code in that match arm: take <code>i</code>, which is <code>5</code>, add one to it, and
create a new <code>Some</code> value with our total inside.</p>
<p>Now let's consider the second call of <code>plus_one()</code>. In this case, <code>x</code> is
<code>None</code>. We enter the <code>match</code>, and compare to the first arm:</p>
<pre><code class="language-text">None =&gt; None,
</code></pre>
<p>Does <code>None</code> match <code>None</code>? Yup! There's no value to add to. So we stop and
return the <code>None</code> value that is on the right side of the <code>=&gt;</code>. We don't
check any other arms since we found one that matched.</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 to the data
inside, and then execute code based on it. It's a bit tricky at first, but
once you get used to it, you'll wish you had it in languages that don't support
it. It's consistently a user favorite.</p>
<h3>Matches are exhaustive</h3>
<p>There's one other aspect of <code>match</code> we didn't talk about. Consider this version
of <code>plus_one()</code>:</p>
<pre><code class="language-rust,ignore">fn plus_one(x: Option&lt;i32&gt;) -&gt; Option&lt;i32&gt; {
match x {
Some(i) =&gt; Some(i + 1),
}
}
</code></pre>
<p>A bug! We didn't handle the <code>None</code> case. Luckily, it's a bug Rust knows how to
catch. If we try to compile this code, we'll get an error:</p>
<pre><code class="language-bash">error: non-exhaustive patterns: `None` not covered [E0004]
match x {
Some(i) =&gt; Some(i + 1),
}
</code></pre>
<p>Rust knows that we did not cover every possible option, and even knows which
pattern we forgot! This is referred to as being &quot;exhaustive&quot;: we must exhaust
every last option possible in order to be valid. Especially in the case of
<code>Option&lt;T&gt;</code>, when Rust prevents us from forgetting to explicitly handle the
<code>None</code> case, it protects us from assuming that we have a value when we might
have null and thus making the billion-dollar mistake we discussed in the
previous section.</p>
<h3>The _ placeholder</h3>
<p>What if we don't care about all of the possible values, though? Especially when
there are a lot of possible values for a type: a <code>u8</code> can have valid values of
zero through 255-- if we only care about 1, 3, 5, and 7, does this mean we must
list out 0, 2, 4, 6, 8, 9, all the way up through 255? Thankfully, no! We can
use a special pattern, <code>_</code>:</p>
<pre><code class="language-rust">let some_u8_value = 0u8;
match some_u8_value {
1 =&gt; println!(&quot;one&quot;),
3 =&gt; println!(&quot;three&quot;),
5 =&gt; println!(&quot;five&quot;),
7 =&gt; println!(&quot;seven&quot;),
_ =&gt; (),
}
</code></pre>
<p>The <code>_</code> pattern will match all the other cases, and <code>()</code> will do nothing, it's
the unit value. This way, we don't have to list individual match arms for all
the other possible values in order to say that we want to do nothing for all of
those-- the <code>_</code> is a placeholder for any value.</p>
<h2>if let</h2>
<p>There's one more advanced control flow structure we haven't discussed: <code>if let</code>. Imagine we're in a situation like this:</p>
<pre><code class="language-rust"># let some_option = Some(5);
match some_option {
Some(x) =&gt; {
// do something with x
},
None =&gt; {},
}
</code></pre>
<p>We care about the <code>Some</code> case, but don't want to do anything with the <code>None</code>
case. With an <code>Option</code>, this isn't <em>too</em> bad, but with a more complex enum,
adding <code>_ =&gt; {}</code> after processing just one variant doesn't feel great. We have
this boilerplate arm and an extra level of indentation (the code that
does something with <code>x</code> is indented twice, rather than just once). We really want
a construct that says &quot;Do something with this one case; I don't care about the
others.&quot;</p>
<p>Enter <code>if let</code>:</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
exactly like a <code>match</code>, where the expression is given to the <code>match</code> and the
pattern is its first arm. In other words, you can think of <code>if let</code> as syntax
sugar:</p>
<pre><code class="language-rust,ignore">if let pattern = expression {
body
}
match expression {
pattern =&gt; body,
_ =&gt; {}
}
</code></pre>
<p>And in fact, we can include an <code>else</code> and it becomes the body of the <code>_</code>
case:</p>
<pre><code class="language-rust,ignore">if let pattern = expression {
body
} else {
else_body
}
match expression {
pattern =&gt; body,
_ =&gt; else_body,
}
</code></pre>
<p>In other words, it's the high-level construct we were originally looking for:
do something special with only one pattern.</p>
<h1>Modules</h1>
<p>When you write a program in Rust, your code might start off living solely in
the <code>main</code> function. As your code grows, you eventually move functionality out
into functions, both for re-use and for nicer organization. By splitting your
code up into smaller chunks, each chunk is easier to understand on its own. So
what happens when you start having too many functions? Rust has a module system
that tackles both the problem of wanting to be able to re-use code and the
problem of 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
those definitions can be visible outside their module or not. Here's an
overview of how the bits fit together:</p>
<ul>
<li><code>mod</code> declares a new module.</li>
<li>Everything starts off as private, but the <code>pub</code> keyword makes it public.</li>
<li>The <code>use</code> keyword allows you to bring modules, or definitions inside of them,
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>Every module in Rust starts with the <code>mod</code> keyword. In this next example, we'll
start again by making a new project with Cargo. This time, instead of a binary,
we're going to make a library: a project that other people would pull into their
projects as a dependency. We saw this with the <code>rand</code> crate in Chapter 2.</p>
<p>Imagine that we're creating a library to provide some general networking
functionality, and we decide to call our library <code>communicator</code>. To create this
library, we won't use the <code>--bin</code> option like we have before. This is because
by default cargo will create a library:</p>
<pre><code class="language-bash">$ cargo new communicator
$ cd communicator
</code></pre>
<p>Notice that Cargo generated <code>src/lib.rs</code> instead of <code>src/main.rs</code> for us, and
inside it we'll find this:</p>
<p>Filename: src/lib.rs</p>
<pre><code class="language-rust">#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
</code></pre>
<p>This is an empty test to help us get our library started, instead of the binary
that says &quot;Hello, world!&quot; that we get with the <code>--bin</code> option. Let's ignore the
<code>#[]</code> stuff and <code>mod tests</code> for a little bit, but we'll make sure to leave it
in <code>src/lib.rs</code> for later.</p>
<p>We're going to look at different ways we could choose to organize our library's
code, any of which could make sense depending on exactly what we were trying to
do. To start, add this code at the beginning of the file:</p>
<p>Filename: src/lib.rs</p>
<pre><code class="language-rust">mod network {
fn connect() {
}
}
</code></pre>
<p>This is our first module declaration. We use the <code>mod</code> keyword, followed by the
name of the module, and 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 try and call this function from outside
the <code>network</code> module, we would say <code>network::connect()</code> rather than <code>connect()</code>.</p>
<p>We could have multiple modules, side-by-side. For example, if we wanted a
<code>client</code> module:</p>
<p>Filename: src/lib.rs</p>
<pre><code class="language-rust">mod network {
fn connect() {
}
}
mod client {
fn connect() {
}
}
</code></pre>
<p>Now we have a <code>network::connect</code> function and a <code>client::connect</code> function.</p>
<p>And we can put modules inside of modules. If we wanted to have <code>client</code> be
within <code>network</code>:</p>
<p>Filename: src/lib.rs</p>
<pre><code class="language-rust">mod network {
fn connect() {
}
mod client {
fn connect() {
}
}
}
</code></pre>
<p>This gives us <code>network::connect</code> and <code>network::client::connect</code>.</p>
<p>In this way, modules form a tree. The contents of <code>src/lib.rs</code> are at the root
of the project's tree, and the submodules form the leaves. Here's what our
first example looks like when thought of this way:</p>
<pre><code class="language-text">communicator
├── network
└── client
</code></pre>
<p>And here's the second:</p>
<pre><code class="language-text">communicator
└── network
└── client
</code></pre>
<p>More complicated projects can have a lot of modules.</p>
<h3>Putting Modules in Another File</h3>
<p>Modules form a hierarchical, tree-like structure. So does another thing:
file systems! The module system is the way that we split larger Rust projects up
into multiple files. Let's imagine we have a module layout like this:</p>
<p>File: src/lib.rs</p>
<pre><code class="language-rust">mod client {
fn connect() {
}
}
mod network {
fn connect() {
}
mod server {
fn connect() {
}
}
}
</code></pre>
<p>Let's extract the <code>client</code> module into another file. First, we need to change
our code in <code>src/lib.rs</code>:</p>
<p>File: src/lib.rs</p>
<pre><code class="language-rust,ignore">mod client;
mod network {
fn connect() {
}
mod server {
fn connect() {
}
}
}
</code></pre>
<p>We still say <code>mod client</code>, but instead of curly braces, we have a semicolon.
This lets Rust know that we have a module, but it's in another file with that
module's name. Open up <code>src/client.rs</code> and put this in it:</p>
<p>File: src/client.rs</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. <code>mod</code> is for
declaring a new module, and we've already declared this module in <code>src/lib.rs</code>.
This file 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>Now, everything should compile successfully, but with a few warnings:</p>
<pre><code class="language-bash">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/client.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/lib.rs:4:5
|
4 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/lib.rs:8:9
|
8 | fn connect() {
| ^
</code></pre>
<p>Don't worry about those warnings for now; we'll clear them up in a future
section. They're just warnings, we've built things successfully!</p>
<p>Let's extract the <code>network</code> module into its own file next, using the same
pattern. Change <code>src/lib.rs</code> to look like this:</p>
<p>Filename: src/lib.rs</p>
<pre><code class="language-rust,ignore">mod client;
mod network;
</code></pre>
<p>And then put this in <code>src/network.rs</code></p>
<p>Filename: src/network.rs</p>
<pre><code class="language-rust">fn connect() {
}
mod server {
fn connect() {
}
}
</code></pre>
<p>And then run <code>cargo build</code> again. Success! We have one more module to extract:
<code>server</code>. Unfortunately, our current tactic of extracting a module into a file
named after that module won't work. Let's try it anyway. Modify
<code>src/network.rs</code> to look like this:</p>
<p>Filename: src/network.rs</p>
<pre><code class="language-rust,ignore">fn connect() {
}
mod server;
</code></pre>
<p>Put this in <code>src/server.rs</code></p>
<p>Filename: src/server.rs</p>
<pre><code class="language-rust">fn connect() {
}
</code></pre>
<p>When we try to <code>cargo build</code>, we'll get an error:</p>
<pre><code class="language-bash">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
error: cannot declare a new module at this location
--&gt; src/network.rs:4:5
|
4 | mod server;
| ^^^^^^
|
note: maybe move this module `network` to its own directory via `network/mod.rs`
--&gt; src/network.rs:4:5
|
4 | mod server;
| ^^^^^^
note: ... or maybe `use` the module `server` instead of possibly redeclaring it
--&gt; src/network.rs:4:5
|
4 | mod server;
| ^^^^^^
</code></pre>
<p>This error is actually pretty helpful. It points out something we didn't know
that we could do yet:</p>
<blockquote>
<p>note: maybe move this module <code>network</code> to its own directory via
<code>network/mod.rs</code></p>
</blockquote>
<p>Here's the problem: in our case, we have different names for our modules:
<code>client</code> and <code>network::server</code>. But what if we had <code>client</code> and
<code>network::client</code>, or <code>server</code> and <code>network::server</code>? Having two modules at
different places in the module hierarchy have the same name is completely
valid, but then which module would the files <code>src/client.rs</code> and
<code>src/server.rs</code>, respectively, be for?</p>
<p>Instead of continuing to follow the same file naming pattern we used
previously, we can do what the error suggests. We'll make a new <em>directory</em>,
move <code>src/server.rs</code> into it, and change <code>src/network.rs</code> to
<code>src/network/mod.rs</code>. Then, when we try to build:</p>
<pre><code class="language-bash">$ mkdir src/network
$ mv src/server.rs src/network
$ mv src/network.rs src/network/mod.rs
$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
&lt;warnings&gt;
$
</code></pre>
<p>It works! So now our module layout looks like this:</p>
<pre><code class="language-text">communicator
├── client
└── network
└── server
</code></pre>
<p>And the corresponding file layout looks like this:</p>
<pre><code class="language-text">├── src
│   ├── client.rs
│   ├── lib.rs
│   └── network
│   ├── mod.rs
│   └── server.rs
</code></pre>
<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 in
the <code>foo</code> module in a file named <code>foo.rs</code>.</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 <code>foo/mod.rs</code>.</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 <code>src</code> 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>At the end of the last section, we had a project, <code>communicator</code>, and when we compiled it, we got some strange warnings:</p>
<pre><code class="language-bash"> Compiling communicator v0.1.0 (file:///projects/communicator)
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/client.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/mod.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>Why does this happen? After all, we're building a library. What if these three
functions are the public interface that we want our <em>users</em> to use? We won't
necessarily be using them within our own project, but the point of creating them
is that they <em>will</em> be used by another project. Let's try using them as if we
were another project using our library to see what happens and understand why
we're getting these unused function warnings. Create a <code>src/main.rs</code> file with
this code:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust,ignore">extern crate communicator;
fn main() {
communicator::client::connect();
}
</code></pre>
<p>We need the <code>extern crate</code> line to bring our <code>communicator</code> library crate into
scope, because our package actually now contains <em>two</em> crates. Cargo treats
src/main.rs as the crate root of a binary crate, and we also have our existing
library crate. This pattern is quite common for executable crates: most
functionality is in a library crate, and the executable crate uses that
library. This way, other programs can also use the library crate, and it’s 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; we picked that one since it's the first warning in our
build output above. Invoking <code>cargo build</code> will now give us an error after the
warnings:</p>
<pre><code class="language-bash">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
error: module `client` is private
--&gt; src/main.rs:4:5
|
4 | communicator::client::connect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>Ah ha! The <code>client</code> module is private. This is the first time we've run into
the concepts of 'public' and 'private' in the context of Rust. There's no
keyword to make something private; that's the default state. In this default
state, no one else could possibly use it, so if we don't use it within our
library crate, Rust will warn us that it's unused. Once we tell Rust something
is public, Rust knows that we intend for code external to our crate to use it,
and Rust considers theoretical external usage that is now possible to count as
being used. Thus, when something is marked as public, Rust will stop warning us
that it is unused.</p>
<p>To tell Rust we want to make something public, we add the <code>pub</code> keyword. This
keyword goes before the declaration of the item we want to make public. Let's
modify <code>src/lib.rs</code> to make the <code>client</code> module public to fix the error we got:</p>
<p>Filename: src/lib.rs</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-bash">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
&lt;warnings&gt;
error: function `connect` is private
--&gt; src/main.rs:4:5
|
4 | communicator::client::connect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code></pre>
<p>Hooray! We have a different error! Yes, different error messages are a cause
for celebration. The new error says &quot;function <code>connect</code> is private&quot;, so let's
edit <code>src/client.rs</code> to make <code>client::connect</code> public:</p>
<p>Filename: src/client.rs</p>
<pre><code class="language-rust">pub fn connect() {
}
</code></pre>
<p>And run <code>cargo build</code> again:</p>
<pre><code class="language-bash"> cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/mod.rs:1:1
|
1 | fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>It compiled! And the warning about <code>client::connect</code> not being used is gone!</p>
<p>Making functions public isn't the only way to fix unused code warnings: if
we <em>didn't</em> want these functions to be part of our public API and we got these
warnings, the warnings could be alerting us to code we no longer needed and
could safely delete. They could also be alerting us to a bug, if we
had just accidentally removed all places within our library where we called
this function.</p>
<p>However, 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 get rid of the remaining warnings.
Modify <code>src/network/mod.rs</code> to be:</p>
<p>Filename: src/network/mod.rs</p>
<pre><code class="language-rust,ignore">pub fn connect() {
}
mod server;
</code></pre>
<p>And compile:</p>
<pre><code class="language-bash">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/mod.rs:1:1
|
1 | pub fn connect() {
| ^
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>Hmmm, it says this is still dead, even though it's <code>pub</code>. While the function is
public within the module, the <code>network</code> module it's in is not public. We're
working from the interior of the library out this time, as opposed to with
<code>client</code> where we worked from the outside in. Let's change <code>src/lib.rs</code> to add
the same fix though, by making <code>network</code> public like <code>client</code> is:</p>
<p>Filename: src/lib.rs</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-bash">$ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator)
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>Only one last warning! 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, then it can be accessed through any of its
parent modules.</li>
<li>If an item is private, it may be accessed by the current module and its
child modules.</li>
</ol>
<p>Let's look at a few more examples to get some practice. What if we had this
code in a new project's <code>src/lib.rs</code>:</p>
<p>Filename: src/lib.rs</p>
<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>
<p>Before you try to compile this code, make a guess about which lines in
<code>try_me</code> will have errors.</p>
<p>Ready? Let's talk through them!</p>
<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 rule says we're allowed to access it
since <code>outermost</code> is in our current, root module.</p>
<p>The function call <code>outermost::middle_function()</code> will work. <code>middle_function</code>
is public, and we are accessing it through its parent module, <code>outermost</code>,
which we just determined we can access in the previous paragraph.</p>
<p><code>outermost::middle_secret_function()</code> will cause a compilation error.
<code>middle_secret_function</code> is private, so the second rule applies. Our current
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>.</p>
<p>Here are some changes to try making with this code. Try each one, make a guess
about what will be allowed or not, compile to see if you're right, and use the
rules to understand why.</p>
<ul>
<li>What if the <code>inside</code> module was public?</li>
<li>What if <code>outside</code> was public and <code>inside</code> was private?</li>
<li>What if, in the body of <code>inner_function</code>, we 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 with <code>use</code></h2>
<p>We've seen how we can call functions defined within a module by using the
module name as part of the call, like this:</p>
<p>Filename: src/main.rs</p>
<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>
<p>However, referring to the fully qualified name can get quite lengthy, as we see
in that example. To solve this issue, Rust has a keyword, <code>use</code>. It works like
this:</p>
<p>Filename: src/main.rs</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>We can <code>use</code> a module, and that will bring its name into scope. This allows us
to shorten our function call, only requiring us to type the final module name,
not the entire chain of them. <code>use</code> is quite powerful and can bring all kinds
of things into scope. For example, we could <code>use</code> the function itself:</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>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 are 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>If you'd like to import all the items in a namespace at once, you can use <code>*</code>:</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 'glob', 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>Remember when we created our crate that Cargo made a <code>tests</code> module for us?
Let's talk about that now. It was in <code>src/lib.rs</code>:</p>
<p>Filename: src/lib.rs</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 XX, 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!</p>
<p>Since tests are for exercising the code within our library, 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>Filename: src/lib.rs</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-bash">$ cargo test
Compiling communicator v0.1.0 (file:///projects/communicator)
error[E0433]: failed to resolve. Use of undeclared type or module `client`
--&gt; src/lib.rs:9:9
|
9 | client::connect();
| ^^^^^^^^^^^^^^^ Use of undeclared type or module `client`
warning: function is never used: `connect`, #[warn(dead_code)] on by default
--&gt; src/network/server.rs:1:1
|
1 | fn connect() {
| ^
</code></pre>
<p>Why doesn't this compile? It's not because we don't have <code>communicator::</code> in
front of the function like we had in <code>src/main.rs</code>: we are definitely within
the <code>communicator</code> library crate here. The reason is that paths anywhere except
in a <code>use</code> statement are relative to the current module (In a <code>use</code> statement,
they're relative to the crate root by default). Our <code>tests</code> module doesn't have
a <code>client</code> module in its scope!</p>
<p>So how do we get back up one module? We can either use leading colons to say
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:</p>
<pre><code class="language-rust,ignore">super::client::connect();
</code></pre>
<p>If we were deep in the module hierarchy, starting from the root every time
would get long. Plus, if we rearrange our modules by moving a subtree to
another place, there might be a lot of places the path would need to be updated
if we always used the path from the root.</p>
<p>It would also be annoying to have to type <code>super::</code> all the time in each test,
but we now have a tool for that solution: <code>use</code>! <code>super::</code> is special and
changes the path we 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>Filename: src/lib.rs</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-bash">$ 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>
<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>
<h1>Fundamental Collections</h1>
<p>Rust's standard library includes a number of really useful data structures
called <em>collections</em>. Most other types represent one specific value, but
collections can contain multiple values inside of them. Each collection has
different capabilities and costs, and choosing an appropriate one for the
situation you're in is a skill you'll develop over time. In this chapter, we'll
go over three collections which are used very often in Rust programs:</p>
<ul>
<li>A <em>vector</em> allows us to store a variable number of values next to each other.</li>
<li>A <em>string</em> is a collection of characters. We've seen the <code>String</code> type
before, but we'll talk about it in depth now.</li>
<li>A <em>hash map</em> allows us to associate a value with a particular key.</li>
</ul>
<p>There are more specialized variants of each of these data structures for
particular situations, but these are the most fundamental and common. We're
going to discuss how to create and update each of the collections, as well as
what makes each special.</p>
<h2>Vectors</h2>
<p>The first type we'll look at is <code>Vec&lt;T&gt;</code>, also known as a <em>vector</em>. Vectors
allow us to store more than one value in a single data structure that puts all
the values next to each other in memory.</p>
<h3>Creating a New Vector</h3>
<p>To create a new vector, we can call the <code>new</code> function:</p>
<pre><code class="language-rust">let v: Vec&lt;i32&gt; = Vec::new();
</code></pre>
<p>Note that we added a type annotation here. Since we don't actually do
anything with the 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 generic over
the type stored inside them (we'll talk about Generics more thoroughly in
Chapter 10), and the angle brackets here tell Rust that this vector will hold
elements of the <code>i32</code> type.</p>
<p>That said, in real code, we very rarely need to do this type annotation since
Rust can infer the type of value we want to store once we insert values. Let's
look at how to modify a vector next.</p>
<h3>Updating a Vector</h3>
<p>To put elements in the vector, 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>Since these numbers are <code>i32</code>s, Rust infers the type of data we want to store
in the vector, so we don't need the <code>&lt;i32&gt;</code> annotation.</p>
<p>We can improve this code even further. Creating a vector with some initial
values like this is very common, so there's a macro to do it for us:</p>
<pre><code class="language-rust">let v = vec![5, 6, 7, 8];
</code></pre>
<p>This macro does a similar thing to our previous example, but it's much more
convenient.</p>
<h3>Dropping a Vector Drops its Elements</h3>
<p>Like any other <code>struct</code>, a vector will be freed when it goes out of scope:</p>
<pre><code class="language-rust">{
let v = vec![1, 2, 3, 4];
// do stuff with v
} // &lt;- v goes out of scope and is freed here
</code></pre>
<p>When the vector gets dropped, it will also drop all of its contents, so those
integers are going to be cleaned up as well. 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 we know how creating and destroying vectors works, 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 following examples of these two ways, we've
annotated the types of the values that are returned from these functions for
extra clarity:</p>
<pre><code class="language-rust">let v = vec![1, 2, 3, 4, 5];
let third: &amp;i32 = &amp;v[2];
let third: Option&lt;&amp;i32&gt; = v.get(2);
</code></pre>
<p>First, note that we use the index value of <code>2</code> to get the third element:
vectors are indexed by number, starting at zero. Secondly, the two different
ways to get the third element are using <code>&amp;</code> and <code>[]</code>s and using the <code>get</code>
method. The square brackets give us a reference, and <code>get</code> gives us an
<code>Option&lt;&amp;T&gt;</code>. The reason we have two ways to reference an element is so that we
can choose the behavior we'd like to have if we try to use an index value that
the vector doesn't have an element for:</p>
<pre><code class="language-rust,should_panic">let v = vec![1, 2, 3, 4, 5];
let does_not_exist = &amp;v[100];
let does_not_exist = v.get(100);
</code></pre>
<p>With the <code>[]</code>s, Rust will cause a <code>panic!</code>. With the <code>get</code> method, it will
instead return <code>None</code> without <code>panic!</code>ing. Deciding which way to access
elements in a vector depends on whether we consider an attempted access past
the end of the vector to be an error, in which case we'd want the <code>panic!</code>
behavior, or whether this will happen occasionally under normal circumstances
and our code will have logic to handle getting <code>Some(&amp;element)</code> or <code>None</code>.</p>
<p>Once we have a valid reference, the borrow checker will enforce the ownership
and borrowing rules we covered in Chapter 4 in order to ensure this and other
references to the contents of the vector stay valid. This means in a function
that owns a <code>Vec</code>, we can't return a reference to an element since the <code>Vec</code>
will be cleaned up at the end of the function:</p>
<pre><code class="language-rust,ignore">fn element() -&gt; String {
let list = vec![String::from(&quot;hi&quot;), String::from(&quot;bye&quot;)];
list[1]
}
</code></pre>
<p>Trying to compile this will result in the following error:</p>
<pre><code class="language-bash">error: cannot move out of indexed content [--explain E0507]
|&gt;
4 |&gt; list[1]
|&gt; ^^^^^^^ cannot move out of indexed content
</code></pre>
<p>Since <code>list</code> goes out of scope and gets cleaned up at the end of the function,
the reference <code>list[1]</code> cannot be returned because it would outlive <code>list</code>.</p>
<p>Here's another example of code that looks like it should be allowed, but it
won't compile because the references actually aren't valid anymore:</p>
<pre><code class="language-rust,ignore">let mut v = vec![1, 2, 3, 4, 5];
let first = &amp;v[0];
v.push(6);
</code></pre>
<p>Compiling this will give us this error:</p>
<pre><code class="language-bash">error: cannot borrow `v` as mutable because it is also borrowed as immutable
[--explain E0502]
|&gt;
5 |&gt; let first = &amp;v[0];
|&gt; - immutable borrow occurs here
7 |&gt; v.push(6);
|&gt; ^ mutable borrow occurs here
9 |&gt; }
|&gt; - immutable borrow ends here
</code></pre>
<p>This violates one of the ownership rules we covered in Chapter 4: the <code>push</code>
method needs to have a mutable borrow to the <code>Vec</code>, and we aren't allowed to
have any immutable borrows while we have a mutable borrow.</p>
<p>Why is it an error to have a reference to the first element in a vector while
we try to add a new item to the end, though? Due to the way vectors work,
adding a new element onto the end might require allocating new memory and
copying the old elements over to the new space if there wasn't enough room to
put all the elements next to each other where the vector was. If this happened,
our reference would be pointing to deallocated memory. For more on this, see
<a href="https://doc.rust-lang.org/stable/nomicon/vec.html">The Nomicon</a>.</p>
<h3>Using an Enum to Store Multiple Types</h3>
<p>Let's put vectors together with what we learned about enums in Chapter 6. At
the beginning of this section, we said that vectors will 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 that might be different types. Luckily,
the variants of an enum are all the same type as each other, so when we're in
this scenario, we can define and use an enum!</p>
<p>For example, let's say we're going to be getting values for a row in a
spreadsheet. Some of the columns contain integers, some floating point numbers,
and some strings. We can define an enum whose variants will hold the different
value types. All of the enum variants will then be the same type, that of the
enum. Then we can create a vector that, ultimately, holds different types:</p>
<pre><code class="language-rust">enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from(&quot;blue&quot;)),
SpreadsheetCell::Float(10.12),
];
</code></pre>
<p>This has the advantage of being explicit about what types are allowed in this
vector. If we allowed any type to be in a vector, there would be a chance that
the vector would hold a type that would cause errors with the operations we
performed on the vector. Using an enum plus a <code>match</code> where we access elements
in a vector like this means that Rust will ensure at compile time that we
always handle every possible case.</p>
<p>Using an enum for storing different types in a vector does imply that we need
to know the set of types we'll want to store at compile time. If that's not the
case, instead of an enum, we can use a trait object. We'll learn about those in
Chapter XX.</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 other 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>
<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.</p>
<h3>Many Kinds of Strings</h3>
<p>Strings are a common place for new Rustaceans to get stuck. 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 coming from other languages.</p>
<p>Before we can dig into those aspects, we need to talk about what exactly we
even mean by the word 'string'. Rust actually only has one string type in the
core language itself: <code>&amp;str</code>. We talked about <em>string slices</em> in Chapter 4:
they're a reference to some UTF-8 encoded string data stored somewhere else.
String literals, for example, are stored in the binary output of the program,
and are therefore string slices.</p>
<p>Rust's standard library is what provides the type called <code>String</code>. This is a
growable, mutable, owned, UTF-8 encoded string type. When Rustaceans talk about
'strings' in Rust, they usually mean &quot;<code>String</code> and <code>&amp;str</code>&quot;. This chapter is
largely about <code>String</code>, and these two 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. Similarly to the <code>*String</code>/<code>*Str</code> naming,
they often provide an owned and borrowed variant, just like <code>String</code>/<code>&amp;str</code>.
These string types may store different encodings or be represented in memory in
a different way, for example. We won't be talking about these other string
types in this chapter; see their API documentation for more about how to use
them and when each is appropriate.</p>
<h3>Creating a New String</h3>
<p>Let's look at how to do the same operations on <code>String</code> as we did with <code>Vec</code>,
starting with creating one. Similarly, <code>String</code> has <code>new</code>:</p>
<pre><code class="language-rust">let s = String::new();
</code></pre>
<p>Often, we'll have some initial data that we'd like to start the string off with.
For that, there's the <code>to_string</code> method:</p>
<pre><code class="language-rust">let data = &quot;initial contents&quot;;
let s = data.to_string();
// the method also works on a literal directly:
let s = &quot;initial contents&quot;.to_string();
</code></pre>
<p>This form is equivalent to using <code>to_string</code>:</p>
<pre><code class="language-rust">let s = String::from(&quot;Initial contents&quot;);
</code></pre>
<p>Since strings are used for so many things, there are many different generic
APIs that make sense for strings. There are a lot of options, and some of them
can feel redundant because of this, 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. Some people use <code>String::from</code> for
literals, and <code>.to_string</code> for variable bindings. Most Rust style is pretty
uniform, but this specific question is one of the most debated.</p>
<p>Remember that strings are UTF-8 encoded, so we can include any properly encoded
data in them:</p>
<pre><code class="language-rust">let hello = &quot;السلام عليكم&quot;;
let hello = &quot;Dobrý den&quot;;
let hello = &quot;Hello&quot;;
let hello = &quot;שָׁלוֹם&quot;;
let hello = &quot;नमस्ते&quot;;
let hello = &quot;こんにちは&quot;;
let hello = &quot;안녕하세요&quot;;
let hello = &quot;你好&quot;;
let hello = &quot;Olá&quot;;
let hello = &quot;Здравствуйте&quot;;
let hello = &quot;Hola&quot;;
</code></pre>
<h3>Updating a String</h3>
<p>A <code>String</code> can be changed and can grow in size, just like a <code>Vec</code> can.</p>
<h4>Push</h4>
<p>We can grow a <code>String</code> by using the <code>push_str</code> method to append another
string:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;foo&quot;);
s.push_str(&quot;bar&quot;);
</code></pre>
<p><code>s</code> will contain &quot;foobar&quot; after these two lines.</p>
<p>The <code>push</code> method will add a <code>char</code>:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;lo&quot;);
s.push('l');
</code></pre>
<p><code>s</code> will contain &quot;lol&quot; after this point.</p>
<p>We can make any <code>String</code> contain the empty string with the <code>clear</code> method:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;Noooooooooooooooooooooo!&quot;);
s.clear();
</code></pre>
<p>Now <code>s</code> will be the empty string, &quot;&quot;.</p>
<h4>Concatenation</h4>
<p>Often, we'll want to combine two strings together. One way is to use the <code>+</code>
operator:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;Hello, &quot;);
let s2 = String::from(&quot;world!&quot;);
let s3 = s1 + &amp;s2;
</code></pre>
<p>This code will make <code>s3</code> contain &quot;Hello, world!&quot; There's some tricky bits here,
though, that come from the type signature of <code>+</code> for <code>String</code>. The signature
for the <code>add</code> method that the <code>+</code> operator uses looks something like this:</p>
<pre><code class="language-rust,ignore">fn add(self, s: &amp;str) -&gt; String {
</code></pre>
<p>This isn't exactly what the actual signature is in the standard library because
<code>add</code> is defined using generics there. Here, we're just looking at what the
signature of the method would be if <code>add</code> was defined specifically for
<code>String</code>. This signature gives us the clues we need in order to understand the
tricky bits of <code>+</code>.</p>
<p>First of all, <code>s2</code> has an <code>&amp;</code>. This is because of the <code>s</code> argument in the <code>add</code>
function: we can only add a <code>&amp;str</code> to a <code>String</code>, we can't add two <code>String</code>s
together. Remember back in Chapter 4 when we talked about how <code>&amp;String</code> will
coerce to <code>&amp;str</code>: we write <code>&amp;s2</code> so that the <code>String</code> will coerce to the proper
type, <code>&amp;str</code>.</p>
<p>Secondly, <code>add</code> takes ownership of <code>self</code>, which we can tell because <code>self</code>
does <em>not</em> have an <code>&amp;</code> in the signature. This means <code>s1</code> in the above example
will be moved into the <code>add</code> call and no longer be a valid binding after that.
So while <code>let s3 = s1 + &amp;s2;</code> looks like it will copy both strings and create a
new one, this statement actually takes ownership of <code>s1</code>, appends a copy of
<code>s2</code>'s contents, then returns ownership of the result. In other words, it looks
like it's making a lot of copies, but isn't: the implementation is more
efficient than copying.</p>
<p>If we need to concatenate multiple strings, this behavior of <code>+</code> gets
unwieldy:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;tic&quot;);
let s2 = String::from(&quot;tac&quot;);
let s3 = String::from(&quot;toe&quot;);
let s = s1 + &quot;-&quot; + &amp;s2 + &quot;-&quot; + &amp;s3;
</code></pre>
<p><code>s</code> will be &quot;tic-tac-toe&quot; at this point. With all of the <code>+</code> and <code>&quot;</code>
characters, it gets hard to see what's going on. For more complicated string
combining, we can use the <code>format!</code> macro:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;tic&quot;);
let s2 = String::from(&quot;tac&quot;);
let s3 = String::from(&quot;toe&quot;);
let s = format!(&quot;{}-{}-{}&quot;, s1, s2, s3);
</code></pre>
<p>This code will also set <code>s</code> to &quot;tic-tac-toe&quot;. The <code>format!</code> macro works in the
same way as <code>println!</code>, but instead of printing the output to the screen, it
returns a <code>String</code> with the contents. This version is much easier to read than
all of the <code>+</code>s.</p>
<h3>Indexing into Strings</h3>
<p>In many other languages, accessing individual characters in a string by
referencing the characters by index is a valid and common operation. In Rust,
however, if we try to access parts of a <code>String</code> using indexing syntax, we'll
get an error. That is, this code:</p>
<pre><code class="language-rust,ignore">let s1 = String::from(&quot;hello&quot;);
let h = s1[0];
</code></pre>
<p>will result in this error:</p>
<pre><code class="language-text">error: the trait bound `std::string::String: std::ops::Index&lt;_&gt;` is not
satisfied [--explain E0277]
|&gt;
|&gt; let h = s1[0];
|&gt; ^^^^^
note: the type `std::string::String` cannot be indexed by `_`
</code></pre>
<p>The error and the note tell the story: Rust strings don't support indexing. So
the follow-up question is, why not? In order to answer that, we have to talk a
bit about how Rust stores strings in memory.</p>
<h4>Internal Representation</h4>
<p>A <code>String</code> is a wrapper over a <code>Vec&lt;u8&gt;</code>. Let's take a look at some of our
properly-encoded UTF-8 example strings from before. First, this one:</p>
<pre><code class="language-rust">let len = &quot;Hola&quot;.len();
</code></pre>
<p>In this case, <code>len</code> will be four, which means the <code>Vec</code> storing the string
&quot;Hola&quot; is four bytes long: each of these letters takes one byte when encoded in
UTF-8. What about this example, though?</p>
<pre><code class="language-rust">let len = &quot;Здравствуйте&quot;.len();
</code></pre>
<p>There are two answers that potentially make sense here: the first is 12, which
is the number of letters that a person would count if we asked someone how long
this string was. The second, though, is what Rust's answer is: 24. This is the
number of bytes that it takes to encode &quot;Здравствуйте&quot; in UTF-8, because each
character takes two bytes of storage.</p>
<p>By the same token, imagine this invalid Rust code:</p>
<pre><code class="language-rust,ignore">let hello = &quot;Здравствуйте&quot;;
let answer = &amp;h[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
should <code>answer</code> be <code>208</code>? <code>208</code> is not a valid character on its own, though.
Plus, for Latin letters, this would not return the answer most people would
expect: <code>&amp;&quot;hello&quot;[0]</code> would then return <code>104</code>, not <code>h</code>.</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: bytes, scalar values, and grapheme
clusters. If we look at the string &quot;नमस्ते&quot;, 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. But 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. Finally, if we look at them as grapheme
clusters, which is the closest thing to what humans would call 'letters', we'd
get this:</p>
<pre><code class="language-text">[&quot;न&quot;, &quot;म&quot;, &quot;स्&quot;, &quot;ते&quot;]
</code></pre>
<p>Four elements! It turns out that even within 'grapheme cluster', there are
multiple ways of grouping things. Convinced that strings are actually really
complicated yet?</p>
<p>Another reason that indexing into a <code>String</code> to get a character is not available
is that indexing operations are expected to always be fast. This isn't possible
with a <code>String</code>, since Rust would have to walk through the contents from the
beginning to the index to determine how many valid characters there were, no
matter how we define &quot;character&quot;.</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 bytes 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 from particular bytes:</p>
<pre><code class="language-rust">let hello = &quot;Здравствуйте&quot;;
let s = &amp;hello[0..4];
</code></pre>
<p>Here, <code>s</code> will be a <code>&amp;str</code> that contains the first four bytes of the string.
Earlier, we mentioned that each of these characters was two bytes, so that means
that <code>s</code> will be &quot;Зд&quot;.</p>
<p>What would happen if we did <code>&amp;hello[0..1]</code>? The answer: it will panic at
runtime, in the same way that accessing an invalid index in a vector does:</p>
<pre><code class="language-bash">thread 'main' panicked at 'index 0 and/or 1 in `Здравствуйте` do not lie on
character boundary', ../src/libcore/str/mod.rs:1694
</code></pre>
<h3>Methods for Iterating Over Strings</h3>
<p>If we do need to perform operations on individual characters, the best way to
do that is using the <code>chars</code> method. Calling <code>chars</code> on &quot;नमस्ते&quot; gives us the six
Rust <code>char</code> values:</p>
<pre><code class="language-rust">for c in &quot;नमस्ते&quot;.chars() {
println!(&quot;{}&quot;, c);
}
</code></pre>
<p>This code will print:</p>
<pre><code class="language-bash">न
म
स
्
त
े
</code></pre>
<p>The <code>bytes</code> method returns each raw byte, which might be appropriate for your
domain, but remember that valid UTF-8 characters may be made up of more than
one byte:</p>
<pre><code class="language-rust">for b in &quot;नमस्ते&quot;.bytes() {
println!(&quot;{}&quot;, b);
}
</code></pre>
<p>This code will print the 18 bytes that make up this <code>String</code>, starting with:</p>
<pre><code class="language-bash">224
164
168
224
// ... etc
</code></pre>
<p>There are crates available on crates.io to get grapheme clusters from <code>String</code>s.</p>
<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 attempt to make correct handling of <code>String</code> data be the default
for all Rust programs, which does mean programmers have to put more thought
into handling UTF-8 data upfront. This tradeoff exposes us to more of the
complexity of strings than we have to handle in other languages, but will
prevent us from having to handle errors involving non-ASCII characters later in
our development lifecycle.</p>
<p>Let's switch to something a bit less complex: Hash Map!</p>
<h2>Hash Maps</h2>
<p>The last of our fundamental collections is the <em>hash map</em>. The type <code>HashMap&lt;K, V&gt;</code> stores a mapping of keys of type <code>K</code> to values of type <code>V</code>. It does this
via a <em>hashing function</em>, which determines how it places these keys and values
into memory. Many different programming languages support this kind of data
structure, but often with a different name: hash, map, object, hash table, or
associative array, just to name a few.</p>
<p>We'll go over the basic API 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>:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, &quot;hello&quot;);
map.insert(2, &quot;world&quot;);
</code></pre>
<p>Note that we need to <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 has a bit less support from the language. There's no built-in
macro to construct them, for example, and they're not in the prelude, so we
need to add a <code>use</code> statement for them.</p>
<p>Just like vectors, hash maps store their data on the heap. This <code>HashMap</code> has
keys of type <code>i32</code> and values of type <code>&amp;str</code>. Like vectors, hash maps are
homogeneous: all of the keys must have the same type, and all of the values must
have the same type.</p>
<p>If we have a vector of tuples, we can convert it into a hash map with the
<code>collect</code> method. The first element in each tuple will be the key, and the
second element will be the value:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let data = vec![(1, &quot;hello&quot;), (2, &quot;world&quot;)];
let map: HashMap&lt;_, _&gt; = data.into_iter().collect();
</code></pre>
<p>The type annotation <code>HashMap&lt;_, _&gt;</code> is needed here because it's possible to
<code>collect</code> into many different data structures, so Rust doesn't know which we
want. For the type parameters for the key and value types, however, we can use
underscores and Rust can infer the types that the hash map contains based on the
types of the data in our vector.</p>
<p>For types that implement the <code>Copy</code> trait like <code>i32</code> does, the values are
copied into the hash map. If we insert owned values like <code>String</code>, the values
will be moved and the hash map will be the owner of those values:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let field_name = String::from(&quot;Favorite color&quot;);
let field_value = String::from(&quot;Blue&quot;);
let mut map = HashMap::new();
map.insert(field_name, field_value);
// field_name and field_value are invalid at this point
</code></pre>
<p>We would not be able to use the bindings <code>field_name</code> and <code>field_value</code> after
they have been moved into the hash map with the call to <code>insert</code>.</p>
<p>If we insert references to values, 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 map = HashMap::new();
map.insert(1, &quot;hello&quot;);
map.insert(2, &quot;world&quot;);
let value = map.get(&amp;2);
</code></pre>
<p>Here, <code>value</code> will have the value <code>Some(&quot;world&quot;)</code>, since that's the value
associated with the <code>2</code> key. &quot;world&quot; is wrapped in <code>Some</code> because <code>get</code> returns
an <code>Option&lt;V&gt;</code>. If there's no value for that key in the hash map, <code>get</code> will
return <code>None</code>.</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 map = HashMap::new();
map.insert(1, &quot;hello&quot;);
map.insert(2, &quot;world&quot;);
for (key, value) in &amp;map {
println!(&quot;{}: {}&quot;, key, value);
}
</code></pre>
<p>This will print:</p>
<pre><code class="language-bash">1: hello
2: world
</code></pre>
<h3>Updating a Hash Map</h3>
<p>Since each key can only have one value, 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. 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 change the
existing 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, then insert that key with a different value,
the value associated with that key will be replaced. Even though this code
calls <code>insert</code> twice, the hash map will only contain one key/value pair, since
we're inserting with the key <code>1</code> both times:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, &quot;hello&quot;);
map.insert(1, &quot;Hi There&quot;);
println!(&quot;{:?}&quot;, map);
</code></pre>
<p>This will print <code>{1: &quot;Hi There&quot;}</code>.</p>
<h4>Only Insert If the Key Has No Value</h4>
<p>It's common to want to see if there's some sort of value already stored in the
hash map for a particular key, and if not, insert a value. hash maps have a
special API for this, called <code>entry</code>, that takes the key we want to check as an
argument:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, &quot;hello&quot;);
let e = map.entry(2);
</code></pre>
<p>Here, the value bound to <code>e</code> is a special enum, <code>Entry</code>. An <code>Entry</code> represents a
value that might or might not exist. Let's say that we want to see if the key
<code>2</code> has a value associated with it. If it doesn't, we want to insert the value
&quot;world&quot;. In both cases, we want to return the resulting value that now goes
with <code>2</code>. With the entry API, it looks like this:</p>
<pre><code class="language-rust">use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(1, &quot;hello&quot;);
map.entry(2).or_insert(&quot;world&quot;);
map.entry(1).or_insert(&quot;Hi There&quot;);
println!(&quot;{:?}&quot;, map);
</code></pre>
<p>The <code>or_insert</code> method on <code>Entry</code> does exactly this: 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>{1: &quot;hello&quot;, 2: &quot;world&quot;}</code>. The first call to <code>entry</code> will
insert the key <code>2</code> with the value &quot;world&quot;, since <code>2</code> doesn't have a value
already. The second call to <code>entry</code> will not change the hash map since <code>1</code>
already has the value &quot;hello&quot;.</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, using the old value. For instance, if we wanted to count how many times
each word appeared in some text, we could use a hash map with the words as keys
and increment the value to keep track of how many times we've seen that word.
If this is the first time we've seen a word, we'll first insert the value <code>0</code>.</p>
<pre><code class="language-rust">use std::collections::HashMap;
let text = &quot;hello world wonderful world&quot;;
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!(&quot;{:?}&quot;, map);
</code></pre>
<p>This will print <code>{&quot;world&quot;: 2, &quot;hello&quot;: 1, &quot;wonderful&quot;: 1}</code>. The <code>or_insert</code>
method actually returns a mutable reference (<code>&amp;mut V</code>) to the value in the
hash map for this key. Here we store that mutable reference in the <code>count</code>
variable binding, 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 a good default tradeoff to make. 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 an object 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. Some programs you are now equipped to write and
might want to try include:</p>
<ul>
<li>Given a list of integers, use a vector and return their 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).</li>
<li>Convert strings to Pig Latin, where the first consonant of each word gets
moved to the end with an added &quot;ay&quot;, so &quot;first&quot; becomes &quot;irst-fay&quot;. Words that
start with a vowel get an h instead (&quot;apple&quot; becomes &quot;apple-hay&quot;). Remember
about UTF-8 encoding!</li>
<li>Using a hash map and vectors, create a text interface to allow a user to add
employee names to a department in the company. For example, &quot;Add Sally to
Engineering&quot; or &quot;Add Ron to Sales&quot;. Then let the user retrieve a list of all
people in a department or all people in the company by department, sorted
alphabetically.</li>
</ul>
<p>The standard library API documentation describes methods these types have that
will be helpful for these exercises!</p>
<p>We're getting into more complex programs where operations can fail, which means
it's a perfect time to go over error handling next!</p>
<h1>Patterns</h1>
<p>We've actually used patterns a few times so far: they're used in <code>let</code>
bindings, 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 bindings that have names in the <code>PATTERN</code> slot: a name is just a
particularly humble form of pattern.</p>
<h2>Multiple bindings</h2>
<p>Let’s try a more complex pattern. Change our example program to this:</p>
<p>Filename: src/main.rs</p>
<pre><code class="language-rust">fn main() {
let (x, y) = (5, 6);
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>And run it with <code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 5
The value of y is: 6
</code></pre>
<p>We’ve created two bindings with one <code>let</code>! Here’s our pattern:</p>
<pre><code class="language-text">(x, y)
</code></pre>
<p>And here’s the value:</p>
<pre><code class="language-text">(5, 6)
</code></pre>
<p>As you can see, the two line up visually, and so <code>let</code> binds <code>5</code> to <code>x</code> and <code>6</code>
to <code>y</code>. We could have used two <code>let</code> statements as well:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = 6;
}
</code></pre>
<p>In simple cases like this, two <code>let</code>s may be clearer, but in others, creating
multiple bindings at once is nice. As we become more proficient in Rust, we’ll
figure out which style is better, but it’s mostly a judgement call.</p>
<h2>Type annotations</h2>
<p>Most of the time, Rust uses <em>type inference</em>, meaning that it attempts to infer
the types of your bindings 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 bindings:</p>
<pre><code class="language-rust">let (x, y): (i32, i32) = (5, 6);
</code></pre>
<p>Just like we match up the <code>VALUE</code> with the <code>PATTERN</code>, we match up the <code>TYPE</code>
with the <code>PATTERN</code>.</p>
<h2>Literals &amp; _</h2>
<p>You can match against literals directly, and <code>_</code> acts as an ‘any’ case:</p>
<pre><code class="language-rust">let x = 1;
match x {
1 =&gt; println!(&quot;one&quot;),
2 =&gt; println!(&quot;two&quot;),
3 =&gt; println!(&quot;three&quot;),
_ =&gt; println!(&quot;anything&quot;),
}
</code></pre>
<p>This prints <code>one</code>.</p>
<h1>Multiple patterns</h1>
<p>You can match multiple patterns with <code>|</code>:</p>
<pre><code class="language-rust">let x = 1;
match x {
1 | 2 =&gt; println!(&quot;one or two&quot;),
3 =&gt; println!(&quot;three&quot;),
_ =&gt; println!(&quot;anything&quot;),
}
</code></pre>
<p>This prints <code>one or two</code>.</p>
<h2>ref and ref mut</h2>
<p>Usually, when you match against a pattern, bindings are bound by value.
This means you'll end up moving the value out:</p>
<pre><code class="language-rust,ignore">let name = Some(String::from(&quot;Bors&quot;));
match name {
Some(name) =&gt; println!(&quot;Found a name: {}&quot;, name),
None =&gt; (),
}
// name is moved here. This line will fail to compile:
println!(&quot;name is: {:?}&quot;, name);
</code></pre>
<p>If you'd prefer to bind <code>name</code> by reference, use the <code>ref</code> keyword:</p>
<pre><code class="language-rust">let name = Some(String::from(&quot;Bors&quot;));
match name {
Some(ref name) =&gt; println!(&quot;Found a name: {}&quot;, name),
None =&gt; (),
}
// name is not moved here; the match only took a reference to its data rather
// than moving it. This will work:
println!(&quot;name is: {:?}&quot;, name);
</code></pre>
<p>And for a mutable reference, <code>ref mut</code>:</p>
<pre><code class="language-rust">let mut name = Some(String::from(&quot;Bors&quot;));
match name {
Some(ref mut name) =&gt; *name = String::from(&quot;Another name&quot;),
None =&gt; (),
}
// name is not moved here; the match only took a reference to its data rather
// than moving it
println!(&quot;name is: {:?}&quot;, name);
</code></pre>
<h2>Destructuring</h2>
<p>Patterns can be used to destructure structs and enums:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };
let Point { x, y } = origin;
</code></pre>
<p>This brings an <code>x</code> and <code>y</code> binding into scope, matching the <code>x</code> and <code>y</code> of
<code>origin</code>. While it can be unusual in <code>let</code>, this is the same principle of
patterns in <code>match</code>:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 };
match origin {
Point { x, y } =&gt; { }, // x and y are bound here
}
</code></pre>
<h2>Shadowing</h2>
<p>As with all bindings, anything bound by a pattern will shadow bindings
outside of the binding construct:</p>
<pre><code class="language-rust">let x = Some(5);
match x {
Some(x) =&gt; { }, // x is an i32 here, not an Option&lt;i32&gt;
None =&gt; (),
}
</code></pre>
<h2>Ignoring bindings</h2>
<p>We discussed using <code>_</code> as a whole pattern to ignore it above, but you can
also use <code>_</code> inside of another pattern to ignore just part of it:</p>
<pre><code class="language-rust">let x = Some(5);
match x {
Some(_) =&gt; println!(&quot;got a Some and I don't care what's inside&quot;),
None =&gt; (),
}
</code></pre>
<p>Or like this:</p>
<pre><code class="language-rust">let numbers = (2, 4, 8, 16, 32);
match numbers {
(first, _, third, _, fifth) =&gt; println!(&quot;Some numbers: {}, {}, {}&quot;, first, third, fifth),
}
</code></pre>
<p>If you want, you can use <code>..</code> to ignore all of the parts you haven't defined:</p>
<pre><code class="language-rust">struct Point {
x: i32,
y: i32,
z: i32,
}
let origin = Point { x: 0, y: 0, z: 0 };
match origin {
Point { x, .. } =&gt; { }, // y and z are ignored
}
</code></pre>
<h2>Ranges</h2>
<p>You can match a range of values with <code>...</code>:</p>
<pre><code class="language-rust">let x = 5;
match x {
1 ... 5 =&gt; println!(&quot;one through five&quot;),
_ =&gt; println!(&quot;something else&quot;),
}
</code></pre>
<p>Ranges are usually used with integers or <code>char</code>s:</p>
<pre><code class="language-rust">let x = 'c';
match x {
'a' ... 'j' =&gt; println!(&quot;early ASCII letter&quot;),
'k' ... 'z' =&gt; println!(&quot;late ASCII letter&quot;),
_ =&gt; println!(&quot;something else&quot;),
}
</code></pre>
<h2>Guards</h2>
<p>You can introduce ‘match guards’ with <code>if</code>:</p>
<pre><code class="language-rust">let x = Some(5);
match x {
Some(x) if x &lt; 5 =&gt; println!(&quot;less than five: {}&quot;, x),
Some(x) =&gt; println!(&quot;{}&quot;, x),
None =&gt; (),
}
</code></pre>
<p>If you’re using if with multiple patterns, the if applies to both sides:</p>
<pre><code class="language-rust">let x = 4;
let y = false;
match x {
4 | 5 if y =&gt; println!(&quot;yes&quot;),
_ =&gt; println!(&quot;no&quot;),
}
</code></pre>
<p>This prints <code>no</code>, because the if applies to the whole of <code>4 | 5</code>, and not to only
the <code>5</code>. In other words, the precedence of if behaves like this:</p>
<pre><code class="language-text">(4 | 5) if y =&gt; ...
</code></pre>
<p>not this:</p>
<pre><code class="language-text">4 | (5 if y) =&gt; ...
</code></pre>
<h2>Bindings</h2>
<p>You can bind values to names with <code>@</code>:</p>
<h2>Organizing your Public API</h2>
<p>Here, we will describe the properties that a good public API in Rust has in
order to be pleasant for others to use.</p>
<h3>Re-exports with <code>pub use</code></h3>
<p>If your internal code organization doesn't match your desired public API
organization, you can re-export items in the way you want them to be organized.</p>
<p>To re-export a name, combine the <code>pub</code> keyword with <code>use</code>:</p>
<pre><code class="language-rust"># fn main() {} // this ex needs to be outside main
mod a {
pub mod namespace {
pub fn function() {}
}
}
pub use a::namespace::function;
</code></pre>
<p>Here, the <code>a</code> module is not public to users of our library, so neither are its
children, even though <code>namespace</code> and <code>function</code> are public <em>within</em> our
library. So users of our library couldn't call <code>a::namespace::function()</code>
themselves. However, since we've re-exported <code>function</code> with <code>pub use</code>,
<code>function</code> will be public. Users can just call <code>function</code> themselves,
directly. This allows us to organize our code internally however we'd like,
while presenting a different external interface.</p>
<h2>Documentation</h2>
<!-- Insert why documentation is important here, who your audience is for documentation -->
<h3>Documentation comments</h3>
<p>Rust has another kind of comment: a documentation comment. These
comments don’t affect the way that the code works, but they do work with Rust’s
tools. More specifically, the <code>rustdoc</code> tool that comes with Rust reads
documentation comments and produces HTML documentation from them.</p>
<p>Documentation comments use an extra slash:</p>
<pre><code class="language-rust">/// The foo function doesn’t really do much.
fn foo() {
}
/// We also can use
/// multiple comments here too,
/// like we did before
fn bar() {
}
</code></pre>
<p>This comment would then be interpreted by <code>rustdoc</code> as documenting the thing
that follows it: <code>foo</code> and <code>bar</code>.</p>
<p>Because documentation comments have semantic meaning to <code>rustdoc</code>, the compiler
will pay attention to the placement of your documentation comments. For
example, a program with only this:</p>
<pre><code class="language-rust,ignore">/// What am I documenting?
</code></pre>
<p>Will give a compiler error:</p>
<pre><code class="language-bash">src/main.rs:1:1: 1:27 error: expected item after doc comment
src/main.rs:1 /// What am I documenting?
^~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<h3>Generating HTML documentation</h3>
<h3>Documentation examples</h3>
<p>Another special part about documentation comments is that code examples in
documentation comments are run as part of your tests, so that they're less
likely to go out of date! To use this feature:</p>
<ul>
<li>TODO: insert a documentation example, preferably one that demonstrates a
<code>use</code> statement including parts of the current crate, not just stdlib.</li>
</ul>
<h2>Workspaces and Multiple Related Crates</h2>
<p>Projects can define a workspace which is a set of crates that will all share
the same Cargo.lock and output directory.</p>
<p>We weren't technically precise about the difference between a <em>package</em> and a
<em>crate</em> until now, and casually people will use the words <em>package</em> and <em>crate</em>
interchangeably and everyone will understand.</p>
<p>But there are cases when it makes sense to have multiple crates in one project
because (insert reasons here). For example, (insert examples here, maybe
log/env_log in rust-lang-nursery?)</p>
<p>So let's get more precise now. Earlier, we said:</p>
<blockquote>
<p>A <em>crate</em> is what we call a package of Rust code.</p>
</blockquote>
<p>This definition is problematic because &quot;package&quot; does mean something specific
in terms of Cargo, but we used it in a general sense in that previous
definition.</p>
<p>Historically speaking, a &quot;compilation unit&quot; is the definition we use in Rust.
This comes from C and C++, which has three phases of going from &quot;here's my
source&quot; to &quot;here's something I run&quot;:</p>
<ol>
<li><strong>Preprocessing</strong>: this is where <code>cpp</code> (the c preprocessor, not &quot;c plus
plus&quot;) does <code>#include</code> and all that jazz</li>
<li><strong>Compiling</strong>: taking the output of preprocessing and turning it into an
object file</li>
<li><strong>Linking</strong>: taking one or many object files, putting them together, and
getting an ELF binary or <code>.exe</code></li>
</ol>
<p>Rust doesn't have a preprocessing step in this sense, and we call out to a
system linker, so <code>rustc</code> only really does step 2. So to be incredibly
technically correct, it's &quot;translation unit&quot;, even though most people say
&quot;compilation unit.&quot;</p>
<p>In some sense, a crate is &quot;that pile of source code you pass the root of to
<code>rustc</code>&quot;, but that feels too circular to be good. &quot;compilation unit&quot; is
technically precise, but is gibberish to a lot of people. And a &quot;package&quot; is
&quot;one or more crates&quot;, which confusingly, gets wrapped up by <code>cargo package</code>
into a file which ends in <code>.crate</code>, but is secretly a tarball.</p>
<p>Whew!</p>
<h1>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>
<h1>Derivable Traits</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>