Files
book/print.html
T

4426 lines
214 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
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> if let</a></li></ul></li><li><strong>7.</strong> Crates &amp; Modules</li><li><strong>8.</strong> Error Handling</li><li><strong>9.</strong> Basic Collections</li><li><ul class="section"><li><strong>9.1.</strong> Vectors</li><li><strong>9.2.</strong> Strings</li><li><strong>9.3.</strong> <code>HashMap&lt;K, V&gt;</code></li></ul></li><li><strong>10.</strong> Lifetimes</li><li><a href="chZZ-generics.html"><strong>11.</strong> Generics</a></li><li><strong>12.</strong> Traits</li><li><strong>13.</strong> Closures</li><li><strong>14.</strong> Iterators</li><li><a href="chXX-patterns.html"><strong>15.</strong> Patterns</a></li><li><strong>16.</strong> I/O</li><li><ul class="section"><li><strong>16.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>16.2.</strong> <code>std::fs</code></li><li><strong>16.3.</strong> <code>std::path</code></li><li><strong>16.4.</strong> <code>std::env</code></li></ul></li><li><strong>17.</strong> Testing</li><li><strong>18.</strong> Smart Pointers</li><li><ul class="section"><li><strong>18.1.</strong> <code>Deref</code></li><li><strong>18.2.</strong> <code>Deref</code> coercions</li><li><strong>18.3.</strong> <code>Box&lt;T&gt;</code></li><li><strong>18.4.</strong> <code>Rc&lt;T&gt;</code></li></ul></li><li><strong>19.</strong> Concurrency</li><li><ul class="section"><li><strong>19.1.</strong> Threads</li><li><strong>19.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>19.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>19.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>19.5.</strong> <code>Channels</code></li></ul></li><li><strong>20.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>20.1.</strong> Raw Pointers</li><li><strong>20.2.</strong> transmute</li></ul></li><li><strong>21.</strong> FFI</li><li><ul class="section"><li><strong>21.1.</strong> Conditional Compilation</li><li><strong>21.2.</strong> Bindings to C</li><li><strong>21.3.</strong> Using Rust from Other Languages</li><li><strong>21.4.</strong> <code>static</code></li></ul></li><li><strong>22.</strong> Creating a Library</li><li><ul class="section"><li><strong>22.1.</strong> Cargo</li><li><strong>22.2.</strong> Crates.io</li><li><a href="chYY-YY-documentation.html"><strong>22.3.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>22.4.</strong> Workspaces and Multiple Related Crates</a></li></ul></li><li><strong>23.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>23.1.</strong> Associated Types</li><li><strong>23.2.</strong> Trait Objects</li><li><strong>23.3.</strong> UFCS</li><li><strong>23.4.</strong> Coherence</li></ul></li><li><strong>24.</strong> Interior mutability</li><li><ul class="section"><li><strong>24.1.</strong> <code>Cell&lt;T&gt;</code></li><li><strong>24.2.</strong> <code>RefCell&lt;T&gt;</code></li></ul></li><li><strong>25.</strong> Macros</li><li><strong>26.</strong> Nightly Rust</li><li><a href="appendix-00.html"><strong>27.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>27.1.</strong> Keywords</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>s; 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>If you're on Windows, please download the appropriate <a href="https://www.rust-lang.org/install.html">installer</a>.</p>
<h3>Uninstalling</h3>
<p>Uninstalling Rust is as easy as installing it. On Linux or Mac, just run
the uninstall script:</p>
<pre><code class="language-bash">$ rustup self uninstall
</code></pre>
<p>If you used the Windows installer, you can re-run the <code>.msi</code> and it will give
you an uninstall option.</p>
<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. If it isn't, run the installer again, select &quot;Change&quot; on the &quot;Change,
repair, or remove installation&quot; page and ensure &quot;Add to PATH&quot; is checked.</p>
<p>If not, there are a number of places where you can get help. The easiest is
<a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a>, which you can access through
<a href="http://chat.mibbit.com/?server=irc.mozilla.org&amp;channel=%23rust">Mibbit</a>. Click that link, 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. On Linux or Mac, run <code>rustup doc</code> to open the local
documentation in your browser. On Windows, the documentation is in a
<code>share/doc</code> directory inside the directory where Rust was installed.</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, that's an option.</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>
<pre><code class="language-bash">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<blockquote>
<p>Note: If you’re on Windows and not using PowerShell, the <code>~</code> that represents
your home directory may not work.
Consult the documentation for your shell for more details.</p>
</blockquote>
<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>
<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>). We aren’t returning anything from this function, so we have
omitted the return type entirely. If there was a return type, there would be a
<code>-&gt;</code> and the return type after the parentheses.</p>
<p>Also note that the function body is wrapped in curly braces (<code>{</code> and <code>}</code>). Rust
requires these around all function bodies. It's considered good style to put
the opening curly brace on the same line as the function declaration, with one
space in between.</p>
<p>Inside the <code>main()</code> function:</p>
<pre><code class="language-rust"> println!(&quot;Hello, world!&quot;);
</code></pre>
<p>This line does all of the work in this little program: it prints text to the
screen. There are a number of details that are important here. The first is
that it’s indented with four spaces, not tabs.</p>
<p>The second important part is <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-bash">$ dir
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> since your code depends on them.</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 the way you installed
Rust 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>
<pre><code class="language-bash">$ cd ~/projects
</code></pre>
<p>And then 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 often called
<em>binaries</em> (as in <code>/usr/bin</code>, if you’re on a Unix system). <code>hello_cargo</code> is the
name we've chosen 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; 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>
<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 <em><a href="https://github.com/toml-lang/toml">TOML</a></em> (Tom's Obvious, Minimal Language) format. TOML is
similar to INI but has some extra goodies and is used as Cargo’s
configuration format.</p>
<p>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>
<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>
<ol>
<li>Our code goes in the <code>src</code> directory</li>
<li>The top level contains a <code>Cargo.toml</code> configuration file</li>
</ol>
<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>
<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 actually do both in one step with
<code>cargo run</code> as follows:</p>
<pre><code class="language-bash">$ cargo run
Running `target/debug/hello_cargo`
Hello, world!
</code></pre>
<p>Notice that this time, we didn't see the output 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>
<ol start="3">
<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>
</ol>
<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 might find that 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! We’ll 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>Set up</h2>
<p>Let’s set up a new project. Go to your projects directory, and create a new project using Cargo.</p>
<pre><code class="language-bash">$ cd ~/projects
$ cargo new guessing_game --bin
$ cd guessing_game
</code></pre>
<p>We pass the name of our project to <code>cargo new</code>, then 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>
<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 authors information that Cargo got from your environment is not correct,
go ahead and fix that.</p>
<p>And as we saw in the last chapter, <code>cargo new</code> generates a &quot;Hello, world!&quot; for
us. Check out <code>src/main.rs</code>:</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! The first thing we need to do for our guessing game is
allow our player to input a guess. Put this in your <code>src/main.rs</code>:</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. As such, we
need the <code>io</code> library from the standard library. Rust only imports a few things
by default into every program, <a href="../std/prelude/index.html">the <em>prelude</em></a>. If it’s not in the
prelude, you’ll have to <code>use</code> it directly. Using the <code>std::io</code> library gets
you a number of useful <code>io</code>-related things, so that's what we've done here.</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>We previously learned in Chapter 1 that <code>println!()</code> is a macro that
prints a string to the screen.</p>
<h3>Variable Bindings</h3>
<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 let statement, which is
used to create what are called <em>variable bindings</em>. Here's an 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 tricks up their sleeves.</p>
<p>For example, they’re immutable by default. That’s why our example
uses <code>mut</code>: it makes a binding mutable, rather than immutable.</p>
<pre><code class="language-rust">let foo = 5; // immutable.
let mut bar = 5; // mutable
</code></pre>
<p>Oh, and <code>//</code> will start a comment, until the end of the line. Rust ignores
everything in comments.</p>
<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 what it’s
bound to: <code>String::new()</code>.</p>
<p><code>String</code> is a string type, provided by the standard library. A
<a href="../std/string/struct.String.html"><code>String</code></a> is a growable, UTF-8 encoded bit of text.</p>
<p>The <code>::new()</code> syntax uses <code>::</code> because this is an <em>associated function</em> of
a particular type. That is to say, it’s associated with <code>String</code> itself,
rather than a particular instance of a <code>String</code>. Some languages call this a
<em>static method</em>.</p>
<p>This function is named <code>new()</code>, because it 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>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>Let’s go through this together bit-by-bit. The first line has two parts. Here’s
the first:</p>
<pre><code class="language-rust,ignore">io::stdin()
</code></pre>
<p>Remember how we said <code>use std::io;</code> on the first line of the program? We’re now
calling an associated function on it. If we didn’t <code>use std::io</code>, we could
have written this line as <code>std::io::stdin()</code>.</p>
<p>This particular function returns a handle to the standard input for your
terminal. More specifically, a <a href="../std/io/struct.Stdin.html">std::io::Stdin</a>.</p>
<p>The next part will use this handle to get input from the user:</p>
<pre><code class="language-rust,ignore">.read_line(&amp;mut guess)
</code></pre>
<p>Here, we call the <a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line()</code></a> method on our handle. We’re also
passing one argument to <code>read_line()</code>: <code>&amp;mut guess</code>.</p>
<p>Remember how we bound <code>guess</code> above? We said it was mutable. However,
<code>read_line</code> doesn’t take a <code>String</code> as an argument: it takes a <code>&amp;mut String</code>.
The <code>&amp;</code> is the feature of Rust called a <em>reference</em>, which allows you to have
multiple ways to access one piece of data in order to reduce copying.
References are a complex feature, as one of Rust’s major selling points 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 them 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>.</p>
<p>Why does <code>read_line()</code> take a mutable reference to a string? Its job is
to take what the user types into standard input and place that into a
string. So it takes that string as an argument, and in order to add
the input, that string needs to be mutable.</p>
<p>But we’re not quite done with this line of code, though. While it’s
a single line of text, it’s only the first part of the single logical line of
code. This is the second part of the line:</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, you may introduce a newline
and other whitespace. This helps you split up long lines. We <em>could</em> 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.</p>
<h3>The <code>Result</code> Type</h3>
<p>We already talked about <code>read_line()</code>, but what about <code>expect()</code>? Well,
we already mentioned that <code>read_line()</code> puts what the user types into the <code>&amp;mut String</code> 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>. 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>, and then specific versions for
sub-libraries, like <code>io::Result</code>.</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. In
this case, <code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect()</code> method</a> that takes a value
it’s called on, and if it isn’t a successful result, will cause our program to
crash and display the message that we passed as an argument to <code>expect()</code>.</p>
<p>If we don't call this method, 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 us that we haven’t used the <code>Result</code> value. This warning comes from
a special annotation that <code>io::Result</code> has. Rust is trying to tell you that you
haven’t handled a possible error. The right way to suppress the error is to
actually write error handling. Luckily, if we want to crash if there’s a
problem, we can use <code>expect()</code>. If we can recover from the error somehow, we’d
do something else, but we’ll save that for a future project.</p>
<h3><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. The first <code>{}</code>
holds the first value 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: {} and {}&quot;, x, y);
</code></pre>
<p>Which would print out &quot;x and y: 5 and 10&quot;.</p>
<p>Anyway, back to our guessing game. We can run what we have 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. 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>. A <em>crate</em> is a package of Rust code.
We’ve been building a <em>binary crate</em>, which is an executable. <code>rand</code> is a
<em>library crate</em>, which contains code that’s intended to be used with other
programs.</p>
<p>Using external crates is where Cargo really shines. Before we can write
the code using <code>rand</code>, we need to modify our <code>Cargo.toml</code>. Open it up, and
add this line at the bottom beneath the <code>[dependencies]</code> section header that
Cargo created for you:</p>
<pre><code class="language-toml">[dependencies]
rand = &quot;0.3.14&quot;
</code></pre>
<p>The <code>[dependencies]</code> section of <code>Cargo.toml</code> is like the <code>[package]</code> section:
everything that follows the section heading is part of that section, until
another section starts. Cargo uses the dependencies section to know what
dependencies on external crates you have 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>, 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 versions (but they will be compatible, 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 said we wanted to depend on
<code>rand</code>, we’ve also grabbed a copy of <code>libc</code>. This is because <code>rand</code> depends on
<code>libc</code> to work. After downloading them, it compiles them and then compiles
our project.</p>
<p>If we run <code>cargo build</code> again, we’ll get different output:</p>
<pre><code class="language-bash">$ cargo build
</code></pre>
<p>That’s right, no output! Cargo knows that our project has been built, that
all of its dependencies are built, and that no changes have been made. There’s
no reason to do all that stuff again. 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>What happens when next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out,
with an important bugfix? While getting bugfixes is important, what if <code>0.3.15</code>
contains a regression that breaks 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 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 then use
that specific version rather than do all the work of figuring out versions
again. This lets you have a repeatable build automatically. In other words,
we’ll stay at <code>0.3.14</code> until we explicitly upgrade, and so will anyone who we
share our code with, thanks to the lock file.</p>
<p>What about when we <em>do</em> want to use <code>v0.3.15</code>? Cargo has another command,
<code>update</code>, which says &quot;ignore the <code>Cargo.lock</code> file and figure out all the
latest versions that fit what we’ve specified in <code>Cargo.toml</code>. If that works,
write those versions out to the lock file&quot;. 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 we want to
move to <code>0.4.x</code>, we’d have to update what is in the <code>Cargo.toml</code> file. When we
do, the next time we <code>cargo build</code>, Cargo will update the index and re-evaluate
our <code>rand</code> requirements.</p>
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a> and <a href="http://doc.crates.io/crates-io.html">its
ecosystem</a> 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>
<p>Let’s get on to actually <em>using</em> <code>rand</code>. Here’s our next step:</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>The first thing we’ve done is change the first line. It now says <code>extern crate rand</code>. Because we declared <code>rand</code> in our <code>[dependencies]</code>, we can now put
<code>extern crate</code> in our code to let Rust know we’ll be making use of that
dependency. This also does the equivalent of a <code>use rand;</code> as well, so we can
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>. We’re going to use a
method in a moment, and it requires that <code>Rng</code> be in scope to work. The basic
idea is this: methods are defined on something called <em>traits</em>, and for the
method to work, it needs the trait to be in scope. For more about the
details, read the traits section in Chapter XX.</p>
<p>There are two other lines we added, 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>We use the <code>rand::thread_rng()</code> function to get a copy of the random number
generator, which is local to the particular thread of execution
we’re in. Because we put <code>use rand::Rng</code> above, the random number generator has
a <code>gen_range()</code> method available. This 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>The second line 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 between 1 and</p>
<ol start="100">
<li>Great job! Next up: comparing our guess to the secret number.</li>
</ol>
<h2>Comparing guesses</h2>
<p>Now that we’ve got user input, let’s compare our guess to the secret number.
Here’s part of our next step. It won't quite compile yet though:</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>A few new bits here. The first is another <code>use</code>. We bring a type called
<code>std::cmp::Ordering</code> into scope. Then we add five new lines at the bottom that
use that 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 can be called on anything that can be compared, and it takes
a reference to the thing you want to compare it to. It returns the <code>Ordering</code>
type we imported with the <code>use</code> statement earlier. We use a <a href="match.html"><code>match</code></a>
statement to determine exactly what kind of <code>Ordering</code> it is. <code>Ordering</code> is an
<a href="enums.html"><code>enum</code></a>, short for <em>enumeration</em>, which looks like this:</p>
<pre><code class="language-rust">enum Foo {
Bar,
Baz,
}
</code></pre>
<p>With this definition, anything of type <code>Foo</code> can be either a
<code>Foo::Bar</code> or a <code>Foo::Baz</code>. We use the <code>::</code> to indicate the
namespace for a particular <code>enum</code> variant.</p>
<p>The <a href="../std/cmp/enum.Ordering.html"><code>Ordering</code></a> <code>enum</code> has three possible variants: <code>Less</code>, <code>Equal</code>,
and <code>Greater</code>. The <code>match</code> statement takes a value of a type and lets you
create an <em>arm</em> for each possible value. An arm is made up of a pattern and the
code that we should execute if the pattern matches the value of the type. Since
we have three types of <code>Ordering</code>, we have three arms:</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>If it’s <code>Less</code>, we print <code>Too small!</code>, if it’s <code>Greater</code>, <code>Too big!</code>, and if
<code>Equal</code>, <code>You win!</code>. <code>match</code> is really useful and is used often in Rust.</p>
<p>We did mention that this won’t quite compile yet, though. 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 it is 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>, so it doesn’t make us write out the type. With our
<code>secret_number</code>, there are a number of types which can have a value between one
and a hundred: <code>i32</code>, a thirty-two-bit number, or <code>u32</code>, an unsigned
thirty-two-bit number, or <code>i64</code>, a sixty-four-bit number or others. So far,
that hasn’t mattered, and so Rust defaults to an <code>i32</code>. However, here, Rust
doesn’t know how to compare the <code>guess</code> and the <code>secret_number</code>. They need to
be the same 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. Here’s our new program:</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 new two lines:</p>
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
.expect(&quot;Please type a number!&quot;);
</code></pre>
<p>Wait a minute, didn't we already have a <code>guess</code>? We do, but Rust allows us
to <em>shadow</em> the previous <code>guess</code> with a new one. This is often used in this
exact situation, where <code>guess</code> starts as a <code>String</code>, but we want to convert it
to a <code>u32</code>. Shadowing lets us re-use the <code>guess</code> name rather than forcing us
to come up with two unique names like <code>guess_str</code> and <code>guess</code> or something
else.</p>
<p>We bind <code>guess</code> to an expression that looks like something we wrote earlier:</p>
<pre><code class="language-rust,ignore">guess.trim().parse()
</code></pre>
<p>Here, <code>guess</code> refers to the old <code>guess</code>, the one that was a <code>String</code> with our
input in it. The <code>trim()</code> method on <code>String</code>s will eliminate any white space at
the beginning and end of our string. This is important, as we had to press the
&quot;return&quot; key to satisfy <code>read_line()</code>. 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. <code>trim()</code>
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> parses a string into some kind of
number. Since it can parse a variety of numbers, we need to give Rust a hint as
to the exact type of number we want. Hence, <code>let guess: u32</code>. The colon (<code>:</code>)
after <code>guess</code> tells Rust we’re going to annotate its type. <code>u32</code> is an
unsigned, thirty-two bit integer. Rust has a number of built-in number
types, but we’ve chosen <code>u32</code>. It’s a good default choice for a small
positive number. You'll see the other number types in Chapter XX.</p>
<p>Just like <code>read_line()</code>, our call to <code>parse()</code> could cause an error. What if
our string contained <code>A👍%</code>? There’d be no way to convert that to a number. As
such, we’ll do the same thing we did with <code>read_line()</code>: use the <code>expect()</code>
method to crash if there’s an error.</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. Verify that guessing
the secret number works, as well as guessing a number too small.</p>
<p>Now we’ve got most of the game working, but we can only make one guess. Let’s
change that by adding loops!</p>
<h2>Looping</h2>
<p>The <code>loop</code> keyword gives us an infinite loop. Let’s add that in:</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>And try it out. But wait, didn’t we just add an infinite loop? Yup. Remember
our discussion about <code>parse()</code>? If we give a non-number answer, the program
will crash and, therefore, 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>Ha! <code>quit</code> actually quits. As does any other non-number input. Well, this is
suboptimal to say the least. First, let’s actually quit when you win the game:</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 the <code>You win!</code>, we’ll exit the loop when we
win. Exiting the loop also means exiting the program, since the loop is the last
thing in <code>main()</code>. We have another tweak to make: when someone inputs a
non-number, we don’t want to quit, we want to ignore it. We can do that
like this:</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 = match guess.trim().parse() {
Ok(num) =&gt; num,
Err(_) =&gt; continue,
};
println!(&quot;You guessed: {}&quot;, guess);
match guess.cmp(&amp;secret_number) {
Ordering::Less =&gt; println!(&quot;Too small!&quot;),
Ordering::Greater =&gt; println!(&quot;Too big!&quot;),
Ordering::Equal =&gt; {
println!(&quot;You win!&quot;);
break;
}
}
}
}
</code></pre>
<p>These are the lines that changed:</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 <code>expect()</code> to a <code>match</code> statement. A <code>Result</code> is the
return type of <code>parse()</code>. <code>Result</code> is an <code>enum</code> like <code>Ordering</code>, but in this
case, each variant has some data associated with it. <code>Ok</code> is a success, and
<code>Err</code> is a failure. Each contains more information: in this case, the
successfully parsed integer or an error type, respectively. When we <code>match</code> an
<code>Ok(num)</code>, that pattern sets the name <code>num</code> to the value inside the <code>Ok</code> (the
integer), and the code we run just returns that integer. In the <code>Err</code> case, we
don’t care what kind of error it is, so we just use the catch-all <code>_</code> instead
of a name. So for all errors, we run the code <code>continue</code>, which lets us move to
the next iteration of the loop, effectively ignoring the errors.</p>
<p>Now we should be good! 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. Can you
think of what it is? That’s right, we don’t want to print out the secret
number. It was good for testing, but it kind of ruins the game. Here’s our
final source:</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,
};
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>
<h2>Complete!</h2>
<p>This project showed you a lot: <code>let</code>, <code>match</code>, methods, associated
functions, using external crates, and more.</p>
<p>At this point, you have successfully built the Guessing Game! Congratulations!</p>
<h1>Common Programming Concepts in Rust</h1>
<p>Let's 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>
<p>PROD: START BOX</p>
<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>
<p>PROD: END BOX</p>
<h2>Variable Bindings and Mutability</h2>
<p>We mentioned in Chapter XX that by default, variable bindings are <em>immutable</em>.
This is one of many nudges that Rust's design has to encourage us to write our
code to get 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 with Cargo.
Open a terminal, and navigate to the directory you want to store your projects
in. From there, run these commands:</p>
<pre><code class="language-bash">$ cargo new --bin bindings
$ cd bindings
</code></pre>
<p>Then open <code>src/main.rs</code> and replace its code with the following:</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. Try to keep in mind that the Rust compiler is trying to help your
program be the very best.</p>
<p>PROD: START BOX
######Extended Error Explanations</p>
<p>Now that you've seen an example of a Rust error, let's 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 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
}
```
By default, variables in Rust are immutable. To fix this error, add the keyword
`mut` after the keyword `let` when declaring the variable. For example:
```
fn main(){
let mut x = 3;
x = 5;
}
```
</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>
<p>PROD: END BOX</p>
<p>The error includes the message <code>re-assigment of immutable variable</code> because the
program tried to assign a second value to the <code>x</code> variable.</p>
<p>Getting compile-time errors when your code attempts to change a value that it
previously said was immutable is important because this very situation can lead
to bugs. If one part of your code operates on an assumption that a value it's
operating on will never change, and another part of your code changes that
value, it's possible that the first code won't do what it was designed to do.
Especially when the second piece of code only changes the value <em>sometimes</em>,
this cause of bugs can be difficult to track down after the fact.</p>
<p>In Rust, our code can know that a value our code assumes 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 is 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 telling the compiler it should allow this value to be changed, it
conveys intent to future readers of the code and says 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>
<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>. You might 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
after the second binding. This can be useful if you’d like to perform a few
transformations on a value, but have the binding be immutable after those
transformations have been completed. For example:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>This program first binds <code>x</code> to a value of <code>5</code>. Then, it shadows <code>x</code> by saying
<code>let x =</code> again, 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>Shadowing is useful because it lets us modify <code>x</code> without having to make the
binding mutable. This means the compiler will still keep us from accidentally
trying to mutate <code>x</code> directly later.</p>
<p>Now let's look at some of the 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
of Rust data types: 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. When many types are possible, such as when we
converted a <code>String</code> to a numeric type using <code>parse()</code> in the guessing game
tutorial, we can add a type annotation, like this:</p>
<pre><code class="language-rust,ignore">let x: i32 = 5;
</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 is one that represents a single value. There are four key
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 4-1: Integer types in Rust. Each code (for example, i32) can be used to
declare the type of a 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, meaning the number needs to have a sign with it
(&quot;signed&quot;), or whether it will only ever be positive and can therefore be
represented without a sign (&quot;unsigned&quot;). 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>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>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 need to specify <code>isize</code> or <code>usize</code> is when indexing some sort of
collection, which we'll talk about in the &quot;Arrays&quot; section.</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.</p>
<p>Here's an example showing floating-point numbers in action:</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
modulo. This code shows how you'd use each one in a <code>let</code> statement:</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;
// modulo
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>
<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>
<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. It also means that <code>char</code>s are four bytes each. You can learn more
about Unicode Scalar Values at
<em>http://www.unicode.org/glossary/#unicode_scalar_value</em> and find a chart for
all unicode code points at <em>http://www.unicode.org/charts/</em>.</p>
<h4>The Byte Type</h4>
<p>You can work with the bytes of data directly. Byte literals can be created from
the ASCII characters using <code>b</code> and single quotes:</p>
<pre><code class="language-rust">fn main() {
let byte = b'a';
println!(&quot;byte is {}&quot;, byte);
}
</code></pre>
<p>This will print <code>byte is 97</code>. Similarly, byte string literals can be created
using <code>b</code> and double quotes, like <code>b&quot;some byte string&quot;</code>. Note that since you are
limited to ASCII characters, it's a best practice to use characters instead of
bytes when you're working with natural language text.</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>We’ve seen tuples already, when binding multiple values at once. 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, as in this example:</p>
<pre><code class="language-rust">fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
</code></pre>
<p>Note that, unlike the examples of multiple bindings, here we bind the single
name <code>tup</code> to the entire tuple, emphasizing the fact that a tuple is considered
a single compound element. We could then use pattern matching to destructure
this tuple value, like this:</p>
<pre><code class="language-rust">fn main() {
let tup: (i32, f64, u8) = (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.</p>
<p>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>
<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>
<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, they aren't as
flexible as the <code>Vec</code> (short for &quot;vector&quot;), 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 <code>Vec</code>, you should probably go with a <code>Vec</code>,
and we'll discuss them in more detail in chapter XX.</p>
<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>
<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 <code>first</code> variable will bind to <code>1</code> at index <code>[0]</code> in the
array, and <code>second</code> will bind to <code>2</code> at index <code>[1]</code> in the array. Note that
these values are copied out of the array and into <code>first</code> and <code>second</code> when the
<code>let</code> statement is called. That means if the array changes after the <code>let</code>
statements, these bindings will not, and the two variables should retain their
values.</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>
<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 compiling 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 names. In
snake case, all letters are lower case, and there are underscores separating
words. (Rust also uses snake case for the names of variable bindings; we just
haven't used any variable bindings with enough letters to need underscores
yet). Here's a program containing an example function definition:</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 project to explore functions further. Open a terminal, and
navigate to the directory you're keeping your projects in. From there, use
Cargo to generate a new project, as follows:</p>
<pre><code class="language-bash">$ cargo new --bin functions
$ cd functions
</code></pre>
<p>Place the <code>another_function()</code> example in a file named <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>
<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>Since we passed <code>5</code> to <code>another_function()</code>, the <code>println!</code> macro put <code>5</code> where
the pair of curly braces were in the format string. The declaration of
<code>another_function()</code> shows that it takes one argument named <code>x</code>, and the type
of <code>x</code> is <code>i32</code>.</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>
<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 ending in an optional
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><code>Let</code> bindings are statements. They instruct the program to create a binding
name and assign a value to it. <code>let y = 6;</code> in this example is a statement:</p>
<pre><code class="language-rust">fn main() {
let y = 6;
}
</code></pre>
<p>Function definitions are also statements-- so the entire previous example is a
statement as well.</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>
<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, you
could write <code>x = y = 6</code> and have both <code>x</code> and <code>y</code> have the value <code>6</code>, but that
is not the case in Rust.</p>
<p>Expressions are 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>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = {
let x = 3;
x + 1
};
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>The expression:</p>
<pre><code class="language-rust,ignore">{
let x = 3;
x + 1
}
</code></pre>
<p>is a block that, in this case, gets evaluated to <code>4</code>, which 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 like
most of the lines we've seen up until now have had. 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 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>
<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, too. 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 actually 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> in <code>main()</code> shows that we can
use 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>
<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>
<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>
<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>
<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>Deciding whether or not to run some code depending on if a condition is true,
or deciding to run some code repeatedly while a condition is true, are basic
building blocks in most programming languages. The most common constructs that
let 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, then 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>. Navigate to your projects directory,
and use Cargo to make a new project called <code>branches</code>:</p>
<pre><code class="language-bash">$ cargo new --bin branches
$ cd branches
</code></pre>
<p>Write this sample program using <code>if</code> and save it in the <em>branches</em> directory in
<code>src/main.rs</code>:</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 <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>
statement, which we have chosen to do here. <code>else</code> gives the program a block of
code to execute should <code>condition</code> evaluate to false.</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 <code>condition</code> 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>
<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 your intention is for the <code>if</code> code block to be run if a number is not equal to <code>0</code>, for example, we would change the <code>if</code> expression to read:</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 &quot;number was something other than zero&quot;.</p>
<h4>Multiple Conditions with <code>else if</code></h4>
<p>We can have multiple coniditions by combining <code>if</code> and <code>else</code> in an <code>else if</code>
expression. For example:</p>
<pre><code class="language-rust">fn main() {
let number = 5;
if number == 3 {
println!(&quot;condition was 3&quot;);
} else if number == 4 {
println!(&quot;condition was 4&quot;);
} else if number == 5 {
println!(&quot;condition was 5&quot;);
} else {
println!(&quot;condition was something else&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`
condition was 5
</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.</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 XX, 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 learn 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>
<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 that 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>
<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>The expression in the <code>if</code> block is an integer and the expresion in the <code>else</code>
block is a string. This can’t work, because variable bindings must have a
single type. If we try to run this, we’ll get an error:</p>
<pre><code class="language-bash"> Compiling branches v0.1.0 (file:///projects/branches)
src/main.rs:4:18: 8:6 error: if and else have incompatible types:
expected `_`,
found `&amp;'static str`
(expected integral variable,
found &amp;-ptr) [E0308]
src/main.rs:4 let number = if condition {
src/main.rs:5 5
src/main.rs:6 } else {
src/main.rs:7 &quot;six&quot;
src/main.rs:8 };
src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to previous error
Could not compile `branches`.
</code></pre>
<p>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>
<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 constructs called <em>loops</em>. A loop runs through the code
inside it to the end and then starts immediately back at the beginning. To try
out loops, let’s make a new project. Navigate to your <em>projects</em> folder and use
Cargo to make a new project:</p>
<pre><code class="language-bash">$ cargo new --bin loops
$ cd loops
</code></pre>
<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>
<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 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>A useful thing that many programs do is 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>; try to do
that now 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>
<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>
<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>
<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 resulting 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 be <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 is using a <code>Range</code>, which
is a type provided by the standard library that generates numbers starting from
one number and ending before another number. 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>
<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>
<p>Now that you know how Rust does things that most other languages can do, let's
talk about a concept that <em>doesn't</em> commonly exist: ownership.</p>
<h1>Understanding Ownership</h1>
<p>Ownership is important to understand: it's Rust's most unique feature, and
enables Rust to make memory safety guarantees without needing a garbage
collector. We’ll also talk about several related features: borrowing, slices,
and how Rust lays things out in memory.</p>
<h2>Ownership</h2>
<p>Rust’s central feature is called <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>However, because 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>
<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
them inside of a <code>main()</code> function. This lets our examples be a bit more
concise, letting us focus on the actual details rather than boilerplate.</p>
<p>Anyway, here is our first example:</p>
<pre><code class="language-rust">let s = &quot;hello&quot;;
</code></pre>
<p>This variable binding 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 &quot;into scope&quot;, it is valid.</li>
<li>It remains so until it &quot;goes out of scope&quot;.</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>Strings</h3>
<p>String literals are convenient, but they aren’t the only way that you use
strings. For one thing, they’re immutable. For another, not every string is
literal: what about taking user input and storing it in a string?</p>
<p>For this, Rust has a second string type, <code>String</code>. You can create a <code>String</code>
from a string literal using the <code>from</code> function:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
</code></pre>
<p>We haven’t seen the double colon (<code>::</code>) syntax yet. It 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 can 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>
<h3>Memory and allocation</h3>
<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>
<p>In the case of a string literal, because we know the contents of the string at
compile time, we can hard-code the text of the string directly into the final
executable. This means that string literals are 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 string whose size is unknown at compile
time and whose size might change over the course of running the program.</p>
<p>With <code>String</code>, in order to support a mutable, growable string, we need to
allocate an unknown amount of memory 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>
(<em>GC</em>), 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 our 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. 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. Remember our example? Here’s a version with
<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>We have a natural point at which we can return the memory our <code>String</code> needs
back to the operating system: when it goes out of scope. When a variable goes
out of scope, Rust calls a special function for us. This function is called
<code>drop()</code>, and it is where the author of <code>String</code> can put the code to return the
memory.</p>
<blockquote>
<p>Aside: 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, and 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 obvious right now, but things can get tricky in more advanced situations.
Let’s go over the first one of those right now.</p>
<h3>Move</h3>
<p>What would you expect this code to do?</p>
<pre><code class="language-rust">let x = 5;
let y = x;
</code></pre>
<p>You might say “Make a copy of <code>5</code>”, and that would be correct. We now have two
bindings, <code>x</code> and <code>y</code>, and both equal <code>5</code>.</p>
<p>Now let’s look at <code>String</code>. What would you expect this code to do?</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
</code></pre>
<p>You might say “copy the <code>String</code>!” This is both correct and incorrect at the
same time. It does a <em>shallow</em> copy of the <code>String</code>. What’s that mean? Well,
let’s take a look at what <code>String</code> looks like under the covers:</p>
<p><img alt="string" src="img/foo1.png" class="center" style="width: 50%;" /></p>
<p>A <code>String</code> is made up of three parts: a pointer to the memory that holds the
contents of the string, a length, and a capacity. The length is how much memory
the <code>String</code> is currently using. The capacity is the total amount of memory the
<code>String</code> has gotten from the operating system. The difference between length
and capacity matters but not in this context, so don’t worry about it too much.
For right now, it's fine to ignore the capacity.</p>
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> itself is copied, meaning we copy the
pointer, the length, and the capacity. We do not copy the data that the
<code>String</code>'s pointer refers to. In other words, it looks like this:</p>
<p><img alt="s1 and s2" src="img/foo2.png" class="center" style="width: 50%;" /></p>
<p><em>Not</em> this:</p>
<p><img alt="s1 and s2 to two places" src="img/foo4.png" class="center" style="width: 50%;" /></p>
<p>There’s a problem here. Both data pointers are pointing to the same place. Why
is this a problem? Well, when <code>s2</code> goes out of scope, it will free the memory
that the pointer points to. And then <code>s1</code> goes out of scope, and it will <em>also</em>
try to free the memory that the pointer points to. That’s bad, and is known as
a &quot;double free&quot; error.</p>
<p>So what’s the solution? Here, we stand at a crossroads with a few options.</p>
<p>One way would be to change assignment so that it will also copy out any data.
This works, but is inefficient: what if our <code>String</code> contained a novel?
Also, that solution would only work for memory. What if, instead of a <code>String</code>,
we had a <code>TcpConnection</code>? Opening and closing a network connection is very
similar to allocating and freeing memory, so it would be nice to be able to use
the same mechanism. We wouldn't be able to, though, because creating a new
connection requires more than just copying memory: we have to request a new
connection from the operating system. We could then extend our solution to
allow the programmer to hook into the assignment, similar to <code>drop()</code>, and
write code to fix things up. That would work, but if we did that, an <code>=</code> could
run arbitrary code. That’s also not good, and it doesn’t solve our efficiency
concerns either.</p>
<p>Let’s take a step back: the root of the problem is that <code>s1</code> and <code>s2</code> both
think that they have control of the memory and therefore need to free it.
Instead of trying to copy the allocated memory, we could say that <code>s1</code> is no
longer valid and, therefore, doesn’t need to free anything. This is in fact the
choice that Rust makes. 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 sounded like a shallow copy. Because Rust
also invalidates the first binding, instead of calling this a shallow copy,
it's called 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 this:</p>
<p><img alt="s1 and s2 to the same place" src="img/foo3.png" class="center" style="width: 50%;" /></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>
<h3>Ownership Rules</h3>
<p>This leads us to the Ownership 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 <code>drop()</code>ped.</li>
</ol>
</blockquote>
<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>
<h3>Clone</h3>
<p>But what 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 [<code>structs</code> in Chapter XX], 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;{}&quot;, s1);
</code></pre>
<p>This will work just fine. Remember our diagram from before? In this case,
it <em>is</em> doing this:</p>
<p><img alt="s1 and s2 to two places" src="img/foo4.png" class="center" style="width: 50%;" /></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>
<h3>Copy</h3>
<p>There’s one last wrinkle that we haven’t talked about yet. This code works:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!(&quot;{}&quot;, x);
</code></pre>
<p>But why? We don’t have a call to <code>clone()</code>. Why didn’t <code>x</code> get moved into <code>y</code>?</p>
<p>Types like integers that have a known size at compile time do not ask for
memory from the operating system and therefore do not need to be <code>drop()</code>ped
when they go out of scope. 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 that you can place on types like these, and that
annotation is the <code>Copy</code> trait. 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 you make something have the <code>Copy</code> trait if it has
implemented <code>drop()</code>. If you need to do something special when the value goes
out of scope, being <code>Copy</code> will be an 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,
but 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>Passing a value to a function has similar semantics as assigning it:</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;);
takes_ownership(s);
let x = 5;
makes_copy(x);
}
fn takes_ownership(some_string: String) {
println!(&quot;{}&quot;, some_string);
}
fn makes_copy(some_integer: i32) {
println!(&quot;{}&quot;, some_integer);
}
</code></pre>
<p>Passing a binding to a function will move or copy, just like assignment. Here’s
the same example, but with some annotations showing where things go into and
out of scope:</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;); // s goes into scope.
takes_ownership(s); // s moves into the function...
// ... and so is no longer valid here.
let x = 5; // x goes 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 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>Remember: 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>
<p>Returning values can also transfer ownership:</p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership();
let s2 = String::from(&quot;hello&quot;);
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -&gt; String {
let some_string = String::from(&quot;hello&quot;);
some_string
}
fn takes_and_gives_back(a_string: String) -&gt; String {
a_string
}
</code></pre>
<p>With similiar annotations:</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 something moves it, and when an
owner goes out of scope, if it hasn’t been moved, it will <code>drop()</code>.</p>
<p>This might seem a bit tedious, and it is. 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. It's <em>possible</em> to return multiple values, using a tuple, like this:</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let (s2, len) = calculate_length(s1);
println!(&quot;The length of '{}' is {}.&quot;, s2, len);
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
</code></pre>
<p>But this is too much ceremony and a lot of work for a concept that should be
common. Luckily for us, Rust has a feature for this concept, and it’s what the
next section is about.</p>
<h2>References and Borrowing</h2>
<p>At the end of the last section, we had some example Rust that wasn’t very
good. Here it is again:</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>The issue here is that we have to return the <code>String</code> back to the calling
function so that we can still use it there, since it was moved when we called
<code>calculate_length()</code>.</p>
<p>There is a better way. It looks like this:</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 called <em>references</em>, and they allow you to refer to some value
without taking ownership of it. Here’s a diagram:</p>
<p>DIAGRAM GOES HERE of a &amp;String pointing at a String, with (ptr, len, capacity)</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 with <code>s1</code>. This reference <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, except that because we don’t have ownership,
we don’t drop what a reference points to when the reference goes out of scope.
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>There’s another word for what references do, and that’s <em>borrowing</em>. Just like
with real life, if a person owns something, you can borrow it from them. When
you’re done, you have to give it back.</p>
<p>Speaking of which, what if you try to modify something you borrow from me? Try
this code out. Spoiler alert: it doesn’t work!</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 like 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 bug! Just a small tweak:</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. This code fails:</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>The error is what it says: you cannot borrow something mutably more than once
at a time. 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.</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.</p>
<h3>Dangling references</h3>
<p>In languages with pointers, it’s easy to create a “dangling pointer” 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 something, the compiler will ensure that it will not go
out of scope before the reference does.</p>
<p>Let’s try to create a dangling reference:</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>. The message does contain the key to why this code is a problem,
though:</p>
<pre><code class="language-bash">this function’s return type contains a borrowed value, but there is no value
for it to be borrowed from
</code></pre>
<p>Let’s examine exactly what happens with <code>dangle()</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>So far, we’ve talked about types that have ownership, like <code>String</code>, and ones
that don’t, like <code>&amp;String</code>. There is another kind of 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 you find. If we don’t find a space in the string,
then the whole string is a 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>
<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
a tuple instead. 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 i for the index and &amp;item 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 one, we return the position. Otherwise, we return the length
of the string, using <code>s.len()</code>.</p>
<p>This works, 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:</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 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. Even more chances for
things to go wrong. 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>
<h2>String slices</h2>
<p>A string slice 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 looks just like taking a reference to the whole <code>String</code>, but with the
extra <code>[0..5]</code> bit. Instead of being 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 can 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>In other words, it looks like this:</p>
<p>DIAGRAM GOES HERE of s, hello, and world</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:</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>Now we have a single value, the <code>&amp;str</code>, pronounced &quot;string slice&quot;. It stores
both elements that we care about: a reference to the starting point of the
slice and the number of elements in the slice.</p>
<p>This would also work for a <code>second_word()</code>:</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.</p>
<p>But what about our error condition from before? Slices also fix that. Using
the slice version of <code>first_word()</code> will throw an error:</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 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 the borrowing rules? 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>
<h3>String literals are slices</h3>
<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>
<h3>String slices as arguments</h3>
<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:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Why is this? Well, we aren’t trying to modify <code>s</code> at all. And we can take
a string slice that’s the full length of a <code>String</code>, so we haven’t lost
the ability to talk about full <code>String</code>s. And additionally, we can take
string slices of string literals too, so this function is more useful, but
with no loss of functionality:</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>
<h2>Other slices</h2>
<p>String slices, as you might imagine, are specific to strings. But there’s a more
general slice type, too. Consider arrays:</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:</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>
<h1>Structs</h1>
<p>A <code>struct</code>, short for &quot;structure&quot;, gives us the ability to 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. <code>struct</code> and <code>enum</code> (that we will talk about in the next chapter)
are the building blocks you can use in Rust to create new types in your
program's domain in order to take full advantage of Rust's compile-time type
checking.</p>
<p>Let’s write a program which calculates the distance between two points.
We’ll start off with single variable bindings, and then refactor it to
use <code>struct</code>s instead.</p>
<p>Let’s make a new project with Cargo:</p>
<pre><code class="language-bash">$ cargo new --bin points
$ cd points
</code></pre>
<p>Here’s a short program which calculates the distance between two points. Put
it into your <code>src/main.rs</code>:</p>
<pre><code class="language-rust">fn main() {
let x1 = 0.0;
let y1 = 5.0;
let x2 = 12.0;
let y2 = 0.0;
let answer = distance(x1, y1, x2, y2);
println!(&quot;Point 1: ({}, {})&quot;, x1, y1);
println!(&quot;Point 2: ({}, {})&quot;, x2, y2);
println!(&quot;Distance: {}&quot;, answer);
}
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -&gt; f64 {
let x_squared = f64::powi(x2 - x1, 2);
let y_squared = f64::powi(y2 - y1, 2);
f64::sqrt(x_squared + y_squared)
}
</code></pre>
<p>Let's try running this program with <code>cargo run</code>:</p>
<pre><code class="language-bash">$ cargo run
Compiling points v0.1.0 (file:///projects/points)
Running `target/debug/points`
Point 1: (0, 5)
Point 2: (12, 0)
Distance: 13
</code></pre>
<p>Let's take a quick look at <code>distance()</code> before we move forward. To find the
distance between two points, we can use the Pythagorean Theorem. The theorem is
named after Pythagoras, who was the first person to mathematically prove this
formula. The details aren't that important; just know the theorem says that the
formula for the distance between two points is equal to:</p>
<ul>
<li>squaring the distance between the points horizontally (the &quot;x&quot; direction)</li>
<li>squaring the distance between the points vertically (the &quot;y&quot; direction)</li>
<li>adding those together</li>
<li>and taking the square root of that.</li>
</ul>
<p>So that's what we're implementing here.</p>
<pre><code class="language-rust,ignore">f64::powi(2.0, 3)
</code></pre>
<p>The double colon (<code>::</code>) here is a namespace operator. We haven’t talked about
modules and namespaces in depth yet, but you can think of the <code>powi()</code> function
as being scoped inside of another name. In this case, the name is <code>f64</code>, the
same as the type. The <code>powi()</code> function takes two arguments: the first is a
number, and the second is the power that it raises that number to. In this
case, the second number is an integer, hence the <code>i</code> in its name. Similarly,
<code>sqrt()</code> is a function under the <code>f64</code> module, which takes the square root of
its argument.</p>
<h2>Why <code>struct</code>s?</h2>
<p>Our little program is okay, but we can do better. The key to seeing this is in
the signature of <code>distance()</code>:</p>
<pre><code class="language-rust,ignore">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -&gt; f64 {
</code></pre>
<p>The distance function is supposed to calculate the distance between two points.
But our distance function calculates some distance between four numbers. The
first two and last two arguments are related, but that’s not expressed anywhere
in our program itself. It would be nicer if we had a way to group <code>(x1, y1)</code>
and <code>(x2, y2)</code> together.</p>
<p>We’ve already discussed one way to do that: tuples. Here’s a version of our
program which uses tuples:</p>
<pre><code class="language-rust">fn main() {
let p1 = (0.0, 5.0);
let p2 = (12.0, 0.0);
let answer = distance(p1, p2);
println!(&quot;Point 1: {:?}&quot;, p1);
println!(&quot;Point 2: {:?}&quot;, p2);
println!(&quot;Distance: {}&quot;, answer);
}
fn distance(p1: (f64, f64), p2: (f64, f64)) -&gt; f64 {
let x_squared = f64::powi(p2.0 - p1.0, 2);
let y_squared = f64::powi(p2.1 - p1.1, 2);
f64::sqrt(x_squared + y_squared)
}
</code></pre>
<p>This is a little better, for sure. Tuples let us add a little bit of structure.
We’re now passing two arguments, so that’s more clear. But it’s also worse:
tuples don’t give names to their elements, so our calculation has gotten more
confusing:</p>
<pre><code class="language-rust,ignore">p2.0 - p1.0
p2.1 - p1.1
</code></pre>
<p>When writing this example, your authors almost got it wrong themselves! Distance
is all about <code>x</code> and <code>y</code> points, but our code is talking about <code>0</code> and <code>1</code>.
This isn’t great.</p>
<p>Enter <code>struct</code>s. We can transform our tuples into something with a name for the
whole as well as names for the parts:</p>
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
struct Point {
x: f64,
y: f64,
}
let p1 = Point { x: 0.0, y: 5.0 };
</code></pre>
<p>Here we've defined a <code>struct</code> and given it the name <code>Point</code>. The parts inside
<code>{}</code> are defining the <em>fields</em> of the struct. We can have as many or as few of
them as we'd like, and we give them a name and specify their type. Here we have
two fields named <code>x</code> and <code>y</code>, and they both hold <code>f64</code>s.</p>
<p>We can access the field of a struct in the same way we access an element of
a tuple, except we use its name:</p>
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
let x = p1.0;
struct Point {
x: f64,
y: f64,
}
let p1 = Point { x: 0.0, y: 5.0 };
let x = p1.x;
</code></pre>
<p>Let’s convert our program to use our <code>Point</code> <code>struct</code>. Here’s what it looks
like now:</p>
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
struct Point {
x: f64,
y: f64,
}
fn main() {
let p1 = Point { x: 0.0, y: 5.0};
let p2 = Point { x: 12.0, y: 0.0};
let answer = distance(p1, p2);
println!(&quot;Point 1: {:?}&quot;, p1);
println!(&quot;Point 2: {:?}&quot;, p2);
println!(&quot;Distance: {}&quot;, answer);
}
fn distance(p1: Point, p2: Point) -&gt; f64 {
let x_squared = f64::powi(p2.x - p1.x, 2);
let y_squared = f64::powi(p2.y - p1.y, 2);
f64::sqrt(x_squared + y_squared)
}
</code></pre>
<p>Our function signature for <code>distance()</code> now says exactly what we mean: it
calculates the distance between two <code>Point</code>s. And rather than <code>0</code> and <code>1</code>,
we’ve got back our <code>x</code> and <code>y</code>. This is a win for clarity.</p>
<h2>Derived Traits</h2>
<p>There’s one other thing that’s a bit strange here, this stuff above the
<code>struct</code> declaration:</p>
<pre><code class="language-rust,ignore">#[derive(Debug,Copy,Clone)]
struct Point {
</code></pre>
<p>This is an annotation that tells the compiler our struct should get some
default behavior for the <code>Debug</code>, <code>Copy</code>, and <code>Clone</code> traits. We talked about
marking that types can be <code>Copy</code> and <code>Clone</code>-able in Chapter XX when we
discussed ownership. <code>Debug</code> is the trait that enables us to print out our
struct so that we can see its value while we are debugging our code.</p>
<p>So far, we’ve been printing values using <code>{}</code> in a <code>println!</code> macro. If we try
that with a struct, however, by default, we'll get an error. Say we have the
following program:</p>
<pre><code class="language-rust,ignore">struct Point {
x: f64,
y: f64,
}
fn main() {
let p1 = Point { x: 0.0, y: 5.0};
println!(&quot;Point 1: {}&quot;, p1);
}
</code></pre>
<p>This code tries to print the <code>p1</code> point directly, which may seem innocuous. But
running it produces the following output:</p>
<pre><code class="language-bash">$ cargo run
Compiling points v0.1.0 (file:///projects/points)
error: the trait bound `Point: std::fmt::Display` is not satisfied [--explain E0277]
--&gt; src/main.rs:8:29
8 |&gt; println!(&quot;Point 1: {}&quot;, p1);
|&gt; ^^
&lt;std macros&gt;:2:27: 2:58: note: in this expansion of format_args!
&lt;std macros&gt;:3:1: 3:54: note: in this expansion of print! (defined in &lt;std macros&gt;)
src/main.rs:8:5: 8:33: note: in this expansion of println! (defined in &lt;std macros&gt;)
note: `Point` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
note: required by `std::fmt::Display::fmt`
</code></pre>
<p>Whew! The core of the error is this part: <em>the trait bound <code>Point: std::fmt::Display</code> is not satisfied</em>. <code>println!</code> can do many kinds of
formatting. By default, <code>{}</code> implements a kind of formatting known as
<code>Display</code>: output intended for direct end-user consumption. The primitive types
we’ve seen implement <code>Display</code>, as there’s only one way you’d show a <code>1</code> to a
user. But with structs, the output is less clear. Do you want commas or not?
What about the <code>{}</code>s? Should all the fields be shown?</p>
<p>More complex types in the standard library and that are defined by the
programmer do not automatically implement <code>Display</code> formatting. Standard
library types implement <code>Debug</code> formatting, which is intended for the
programmer to see. The <code>#[derive(Debug)]</code> annotation lets us use a default
implementation of <code>Debug</code> formatting to easily get this ability for types we've
defined. To ask <code>println!</code> to use <code>Debug</code> formatting with our <code>Point</code>, we add
the annotation to derive the trait and include <code>:?</code> in the print string, like
this:</p>
<pre><code class="language-rust">#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
fn main() {
let p1 = Point { x: 0.0, y: 5.0};
println!(&quot;Point 1: {:?}&quot;, p1);
}
</code></pre>
<p>If you run this, it should print the values of each field in the <code>Point</code> struct
as desired:</p>
<pre><code class="language-bash">$ cargo run
Compiling points v0.1.0 (file:///projects/points)
Running `target/debug/points`
Point 1: Point { x: 0, y: 5 }
</code></pre>
<p>You’ll see this repeated later with other types. We’ll cover traits fully in
Chapter XX.</p>
<h2>Method Syntax</h2>
<p>In Chapter 4 when we discussed ownership, we made several references to
<em>methods</em>. Methods look like this:</p>
<pre><code class="language-rust">let s1 = &quot;hello&quot;;
// call a method on s1
let s2 = s1.clone();
println!(&quot;{}&quot;, s1);
</code></pre>
<p>The call to <code>clone()</code> is attached to <code>s1</code> with a dot. This is called <em>method
syntax</em>, and it’s a way to call certain functions with a different style.</p>
<p>Why have two ways to call functions? We’ll talk about some deeper reasons
related to ownership in a moment, but one big reason is that methods look nicer
when chained together:</p>
<pre><code class="language-rust,ignore">// with functions
h(g(f(x)));
// with methods
x.f().g().h();
</code></pre>
<p>The nested-functions version reads in reverse: the program executes <code>f()</code>, then
<code>g()</code>, then <code>h()</code>, but we read it left-to-right as <code>h()</code>, then <code>g()</code>, then
<code>f()</code>. The method syntax is executed in the same order as we would read it.</p>
<p>Before we get into the details, let’s talk about how to define your own
methods.</p>
<h3>Defining methods</h3>
<p>We can define methods with the <code>impl</code> keyword. <code>impl</code> is short for
<em>implementation</em>. Doing so looks like this:</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 };
assert_eq!(8.200609733428363, p1.distance(&amp;p2));
</code></pre>
<p>Let’s break this down. First, we have our <code>Point</code> struct from earlier in the
chapter. Next comes our first use of the <code>impl</code> keyword:</p>
<pre><code class="language-rust,ignore">impl Point {
// ...
}
</code></pre>
<p>Everything we put inside of the curly braces will be methods implemented on
<code>Point</code>. Next is our definition:</p>
<pre><code class="language-rust,ignore">fn distance(&amp;self, other: &amp;Point) -&gt; f64 {
// ...
}
</code></pre>
<p>Other than this, the rest of the example is familiar: an implementation of
<code>distance()</code> and using the method to find an answer.</p>
<p>Our definition of <code>distance()</code> here as a method looks very similar to our
previous definition of <code>distance()</code> as a function, but with two differences.
Here's the <code>distance()</code> function again:</p>
<pre><code class="language-rust,ignore">fn distance(p1: Point, p2: Point) -&gt; f64 {
// ...
}
</code></pre>
<p>The first difference is in the first argument. Instead of a name and a type, we
have written <code>&amp;self</code>. This is what distinguishes a method from a function:
using <code>self</code> inside of an <code>impl</code> block means we have a method. Because we
already know that we are implementing this method on <code>Point</code> because of the
surrounding <code>impl Point</code> block, we don’t need to write the type of <code>self</code> out.</p>
<p>Note that we have written <code>&amp;self</code>, not just <code>self</code>. This is because we want to
take a reference to our argument's value rather than taking ownership of it. In
other words, these two forms are the same:</p>
<pre><code class="language-rust,ignore">fn foo(self: &amp;Point)
fn foo(&amp;self)
</code></pre>
<p>Just like any other parameter, you can take <code>self</code> in three forms. Here’s the
list, with the most common form first:</p>
<pre><code class="language-rust,ignore">fn foo(&amp;self) // take self by reference
fn foo(&amp;mut self) // take self by mutable reference
fn foo(self) // take self by ownership
</code></pre>
<p>In this case, we only need a reference. We don’t need to mutate either <code>Point</code>
to get the distance between them, so we won't take a mutable reference to the
<code>Point</code> that we call the method on. Methods that take ownership of <code>self</code> are
rarely used. An example of a time to do that would be if we wanted to have a
method that would transform <code>self</code> into something else and prevent other code
from using the value of <code>self</code> after the transformation happens.</p>
<h4>Methods and automatic referencing</h4>
<p>We’ve left out an important detail. It’s in this line of the example:</p>
<pre><code class="language-rust,ignore">assert_eq!(8.200609733428363, p1.distance(&amp;p2));
</code></pre>
<p>When we defined <code>distance()</code>, we took both <code>self</code> and the other argument by
reference. Yet, we needed a <code>&amp;</code> for <code>p2</code> but not <code>p1</code>. What gives?</p>
<p>This feature is called <em>automatic referencing</em>, and calling methods is one
of the few places in Rust that has behavior like this. Here’s how it works:
when you call a method with <code>self.(</code>, Rust will automatically add in <code>&amp;</code>s
or <code>&amp;mut</code>s to match the signature. 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. Here’s another example:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;Hello,&quot;);
s.push_str(&quot; world!&quot;);
// The above is the same as:
// (&amp;mut s).push_str(&quot; world!&quot;);
assert_eq!(&quot;Hello, world!&quot;, s);
</code></pre>
<p>Because <a href="http://doc.rust-lang.org/collections/string/struct.String.html#method.push_str"><code>push_str()</code></a> has the following signature:</p>
<pre><code class="language-rust,ignore">fn push_str(&amp;mut self, string: &amp;str) {
</code></pre>
<p>This automatic referencing behavior works because methods have a clear receiver
— the type of <code>self</code> — and in most cases it’s clear given the receiver and name
of a method 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>
<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="http://doc.rust-lang.org/std/net/enum.IpAddr.html">in the standard library</a>, 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>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>, 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>, 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">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>.</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>Generics</h1>
<p>We've been working with a <code>Point</code> struct that looks like this:</p>
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
struct Point {
x: f64,
y: f64,
}
</code></pre>
<p>But what if we didn't want to always use an <code>f64</code> here? What about an <code>f32</code> for
when we need less precision? Or an <code>i32</code> if we only want integer coordinates?</p>
<p>While our simple <code>Point</code> struct may be a bit too simple to bother making
generic in a real application, we're going to stick with it to show you the
syntax. Especially when building library code, generics allow for more code
re-use, and unlock a lot of powerful techniques.</p>
<h2>Generic data types</h2>
<p>'Generics' let us write code that allows for several different types, while
letting us have one definition. A more generic <code>Point</code> would look like this:</p>
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
struct Point&lt;T&gt; {
x: T,
y: T,
}
</code></pre>
<p>There are two changes here, and they both involve this new <code>T</code>. The first change
is in the definition:</p>
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
struct Point&lt;T&gt; {
# x: T,
# y: T,
# }
</code></pre>
<p>Our previous definition said, &quot;We are defining a struct named Point.&quot; This
definition says something slightly different: &quot;We are defining a struct named
Point with one type parameter <code>T</code>.&quot;</p>
<p>Let's talk about this term <em>type parameter</em>. We've already seen one other thing
called a &quot;parameter&quot; in Rust: function parameters:</p>
<pre><code class="language-rust">fn plus_one(x: i32) -&gt; i32 {
x + 1
}
</code></pre>
<p>Here, <code>x</code> is a parameter to this function. We can call this function with a
different value, and <code>x</code> will change each time it's called:</p>
<pre><code class="language-rust"># fn plus_one(x: i32) -&gt; i32 {
# x + 1
# }
let six = plus_one(5);
let eleven = plus_one(10);
</code></pre>
<p>In the same way, a type parameter allows us to define a data type which can be
different each time we use it:</p>
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
struct Point&lt;T&gt; {
x: T,
y: T,
}
let integral_point = Point { x: 5, y: 5 };
let floating_point = Point { x: 5.0, y: 5.0 };
</code></pre>
<p>Here, <code>integral_point</code> uses <code>i32</code> values for <code>T</code>, and <code>floating_point</code> uses
<code>f64</code> values. This also leads us to talk about the second change we made to <code>Point</code>:</p>
<pre><code class="language-rust"># #[derive(Debug,Copy,Clone)]
# struct Point&lt;T&gt; {
x: T,
y: T,
# }
</code></pre>
<p>Instead of saying <code>x: i32</code>, we say <code>x: T</code>. This <code>T</code> is the same one that we
used above in the struct declaration. Because <code>x</code> and <code>y</code> both use <code>T</code>, they'll
be the same type. We could give them different types:</p>
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
struct Point&lt;T, OtherT&gt; {
x: T,
y: OtherT,
}
let different = Point { x: 5, y: 5.0 };
let same = Point { x: 5.0, y: 5.0 };
</code></pre>
<p>Here, instead of a single parameter, <code>T</code>, we have two: <code>T</code> and <code>OtherT</code>. Type
parameters have the same naming convention as other types: <code>CamelCase</code>.
However, you'll often see short, one-letter names used for types. <code>T</code> is very
common, because it's short for &quot;type&quot;, but you can name them something longer
if you'd like. In this version of <code>Point</code>, we say that <code>x</code> has the type <code>T</code>,
and <code>y</code> has the type <code>OtherT</code>. This lets us give them two different types, but
they don't have to be.</p>
<h2>Generic functions</h2>
<p>Regular old functions can also take generic parameters, with a syntax that looks
very similar:</p>
<pre><code class="language-rust">fn foo&lt;T&gt;(x: T) {
// ...
}
</code></pre>
<p>This <code>foo()</code> function has one generic parameter, <code>T</code>, and takes one argument,
<code>x</code>, which has the type <code>T</code>. Let's talk a little bit more about what this means.</p>
<h2>Generic methods</h2>
<p>We've seen how to define methods with the <code>impl</code> keyword. Our generic <code>Point</code>
can have generic methods, too:</p>
<pre><code class="language-rust">#[derive(Debug,Copy,Clone)]
struct Point&lt;T&gt; {
x: T,
y: T,
}
impl&lt;T&gt; Point&lt;T&gt; {
fn some_method(&amp;self) {
// ...
}
}
</code></pre>
<p>We also need the <code>&lt;T&gt;</code> after <code>impl</code>. This line reads, &quot;We will be implementing
methods with one generic type parameter, <code>T</code>, for a type, <code>Point</code>, which takes
one generic type <code>T</code>.&quot; In a sense, the <code>impl&lt;T&gt;</code> says &quot;we will be using a type
<code>T</code>&quot; and the <code>Point&lt;T&gt;</code> says &quot;that <code>T</code> is used for <code>Point</code>.&quot; In this simple
case, this syntax can feel a bit redundant, but when we get into some of Rust's
more advanced features later, this distinction will become more useful.</p>
<h2>There's more to the story</h2>
<p>This section covered the basic syntax of generics, but it's not the full story.
For example, let's try to implement our <code>foo()</code> function: we'll have it print out
the value of <code>x</code>:</p>
<pre><code class="language-rust,ignore">fn foo&lt;T&gt;(x: T) {
println!(&quot;x is: {}&quot;, x);
}
</code></pre>
<p>We'll get an error:</p>
<pre><code class="language-bash">error: the trait `core::fmt::Display` is not implemented for the type `T` [E0277]
println!(&quot;x is: {}&quot;, x);
^
</code></pre>
<p>We can't print out <code>x</code>! The error messages reference something we talked about
briefly before, the <code>Display</code> trait. In order to implement this function, we
need to talk about traits. But we only need to talk about traits to implement
our own generic functions; we don't need this understanding to use them. So
rather than get into more details about this right now, let's talk about other
useful Rust data types, and we can come back to implementing generic functions
in the chapter about traits.</p>
<p>For now, the important bits to understand:</p>
<ul>
<li>Generic type parameters are kind of like function parameters, but for types
instead of values.</li>
<li>Type parameters go inside <code>&lt;&gt;</code>s and are usually named things like <code>T</code>.</li>
</ul>
<p>With that, let's talk about another fundamental Rust data type: enums.</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>
<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">fn main() {
let x: i32 = 5;
}
</code></pre>
<p>We can add a colon, followed by the type name. Here’s the structure of a <code>let</code>
statement with a type annotation:</p>
<pre><code class="language-text">let PATTERN: TYPE = VALUE;
</code></pre>
<p>Note that the colon and the <code>TYPE</code> go <em>after</em> the <code>PATTERN</code>, not in the pattern
itself. As an example, here’s our more complex pattern with two bindings:</p>
<pre><code class="language-rust">fn main() {
let (x, y): (i32, i32) = (5, 6);
}
</code></pre>
<p>Just like we match up the <code>VALUE</code> with the <code>PATTERN</code>, we match up the <code>TYPE</code>
with the <code>PATTERN</code>.</p>
<h2>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
</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">fn main() {
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>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>
<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>
</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>