mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 21:51:17 -06:00
5398 lines
264 KiB
HTML
5398 lines
264 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>The Rust Programming Language</title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body class="light">
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts-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 & 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><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing names with <code>use</code></a></li></ul></li><li><strong>8.</strong> Basic Collections</li><li><ul class="section"><li><strong>8.1.</strong> Vectors</li><li><strong>8.2.</strong> Strings</li><li><strong>8.3.</strong> <code>HashMap<K, V></code></li></ul></li><li><strong>9.</strong> Error Handling</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> & <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> Debugging</li><li><strong>19.</strong> Smart Pointers</li><li><ul class="section"><li><strong>19.1.</strong> <code>Deref</code></li><li><strong>19.2.</strong> <code>Deref</code> coercions</li><li><strong>19.3.</strong> <code>Box<T></code></li><li><strong>19.4.</strong> <code>Rc<T></code></li></ul></li><li><strong>20.</strong> Concurrency</li><li><ul class="section"><li><strong>20.1.</strong> Threads</li><li><strong>20.2.</strong> <code>Send</code> & <code>Sync</code></li><li><strong>20.3.</strong> <code>Arc<T></code></li><li><strong>20.4.</strong> <code>Mutex<T></code></li><li><strong>20.5.</strong> <code>Channels</code></li></ul></li><li><strong>21.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>21.1.</strong> Raw Pointers</li><li><strong>21.2.</strong> transmute</li></ul></li><li><strong>22.</strong> FFI</li><li><ul class="section"><li><strong>22.1.</strong> Conditional Compilation</li><li><strong>22.2.</strong> Bindings to C</li><li><strong>22.3.</strong> Using Rust from Other Languages</li><li><strong>22.4.</strong> <code>static</code></li></ul></li><li><strong>23.</strong> Creating a Library</li><li><ul class="section"><li><strong>23.1.</strong> Cargo</li><li><strong>23.2.</strong> Crates.io</li><li><a href="chYY-YY-public-api.html"><strong>23.3.</strong> Organizing your Public API</a></li><li><a href="chYY-YY-documentation.html"><strong>23.4.</strong> Documentation</a></li><li><a href="chYY-YY-workspaces.html"><strong>23.5.</strong> Workspaces and Multiple Related Crates</a></li></ul></li><li><strong>24.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>24.1.</strong> Associated Types</li><li><strong>24.2.</strong> Trait Objects</li><li><strong>24.3.</strong> UFCS</li><li><strong>24.4.</strong> Coherence</li></ul></li><li><strong>25.</strong> Interior mutability</li><li><ul class="section"><li><strong>25.1.</strong> <code>Cell<T></code></li><li><strong>25.2.</strong> <code>RefCell<T></code></li></ul></li><li><strong>26.</strong> Macros</li><li><strong>27.</strong> Nightly Rust</li><li><a href="appendix-00.html"><strong>28.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>28.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> character; they are there to indicate
|
||
the start of each command. You’ll see many tutorials and examples around the web
|
||
that follow this convention: <code>$</code> for commands run as a regular user, and <code>#</code>
|
||
for commands you should be running as an administrator. Lines that don't start
|
||
with <code>$</code> are typically showing the output of the previous command.</p>
|
||
<h3>Installing on Linux or Mac</h3>
|
||
<p>If you're on Linux or a Mac, all you need to do is open a terminal and type
|
||
this:</p>
|
||
<pre><code class="language-bash">$ curl https://sh.rustup.rs -sSf | sh
|
||
</code></pre>
|
||
<p>This will download a script and start the installation. You may be prompted for
|
||
your password. If it all goes well, you’ll see this appear:</p>
|
||
<pre><code class="language-bash">Rust is installed now. Great!
|
||
</code></pre>
|
||
<h3>Installing on Windows</h3>
|
||
<p>On Windows, go to <a href="https://rustup.rs/">https://rustup.rs</a><!-- ignore --> and
|
||
follow the instructions to download rustup-init.exe. Run that and follow the
|
||
rest of the instructions it gives you.</p>
|
||
<p>The rest of the Windows-specific commands in the book will assume that you are
|
||
using <code>cmd</code> as your shell. If you use a different shell, you may be able to run
|
||
the same commands that Linux and Mac users do. If neither work, consult the
|
||
documentation for the shell you are using.</p>
|
||
<h3>Custom installations</h3>
|
||
<p>If you have reasons for preferring not to use rustup.rs, please see <a href="https://www.rust-lang.org/install.html">the Rust
|
||
installation page</a> for other options.</p>
|
||
<h3>Uninstalling</h3>
|
||
<p>Uninstalling Rust is as easy as installing it. From your shell, run
|
||
the uninstall script:</p>
|
||
<pre><code class="language-bash">$ rustup self uninstall
|
||
</code></pre>
|
||
<h3>Troubleshooting</h3>
|
||
<p>If you've got Rust installed, you can open up a shell, and type this:</p>
|
||
<pre><code class="language-bash">$ rustc --version
|
||
</code></pre>
|
||
<p>You should see the version number, commit hash, and commit date in a format
|
||
similar to this for the latest stable version at the time you install:</p>
|
||
<pre><code class="language-bash">rustc x.y.z (abcabcabc yyyy-mm-dd)
|
||
</code></pre>
|
||
<p>If you see this, Rust has been installed successfully!
|
||
Congrats!</p>
|
||
<p>If you don't and you're on Windows, check that Rust is in your <code>%PATH%</code> system
|
||
variable.</p>
|
||
<p>If it still isn't working, there are a number of places where you can get help.
|
||
The easiest is <a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a><!-- ignore -->,
|
||
which you can access through <a href="http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust">Mibbit</a>. Go to that address, and you'll
|
||
be chatting with other Rustaceans (a silly nickname we call ourselves) who can
|
||
help you out. Other great resources include <a href="https://users.rust-lang.org/">the user’s forum</a> and
|
||
<a href="http://stackoverflow.com/questions/tagged/rust">Stack Overflow</a>.</p>
|
||
<h3>Local documentation</h3>
|
||
<p>The installer also includes a copy of the documentation locally, so you can
|
||
read it offline. Run <code>rustup doc</code> to open the local documentation in your
|
||
browser.</p>
|
||
<p>Any time there's a type or function provided by the standard library and you're
|
||
not sure what it does, use the API documentation to find out!</p>
|
||
<h2>Hello, World!</h2>
|
||
<p>Now that you have Rust installed, let’s write your first Rust program. It's
|
||
traditional when learning a new language to write a little program to print the
|
||
text “Hello, world!” to the screen, and in this section, we'll follow that
|
||
tradition.</p>
|
||
<blockquote>
|
||
<p>Note: This book assumes basic familiarity with the command line. Rust itself
|
||
makes no specific demands about your editing, tooling, or where your code
|
||
lives, so if you prefer an IDE to the command line, feel free to use your
|
||
favorite IDE.</p>
|
||
</blockquote>
|
||
<h3>Creating a Project File</h3>
|
||
<p>First, make a file to put your Rust code in. Rust doesn't care where your code
|
||
lives, but for this book, we'd suggest making a <em>projects</em> directory in your
|
||
home directory and keeping all your projects there. Open a terminal and enter
|
||
the following commands to make a directory for this particular project:</p>
|
||
<p>Linux and Mac:</p>
|
||
<pre><code class="language-bash">$ mkdir ~/projects
|
||
$ cd ~/projects
|
||
$ mkdir hello_world
|
||
$ cd hello_world
|
||
</code></pre>
|
||
<p>Windows:</p>
|
||
<pre><code class="language-cmd">> mkdir %USERPROFILE%\projects
|
||
> cd %USERPROFILE%\projects
|
||
> mkdir hello_world
|
||
> cd hello_world
|
||
</code></pre>
|
||
<h3>Writing and Running a Rust Program</h3>
|
||
<p>Next, make a new source file and call it <code>main.rs</code>. Rust files always end with
|
||
the <code>.rs</code> extension. If you’re using more than one word in your filename, use
|
||
an underscore to separate them. For example, you'd use <code>hello_world.rs</code> rather
|
||
than <code>helloworld.rs</code>.</p>
|
||
<p>Now open the <code>main.rs</code> file you just created, and type the following code:</p>
|
||
<p>Filename: main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Save the file, and go back to your terminal window. On Linux or OSX, enter the
|
||
following commands:</p>
|
||
<pre><code class="language-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 "Hello, world!" program in
|
||
detail. Here's the first piece of the puzzle:</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
|
||
}
|
||
</code></pre>
|
||
<p>These lines define a <em>function</em> in Rust. The <code>main</code> function is special: it's
|
||
the first thing that is run for every executable Rust program. The first line
|
||
says, “I’m declaring a function named <code>main</code> that takes no arguments and
|
||
returns nothing.” If there were arguments, they would go inside the parentheses,
|
||
<code>(</code> and <code>)</code>.</p>
|
||
<p>Also note that the function body is wrapped in curly braces, <code>{</code> and <code>}</code>. Rust
|
||
requires these around all function bodies. It's considered good style to put
|
||
the opening curly brace on the same line as the function declaration, with one
|
||
space in between.</p>
|
||
<p>Inside the <code>main</code> function:</p>
|
||
<pre><code class="language-rust"> println!("Hello, world!");
|
||
</code></pre>
|
||
<p>This line does all of the work in this little program: it prints text to the
|
||
screen. There are a number of details that are important here. The first is
|
||
that it’s indented with four spaces, not a tab.</p>
|
||
<p>The second important part is <code>println!</code>. This is calling a Rust <em>macro</em>,
|
||
which is how metaprogramming is done in Rust. If it were calling a function
|
||
instead, it would look like this: <code>println</code> (without the <code>!</code>). We'll discuss
|
||
Rust macros in more detail in Chapter XX, but for now you just need to know
|
||
that when you see a <code>!</code> that means that you’re calling a macro instead of a
|
||
normal function.</p>
|
||
<p>Next is <code>"Hello, world!"</code> which is a <em>string</em>. We pass this string as an
|
||
argument to <code>println!</code>, which prints the string to the screen. Easy enough!</p>
|
||
<p>The line ends with a semicolon (<code>;</code>). The <code>;</code> indicates that this expression is
|
||
over, and the next one is ready to begin. Most lines of Rust code end with a
|
||
<code>;</code>.</p>
|
||
<h3>Compiling and Running Are Separate Steps</h3>
|
||
<p>In "Writing and Running a Rust Program", we showed you how to run a newly
|
||
created program. We'll break that process down and examine each step now.</p>
|
||
<p>Before running a Rust program, you have to compile it. You can use the Rust
|
||
compiler by entering the <code>rustc</code> command and passing it the name of your source
|
||
file, like this:</p>
|
||
<pre><code class="language-bash">$ rustc main.rs
|
||
</code></pre>
|
||
<p>If you come from a C or C++ background, you'll notice that this is similar to
|
||
<code>gcc</code> or <code>clang</code>. After compiling successfully, Rust should output a binary
|
||
executable, which you can see on Linux or OSX by entering the <code>ls</code> command in
|
||
your shell as follows:</p>
|
||
<pre><code class="language-bash">$ ls
|
||
main main.rs
|
||
</code></pre>
|
||
<p>On Windows, you'd enter:</p>
|
||
<pre><code class="language-cmd">> dir /B %= the /B option says to only show the file names =%
|
||
main.exe
|
||
main.rs
|
||
</code></pre>
|
||
<p>This shows we have two files: the source code, with the <code>.rs</code> extension, and the
|
||
executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else). All that's left to
|
||
do from here is run the <code>main</code> or <code>main.exe</code> file, like this:</p>
|
||
<pre><code class="language-bash">$ ./main # or .\main.exe on Windows
|
||
</code></pre>
|
||
<p>If <code>main.rs</code> were your "Hello, world!" program, this would print <code>Hello, world!</code> to your terminal.</p>
|
||
<p>If you come from a dynamic language like Ruby, Python, or JavaScript, you may
|
||
not be used to compiling and running a program being separate steps. Rust is an
|
||
<em>ahead-of-time compiled</em> language, which means that you can compile a program,
|
||
give it to someone else, and they can run it even without having Rust
|
||
installed. If you give someone a <code>.rb</code>, <code>.py</code>, or <code>.js</code> file, on the other
|
||
hand, they need to have a Ruby, Python, or JavaScript implementation installed
|
||
(respectively), but you only need one command to both compile and run your
|
||
program. Everything is a tradeoff in language design.</p>
|
||
<p>Just compiling with <code>rustc</code> is fine for simple programs, but as your project
|
||
grows, you'll want to be able to manage all of the options your project has
|
||
and make it easy to share your code with other people and projects. Next, we'll
|
||
introduce you to a tool called Cargo, which will help you write real-world Rust
|
||
programs.</p>
|
||
<h2>Hello, Cargo!</h2>
|
||
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
|
||
manage their Rust projects because it makes a lot of tasks easier. For example,
|
||
Cargo takes care of building your code, downloading the libraries your code
|
||
depends on, and building those libraries. We call libraries your code needs
|
||
<em>dependencies</em>.</p>
|
||
<p>The simplest Rust programs, like the one we've written so far, don’t have any
|
||
dependencies, so right now, you'd only be using the part of Cargo that can take
|
||
care of building your code. As you write more complex Rust programs, you’ll
|
||
want to add dependencies, and if you start off using Cargo, that will be a lot
|
||
easier to do.</p>
|
||
<p>As the vast, vast majority of Rust projects use Cargo, we will assume that
|
||
you’re using it for the rest of the book. Cargo comes installed with Rust
|
||
itself, if you used the official installers as covered in the Installation
|
||
chapter. If you installed Rust through some other means, you can check if you
|
||
have Cargo installed by typing the following into your terminal:</p>
|
||
<pre><code class="language-bash">$ cargo --version
|
||
</code></pre>
|
||
<p>If you see a version number, great! If you see an error like <code>command not found</code>, then you should look at the documentation for your method of
|
||
installation to determine how to install Cargo separately.</p>
|
||
<h3>Creating a Project with Cargo</h3>
|
||
<p>Let's create a new project using Cargo and look at how it differs from our
|
||
project in <code>hello_world</code>. Go back to your projects directory (or wherever you
|
||
decided to put your code):</p>
|
||
<p>Linux and Mac:</p>
|
||
<pre><code class="language-bash">$ cd ~/projects
|
||
</code></pre>
|
||
<p>Windows:</p>
|
||
<pre><code class="language-cmd">> cd %USERPROFILE%\projects
|
||
</code></pre>
|
||
<p>And then on any operating system run:</p>
|
||
<pre><code class="language-bash">$ cargo new hello_cargo --bin
|
||
$ cd hello_cargo
|
||
</code></pre>
|
||
<p>We passed the <code>--bin</code> argument to <code>cargo new</code> because our goal is to make an
|
||
executable application, as opposed to a library. Executables are binary
|
||
executable files often called just <em>binaries</em>. We've given <code>hello_cargo</code>
|
||
as the name for our project, and Cargo creates its files in a directory
|
||
of the same name that we can then go into.</p>
|
||
<p>If we list the files in the <code>hello_cargo</code> directory, we can see that Cargo has
|
||
generated two files and one directory for us: a <code>Cargo.toml</code> and a <code>src</code>
|
||
directory with a <code>main.rs</code> file inside. It has also initialized a new <code>git</code>
|
||
repository in the <code>hello_cargo</code> directory for us, along with a <code>.gitignore</code>
|
||
file; you can change this to use a different version control system, or no
|
||
version control system, by using the <code>--vcs</code> flag.</p>
|
||
<p>Open up <code>Cargo.toml</code> in your text editor of choice. It should look something
|
||
like this:</p>
|
||
<p>Filename: Cargo.toml</p>
|
||
<pre><code class="language-toml">[package]
|
||
name = "hello_cargo"
|
||
version = "0.1.0"
|
||
authors = ["Your Name <you@example.com>"]
|
||
|
||
[dependencies]
|
||
</code></pre>
|
||
<p>This file is in the <a href="https://github.com/toml-lang/toml"><em>TOML</em></a><!-- ignore --> (Tom's Obvious, Minimal
|
||
Language) format. TOML is similar to INI but has some extra goodies and is used
|
||
as Cargo’s configuration format.</p>
|
||
<p>The first line, <code>[package]</code>, is a section heading that indicates that the
|
||
following statements are configuring a package. As we add more information to
|
||
this file, we’ll add other sections.</p>
|
||
<p>The next three lines set the three bits of configuration that Cargo needs to
|
||
see in order to know that it should compile your program: its name, what
|
||
version it is, and who wrote it. Cargo gets your name and email information
|
||
from your environment. If it’s not correct, go ahead and fix that and save the
|
||
file.</p>
|
||
<p>The last line, <code>[dependencies]</code>, is the start of a section for you to list any
|
||
<em>crates</em> (which is what we call packages of Rust code) that your project will
|
||
depend on so that Cargo knows to download and compile those too. We won't need
|
||
any other crates for this project, but we will in the guessing game tutorial in
|
||
the next chapter.</p>
|
||
<p>Now let's look at <code>src/main.rs</code>:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Cargo has generated a "Hello World!" for you, just like the one we wrote
|
||
earlier! So that part is the same. The differences between our previous project
|
||
and the project generated by Cargo that we've seen so far are:</p>
|
||
<ul>
|
||
<li>Our code goes in the <code>src</code> directory</li>
|
||
<li>The top level contains a <code>Cargo.toml</code> configuration file</li>
|
||
</ul>
|
||
<p>Cargo expects your source files to live inside the <code>src</code> directory so that the
|
||
top-level project directory is just for READMEs, license information,
|
||
configuration files, and anything else not related to your code. In this way,
|
||
using Cargo helps you keep your projects nice and tidy. There's a place for
|
||
everything, and everything is in its place.</p>
|
||
<p>If you started a project that doesn't use Cargo, as we did with our project in
|
||
the <code>hello_world</code> directory, you can convert it to a project that does use
|
||
Cargo by moving your code into the <code>src</code> directory and creating an appropriate
|
||
<code>Cargo.toml</code>.</p>
|
||
<h3>Building and Running a Cargo Project</h3>
|
||
<p>Now let's look at what's different about building and running your Hello World
|
||
program through Cargo! To do so, enter the following commands:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
|
||
</code></pre>
|
||
<p>This should have created an executable file in <code>target/debug/hello_cargo</code> (or
|
||
<code>target\debug\hello_cargo.exe</code> on Windows), which you can run with this command:</p>
|
||
<pre><code class="language-bash">$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
|
||
<p>Running <code>cargo build</code> for the first time also causes Cargo to create a new file
|
||
at the top level called <code>Cargo.lock</code>, which looks like this:</p>
|
||
<p>Filename: Cargo.lock</p>
|
||
<pre><code class="language-toml">[root]
|
||
name = "hello_cargo"
|
||
version = "0.1.0"
|
||
</code></pre>
|
||
<p>Cargo uses the <code>Cargo.lock</code> file to keep track of dependencies in your
|
||
application. This project doesn't have dependencies, so the file is a bit
|
||
sparse. Realistically, you won't ever need to touch this file yourself; just
|
||
let Cargo handle it.</p>
|
||
<p>We just built a project with <code>cargo build</code> and ran it with
|
||
<code>./target/debug/hello_cargo</code>, but we can also use <code>cargo run</code> to compile
|
||
and then run:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Running `target/debug/hello_cargo`
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>Notice that this time, we didn't see the output telling us that Cargo was
|
||
compiling <code>hello_cargo</code>. Cargo figured out that the files haven’t changed, so
|
||
it just ran the binary. If you had modified your source code, Cargo would have
|
||
rebuilt the project before running it, and you would have seen something like
|
||
this:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
|
||
Running `target/debug/hello_cargo`
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>So a few more differences we've now seen:</p>
|
||
<ul>
|
||
<li>Instead of using <code>rustc</code>, build a project using <code>cargo build</code> (or build and
|
||
run it in one step with <code>cargo run</code>)</li>
|
||
<li>Instead of the result of the build being put in the same directory as our
|
||
code, Cargo will put it in the <code>target/debug</code> directory.</li>
|
||
</ul>
|
||
<p>The other advantage of using Cargo is that the commands are the same no matter
|
||
what operating system you're on, so at this point we will no longer be
|
||
providing specific instructions for Linux and Mac versus Windows.</p>
|
||
<h3>Building for Release</h3>
|
||
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. This will create an
|
||
executable in <code>target/release</code> instead of <code>target/debug</code>. These optimizations
|
||
make your Rust code run faster, but turning them on makes your program take
|
||
longer to compile. This is why there are two different profiles: one for
|
||
development when you want to be able to rebuild quickly and often, and one for
|
||
building the final program you’ll give to a user that won't be rebuilt and
|
||
that we want to run as fast as possible. If you're benchmarking the running
|
||
time of your code, be sure to run <code>cargo build --release</code> and benchmark with
|
||
the executable in <code>target/release</code>.</p>
|
||
<h3>Cargo as Convention</h3>
|
||
<p>With simple projects, Cargo doesn't provide a whole lot of value over just
|
||
using <code>rustc</code>, but it will prove its worth as you continue. With complex
|
||
projects composed of multiple crates, it’s much easier to let Cargo coordinate
|
||
the build. With Cargo, you can just run <code>cargo build</code>, and it should work the
|
||
right way. Even though this project is simple, it now uses much of the real
|
||
tooling you’ll use for the rest of your Rust career. In fact, you can get
|
||
started with virtually all Rust projects you want to work
|
||
on with the following commands:</p>
|
||
<pre><code class="language-bash">$ git clone someurl.com/someproject
|
||
$ cd someproject
|
||
$ cargo build
|
||
</code></pre>
|
||
<blockquote>
|
||
<p>Note: If you want to look at Cargo in more detail, check out the official
|
||
<a href="http://doc.crates.io/guide.html">Cargo guide</a>, which covers all of its features.</p>
|
||
</blockquote>
|
||
<h1>Guessing Game</h1>
|
||
<p>Let's jump into Rust with a hands-on project! This chapter will introduce you to
|
||
a few common Rust concepts by showing how you would use them in a real program.
|
||
You'll learn about <code>let</code>, <code>match</code>, methods, associated functions, using
|
||
external crates, and more! Following chapters will explore these ideas in more
|
||
detail; this chapter will get you practicing the fundamentals.</p>
|
||
<p>We’re going to implement a classic beginner programming problem: the guessing
|
||
game. Here’s how it works: Our program will generate a random integer between
|
||
one and a hundred. It will then prompt us to enter a guess. Upon entering our
|
||
guess, it will tell us if we’re too low or too high. Once we guess correctly,
|
||
it will congratulate us.</p>
|
||
<h2>Setting Up a New Project</h2>
|
||
<p>Let’s set up a new project. Go to your projects directory from the previous
|
||
chapter, and create a new project using Cargo, like so:</p>
|
||
<pre><code class="language-bash">$ cargo new guessing_game --bin
|
||
$ cd guessing_game
|
||
</code></pre>
|
||
<p>We pass the name of our project to <code>cargo new</code> and pass the <code>--bin</code> flag, since
|
||
we’re going to be making another binary like in Chapter 1.</p>
|
||
<p>Take a look at the generated <code>Cargo.toml</code>:</p>
|
||
<p>Filename: Cargo.toml</p>
|
||
<pre><code class="language-toml">[package]
|
||
name = "guessing_game"
|
||
version = "0.1.0"
|
||
authors = ["Your Name <you@example.com>"]
|
||
|
||
[dependencies]
|
||
</code></pre>
|
||
<p>If the author information that Cargo got from your environment is not correct,
|
||
go ahead and fix that in the file and save it again.</p>
|
||
<p>As we saw in the last chapter, cargo new generates a “Hello, world!” program
|
||
for us. Check out src/main.rs:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Let’s try compiling what Cargo gave us and running it in the same step, using
|
||
the <code>cargo run</code> command:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>Great! The <code>run</code> command comes in handy when you need to rapidly iterate on a
|
||
project. Our game is such a project: we want to quickly test each
|
||
iteration before moving on to the next one.</p>
|
||
<p>Now open up your <code>src/main.rs</code> again. We’ll be writing all of our code in this
|
||
file.</p>
|
||
<h2>Processing a Guess</h2>
|
||
<p>Let’s get to it! We'll split the development of this game up into parts. This
|
||
first part will ask for input from a user and process the input, checking that
|
||
the input is in the form we expect. First we need to allow our player to input
|
||
a guess. Enter this in your <code>src/main.rs</code>:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">use std::io;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
}
|
||
</code></pre>
|
||
<p>There’s a lot here! Let’s go over it, bit by bit.</p>
|
||
<pre><code class="language-rust,ignore">use std::io;
|
||
</code></pre>
|
||
<p>We’ll need to take user input and then print the result as output, and for that
|
||
functionality we need to import the <code>io</code> (input/output) library from the
|
||
standard library (which is known as <code>std</code>).</p>
|
||
<p>By default, Rust only imports a few things into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
|
||
<em>prelude</em></a><!-- ignore -->. If it’s not in the prelude, you’ll have to
|
||
import it into your program explicitly with a <code>use</code> statement. Using the
|
||
<code>std::io</code> library gets you a number of useful <code>io</code>-related things, including
|
||
the functionality to accept user input.</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
</code></pre>
|
||
<p>As you’ve seen in Chapter 1, the <code>main</code> function is the entry point into the
|
||
program. The <code>fn</code> syntax declares a new function, the <code>()</code>s indicate that
|
||
there are no arguments, and <code>{</code> starts the body of the function.</p>
|
||
<pre><code class="language-rust,ignore">println!("Guess the number!");
|
||
|
||
println!("Please input your guess.");
|
||
</code></pre>
|
||
<p>As we learned in Chapter 1, <code>println!</code> is a macro that prints a string to the
|
||
screen. This is just a prompt stating what the game is and requesting input from
|
||
the user.</p>
|
||
<h3>Storing Values with Variable Bindings</h3>
|
||
<p>Next we need to store the user input.</p>
|
||
<pre><code class="language-rust,ignore">let mut guess = String::new();
|
||
</code></pre>
|
||
<p>Now we’re getting interesting! There’s a lot going on in this little line.
|
||
The first thing to notice is that this is a <code>let</code> statement, which is
|
||
used to create <em>variable bindings</em>. Here's another example:</p>
|
||
<pre><code class="language-rust,ignore">let foo = bar;
|
||
</code></pre>
|
||
<p>This will create a new binding named <code>foo</code>, and bind it to the value <code>bar</code>. In
|
||
many languages, this is called a <em>variable</em>, but Rust’s variable bindings have
|
||
a few differences.</p>
|
||
<p>For example, they’re immutable by default. To make our binding mutable, our
|
||
example uses <code>mut</code> before the binding name.</p>
|
||
<pre><code class="language-rust">let foo = 5; // immutable.
|
||
let mut bar = 5; // mutable
|
||
</code></pre>
|
||
<blockquote>
|
||
<p>Note: The <code>//</code> syntax will start a comment that continues until the end of the
|
||
line. Rust ignores everything in comments.</p>
|
||
</blockquote>
|
||
<p>So now we know that <code>let mut guess</code> will introduce a mutable binding named
|
||
<code>guess</code>, but we have to look at the other side of the <code>=</code> for the value it’s
|
||
bound to: <code>String::new</code>. <code>String</code> is a string type, provided by the standard
|
||
library. A <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a growable, UTF-8 encoded bit
|
||
of text.</p>
|
||
<p>The <code>::</code> syntax in the <code>::new</code> line indicates that <code>new</code> is an <em>associated
|
||
function</em> of a particular type. An associated function is a function that is
|
||
associated with a type, in this case <code>String</code>, rather than a particular
|
||
instance of a <code>String</code>. Some languages call this a <em>static method</em>.</p>
|
||
<p>This <code>new</code> function creates a new, empty <code>String</code>.
|
||
You’ll find a <code>new</code> function on many types, as it’s a common name for making
|
||
a new value of some kind.</p>
|
||
<p>So to summarize, the <code>let mut guess = String::new();</code> line has created a
|
||
mutable binding that is currently bound to a new, empty instance of a <code>String</code>.
|
||
Whew!</p>
|
||
<p>Let’s move forward:</p>
|
||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
</code></pre>
|
||
<p>We included the input/output functionality from the standard library with use
|
||
std::io; on the first line of the program. We are now calling an associated
|
||
function, stdin(), on io. If we didn’t have the use std::io line at the
|
||
beginning of the program, we could have written this function call as
|
||
std::io::stdin(). The stdin() function returns an instance of std::io::Stdin,
|
||
which is a type that represents a handle to the standard input for your
|
||
terminal.</p>
|
||
<p>The next part, <code>.read_line(&mut guess)</code>, calls the
|
||
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle
|
||
to get input from the user. We’re also passing one argument to <code>read_line</code>:
|
||
<code>&mut guess</code>.</p>
|
||
<p>The job of <code>read_line</code> is to take whatever the user types into standard input
|
||
and place that into a string, so it takes that string as an argument. The
|
||
string argument needs to be mutable so that the method can change the string's
|
||
content by adding the user input.</p>
|
||
<p>The <code>&</code> indicates that this argument is a <em>reference</em>, which gives you a way to
|
||
let multiple parts of your code access one piece of data without needing to
|
||
copy that data into memory multiple times. References are a complex feature,
|
||
and one of Rust’s major advantages is how safe and easy it is to use
|
||
references. We don’t need to know a lot of those details to finish our program
|
||
right now, though; Chapter XX will cover references in more detail. For now,
|
||
all we need to know is that like <code>let</code> bindings, references are immutable by
|
||
default. Hence, we need to write <code>&mut guess</code>, rather than <code>&guess</code>, to make it
|
||
mutable.</p>
|
||
<p>We’re not quite done with this line of code. While it’s a single line of text,
|
||
it’s only the first part of the single logical line of code. The second part is
|
||
this method:</p>
|
||
<pre><code class="language-rust,ignore">.expect("Failed to read line");
|
||
</code></pre>
|
||
<p>When you call a method with the <code>.foo()</code> syntax, it's often wise to introduce a
|
||
newline and other whitespace. This helps you split up long lines. We could have
|
||
written this code as:</p>
|
||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess).expect("failed to read line");
|
||
</code></pre>
|
||
<p>But that gets hard to read. So we’ve split it up, two lines for two method
|
||
calls. Now let's see what this line does.</p>
|
||
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
|
||
<p>We mentioned that <code>read_line</code> puts what the user types into the string we
|
||
pass it, but it also returns a value: in this case, an
|
||
<a href="../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
|
||
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore -->,
|
||
and then specific versions for sub-libraries, like <code>io::Result</code>.</p>
|
||
<p>The <code>Result</code> types are <a href="ch06-00-enums.html">enums</a><!-- ignore -->, which is short for
|
||
<em>enumerations</em>. An enumeration is a type that can have a fixed set of values,
|
||
which are called the enum's <em>variants</em>. We will be covering enums in more
|
||
detail in Chapter XX.</p>
|
||
<p>For <code>Result</code>, the variants are <code>Ok</code> or <code>Err</code>. <code>Ok</code> indicates the operation was
|
||
successful, and inside the <code>Ok</code> variant is the successfully generated value.
|
||
<code>Err</code> means the operation failed, and the <code>Err</code> contains information about how
|
||
or why the operation failed.</p>
|
||
<p>The purpose of these <code>Result</code> types is to encode error handling information.
|
||
Values of the <code>Result</code> type, like any type, have methods defined on them.
|
||
<code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that we can call.
|
||
If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will cause our
|
||
program to crash and display the message that we passed as an argument to
|
||
<code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would likely be the
|
||
result of an error coming from the underlying operating system. If this
|
||
instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the return value
|
||
that <code>Ok</code> is holding and return just that value to us so that we could use it.
|
||
In this case, that value is the number of characters the user entered into
|
||
standard input.</p>
|
||
<p>If we don't call <code>expect</code>, our program will compile, but we’ll get a warning:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||
#[warn(unused_must_use)] on by default
|
||
src/main.rs:10 io::stdin().read_line(&mut guess);
|
||
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
</code></pre>
|
||
<p>Rust warns that we haven’t used the <code>Result</code> value, telling us that we
|
||
haven’t handled a possible error. The right way to suppress the warning is to
|
||
actually write error handling, but if we just want to crash the program when a
|
||
problem occurs, we can use <code>expect</code>. We’ll save recovering from errors for a
|
||
future project.</p>
|
||
<h3>Printing Values with <code>println!</code> Placeholders</h3>
|
||
<p>There’s only one line of this first example left, aside from the closing curly
|
||
brace:</p>
|
||
<pre><code class="language-rust,ignore"> println!("You guessed: {}", guess);
|
||
</code></pre>
|
||
<p>This prints out the string we saved our input in. The <code>{}</code>s are a placeholder:
|
||
think of <code>{}</code> as little crab pincers, holding a value in place. You can print
|
||
more than one value this way: the first <code>{}</code> holds the first value listed after
|
||
the format string, the second set holds the second value, and so on. Printing
|
||
out multiple values in one call to <code>println!</code> would then look like this:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
let y = 10;
|
||
|
||
println!("x = {} and y = {}", x, y);
|
||
</code></pre>
|
||
<p>Which would print out "x = 5 and y = 10".</p>
|
||
<h3>Testing the First Part</h3>
|
||
<p>Back to our guessing game, let's test what we have so far. We can run it with
|
||
<code>cargo run</code>:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
Please input your guess.
|
||
6
|
||
You guessed: 6
|
||
</code></pre>
|
||
<p>All right! Our first part is done: we can get input from the keyboard and then
|
||
print it back out.</p>
|
||
<h2>Generating a Secret Number</h2>
|
||
<p>Next, we need to generate a secret number that the user will try to guess. The
|
||
secret number should be different every time so that the game is fun to play
|
||
more than once, and we'd like to have a random number between 1 and 100 so the
|
||
game isn’t too difficult. Rust does not yet include random number functionality
|
||
in its standard library. The Rust team does, however, provide a <a href="https://crates.io/crates/rand"><code>rand</code>
|
||
crate</a>.</p>
|
||
<h3>Using a Crate to Get More Functionality</h3>
|
||
<p>Remember that <em>crate</em> is what we call a package of Rust code. The project we’ve
|
||
been building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is
|
||
a <em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||
<p>Cargo's use of external crates is where it really shines. Before we can write
|
||
the code using <code>rand</code>, we need to modify our <code>Cargo.toml</code> to include the <code>rand</code>
|
||
crate as a dependency. Open it up, and add this line at the bottom beneath the
|
||
<code>[dependencies]</code> section header that Cargo created for you:</p>
|
||
<p>Filename: Cargo.toml</p>
|
||
<pre><code class="language-toml">[dependencies]
|
||
|
||
rand = "0.3.14"
|
||
</code></pre>
|
||
<p>In the <code>Cargo.toml</code> file, everything that follows a header is part of a section
|
||
that goes until another section starts. Cargo uses the <code>[dependencies]</code> section
|
||
to know what external crates your project depends on and what versions of those
|
||
crates you require. In this case, we’ve specified the <code>rand</code> crate with the
|
||
semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
|
||
Versioning</a><!-- ignore --> (sometimes called <em>semver</em>), which is a
|
||
standard for writing version numbers. A bare number like above is actually
|
||
shorthand for <code>^0.3.14</code>, which means "any version that has a public API
|
||
compatible with version 0.3.14".</p>
|
||
<p>Now, without changing any of our code, let’s build our project:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||
Downloading rand v0.3.14
|
||
Downloading libc v0.2.14
|
||
Compiling libc v0.2.14
|
||
Compiling rand v0.3.14
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
</code></pre>
|
||
<p>You may see different version numbers (but they will all be compatible with
|
||
your code, thanks to semver!) and the lines may be in a different order.</p>
|
||
<p>Lots of new output! Now that we have an external dependency, Cargo fetches the
|
||
latest versions of everything from the <em>registry</em>, which is a copy of data from
|
||
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem
|
||
post their open source Rust projects for others to use.</p>
|
||
<p>After updating the registry, Cargo checks our <code>[dependencies]</code> and downloads
|
||
any we don’t have yet. In this case, while we only listed <code>rand</code> as a
|
||
dependency, we’ve also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
|
||
<code>libc</code> to work. After downloading them, Rust compiles them and then compiles
|
||
our project.</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>This just updates the build with your tiny change to the <code>main.rs</code> file.</p>
|
||
<h4>The Cargo.lock File that Ensures Reproducible Builds</h4>
|
||
<p>Cargo has a mechanism to make sure we can rebuild the exact same artifact every
|
||
time we or anyone else builds our code: Cargo will only use the versions of the
|
||
dependencies you specified until you say otherwise. For example, what happens
|
||
if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out, containing an
|
||
important bugfix, but that also contains a regression that will break our code?</p>
|
||
<p>The answer to this problem is the <code>Cargo.lock</code> file created the first time we
|
||
ran <code>cargo build</code> that is now in your project directory. When you build your
|
||
project for the first time, Cargo figures out all of the versions of your
|
||
dependencies that fit your criteria then writes them to the <code>Cargo.lock</code> file.
|
||
When you build your project in the future, Cargo will see that the <code>Cargo.lock</code>
|
||
file exists and use the versions specified there rather than doing all the work
|
||
of figuring out versions again. This lets you have a reproducible build
|
||
automatically. In other words, our project will stay at <code>0.3.14</code> until we
|
||
explicitly upgrade, thanks to the lock file.</p>
|
||
<h4>Updating a Crate to Get a New Version</h4>
|
||
<p>When we <em>do</em> want to update a crate, Cargo has another command,
|
||
<code>update</code>, which will:</p>
|
||
<ul>
|
||
<li>Ignore the <code>Cargo.lock</code> file and figure out all the latest versions that fit
|
||
our specifications in <code>Cargo.toml</code>.</li>
|
||
<li>If that works, write those versions out to the lock file.</li>
|
||
</ul>
|
||
<p>But by default, Cargo will only look for versions larger than <code>0.3.0</code> and
|
||
smaller than <code>0.4.0</code>. If the <code>rand</code> crate has released two new versions,
|
||
<code>0.3.15</code> and <code>0.4.0</code>, this is what we would see if we ran <code>cargo update</code>:</p>
|
||
<pre><code class="language-bash">$ cargo update
|
||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||
Updating rand v0.3.14 -> v0.3.15
|
||
</code></pre>
|
||
<p>At this point, you would also notice a change in your <code>Cargo.lock</code> file noting
|
||
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</p>
|
||
<p>If we wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
|
||
series, we’d have to update what is in the <code>Cargo.toml</code> file to look like this
|
||
instead:</p>
|
||
<pre><code class="language-toml">[dependencies]
|
||
|
||
rand = "0.4.0"
|
||
</code></pre>
|
||
<p>The next time we <code>cargo build</code>, assuming that the <code>rand</code> crate version <code>0.4.0</code>
|
||
has been released, Cargo will update the crates index and re-evaluate our
|
||
<code>rand</code> requirements according to the new version we have specified.</p>
|
||
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a><!-- ignore --> and <a href="http://doc.crates.io/crates-io.html">its
|
||
ecosystem</a><!-- ignore --> that we will get into in Chapter XX, but
|
||
for now, that’s all we need to know. Cargo makes it really easy to re-use
|
||
libraries, so Rustaceans are able to write smaller projects which are assembled
|
||
out of a number of sub-packages.</p>
|
||
<h3>Generating a Random Number</h3>
|
||
<p>Let’s get on to actually <em>using</em> <code>rand</code>. Our next step is to update our
|
||
<code>main.rs</code> code as follows:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
}
|
||
</code></pre>
|
||
<p>First we've added a line to the top, <code>extern crate rand</code>, that lets Rust know
|
||
we’ll be making use of that external dependency. This also does the equivalent
|
||
of calling <code>use rand</code>, so we can now call anything in the <code>rand</code> crate by
|
||
prefixing it with <code>rand::</code>.</p>
|
||
<p>Next, we added another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
|
||
defines methods that random number generators implement, and this trait must be
|
||
in scope for us to use those methods. We'll cover traits in detail in the
|
||
Traits section in Chapter XX.</p>
|
||
<p>We also added two more lines in the middle:</p>
|
||
<pre><code class="language-rust,ignore">let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
</code></pre>
|
||
<p>The <code>rand::thread_rng</code> function will give us the particular random number
|
||
generator that we're going to use: one that is local to our current thread of
|
||
execution and seeded by the operating system. Next, we call the <code>gen_range</code>
|
||
method on our random number generator. This method is defined by the <code>Rng</code>
|
||
trait that we brought into scope with the <code>use rand::Rng</code> statement above. The
|
||
<code>gen_range</code> method takes two numbers as arguments and generates a random
|
||
number between them. It's inclusive on the lower bound but exclusive on the
|
||
upper bound, so we need <code>1</code> and <code>101</code> to ask for a number ranging from one to a
|
||
hundred.</p>
|
||
<p>Knowing what traits to import and what functions and methods to use from a
|
||
crate isn't something that you'll just <em>know</em>. Instructions for using a crate
|
||
are in each crate's documentation. Another neat feature of Cargo is that you
|
||
can run the <code>cargo doc --open</code> command to build documentation provided by all
|
||
of your dependencies locally and then open it in your browser. If you're
|
||
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> then click on "rand" in the sidebar on the left.</p>
|
||
<p>The second line that we added to our code prints out the secret number. This is
|
||
useful while we’re developing our program to let us easily test it out, but
|
||
we’ll be deleting it for the final version. It’s not much of a game if it
|
||
prints out the answer when you start it up!</p>
|
||
<p>Try running our new program a few times:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 7
|
||
Please input your guess.
|
||
4
|
||
You guessed: 4
|
||
$ cargo run
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 83
|
||
Please input your guess.
|
||
5
|
||
You guessed: 5
|
||
</code></pre>
|
||
<p>You should get different random numbers, and they should all be numbers between
|
||
1 and 100. Great job!</p>
|
||
<h2>Comparing Our Guesses</h2>
|
||
<p>Now that we’ve got user input, let’s compare our guess to the secret number.
|
||
Here’s that part of our next step:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>There are a few new bits here. The first is another <code>use</code>, bringing a type
|
||
called <code>std::cmp::Ordering</code> into scope from the standard crate. <code>Ordering</code> is
|
||
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
|
||
<code>Greater</code>, and <code>Equal</code>. These are the three outcomes that are possible when you
|
||
compare two values.</p>
|
||
<p>Then we add five new lines at the bottom that use the <code>Ordering</code> type:</p>
|
||
<pre><code class="language-rust,ignore">match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
</code></pre>
|
||
<p>The <code>cmp</code> method compares two values, and can be called on anything that can
|
||
be compared. It takes a reference to whatever you want to compare with, so here
|
||
it's comparing our <code>guess</code> to our <code>secret_number</code>. <code>cmp</code> returns a variant of
|
||
the <code>Ordering</code> enum we imported with the <code>use</code> statement earlier. We use a
|
||
<a href="match.html"><code>match</code></a><!-- ignore --> statement to decide what to do next based on
|
||
which variant of <code>Ordering</code> we got back from our call to <code>cmp</code> with the values
|
||
in <code>guess</code> and <code>secret_number</code>.</p>
|
||
<p><code>match</code> statements are made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
|
||
the code that we should run if the value given to the beginning of the <code>match</code>
|
||
statement fits that arm's pattern. Rust takes the value given to <code>match</code> and
|
||
looks through each arm's pattern in turn. The <code>match</code> construct and patterns
|
||
are powerful features in Rust that will be covered in detail in Chapter XX and
|
||
Chapter XX, respectively.</p>
|
||
<p>Let's walk through an example of what would happen with our <code>match</code>. Say that
|
||
the user has guessed 50, and the randomly-generated secret number this time
|
||
is 38. So when we compare 50 to 38, the <code>cmp</code> method will return
|
||
<code>Ordering::Greater</code>, since 50 is greater than 38. <code>Ordering::Greater</code> is the
|
||
value that the <code>match</code> statement gets. It looks at the first arm's pattern,
|
||
<code>Ordering::Less</code>, and says nope, the value we have (<code>Ordering::Greater</code>) does
|
||
not match <code>Ordering::Less</code>. So it ignores the code in that arm and moves on to
|
||
the next arm. The next arm's pattern, <code>Ordering::Greater</code>, <strong>does</strong> match
|
||
<code>Ordering::Greater</code>! The associated code in that arm will get executed, which
|
||
prints "Too big!" to the screen. Then we're done with the <code>match</code> statement; we
|
||
don't look at the last arm at all in this particular scenario.</p>
|
||
<p>However, this code won’t quite compile yet. Let’s try it:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
src/main.rs:23:21: 23:35 error: mismatched types [E0308]
|
||
src/main.rs:23 match guess.cmp(&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 `&std::string::String`
|
||
src/main.rs:23:21: 23:35 note: found type `&_`
|
||
error: aborting due to previous error
|
||
Could not compile `guessing_game`.
|
||
</code></pre>
|
||
<p>Whew! This is a big error. The core of the error says that we have <em>mismatched
|
||
types</em>. Rust has a strong, static type system. However, it also has type
|
||
inference. When we wrote <code>let guess = String::new()</code>, Rust was able to infer
|
||
that <code>guess</code> should be a <code>String</code> and didn’t make us write the type out. Our
|
||
<code>secret_number</code> on the other hand is a number type. There are a few number
|
||
types which can have a value between one and a hundred: <code>i32</code>, a thirty-two-bit
|
||
number; <code>u32</code>, an unsigned thirty-two-bit number; <code>i64</code>, a sixty-four-bit
|
||
number; or others. Rust defaults to an <code>i32</code>, so that's the type of
|
||
<code>secret_number</code> unless we add type information elsewhere that would cause Rust
|
||
to infer a different numerical type. The error is because Rust will not compare
|
||
a string and a number type.</p>
|
||
<p>Ultimately, we want to convert the <code>String</code> we read as input into a real number
|
||
type so that we can compare it to the guess numerically. We can do that with
|
||
two more lines; to your <code>main</code> function body, add the following two lines:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>The two new lines are:</p>
|
||
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
</code></pre>
|
||
<p>We create a variable binding <code>guess</code>. But wait a minute, don't we already have
|
||
a variable binding named <code>guess</code>? We do, but Rust allows us to <em>shadow</em> the
|
||
previous value of <code>guess</code> with a new one. This is often used in this exact
|
||
situation, where we want to convert a value from one type into another type.
|
||
Shadowing lets us re-use the <code>guess</code> variable name rather than forcing us to
|
||
come up with two unique bindings, like <code>guess_str</code> and <code>guess</code> or something
|
||
(we'll cover shadowing in more detail in Chapter 3).</p>
|
||
<p>We bind <code>guess</code> to the expression <code>guess.trim().parse()</code>. The <code>guess</code> in the
|
||
expression refers to the original <code>guess</code> that was a <code>String</code> with our input in
|
||
it. The <code>trim</code> method on <code>String</code>s will eliminate any whitespace at the
|
||
beginning and end. Our <code>u32</code> can only contain numerical characters, but we have
|
||
to press the return key to satisfy <code>read_line</code>. When we press the return
|
||
key, it introduces a newline character. For example, if we type <code>5</code> and hit
|
||
return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents "newline", the
|
||
return key. The <code>trim</code> method gets rid of this, leaving our string with only
|
||
the <code>5</code>.</p>
|
||
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into
|
||
some kind of number. Since this method can parse a variety of number types, we
|
||
need to tell Rust the exact type of number we want with <code>let guess: u32</code>. The
|
||
colon (<code>:</code>) after <code>guess</code> tells Rust we’re going to annotate its type. Rust has
|
||
a few built-in number types, but we’ve chosen <code>u32</code>, an unsigned, thirty-two
|
||
bit integer. It’s a good default choice for a small positive number. You'll see
|
||
the other number types in Chapter XX. Additionally, our <code>u32</code> annotation here
|
||
and the comparison with <code>secret_number</code> means that Rust will infer that
|
||
<code>secret_number</code> should be a <code>u32</code> as well. So now the comparison will be
|
||
between two values of the same type!</p>
|
||
<p>Our call to <code>parse</code> could quite easily cause an error. If, for example, our
|
||
string contained <code>A👍%</code>, there’d be no way to convert that to a number. Because
|
||
it might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
|
||
<code>read_line</code> method does that we discussed earlier. We're going to treat this
|
||
<code>Result</code> the same way by using the <code>expect</code> method again. If <code>parse</code>
|
||
returns an <code>Err</code> <code>Result</code> variant because it could not create a number from the
|
||
string, the <code>expect</code> call will crash the game and print the message we give
|
||
it. If <code>parse</code> can successfully turn the string into a number, it will return
|
||
the <code>Ok</code> variant of <code>Result</code>, and <code>expect</code> will return the number that we
|
||
want that it will take out of the <code>Ok</code> value for us.</p>
|
||
<p>Let’s try our program out!</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 58
|
||
Please input your guess.
|
||
76
|
||
You guessed: 76
|
||
Too big!
|
||
</code></pre>
|
||
<p>Nice! You can see we even added spaces before our guess, and it still figured
|
||
out that we guessed 76. Run the program a few times to verify the different
|
||
behavior with different kinds of input: guess the number correctly, guess a
|
||
number that is too high, and guess a number that is too low.</p>
|
||
<p>Now we’ve got most of the game working, but we can only make one guess. Let’s
|
||
change that by adding a loop!</p>
|
||
<h2>Allowing Multiple Guesses with Looping</h2>
|
||
<p>The <code>loop</code> keyword gives us an infinite loop. We'll add that in to give us more
|
||
chances at guessing the number:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>As you can see, we've moved everything from the guess input onwards into a
|
||
loop. Make sure to indent those lines another four spaces each, and try it out.
|
||
You'll notice we have a new problem because the program is doing exactly what we
|
||
told it to do: ask for another guess forever! It doesn't seem like we can quit!</p>
|
||
<p>We could always halt the program by using the keyboard shortcut <code>control-c</code>.
|
||
There's another way to escape the insatiable monster we've created, though,
|
||
that can be found in our discussion about <code>parse</code>: if we give a non-number
|
||
answer, the program will crash. We can use that to quit! Observe:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 59
|
||
Please input your guess.
|
||
45
|
||
You guessed: 45
|
||
Too small!
|
||
Please input your guess.
|
||
60
|
||
You guessed: 60
|
||
Too big!
|
||
Please input your guess.
|
||
59
|
||
You guessed: 59
|
||
You win!
|
||
Please input your guess.
|
||
quit
|
||
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
|
||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
|
||
</code></pre>
|
||
<p>This method means that typing <code>quit</code> actually quits the game, but so does any
|
||
other non-number input. This is suboptimal, to say the least. We want the game
|
||
to automatically stop when the correct number is guessed.</p>
|
||
<h4>Quitting When you Win</h4>
|
||
<p>Let’s program the game to quit when you win by adding a <code>break</code> in that case:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => {
|
||
println!("You win!");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>By adding the <code>break</code> line after <code>You win!</code>, we’ll exit the loop when we guess
|
||
the secret number correctly. Exiting the loop also means exiting the program,
|
||
since the loop is the last thing in <code>main</code>.</p>
|
||
<h4>Handling Invalid Input</h4>
|
||
<p>For our final refinement of the game's behavior, rather than crashing the
|
||
program when someone inputs a non-number, we want the game to ignore it so we
|
||
can continue guessing. We can do that by altering the line where we convert
|
||
<code>guess</code> from a <code>String</code> to a <code>u32</code>:</p>
|
||
<pre><code class="language-rust,ignore">let guess: u32 = match guess.trim().parse() {
|
||
Ok(num) => num,
|
||
Err(_) => continue,
|
||
};
|
||
</code></pre>
|
||
<p>This is how you generally move from "crash on error" to "actually handle the
|
||
error": by switching from an <code>expect</code> statement to a <code>match</code> statement.
|
||
Remember that <code>parse</code> returns a <code>Result</code> type, and <code>Result</code> is an enum that
|
||
has the variants <code>Ok</code> or <code>Err</code>. We're going to use a <code>match</code> statement here,
|
||
like we did with the <code>Ordering</code> result of the <code>cmp</code> method.</p>
|
||
<p>If <code>parse</code> is able to successfully turn the string into a number, it will
|
||
return an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will
|
||
match the first arm's pattern, and the match statement will just return the
|
||
<code>num</code> value that <code>parse</code> produced and put inside the <code>Ok</code> value. That number
|
||
will end up right where we want it, in the new <code>guess</code> binding we're creating.</p>
|
||
<p>If <code>parse</code> is <em>not</em> able to turn the string into a number, it will return an
|
||
<code>Err</code> value that contains more information about the error. The <code>Err</code> value
|
||
does not match the <code>Ok(num)</code> pattern in the first match arm, but it does match
|
||
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catch-all value; we're
|
||
saying we want to match all <code>Err</code> values, no matter what information they have
|
||
inside them. So we execute the second arm's code, <code>continue</code>: this means to go
|
||
to the next iteration of the <code>loop</code> and ask for another guess. So we have
|
||
effectively ignored all errors that <code>parse</code> might hit!</p>
|
||
<p>Now everything in our program should work as we expect it to! Let’s try it:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 61
|
||
Please input your guess.
|
||
10
|
||
You guessed: 10
|
||
Too small!
|
||
Please input your guess.
|
||
99
|
||
You guessed: 99
|
||
Too big!
|
||
Please input your guess.
|
||
foo
|
||
Please input your guess.
|
||
61
|
||
You guessed: 61
|
||
You win!
|
||
</code></pre>
|
||
<p>Awesome! With one tiny last tweak, we can finish the guessing game: we're still
|
||
printing out the secret number. That was good for testing, but it kind of ruins
|
||
the game. Let's delete the <code>println!</code> that outputs the secret number. Here’s our
|
||
full, final code:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("failed to read line");
|
||
|
||
let guess: u32 = match guess.trim().parse() {
|
||
Ok(num) => num,
|
||
Err(_) => continue,
|
||
};
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => {
|
||
println!("You win!");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<h2>Complete!</h2>
|
||
<p>At this point, you have successfully built the Guessing Game! Congratulations!</p>
|
||
<p>This project was a hands-on way to introduce you to a lot of new Rust concepts:
|
||
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
|
||
In the next few chapters, we will go through these concepts in more detail.
|
||
Chapter 3 covers concepts that most programming languages have, like variables,
|
||
data types, and functions, and shows how to use them in Rust. Chapter 4 gets
|
||
into ownership, which is the feature of Rust that is most different from other
|
||
languages. Chapter 5 discusses structs and method syntax, and Chapter 6
|
||
endeavors to explain enums.</p>
|
||
<h1>Common Programming Concepts in Rust</h1>
|
||
<p>Let's first look at concepts that appear in almost every programming language
|
||
and see how they work in Rust. Many programming languages have much in common
|
||
at their core. None of the concepts presented in this chapter are unique to
|
||
Rust, but we’ll discuss Rust’s particular syntax and conventions concerning
|
||
these common concepts.</p>
|
||
<p>Specifically, we’ll be talking about variable bindings, basic types, functions,
|
||
comments, and control flow. These foundations will be in every Rust
|
||
program, and learning them early will give you a strong core to start from.</p>
|
||
<!-- PROD: START BOX -->
|
||
<p>Keep in mind as we get into variables and functions that the Rust language has
|
||
a set of <em>keywords</em> that have been reserved for use by the language only, much
|
||
like other languages do. This means you cannot use these words as names of
|
||
variables or functions, for example. Most of these have special meaning and we
|
||
will be using them to do various things in our Rust programs; a few have no
|
||
current functionality associated but have been reserved for functionality that
|
||
might be in the Rust language in the future. You can find a list of the
|
||
keywords in Appendix XX.</p>
|
||
<!-- PROD: END BOX -->
|
||
<h2>Variable Bindings and Mutability</h2>
|
||
<p>We mentioned in Chapter 2 that by default, variable bindings are <em>immutable</em>.
|
||
This is one of many nudges in Rust that encourages us to write our code in a
|
||
way that gets the most of the safety and easy concurrency that Rust has to
|
||
offer. We still have the option to make our bindings mutable, though. Let's
|
||
explore how and why Rust encourages us to favor immutability, and why we might
|
||
want to opt out of that.</p>
|
||
<p>Variable bindings being immutable means that once a value is bound, you can't
|
||
change that value. To illustrate this, let's generate a new project in your
|
||
projects directory called <code>bindings</code> by using <code>cargo new --bin bindings</code>.</p>
|
||
<p>Then, in your new <code>bindings</code> directory, open <code>src/main.rs</code> and replace its code
|
||
with the following:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let x = 5;
|
||
println!("The value of x is: {}", x);
|
||
x = 6;
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>Save and run the program using <code>cargo run</code>, 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]
|
||
--> src/main.rs:4:5
|
||
4 |> x = 6;
|
||
|> ^^^^^
|
||
note: prior assignment occurs here
|
||
--> src/main.rs:2:9
|
||
2 |> let x = 5;
|
||
|> ^
|
||
</code></pre>
|
||
<p>This is our first example of the compiler helping us find an error in our
|
||
program! Compiler errors can be frustrating. Keep in mind that they only mean
|
||
your program isn't safely doing what you want it to do yet; they do <em>not</em> mean
|
||
that you're not a good programmer! Experienced Rustaceans still get compiler
|
||
errors. The Rust compiler is trying to help your program be the very best.</p>
|
||
<!-- PROD: START BOX -->
|
||
###### Extended Error Explanations
|
||
<p>Now that you've seen a Rust error, let's take a moment to look at one
|
||
particularly useful aspect of errors. Rust encourages you to seek further
|
||
information on the kind of error you've received with output like this:</p>
|
||
<pre><code class="language-bash">error: re-assignment of immutable variable `x` [--explain E0384]
|
||
</code></pre>
|
||
<p>This tells us that if we pass the <code>--explain</code> flag to <code>rustc</code> with the provided
|
||
error code, we can see an extended explanation which will try to explain common
|
||
causes of and solutions to that kind of error. Not every error has a longer
|
||
explanation, but many do. Here’s a portion of the explanation for the <code>E0384</code>
|
||
error we received:</p>
|
||
<pre><code class="language-bash">$ rustc --explain E0384
|
||
This error occurs when an attempt is made to reassign an immutable variable.
|
||
For example:
|
||
|
||
```
|
||
fn main(){
|
||
let x = 3;
|
||
x = 5; // error, reassignment of immutable variable
|
||
}
|
||
```
|
||
</code></pre>
|
||
<p>These explanations can really help if you’re stuck on an error, so don't
|
||
hesitate to look up the error code. The compiler is your friend, and it's there
|
||
to help.</p>
|
||
<!-- PROD: END BOX -->
|
||
<p>The error tells us that the cause of the error is <code>re-assigment of immutable variable</code>, because we tried to assign a second value to the immutable <code>x</code>
|
||
variable.</p>
|
||
<p>It's important that we get compile-time errors when we attempt to change a
|
||
value that we previously said was immutable because this very situation can
|
||
lead to bugs. If one part of our code operates on an assumption that a value
|
||
will never change, and another part of our code changes that value, it's
|
||
possible that the first part of the code won't do what it was designed to do.
|
||
This cause of bugs can be difficult to track down after the fact, especially
|
||
when the second piece of code only changes the value <em>sometimes</em>.</p>
|
||
<p>In Rust, we can trust that a value we say won't change really won't change,
|
||
because the compiler is enforcing that guarantee for us. When reading and
|
||
writing code, we don't have to keep track in our head how and where a value
|
||
might change. This can make code easier to reason about.</p>
|
||
<p>Mutability can be really useful, though! Bindings are immutable only by
|
||
default; you can make them mutable by adding <code>mut</code> in front of the variable
|
||
name. In addition to allowing this value to be changed, it conveys intent to
|
||
future readers of the code by indicating that other parts of the code will be
|
||
changing this value.</p>
|
||
<p>For example, change the program you just wrote to the following:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let mut x = 5;
|
||
println!("The value of x is: {}", x);
|
||
x = 6;
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>Running this, we get:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling bindings v0.1.0 (file:///projects/bindings)
|
||
Running `target/debug/bindings`
|
||
The value of x is: 5
|
||
The value of x is: 6
|
||
</code></pre>
|
||
<p>Using <code>mut</code>, we are allowed to change the value that <code>x</code> binds to from <code>5</code> to
|
||
<code>6</code>. In some cases you'll want to make a binding mutable because it makes the
|
||
code easier to understand than an implementation that only uses immutable
|
||
bindings. In cases where you're using large data structures, mutating an
|
||
instance in place may be faster than copying and returning newly allocated
|
||
instances. It all depends on the tradeoffs you want to make in your situation.</p>
|
||
<h3>Shadowing</h3>
|
||
<p>As we saw in the guessing game tutorial, we can declare new bindings with the
|
||
same name as a previous binding, and the new binding <em>shadows</em> the previous
|
||
binding. We say that the first binding is <em>shadowed</em> by the second, which means
|
||
that the second binding's value is what you will see when you use the variable.
|
||
We can shadow a binding by using the same binding's name and repeating the use
|
||
of the <code>let</code> keyword as follows:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 5;
|
||
|
||
let x = x + 1;
|
||
|
||
let x = x * 2;
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>This program first binds <code>x</code> to a value of <code>5</code>. Then, it shadows <code>x</code> by
|
||
repeating <code>let x =</code>, taking the original value and adding <code>1</code> so that the value
|
||
of <code>x</code> is then <code>6</code>. The third <code>let</code> statement also shadows <code>x</code>, taking the
|
||
previous value and multiplying it by <code>2</code> to give <code>x</code> a final value of <code>12</code>. If
|
||
you run this, it will output:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling bindings v0.1.0 (file:///projects/bindings)
|
||
Running `target/debug/bindings`
|
||
The value of x is: 12
|
||
</code></pre>
|
||
<p>This is different from marking a binding as <code>mut</code> because unless we use the
|
||
<code>let</code> keyword again, we'll get a compile-time error if we accidentally try to
|
||
reassign to this binding. We can perform a few transformations on a value, but
|
||
have the binding be immutable after those transformations have been completed.</p>
|
||
<p>The other difference between <code>mut</code> and shadowing is that, since we're
|
||
effectively creating a new binding when we use the <code>let</code> keyword again, we can
|
||
change the type of the value we're binding to but reuse the same name. For
|
||
example, say we ask a user to show us how many spaces they want between some
|
||
text by sending us space characters, but we really want to store that as a
|
||
number:</p>
|
||
<pre><code class="language-rust">let spaces = " ";
|
||
let spaces = spaces.len();
|
||
</code></pre>
|
||
<p>This is allowed: the first <code>spaces</code> binding is a string type, and the second
|
||
<code>spaces</code> binding, which is a brand new binding that happens to have the same
|
||
name as the first one, is a number type. Shadowing thus saves us from having to
|
||
come up with different names like <code>spaces_str</code> and <code>spaces_num</code>; we can reuse
|
||
the simpler <code>spaces</code> name. If we try to use <code>mut</code> for this, however, like this:</p>
|
||
<pre><code class="language-rust,ignore">let mut spaces = " ";
|
||
spaces = spaces.len();
|
||
</code></pre>
|
||
<p>We will get a compile-time error because we are not allowed to mutate a
|
||
binding's type:</p>
|
||
<pre><code class="language-bash">error: mismatched types [--explain E0308]
|
||
-->
|
||
|>
|
||
4 |> spaces = spaces.len();
|
||
|> ^^^^^^^^^^^^ expected &-ptr, found usize
|
||
note: expected type `&str`
|
||
note: found type `usize`
|
||
|
||
error: aborting due to previous error
|
||
</code></pre>
|
||
<p>Now that we've explored how variable bindings work, let's look at some more
|
||
data types of values that we can bind variables to.</p>
|
||
<h2>Data Types</h2>
|
||
<p>Every value in Rust is of a certain <em>type</em>, which tells Rust what kind of data
|
||
is being given so it knows how to work with that data. In this section, we'll
|
||
look at a number of types built into the language itself split into two subsets:
|
||
scalar and compound.</p>
|
||
<p>Something to keep in mind throughout this section: Rust is a <em>statically typed</em>
|
||
language, which means that it must know the types of all bindings at compile
|
||
time. The compiler can usually infer what type we want to use based on the
|
||
value and how we use it. In cases when many types are possible, such as when we
|
||
converted a <code>String</code> to a numeric type using <code>parse</code> in Chapter 2, we must
|
||
add a type annotation, like this:</p>
|
||
<pre><code class="language-rust">let guess: u32 = "42".parse().unwrap();
|
||
</code></pre>
|
||
<p>If we don't put the type annotation here, Rust will give us this error that
|
||
means the compiler needs more information from us to know which possible type
|
||
we want:</p>
|
||
<pre><code class="language-bash">error: unable to infer enough type information about `_`; type annotations or
|
||
generic parameter binding required [--explain E0282]
|
||
-->
|
||
|>
|
||
3 |> let guess = "42".parse().unwrap();
|
||
|> ^^^^^
|
||
</code></pre>
|
||
<p>You will see some type annotations as we discuss the various data types.</p>
|
||
<h3>Scalar Types</h3>
|
||
<p>A <em>scalar</em> type represents a single value. There are four primary scalar
|
||
types in Rust: integers, floating point numbers, booleans, and characters.
|
||
You'll likely recognize these from other programming languages, but let's jump
|
||
into how they work in Rust.</p>
|
||
<h4>Integer Types</h4>
|
||
<p>An <em>integer</em> is a number without a fractional component. We've used one integer
|
||
type already in this chapter, the <code>i32</code> type. This type declaration indicates
|
||
that the value it's associated with should be a signed integer (hence the <code>i</code>,
|
||
as opposed to a <code>u</code> for unsigned) for a 32-bit system. There are a number of
|
||
built-in integer types in Rust, shown in Table 3-1.</p>
|
||
<table><thead><tr><td> Length </td><td> signed </td><td> unsigned </td></tr></thead>
|
||
<tr><td> 8-bit </td><td> i8 </td><td> u8 </td></tr>
|
||
<tr><td> 16-bit </td><td> i16 </td><td> u16 </td></tr>
|
||
<tr><td> 32-bit </td><td> i32 </td><td> u32 </td></tr>
|
||
<tr><td> 64-bit </td><td> i64 </td><td> u64 </td></tr>
|
||
<tr><td> arch </td><td> isize </td><td> usize </td></tr>
|
||
</table>
|
||
<p><em>Table 3-1: Integer types in Rust. Each variant in the signed and unsigned
|
||
columns (for example, <code>i32</code>) can be used to declare the type of an integer
|
||
value.</em></p>
|
||
<p>Each variant can be either signed or unsigned and has an explicit size. Signed
|
||
and unsigned merely refers to whether it is possible for the number to be
|
||
either negative or positive; in other words, whether the number needs to have a
|
||
sign with it (signed), or whether it will only ever be positive and can
|
||
therefore be represented without a sign (unsigned). It's like writing numbers
|
||
on paper: when the sign matters, a number is shown with a plus sign or minus
|
||
sign, but when it's safe to assume the number is positive, it's shown with no
|
||
sign. Signed numbers are stored using two’s complement representation (if
|
||
you're unsure what this is you can search for it online; an explanation is
|
||
outside the scope of this text).</p>
|
||
<p>Each signed variant can store numbers from -(2<sup>n - 1</sup>) to 2<sup>n -
|
||
1</sup> - 1 inclusive, where <code>n</code> is the number of bits that variant uses. So an
|
||
<code>i8</code> can store from -(2<sup>7</sup>) to 2<sup>7</sup> - 1, which equals -128
|
||
to 127. Unsigned variants can store numbers from 0 to 2<sup>n</sup> - 1, so a
|
||
<code>u8</code> can store from 0 to 2<sup>8</sup> - 1, which equals 0 to 255.</p>
|
||
<p>Finally, the <code>isize</code> and <code>usize</code> types depend on the kind of computer your
|
||
program is running on: 64-bits if you're on a 64-bit architecture, and 32-bits
|
||
if you’re on a 32-bit architecture.</p>
|
||
<p>You can write integer literals in any of the forms shown in Table 3-2. Note that
|
||
all number literals except for the byte literal allow a type suffix, such as
|
||
<code>57u8</code>, and <code>_</code> as a visual separator, such as <code>1_000</code>.</p>
|
||
<table><thead><tr><td> Number literals </td><td> Example </td></tr></thead>
|
||
<tr><td> Decimal </td><td> <code>98_222</code> </td></tr>
|
||
<tr><td> Hex </td><td> <code>0xff</code> </td></tr>
|
||
<tr><td> Octal </td><td> <code>0o77</code> </td></tr>
|
||
<tr><td> Binary </td><td> <code>0b1111_0000</code> </td></tr>
|
||
<tr><td> Byte (<code>u8</code> only) </td><td> <code>b'A'</code> </td></tr>
|
||
</table>
|
||
<p><em>Table 3-2: Integer literals in Rust.</em></p>
|
||
<p>So how do you know which type of integer to use? If you're unsure, Rust's
|
||
defaults are generally good choices, and integer types default to <code>i32</code>: it’s
|
||
generally the fastest, even on 64-bit systems. The primary situation in which
|
||
you'd use <code>isize</code> or <code>usize</code> is when indexing some sort of collection.</p>
|
||
<h4>Floating-Point Types</h4>
|
||
<p>Rust also has two primitive types for <em>floating-point numbers</em>, which are
|
||
numbers with decimal points. Rust's floating-point types are <code>f32</code> and <code>f64</code>,
|
||
which are 32 bits and 64 bits in size, respectively. The default type is <code>f64</code>,
|
||
as it’s roughly the same speed as <code>f32</code>, but has a larger precision. It is
|
||
possible to use an <code>f64</code> on 32 bit systems, but it will be slower than using an
|
||
<code>f32</code> on those systems. Most of the time, trading potential worse performance
|
||
for better precision is a reasonable initial choice, and you should benchmark
|
||
your code if you suspect floating-point size is a problem in your case. See
|
||
Chapter XX for how to run benchmarks.</p>
|
||
<p>Here's an example showing floating-point numbers in action:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 2.0; // f64
|
||
|
||
let y: f32 = 3.0; // f32
|
||
}
|
||
</code></pre>
|
||
<p>Floating-point numbers are represented according to the IEEE-754 standard. The
|
||
<code>f32</code> type is a single-precision float, while <code>f64</code> has double-precision.</p>
|
||
<h4>Numeric Operations</h4>
|
||
<p>Rust supports the usual basic mathematic operations you’d expect for all of
|
||
these number types: addition, subtraction, multiplication, division, and
|
||
remainder. This code shows how you'd use each one in a <code>let</code> statement:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
// addition
|
||
let sum = 5 + 10;
|
||
|
||
// subtraction
|
||
let difference = 95.5 - 4.3;
|
||
|
||
// multiplication
|
||
let product = 4 * 30;
|
||
|
||
// division
|
||
let quotient = 56.7 / 32.2;
|
||
|
||
// remainder
|
||
let remainder = 43 % 5;
|
||
}
|
||
</code></pre>
|
||
<p>Each expression in these statements uses a mathematical operator and evaluates
|
||
to a single value, which is then bound to a variable.</p>
|
||
<h4>The Boolean Type</h4>
|
||
<p>As in most other programming languages, a boolean type in Rust has two possible
|
||
values: <code>true</code> and <code>false</code>. The boolean type in Rust is specified with <code>bool</code>.
|
||
For example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let t = true;
|
||
|
||
let f: bool = false; // with explicit type annotation
|
||
}
|
||
</code></pre>
|
||
<p>The main way to consume boolean values is through conditionals like an <code>if</code>
|
||
statement. We’ll cover how <code>if</code> statements work in Rust in the "Control Flow"
|
||
section of this chapter.</p>
|
||
<h4>The Character Type</h4>
|
||
<p>So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
|
||
<code>char</code> type is the language's most primitive alphabetic type, and this code
|
||
shows one way to use it:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let c = 'z';
|
||
let z = 'ℤ';
|
||
let heart_eyed_cat = '😻';
|
||
}
|
||
</code></pre>
|
||
<p>Rust’s <code>char</code> represents a Unicode Scalar Value, which means that it can
|
||
represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
|
||
ideographs, emoji, and zero width spaces are all valid <code>char</code>s in Rust. Unicode
|
||
Scalar Values range from <code>U+0000</code> to <code>U+D7FF</code> and <code>U+E000</code> to <code>U+10FFFF</code>
|
||
inclusive. A "character" isn’t really a concept in Unicode, however, so your
|
||
human intuition for what a "character" is may not match up with what a <code>char</code>
|
||
is in Rust. We'll discuss this in detail in the Strings section of Chapter 8.</p>
|
||
<h3>Compound Types</h3>
|
||
<p><em>Compound types</em> can group multiple values of other types into one type. Rust
|
||
has two primitive compound types: tuples and arrays.</p>
|
||
<h4>Grouping Values into Tuples</h4>
|
||
<p>A tuple is a general way of grouping together some number of other values with
|
||
distinct types into one compound type.</p>
|
||
<p>We create a tuple by writing a comma-separated list of values inside
|
||
parentheses. Each position in the tuple has a distinct type, and the types of
|
||
the different values in the tuple do not have to be the same. We've added
|
||
optional type annotations in this example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let tup: (i32, f64, u8) = (500, 6.4, 1);
|
||
}
|
||
</code></pre>
|
||
<p>Note that the single name <code>tup</code> binds to the entire tuple, emphasizing the fact
|
||
that a tuple is considered a single compound element. To get the individual
|
||
values out of a tuple, we can use pattern matching to destructure a tuple
|
||
value, like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let tup = (500, 6.4, 1);
|
||
|
||
let (x, y, z) = tup;
|
||
|
||
println!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<p>In this program, we first create a tuple and bind it to the name <code>tup</code>. We then
|
||
use a pattern with <code>let</code> to take <code>tup</code> and turn it into three separate
|
||
bindings, <code>x</code>, <code>y</code>, and <code>z</code>. This is called <em>destructuring</em>, because it breaks
|
||
the single tuple into three parts. Finally, we print the value of <code>y</code>, which is
|
||
<code>6.4</code>.</p>
|
||
<h4>Tuple Indexing</h4>
|
||
<p>In addition to destructuring through pattern matching, we can also access a
|
||
tuple element directly by using a period (<code>.</code>) followed by the index of the
|
||
value we want to access. For example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x: (i32, f64, u8) = (500, 6.4, 1);
|
||
|
||
let five_hundred = x.0;
|
||
|
||
let six_point_four = x.1;
|
||
|
||
let one = x.2;
|
||
}
|
||
</code></pre>
|
||
<p>This program creates a tuple, <code>x</code>, and then makes new bindings to each element
|
||
by using their index. As with most programming languages, the first index in a
|
||
tuple is 0.</p>
|
||
<h3>Arrays</h3>
|
||
<p>Another way to bind a name to a collection of multiple values is with an
|
||
<em>array</em>. Unlike a tuple, every element of an array must have the same type.
|
||
Arrays in Rust are different than arrays in some other languages because arrays
|
||
in Rust have a fixed length: once declared, they cannot grow or shrink in size.</p>
|
||
<p>In Rust, the values going into an array are written as a comma separated list
|
||
inside square brackets:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [1, 2, 3, 4, 5];
|
||
}
|
||
</code></pre>
|
||
<p>While arrays can be useful since they are a primitive type so using them can be
|
||
very fast, they aren't as flexible as the vector type. The vector type is a
|
||
similar collection type provided by the standard library that <em>is</em> allowed to
|
||
grow or shrink in size. If you're unsure whether to use an array or a vector,
|
||
you should probably go with a vector, and we'll discuss them in more detail in
|
||
Chapter 8.</p>
|
||
<p>An example of when we might want to use an array is storing the months of the
|
||
year. It's very unlikely that our program will need to add or remove months, so
|
||
we can use an array since we know we will always have 12 items:</p>
|
||
<pre><code class="language-rust">let months = ["January", "February", "March", "April", "May", "June", "July",
|
||
"August", "September", "October", "November", "December"];
|
||
</code></pre>
|
||
<h4>Accessing Array Elements</h4>
|
||
<p>An array is a single chunk of memory, allocated on the stack. We can access
|
||
elements of an array using indexing, like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [1, 2, 3, 4, 5];
|
||
|
||
let first = a[0];
|
||
let second = a[1];
|
||
}
|
||
</code></pre>
|
||
<p>In this example, the binding named <code>first</code> will get the value <code>1</code>, since that
|
||
is the value at index <code>[0]</code> in the array. The binding named <code>second</code> will get
|
||
the value <code>2</code> from index <code>[1]</code> in the array.</p>
|
||
<h4>Invalid Array Element Access</h4>
|
||
<p>What happens if you try to access an element of an array past the end of the
|
||
array? Say we changed our program to:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let a = [1, 2, 3, 4, 5];
|
||
|
||
let element = a[10];
|
||
|
||
println!("The value of element is: {}", 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 '<main>' panicked at 'index out of bounds: the len is 5 but the index is
|
||
10', src/main.rs:4
|
||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||
error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
|
||
</code></pre>
|
||
<p>We can see that the compilation did not give us any errors, but we got a
|
||
<em>runtime</em> error and our program didn't exit successfully. When we attempt to
|
||
access an element using indexing, Rust will check that the index we've
|
||
specified is less than the array length. If the index is greater than the
|
||
length, it will "panic", which is what it's called when a Rust program exits
|
||
with an error.</p>
|
||
<p>This is our first example of Rust’s safety principles in action. In many
|
||
low-level languages, this kind of check is not done, and when you provide an
|
||
incorrect index, invalid memory can be accessed. Rust protects us against this
|
||
kind of error by immediately exiting instead of allowing the memory access and
|
||
continuing. We'll discuss more of Rust’s error handling in Chapter XX.</p>
|
||
<h2>How Functions Work</h2>
|
||
<p>Functions are pervasive in Rust code. We’ve already seen one of the most
|
||
important functions in the language: the <code>main</code> function that’s the entry
|
||
point of many programs. We've also seen the <code>fn</code> keyword, which allows us to
|
||
declare new functions.</p>
|
||
<p>Rust code uses <em>snake case</em> as the conventional style for function and variable
|
||
names. In snake case, all letters are lower case, and there are underscores
|
||
separating words. Here's a program containing an example function definition:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
|
||
another_function();
|
||
}
|
||
|
||
fn another_function() {
|
||
println!("Another function.");
|
||
}
|
||
</code></pre>
|
||
<p>Function definitions in Rust start with <code>fn</code> and have a set of parentheses
|
||
after the function name. The curly braces tell the compiler where the function
|
||
body begins and ends.</p>
|
||
<p>We can call any function we’ve defined by entering its name followed by a pair
|
||
of parentheses. Since <code>another_function</code> is defined in the program, it can be
|
||
called from inside the <code>main</code> function. Note that we defined
|
||
<code>another_function</code> <em>after</em> the <code>main</code> function in our source code; we could
|
||
have defined it before as well. Rust doesn’t care where you define your
|
||
functions, only that they are defined somewhere.</p>
|
||
<p>Let’s start a new binary project named <code>functions</code> so that we can explore
|
||
further. Place the <code>another_function</code> example in <code>src/main.rs</code> and run it.
|
||
You should see the following output:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
Hello, world!
|
||
Another function.
|
||
</code></pre>
|
||
<p>The lines execute in the order they appear in the <code>main</code> function. First, our
|
||
“Hello, world!” message prints, and then <code>another_function</code> is called and its
|
||
message is printed.</p>
|
||
<h3>Function Arguments</h3>
|
||
<p>Functions can also take arguments. The following rewritten version of
|
||
<code>another_function</code> shows what arguments look like in Rust:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
another_function(5);
|
||
}
|
||
|
||
fn another_function(x: i32) {
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>Try running this program, and you should get this output:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
The value of x is: 5
|
||
</code></pre>
|
||
<p>In the declaration of <code>another_function</code>, we place one argument named <code>x</code>. We
|
||
specify the type of <code>x</code> as <code>i32</code>. When we pass <code>5</code> to <code>another_function</code>,
|
||
the <code>println!</code> macro puts <code>5</code> where the pair of curly braces were in the format
|
||
string.</p>
|
||
<p>In function signatures, we <em>must</em> declare the type. This is a deliberate
|
||
decision in the design of Rust; requiring type annotations in function
|
||
definitions means the compiler almost never needs you to use them elsewhere in
|
||
the code in order to figure out what you mean.</p>
|
||
<p>When you want a function to have multiple arguments, just separate them inside
|
||
the function signature with commas, like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
another_function(5, 6);
|
||
}
|
||
|
||
fn another_function(x: i32, y: i32) {
|
||
println!("The value of x is: {}", x);
|
||
println!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<p>In this example, we make a function with two arguments, both of which are
|
||
<code>i32</code>s. If your function has multiple arguments, they don’t need to be the same
|
||
type, but they just happen to be in this example. Our function then prints out
|
||
the values of both of its arguments.</p>
|
||
<p>Let’s try out this code. Replace the program currently in your <code>function</code>
|
||
project's <code>main.rs</code> file with the example above, and run it as follows:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
The value of x is: 5
|
||
The value of y is: 6
|
||
</code></pre>
|
||
<p>Since <code>5</code> is passed as the <code>x</code> argument and <code>6</code> is passed as the <code>y</code> argument,
|
||
the two strings are printed with these values.</p>
|
||
<h3>Function Bodies</h3>
|
||
<p>Function bodies are made up of a series of statements optionally ending in an
|
||
expression. So far, we've only seen functions without an ending expression, but
|
||
we have seen expressions as parts of statements. Since Rust is an
|
||
expression-based language, this is an important distinction to understand.
|
||
Other languages don't have the same distinctions, so let's look at what
|
||
statements and expressions are and how their differences affect the bodies of
|
||
functions.</p>
|
||
<h4>Statements and Expressions</h4>
|
||
<p>We've already been using both statements and expressions. <em>Statements</em> are
|
||
instructions that perform some action and do not return a value. <em>Expressions</em>
|
||
evaluate to a resulting value. Let's look at some examples.</p>
|
||
<p>Creating a variable binding and assigning a value to it with the <code>let</code> keyword
|
||
is a statement. In this example, <code>let y = 6;</code> is a statement:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let y = 6;
|
||
}
|
||
</code></pre>
|
||
<p>Function definitions are also statements; the entire previous example is a
|
||
statement in itself.</p>
|
||
<p>Statements do not return values themselves. Therefore, you can’t assign a <code>let</code>
|
||
binding to another binding, as this code tries to do:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let x = (let y = 6);
|
||
}
|
||
</code></pre>
|
||
<p>If we were to run this program, we’d get an error like this:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
error: expected expression, found statement (`let`)
|
||
--> src/main.rs:2:14
|
||
2 |> let x = (let y = 6);
|
||
|> ^^^
|
||
note: variable declaration using `let` is a statement
|
||
|
||
error: aborting due to previous error
|
||
error: Could not compile `functions`.
|
||
</code></pre>
|
||
<p>The <code>let y = 6</code> statement does not return a value, so there isn't anything for
|
||
<code>x</code> to bind to. This is different than in other languages like C and Ruby where
|
||
the assignment returns the value of the assignment. In those languages, we can
|
||
write <code>x = y = 6</code> and have both <code>x</code> and <code>y</code> have the value <code>6</code>; that is not the
|
||
case in Rust.</p>
|
||
<p>Expressions are code that evaluate to something, and make up most of the rest
|
||
of the code that you will write in Rust. Consider a simple math operation, like
|
||
this:</p>
|
||
<pre><code class="language-rust,ignore">5 + 6
|
||
</code></pre>
|
||
<p>This is an expression, and evaluating it results in the value <code>11</code>. Expressions
|
||
can be part of statements-- in the previous example that had the statement <code>let y = 6;</code>, <code>6</code> is an expression that evaluates to the value <code>6</code>. Calling a
|
||
function is an expression. Calling a macro is an expression. The block that we
|
||
use to create new scopes, <code>{}</code>, is an expression, for example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 5;
|
||
|
||
let y = {
|
||
let x = 3;
|
||
x + 1
|
||
};
|
||
|
||
println!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<!-- If we use wingding numbers to call out code, we might delete the
|
||
repetition here and just use those numbers--that can help the flow of the text.
|
||
I'm flagging this as a reminder for when we transfer to libreoffice -->
|
||
<p>The expression:</p>
|
||
<pre><code class="language-rust,ignore">{
|
||
let x = 3;
|
||
x + 1
|
||
}
|
||
</code></pre>
|
||
<p>is a block that, in this case, evaluates to <code>4</code>, and then gets bound to
|
||
<code>y</code> as part of the <code>let</code> statement.</p>
|
||
<p>Note that the line containing <code>x + 1</code> does not have a semicolon at the end,
|
||
unlike most of the lines we've seen up until now. This is the most important
|
||
distinction between expressions and statements to remember: statements end in
|
||
semicolons while expressions do not. If you add a semicolon to the end of an
|
||
expression, that will turn it into a statement, which will then not return a
|
||
value. Keep this in mind as we explore function return values and expressions.</p>
|
||
<h3>Functions with Return Values</h3>
|
||
<p>Functions can return values back to the code that calls them. We don’t name
|
||
return values, but we do declare their type, after an arrow (<code>-></code>). In Rust,
|
||
the "return value of the function” is synonymous with the "value of the final
|
||
expression in the block of the body of a function.” Here's an example of a
|
||
function that returns a value:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn five() -> i32 {
|
||
5
|
||
}
|
||
|
||
fn main() {
|
||
let x = five();
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>There are no function calls, macros, or even <code>let</code> statements in the <code>five</code>
|
||
function: just the number <code>5</code> by itself. That's a perfectly valid function in
|
||
Rust. Note the function's return type is specified, too, as <code>-> i32</code>. Try
|
||
running this code, and the output should look like this:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling functions v0.1.0 (file:///projects/functions)
|
||
Running `target/debug/functions`
|
||
The value of x is: 5
|
||
</code></pre>
|
||
<p>The <code>5</code> in <code>five</code> is the function's return value, which is why the return type
|
||
is <code>i32</code>. Let’s examine this in more detail. There are two important bits.
|
||
First, the line <code>let x = five();</code> shows us using the return value of a function
|
||
to initialize a binding.</p>
|
||
<p>Because the function <code>five</code> returns a <code>5</code>, that line is the same as saying:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
</code></pre>
|
||
<p>The second interesting bit is the <code>five</code> function itself. It requires no
|
||
arguments and defines the type of the return value, but the body of the
|
||
function is a lonely <code>5</code> with no semicolon because it is an expression whose
|
||
value we want to return. Let's look at another example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = plus_one(5);
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
|
||
fn plus_one(x: i32) -> i32 {
|
||
x + 1
|
||
}
|
||
</code></pre>
|
||
<p>Running this code will print <code>The value of x is: 6</code>. What happens if we put a
|
||
semicolon at the end of the line containing <code>x + 1</code>, changing it from an
|
||
expression to a statement?</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let x = plus_one(5);
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
|
||
fn plus_one(x: i32) -> 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]
|
||
--> src/main.rs:7:1
|
||
7 |> fn plus_one(x: i32) -> i32 {
|
||
|> ^
|
||
help: consider removing this semicolon:
|
||
--> src/main.rs:8:10
|
||
8 |> x + 1;
|
||
|> ^
|
||
|
||
error: aborting due to previous error
|
||
error: Could not compile `functions`.
|
||
</code></pre>
|
||
<p>The main error message, "not all control paths return a value", reveals the
|
||
core of the issue with this code. The definition of the function <code>plus_one</code>
|
||
says that it will return an <code>i32</code>, but statements don’t evaluate to a value.
|
||
Therefore, nothing is returned, which contradicts the function definition and
|
||
results in an error. In this output, Rust gives an option to rectify this: it
|
||
suggests removing the semicolon, which would fix the error.</p>
|
||
<h2>Comments</h2>
|
||
<p>All programmers strive to make their code easy to understand, but sometimes
|
||
extra explanation is warranted. In these cases, we leave notes in our source
|
||
code that the compiler will ignore but people reading the source code may find
|
||
useful. These notes are called <em>comments</em>.</p>
|
||
<p>Here’s a simple comment:</p>
|
||
<pre><code class="language-rust">// Hello, world.
|
||
</code></pre>
|
||
<p>In Rust, comments must start with two slashes and will last until the end of
|
||
the line. For comments that extend beyond a single line, you'll need to
|
||
include <code>//</code> on each line, like this:</p>
|
||
<pre><code class="language-rust">// So we’re doing something complicated here, long enough that we need
|
||
// multiple lines of comments to do it! Whew! Hopefully, this comment will
|
||
// explain what’s going on.
|
||
</code></pre>
|
||
<p>Comments can also be placed at the end of lines of code:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let lucky_number = 7; // I’m feeling lucky today.
|
||
}
|
||
</code></pre>
|
||
<p>But you’ll more often see them above, like so:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
// I’m feeling lucky today.
|
||
let lucky_number = 7;
|
||
}
|
||
</code></pre>
|
||
<p>That’s all there is to it. Comments are not particularly complicated.</p>
|
||
<h2>Control Flow</h2>
|
||
<p>Decisions on whether or not to run some code depending on if a condition is
|
||
true, or deciding to run some code repeatedly while a condition is true, are
|
||
basic building blocks in most programming languages. The most common constructs
|
||
that let us control the flow of execution of our Rust code are <code>if</code> expressions
|
||
and loops.</p>
|
||
<h3><code>if</code> Expressions</h3>
|
||
<p>An <code>if</code> expression allows us to branch our code depending on conditions. We
|
||
provide a condition and then say, "If this condition is met, run this
|
||
block of code. If the condition is not met, do not run this block of code."</p>
|
||
<p>Let’s make a new project to explore <code>if</code>, called <code>branches</code>. In <code>src/main.rs</code>,
|
||
put:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let number = 3;
|
||
|
||
if number < 5 {
|
||
println!("condition was true");
|
||
} else {
|
||
println!("condition was false");
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>All <code>if</code> expressions start with the keyword <code>if</code>, which is followed by a
|
||
condition. In this case, our condition is checking if our variable binding
|
||
<code>number</code> has a value that is less than 5. The block of code we want to execute
|
||
if the condition is true goes immediately after the condition, inside curly
|
||
braces. These blocks are sometimes called <em>arms</em>. We can optionally also
|
||
include an <code>else</code> expression, which we have chosen to do here. This gives the
|
||
program an alternative block of code to execute should the condition evaluate
|
||
to false. If you don't give an <code>else</code> expression and the condition is false,
|
||
the program will just skip the <code>if</code> block and move on to the next bit of code.</p>
|
||
<p>Try running this code, and you should see output like this:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling branches v0.1.0 (file:///projects/branches)
|
||
Running `target/debug/branches`
|
||
condition was true
|
||
</code></pre>
|
||
<p>Let’s try changing the value of <code>number</code> to a value that makes the condition
|
||
<code>false</code> to see what happens:</p>
|
||
<pre><code class="language-rust,ignore">let number = 7;
|
||
</code></pre>
|
||
<p>Run the program again, and look at the output:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling branches v0.1.0 (file:///projects/branches)
|
||
Running `target/debug/branches`
|
||
condition was false
|
||
</code></pre>
|
||
<p>It’s also worth noting that the condition here <em>must</em> be a <code>bool</code>. To see what
|
||
happens if the condition isn't a <code>bool</code>, try running this code:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let number = 3;
|
||
|
||
if number {
|
||
println!("number was three");
|
||
}
|
||
}
|
||
</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]
|
||
--> src/main.rs:4:8
|
||
4 |> if number {
|
||
|> ^^^^^^ expected bool, found integral variable
|
||
note: expected type `bool`
|
||
note: found type `_`
|
||
|
||
error: aborting due to previous error
|
||
Could not compile `branches`.
|
||
</code></pre>
|
||
<p>The error tells us that Rust expected a <code>bool</code>, but got an integer. Rust will
|
||
not automatically try to convert non-boolean types to a boolean here, unlike
|
||
languages like Ruby or JavaScript. We must be explicit and always give <code>if</code> a
|
||
<code>boolean</code> as its condition. If you wanted your <code>if</code> code block to run only when
|
||
a number is not equal to <code>0</code>, for example, we would change the <code>if</code> expression
|
||
to read:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let number = 3;
|
||
|
||
if number != 0 {
|
||
println!("number was something other than zero");
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Running this will print <code>number was something other than zero</code>.</p>
|
||
<h4>Multiple Conditions with <code>else if</code></h4>
|
||
<p>We can have multiple conditions by combining <code>if</code> and <code>else</code> in an <code>else if</code>
|
||
expression. For example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let number = 6;
|
||
|
||
if number % 4 == 0 {
|
||
println!("number is divisible by 4");
|
||
} else if number % 3 == 0 {
|
||
println!("number is divisible by 3");
|
||
} else if number % 2 == 0 {
|
||
println!("number is divisible by 2");
|
||
} else {
|
||
println!("number is not divisible by 4, 3, or 2");
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>This program has four possible paths it can take. If you try running it, you
|
||
should see output like this:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling branches v0.1.0 (file:///projects/branches)
|
||
Running `target/debug/branches`
|
||
number is divisible by 3
|
||
</code></pre>
|
||
<p>When this program executes, it will check each <code>if</code> expression in turn and
|
||
execute the first body for which the condition holds true. Note that even
|
||
though 6 is divisible by 2, we did not see the output <code>number is divisible by 2</code>, nor did we see the <code>number is not divisible by 4, 3, or 2</code> text from the
|
||
<code>else</code> block. That's because Rust will only execute the block for the first
|
||
true condition, and once it finds one, it won't even check the rest.</p>
|
||
<p>Using too many <code>else if</code> expressions can clutter your code, so if you find
|
||
yourself with more than one, you may want to look at refactoring your code. In
|
||
Chapter 6, we'll talk about a powerful Rust branching construct called <code>match</code>
|
||
for these cases.</p>
|
||
<h4>Using <code>if</code> in a Binding</h4>
|
||
<p>The last detail you need to know about <code>if</code> is that it’s an expression. That
|
||
means that we can use it on the right hand side of a <code>let</code> binding, for
|
||
instance:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let condition = true;
|
||
let number = if condition {
|
||
5
|
||
} else {
|
||
6
|
||
};
|
||
|
||
println!("The value of number is: {}", number);
|
||
}
|
||
</code></pre>
|
||
<p>The <code>number</code> variable will be bound to a value based on the outcome of the <code>if</code>
|
||
expression. Let’s run this to see what happens:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling branches v0.1.0 (file:///projects/branches)
|
||
Running `target/debug/branches`
|
||
The value of number is: 5
|
||
</code></pre>
|
||
<p>Remember, blocks of code evaluate to the last expression in them, and numbers
|
||
by themselves are also expressions. In this case, the value of the whole <code>if</code>
|
||
expression depends on which block of code executes. This means the value that
|
||
results from both arms of the <code>if</code> must be the same type; in the previous
|
||
example, they were both <code>i32</code> integers. But what happens if the types are
|
||
mismatched, as in the following example?</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let condition = true;
|
||
|
||
let number = if condition {
|
||
5
|
||
} else {
|
||
"six"
|
||
};
|
||
|
||
println!("The value of number is: {}", number);
|
||
}
|
||
</code></pre>
|
||
<p>If we try to run this, we’ll get an error. The <code>if</code> and <code>else</code> arms have value
|
||
types that are incompatible, and Rust tells us exactly where to find the
|
||
problem in our program:</p>
|
||
<pre><code class="language-bash"> Compiling branches v0.1.0 (file:///projects/branches)
|
||
error[E0308]: if and else have incompatible types
|
||
--> src/main.rs:4:18
|
||
|
|
||
4 | let number = if condition {
|
||
| ^ expected integral variable, found reference
|
||
|
|
||
= note: expected type `{integer}`
|
||
= note: found type `&'static str`
|
||
|
||
error: aborting due to previous error
|
||
|
||
error: Could not compile `branches`.
|
||
</code></pre>
|
||
<p>The expression in the <code>if</code> block evaluates to an integer and the expresion in
|
||
the <code>else</code> block evaluates to a string. This can’t work, because variable
|
||
bindings must have a single type. Rust needs to know at compile time what type
|
||
the <code>number</code> binding is, definitively, so that it can verify at compile time
|
||
that its type is valid everywhere we use <code>number</code>. Rust wouldn't be able to do
|
||
that if the type of <code>number</code> was only determined at runtime; the compiler would
|
||
be more complex and be able to make fewer guarantees about our code if it had
|
||
to keep track of multiple hypothetical types for any variable binding.</p>
|
||
<h3>Repetition with Loops</h3>
|
||
<p>It’s often useful to be able to execute a block of code more than one time. For
|
||
this, Rust has several <em>loops</em>. A loop runs through the code inside the loop
|
||
body to the end and then starts immediately back at the beginning. To try out
|
||
loops, let’s make a new project called <code>loops</code>.</p>
|
||
<p>There are three kinds of loops in Rust: <code>loop</code>, <code>while</code>, and <code>for</code>. Let’s dig
|
||
in.</p>
|
||
<h4>Repeating Code with <code>loop</code></h4>
|
||
<p>The <code>loop</code> keyword tells Rust to execute a block of code over and over again
|
||
forever or until we explicitly tell it to stop.</p>
|
||
<p>For an example, change the <code>src/main.rs</code> file in your <em>loops</em> directory to look
|
||
like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
loop {
|
||
println!("again!");
|
||
}
|
||
}
|
||
</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 "again!"
|
||
printed after the <code>^C</code>, depending on where the code was in the loop when it
|
||
received the signal to halt.</p>
|
||
<p>Fortunately, Rust provides another, more reliable way to break out of a loop.
|
||
We can place the <code>break</code> keyword within the loop to tell the program when to
|
||
stop executing the loop. Recall that we did this in the guessing game in
|
||
Chapter 2 to exit the program when the user won the game by guessing the number
|
||
correctly.</p>
|
||
<h4>Conditional Loops With <code>while</code></h4>
|
||
<p>It's often useful for a program to have a condition that can be evaluated
|
||
within a loop. While the condition is true, the loop runs. When the condition
|
||
ceases to be true, we call <code>break</code>, stopping the loop. This could be
|
||
implemented with a combination of <code>loop</code>, <code>if</code>, <code>else</code>, and <code>break</code>; you could
|
||
try that now in a program, if you'd like.</p>
|
||
<p>But this pattern is so common that Rust has a more efficient language construct
|
||
for it, called a <code>while</code> loop. Here's an example using <code>while</code>: this program
|
||
loops three times, counting down each time. Finally, after the loop, it prints
|
||
another message, then exits:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let mut number = 3;
|
||
|
||
while number != 0 {
|
||
println!("{}!", number);
|
||
|
||
number = number - 1;
|
||
}
|
||
|
||
println!("LIFTOFF!!!");
|
||
}
|
||
</code></pre>
|
||
<p>This gets rid of a lot of nesting that would be necessary if we used <code>loop</code>,
|
||
<code>if</code>, <code>else</code>, and <code>break</code>, and it's more clear. While a condition holds, run
|
||
this code; otherwise, exit the loop.</p>
|
||
<h4>Looping Through a Collection with <code>for</code></h4>
|
||
<p>We could use this <code>while</code> construct to loop over the elements of a collection,
|
||
like an array. For example:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [10, 20, 30, 40, 50];
|
||
let mut index = 0;
|
||
|
||
while index < 5 {
|
||
println!("the value is: {}", 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 < 5</code>
|
||
is no longer true). Running this will print out every element of the array:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling loops v0.1.0 (file:///projects/loops)
|
||
Running `target/debug/loops`
|
||
the value is: 10
|
||
the value is: 20
|
||
the value is: 30
|
||
the value is: 40
|
||
the value is: 50
|
||
</code></pre>
|
||
<p>All five array values appear in the terminal, as expected. Even though <code>index</code>
|
||
will reach a value of <code>6</code> at some point, the loop stops executing before trying
|
||
to fetch a sixth value from the array.</p>
|
||
<p>This approach is error-prone, though; we could cause our program to panic by
|
||
getting the index length incorrect. It's also slow, as the compiler needs to
|
||
perform the conditional check on every element on every iteration through the
|
||
loop.</p>
|
||
<p>As a more efficient alternative, we can use a <code>for</code> loop and execute some code
|
||
for each item in a collection. A <code>for</code> loop looks like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let a = [10, 20, 30, 40, 50];
|
||
|
||
for element in a.iter() {
|
||
println!("the value is: {}", element);
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>If we run this, we'll see the same output as the previous example. Importantly,
|
||
though, we've now increased the safety of our code and eliminated the chance of
|
||
bugs that might result from going beyond the end of the array or not going far
|
||
enough and missing some items.</p>
|
||
<p>For example, in the previous code that uses the <code>while</code> loop, if we removed an
|
||
item from the <code>a</code> array but forgot to update the condition to <code>while index < 4</code>, our code would panic. Using the <code>for</code> loop means we would not need to
|
||
remember to change any other code if we changed the number of values in the
|
||
array.</p>
|
||
<p>If you're wondering about the <code>iter</code> code in this example, keep reading! We
|
||
will cover method syntax generally in Chapter XX and iterators specifically in
|
||
Chapter XX.</p>
|
||
<p>The safety and conciseness of <code>for</code> loops make them the most commonly used loop
|
||
construct in Rust. Even in situations where you want to run some code a certain
|
||
number of times, like our countdown example that used a <code>while</code> loop, most
|
||
Rustaceans would use a <code>for</code> loop. The way to do that would be to use a
|
||
<code>Range</code>, which is a type provided by the standard library that generates all
|
||
numbers in sequence starting from one number and ending before another number.</p>
|
||
<p>Here's what the countdown would look like with a for loop, and using another
|
||
method we haven't yet talked about, <code>rev</code>, to reverse the range:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
for number in (1..4).rev() {
|
||
println!("{}!", number);
|
||
}
|
||
println!("LIFTOFF!!!");
|
||
}
|
||
</code></pre>
|
||
<p>That's a bit nicer, isn't it?</p>
|
||
<h2>Summary</h2>
|
||
<p>You made it! That was a big chapter: we covered variable bindings, scalar and
|
||
compound data types, functions, comments, <code>if</code> expressions, and loops! If you'd
|
||
like to get some practice with the concepts in this chapter, try building
|
||
programs to do things like:</p>
|
||
<ul>
|
||
<li>Converting temperatures between Fahrenheit and Celsius.</li>
|
||
<li>Generate the nth Fibonacci number.</li>
|
||
<li>Print the lyrics to the Christmas carol <em>The Twelve Days of Christmas</em>,
|
||
taking advantage of the repetition in the song.</li>
|
||
</ul>
|
||
<p>When you're ready to move on, we'll talk about a concept in Rust that <em>doesn't</em>
|
||
commonly exist in other programming languages: ownership.</p>
|
||
<h1>Understanding Ownership</h1>
|
||
<p>Ownership is Rust's most unique feature, and enables Rust to make memory safety
|
||
guarantees without needing a garbage collector. It's therefore important to
|
||
understand how ownership works in Rust. In this chapter we'll talk about
|
||
ownership as well as several related features: borrowing, slices, and how Rust
|
||
lays things out in memory.</p>
|
||
<h2>Ownership</h2>
|
||
<p>Rust’s central feature is <em>ownership</em>. It is a feature that is straightforward
|
||
to explain, but has deep implications for the rest of the language.</p>
|
||
<p>All programs have to manage the way they use a computer's memory while running.
|
||
Some languages have garbage collection, while in others, the programmer has to
|
||
explicitly allocate and free the memory. Rust takes a third approach: memory is
|
||
managed through a system of ownership with a set of rules that the compiler
|
||
checks at compile-time. You do not pay any run-time cost for any of these
|
||
features.</p>
|
||
<p>Since ownership is a new concept for many programmers, it does take
|
||
some time to get used to. There is good news, though: the more experienced you
|
||
become with Rust and the rules of the ownership system, the more you'll be
|
||
able to naturally develop code that is both safe and efficient. Keep at it!</p>
|
||
<p>Once you understand ownership, you have a good foundation for understanding the
|
||
features that make Rust unique. In this chapter, we'll learn ownership by going
|
||
through some examples, focusing on a very common data structure: strings.</p>
|
||
<!-- PROD: START BOX -->
|
||
<h6>The Stack and the Heap</h6>
|
||
<p>In many programming languages, we don't have to think about the stack and the
|
||
heap very often. But in a systems programming language like Rust, whether a
|
||
value is on the stack or the heap has more of an effect on how the language
|
||
behaves and why we have to make certain decisions. We're going to be describing
|
||
parts of ownership in relation to the stack and the heap, so here is a brief
|
||
explanation.</p>
|
||
<p>Both the stack and the heap are parts of memory that is available to your code
|
||
to use at runtime, but they are structured in different ways. The stack stores
|
||
values in the order it gets them and removes the values in the opposite order.
|
||
This is referred to as <em>last in, first out</em>. Think of a stack of plates: when
|
||
you add more plates, you put them on top of the pile, and when you need a
|
||
plate, you take one off the top. Adding or removing plates from the middle or
|
||
bottom wouldn't work as well! Adding data is called <em>pushing onto the stack</em>
|
||
and removing data is called <em>popping off the stack</em>.</p>
|
||
<p>The stack is fast because of the way it accesses the data: it never has to look
|
||
around for a place to put new data or a place to get data from; that place is
|
||
always the top. Another property that makes the stack fast is that all data on
|
||
the stack must take up a known, fixed size.</p>
|
||
<p>For data with a size unknown to us at compile time, or a size that might
|
||
change, we can store data on the heap instead. The heap is less organized: when
|
||
we put data on the heap, we ask for some amount of space. The operating system
|
||
finds an empty spot somewhere in the heap that is big enough, marks it as being
|
||
in use, and returns to us a pointer to that location. This process is called
|
||
<em>allocating on the heap</em>, and sometimes we just say "allocating" for short.
|
||
Pushing values onto the stack is not considered allocating. Since the pointer
|
||
is a known, fixed size, we can store the pointer on the stack, but when we want
|
||
the actual data, we have to follow the pointer.</p>
|
||
<p>Think of being seated at a restaurant. When you enter, you say how many people
|
||
are in your group, and the staff finds an empty table that would fit everyone
|
||
and leads you there. If someone in your group comes late, they can ask where
|
||
you have been seated to find you.</p>
|
||
<p>Accessing data in the heap is slower because we have to follow a pointer to
|
||
get there. Allocating a large amount of space can also take time.</p>
|
||
<p>When our code calls a function, the values passed into the function (including,
|
||
potentially, pointers to data on the heap) and the function's local variables
|
||
get pushed onto the stack. When the function is over, those values get popped
|
||
off the stack.</p>
|
||
<p>Keeping track of what parts of code are using what data on the heap, minimizing
|
||
the amount of duplicate data on the heap, and cleaning up unused data on the
|
||
heap so that we don't run out of space are all problems that ownership
|
||
addresses. Once you understand ownership, you won't need to think about the
|
||
stack and the heap very often, but knowing that managing heap data is why
|
||
ownership exists can help explain why it works the way it does.</p>
|
||
<!-- PROD: END BOX -->
|
||
<h3>Ownership Rules</h3>
|
||
<p>First, let's take a look at the rules. Keep these in mind as we go through the
|
||
examples that will illustrate the rules:</p>
|
||
<blockquote>
|
||
<ol>
|
||
<li>Each value in Rust has a variable binding that’s called its <em>owner</em>.</li>
|
||
<li>There can only be one owner at a time.</li>
|
||
<li>When the owner goes out of scope, the value will be dropped.</li>
|
||
</ol>
|
||
</blockquote>
|
||
<h3>Variable Binding Scope</h3>
|
||
<p>We've walked through an example of a Rust program already in the tutorial
|
||
chapter. Now that we’re past basic syntax, we won’t include all of the <code>fn main() {</code> stuff in examples, so if you’re following along, you will have to put
|
||
the following examples inside of a <code>main</code> function yourself. This lets our
|
||
examples be a bit more concise, letting us focus on the actual details rather
|
||
than boilerplate.</p>
|
||
<p>As a first example of ownership, we'll look at the <em>scope</em> of some variable
|
||
bindings. A scope is the range within a program for which an item is valid.
|
||
Let's say we have a variable binding that looks like this:</p>
|
||
<pre><code class="language-rust">let s = "hello";
|
||
</code></pre>
|
||
<p>The variable binding <code>s</code> refers to a string literal, where the value of the
|
||
string is hard coded into the text of our program. The binding is valid from
|
||
the point at which it’s declared until the end of the current <em>scope</em>. That is:</p>
|
||
<pre><code class="language-rust">{ // s is not valid here, it’s not yet declared
|
||
let s = "hello"; // s is valid from this point forward
|
||
|
||
// do stuff with s
|
||
} // this scope is now over, and s is no longer valid
|
||
</code></pre>
|
||
<p>In other words, there are two important points in time here:</p>
|
||
<ul>
|
||
<li>When <code>s</code> comes <em>into scope</em>, it is valid.</li>
|
||
<li>It remains so until it <em>goes out of scope</em>.</li>
|
||
</ul>
|
||
<p>At this point, things are similar to other programming languages. Now let’s
|
||
build on top of this understanding by introducing the <code>String</code> type.</p>
|
||
<h3>The <code>String</code> Type</h3>
|
||
<p>In order to illustrate the rules of ownership, we need a data type that is more
|
||
complex than the ones we covered in Chapter 3. All of the data types we've
|
||
looked at previously are stored on the stack and popped off the stack when
|
||
their scope is over, but we want to look at data that is stored on the heap and
|
||
explore how Rust knows when to clean that data up.</p>
|
||
<p>We're going to use <code>String</code> as the example here and concentrate on the parts of
|
||
<code>String</code> that relate to ownership. These aspects also apply to other complex
|
||
data types provided by the standard library and that you create. We'll go into
|
||
more depth about <code>String</code> specifically in Chapter XX.</p>
|
||
<p>We've already seen string literals, where a string value is hard-coded into our
|
||
program. String literals are convenient, but they aren’t always suitable for
|
||
every situation you want to use text. For one thing, they’re immutable. For
|
||
another, not every string value can be known when we write our code: what if we
|
||
want to take user input and store it?</p>
|
||
<p>For things like this, Rust has a second string type, <code>String</code>. This type is
|
||
allocated on the heap, and as such, is able to store an amount of text that is
|
||
unknown to us at compile time. You can create a <code>String</code> from a string literal
|
||
using the <code>from</code> function, like so:</p>
|
||
<pre><code class="language-rust">let s = String::from("hello");
|
||
</code></pre>
|
||
<p>The double colon (<code>::</code>) is an operator that allows us to namespace this
|
||
particular <code>from</code> function under the <code>String</code> type itself, rather than using
|
||
some sort of name like <code>string_from</code>. We’ll discuss this syntax more in the
|
||
“Method Syntax” and “Modules” chapters.</p>
|
||
<p>This kind of string <em>can</em> be mutated:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("hello");
|
||
|
||
s.push_str(", world!"); // push_str() appends a literal to a String
|
||
|
||
println!("{}", s); // This will print `hello, world!`
|
||
</code></pre>
|
||
<p>So, what’s the difference here? Why can <code>String</code> be mutated, but literals
|
||
cannot? The difference comes down to how these two types deal with memory.</p>
|
||
<h3>Memory and Allocation</h3>
|
||
<p>In the case of a string literal, because we know the contents at compile time,
|
||
the text is hard-coded directly into the final executable. This makes string
|
||
literals quite fast and efficient. But these properties only come from its
|
||
immutability. Unfortunately, we can’t put a blob of memory into the binary for
|
||
each piece of text whose size is unknown at compile time and whose size might
|
||
change over the course of running the program.</p>
|
||
<p>With the <code>String</code> type, in order to support a mutable, growable piece of text,
|
||
we need to allocate an amount of memory on the heap, unknown at compile time,
|
||
to hold the contents. This means two things:</p>
|
||
<ol>
|
||
<li>The memory must be requested from the operating system at runtime.</li>
|
||
<li>We need a way of giving this memory back to the operating system when we’re
|
||
done with our <code>String</code>.</li>
|
||
</ol>
|
||
<p>That first part is done by us: when we call <code>String::from</code>, its
|
||
implementation requests the memory it needs. This is pretty much universal in
|
||
programming languages.</p>
|
||
<p>The second case, however, is different. In languages with a <em>garbage collector</em>
|
||
(GC), the GC will keep track and clean up memory that isn't being used anymore,
|
||
and we, as the programmer, don’t need to think about it. Without GC, it’s the
|
||
programmer's responsibility to identify when memory is no longer being used and
|
||
call code to explicitly return it, just as we did to request it. Doing this
|
||
correctly has historically been a difficult problem in programming. If we
|
||
forget, we will waste memory. If we do it too early, we will have an invalid
|
||
variable. If we do it twice, that’s a bug too. We need to pair exactly one
|
||
<code>allocate</code> with exactly one <code>free</code>.</p>
|
||
<p>Rust takes a different path: the memory is automatically returned once the
|
||
binding to it goes out of scope. Here’s a version of our scope example from
|
||
earlier using <code>String</code>:</p>
|
||
<pre><code class="language-rust">{
|
||
let s = String::from("hello"); // s is valid from this point forward
|
||
|
||
// do stuff with s
|
||
} // this scope is now over, and s is no longer valid
|
||
</code></pre>
|
||
<p>There is a natural point at which we can return the memory our <code>String</code> needs
|
||
back to the operating system: when <code>s</code> goes out of scope. When a variable
|
||
binding goes out of scope, Rust calls a special function for us. This function
|
||
is called <code>drop</code>, and it is where the author of <code>String</code> can put the code to
|
||
return the memory. Rust calls <code>drop</code> automatically at the closing <code>}</code>.</p>
|
||
<blockquote>
|
||
<p>Note: This pattern is sometimes called *Resource Acquisition Is
|
||
Initialization* in C++, or RAII for short. While they are very similar,
|
||
Rust’s take on this concept has a number of differences, so we don’t tend
|
||
to use the same term. If you’re familiar with this idea, keep in mind that it
|
||
is <em>roughly</em> similar in Rust, but not identical.</p>
|
||
</blockquote>
|
||
<p>This pattern has a profound impact on the way that Rust code is written. It may
|
||
seem simple right now, but things can get tricky in more advanced situations
|
||
when we want to have multiple variable bindings use the data that we have
|
||
allocated on the heap. Let’s go over some of those situations now.</p>
|
||
<h4>Ways Bindings and Data Interact: Move</h4>
|
||
<p>There are different ways that multiple bindings can interact with the same data
|
||
in Rust. Let's take an example using an integer:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
let y = x;
|
||
</code></pre>
|
||
<p>We can probably guess what this is doing based on our experience with other
|
||
languages: “Bind the value <code>5</code> to <code>x</code>, then make a copy of the value in <code>x</code> and
|
||
bind it to <code>y</code>.” We now have two bindings, <code>x</code> and <code>y</code>, and both equal <code>5</code>.
|
||
This is indeed what is happening since integers are simple values with a known,
|
||
fixed size, and these two <code>5</code> values are pushed onto the stack.</p>
|
||
<p>Now let’s look at the <code>String</code> version:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("hello");
|
||
let s2 = s1;
|
||
</code></pre>
|
||
<p>This looks very similar to the previous code, so we might assume that the way
|
||
it works would be the same: that the second line would make a copy of the value
|
||
in <code>s1</code> and bind it to <code>s2</code>. This isn't quite what happens.</p>
|
||
<p>To explain this more thoroughly, let’s take a look at what <code>String</code> looks like
|
||
under the covers in Figure 4-1. A <code>String</code> is made up of three parts, shown on
|
||
the left: a pointer to the memory that holds the contents of the string, a
|
||
length, and a capacity. This group of data is stored on the stack. On the right
|
||
is the memory that holds the contents, and this is on the heap.</p>
|
||
<p><img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" /></p>
|
||
<p>Figure 4-1: Representation in memory of a <code>String</code> holding the value "hello"
|
||
bound to <code>s1</code></p>
|
||
<p>The length is how much memory, in bytes, the contents of the <code>String</code> is
|
||
currently using. The capacity is the total amount of memory, in bytes, that the
|
||
<code>String</code> has gotten from the operating system. The difference between length
|
||
and capacity matters but not in this context, so for now, it's fine to ignore
|
||
the capacity.</p>
|
||
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> data itself is copied, meaning we
|
||
copy the pointer, the length, and the capacity that are on the stack. We do not
|
||
copy the data on the heap that the <code>String</code>'s pointer refers to. In other
|
||
words, it looks like figure 4-2.</p>
|
||
<p><img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" /></p>
|
||
<p>Figure 4-2: Representation in memory of the binding <code>s2</code> that has a copy of
|
||
<code>s1</code>'s pointer, length and capacity</p>
|
||
<p>And <em>not</em> Figure 4-3, which is what memory would look like if Rust instead
|
||
copied the heap data as well. If Rust did this, the operation <code>s2 = s1</code> could
|
||
potentially be very expensive if the data on the heap was large.</p>
|
||
<p><img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" /></p>
|
||
<p>Figure 4-3: Another possibility for what <code>s2 = s1</code> might do, if Rust chose to
|
||
copy heap data as well.</p>
|
||
<p>Earlier, we said that when a binding goes out of scope, Rust will automatically
|
||
call the <code>drop</code> function and clean up the heap memory for that binding. But
|
||
in figure 4-2, we see both data pointers pointing to the same location. This is
|
||
a problem: when <code>s2</code> and <code>s1</code> go out of scope, they will both try to free the
|
||
same memory. This is known as a <em>double free</em> error and is one of the memory
|
||
safety bugs we mentioned before. Freeing memory twice can lead to memory
|
||
corruption, which can potentially lead to security vulnerabilities.</p>
|
||
<p>In order to ensure memory safety, there's one more detail to what happens in
|
||
this situation in Rust. Instead of trying to copy the allocated memory, Rust
|
||
says that <code>s1</code> is no longer valid and, therefore, doesn’t need to free anything
|
||
when it goes out of scope. Check out what happens when you try to use <code>s1</code>
|
||
after <code>s2</code> is created:</p>
|
||
<pre><code class="language-rust,ignore">let s1 = String::from("hello");
|
||
let s2 = s1;
|
||
|
||
println!("{}", 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!("{}", s1);
|
||
^~
|
||
5:24 note: in this expansion of println! (defined in <std macros>)
|
||
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default
|
||
let s2 = s1;
|
||
^~
|
||
</code></pre>
|
||
<p>If you have heard the terms "shallow copy" and "deep copy" while working with
|
||
other languages, the concept of copying the pointer, length, and capacity
|
||
without copying the data probably sounds like a shallow copy. But because Rust
|
||
also invalidates the first binding, instead of calling this a shallow copy,
|
||
it's known as a <em>move</em>. Here we would read this by saying that <code>s1</code> was <em>moved</em>
|
||
into <code>s2</code>. So what actually happens looks like Figure 4-4.</p>
|
||
<p><img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" /></p>
|
||
<p>Figure 4-4: Representation in memory after <code>s1</code> has been invalidated</p>
|
||
<p>That solves our problem! With only <code>s2</code> valid, when it goes out of scope, it
|
||
alone will free the memory, and we’re done.</p>
|
||
<p>Furthermore, there’s a design choice that’s implied by this: Rust will never
|
||
automatically create "deep" copies of your data. Therefore, any <em>automatic</em>
|
||
copying can be assumed to be inexpensive.</p>
|
||
<h4>Ways Bindings and Data Interact: Clone</h4>
|
||
<p>If we <em>do</em> want to deeply copy the <code>String</code>’s data and not just the <code>String</code>
|
||
itself, there’s a common method for that: <code>clone</code>. We will discuss methods in
|
||
the section on <a href="ch05-01-structs.html"><code>structs</code> in Chapter XX</a><!-- ignore -->, but they’re a
|
||
common enough feature in many programming languages that you have probably seen
|
||
them before.</p>
|
||
<p>Here’s an example of the <code>clone</code> method in action:</p>
|
||
<pre><code class="language-rust">let s1 = String::from("hello");
|
||
let s2 = s1.clone();
|
||
|
||
println!("s1 = {}, s2 = {}", s1, s2);
|
||
</code></pre>
|
||
<p>This will work just fine, and this is how you can explicitly get the behavior
|
||
we showed in Figure 4-3, where the heap data <em>does</em> get copied.</p>
|
||
<p>When you see a call to <code>clone</code>, you know that some arbitrary code is being
|
||
executed, and that code may be expensive. It’s a visual indicator that something
|
||
different is going on here.</p>
|
||
<h4>Stack-only Data: Copy</h4>
|
||
<p>There’s another wrinkle we haven’t talked about yet. This code, that we showed
|
||
earlier, works and is valid:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
let y = x;
|
||
|
||
println!("x = {}, y = {}", x, y);
|
||
</code></pre>
|
||
<p>This seems to contradict what we just learned: we don't have a call to
|
||
<code>clone</code>, but <code>x</code> is still valid, and wasn't moved into <code>y</code>.</p>
|
||
<p>This is because types like integers that have a known size at compile time are
|
||
stored entirely on the stack, so copies of the actual values are quick to make.
|
||
That means there's no reason we would want to prevent <code>x</code> from being valid
|
||
after we create the binding <code>y</code>. In other words, there’s no difference between
|
||
deep and shallow copying here, so calling <code>clone</code> wouldn’t do anything
|
||
differently from the usual shallow copying and we can leave it out.</p>
|
||
<p>Rust has a special annotation called the <code>Copy</code> trait that we can place on
|
||
types like these (we'll talk more about traits in Chapter XX). If a type has
|
||
the <code>Copy</code> trait, an older binding is still usable after assignment. Rust will
|
||
not let us annotate a type with the <code>Copy</code> trait if the type, or any of its
|
||
parts, has implemented <code>drop</code>. If the type needs something special to happen
|
||
when the value goes out of scope and we add the <code>Copy</code> annotation to that type,
|
||
we will get a compile-time error.</p>
|
||
<p>So what types are <code>Copy</code>? You can check the documentation for the given type to
|
||
be sure, but as a rule of thumb, any group of simple scalar values can be Copy,
|
||
and nothing that requires allocation or is some form of resource is <code>Copy</code>.
|
||
Here’s some of the types that are <code>Copy</code>:</p>
|
||
<ul>
|
||
<li>All of the integer types, like <code>u32</code>.</li>
|
||
<li>The booleans, <code>true</code> and <code>false</code>.</li>
|
||
<li>All of the floating point types, like <code>f64</code>.</li>
|
||
<li>Tuples, but only if they contain types which are also <code>Copy</code>. <code>(i32, i32)</code>
|
||
is <code>Copy</code>, but <code>(i32, String)</code> is not.</li>
|
||
</ul>
|
||
<h3>Ownership and Functions</h3>
|
||
<p>The semantics for passing a value to a function are similar to assigning a
|
||
value to a binding. Passing a binding to a function will move or copy, just
|
||
like assignment. Here’s an example, with some annotations showing where bindings
|
||
go into and out of scope:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let s = String::from("hello"); // s comes into scope.
|
||
|
||
takes_ownership(s); // s's value moves into the function...
|
||
// ... and so is no longer valid here.
|
||
let x = 5; // x comes into scope.
|
||
|
||
makes_copy(x); // x would move into the function,
|
||
// but i32 is Copy, so it’s okay to still
|
||
// use x afterward.
|
||
|
||
} // Here, x goes out of scope, then s. But since s's value was moved, nothing
|
||
// special happens.
|
||
|
||
fn takes_ownership(some_string: String) { // some_string comes into scope.
|
||
println!("{}", some_string);
|
||
} // Here, some_string goes out of scope and `drop` is called. The backing
|
||
// memory is freed.
|
||
|
||
fn makes_copy(some_integer: i32) { // some_integer comes into scope.
|
||
println!("{}", some_integer);
|
||
} // Here, some_integer goes out of scope. Nothing special happens.
|
||
</code></pre>
|
||
<p>If we tried to use <code>s</code> after the call to <code>takes_ownership</code>, Rust
|
||
would throw a compile-time error. These static checks protect us from mistakes.
|
||
Try adding code to <code>main</code> that uses <code>s</code> and <code>x</code> to see where you can use them
|
||
and where the ownership rules prevent you from doing so.</p>
|
||
<h3>Return Values and Scope</h3>
|
||
<p>Returning values can also transfer ownership. Here's an example with similar annotations:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let s1 = gives_ownership(); // gives_ownership moves its return
|
||
// value into s1.
|
||
|
||
let s2 = String::from("hello"); // s2 comes into scope
|
||
|
||
let s3 = takes_and_gives_back(s2); // s2 is moved into
|
||
// takes_and_gives_back, which also
|
||
// moves its return value into s3.
|
||
} // Here, s3 goes out of scope, and is dropped. s2 goes out of scope, but was
|
||
// moved, so nothing happens. s1 goes out of scope, and is dropped.
|
||
|
||
fn gives_ownership() -> String { // gives_ownership will move its
|
||
// return value into the function
|
||
// that calls it.
|
||
|
||
let some_string = String::from("hello"); // some_string comes into scope.
|
||
|
||
some_string // some_string is returned, and
|
||
// moves out to the calling
|
||
// function.
|
||
}
|
||
|
||
// takes_and_gives_back will both take a String and return one
|
||
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into scope
|
||
|
||
a_string // a_string is returned, and moves out to the calling function
|
||
}
|
||
</code></pre>
|
||
<p>It’s the same pattern, every time: assigning a value to another binding moves
|
||
it, and when heap data values' bindings go out of scope, if the data hasn’t
|
||
been moved to be owned by another binding, the value will be cleaned up by
|
||
<code>drop</code>.</p>
|
||
<p>Taking ownership then returning ownership with every function is a bit tedious.
|
||
What if we want to let a function use a value but not take ownership? It’s
|
||
quite annoying that anything we pass in also needs to be passed back if we want
|
||
to use it again, in addition to any data resulting from the body of the
|
||
function that we might want to return as well.</p>
|
||
<p>It is possible to return multiple values using a tuple, like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let s1 = String::from("hello");
|
||
|
||
let (s2, len) = calculate_length(s1);
|
||
|
||
println!("The length of '{}' is {}.", s2, len);
|
||
}
|
||
|
||
fn calculate_length(s: String) -> (String, usize) {
|
||
let length = s.len(); // len() returns the length of a String.
|
||
|
||
(s, length)
|
||
}
|
||
</code></pre>
|
||
<p>But this is too much ceremony and a lot of work for a concept that should be
|
||
common. Luckily for us, Rust has a feature for this concept: references.</p>
|
||
<h2>References and Borrowing</h2>
|
||
<p>The issue with the tuple code at the end of the last section is that we have to
|
||
return the <code>String</code> back to the calling function so that we can still use the
|
||
<code>String</code> after the call to <code>calculate_length</code>, since the <code>String</code> was moved
|
||
into <code>calculate_length</code>.</p>
|
||
<p>Here is how you would use a function without taking ownership of it using
|
||
<em>references:</em></p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let s1 = String::from("hello");
|
||
|
||
let len = calculate_length(&s1);
|
||
|
||
println!("The length of '{}' is {}.", s1, len);
|
||
}
|
||
|
||
fn calculate_length(s: &String) -> 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>&s1</code> into
|
||
<code>calculate_length</code>, and in its definition, we take <code>&String</code> rather than
|
||
<code>String</code>.</p>
|
||
<p>These <code>&</code>s are <em>references</em>, and they allow you to refer to some value
|
||
without taking ownership of it. Figure 4-5 shows a diagram of this.</p>
|
||
<p><img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" /></p>
|
||
<p>Figure 4-5: <code>&String s</code> pointing at <code>String s1</code></p>
|
||
<p>Let’s take a closer look at the function call here:</p>
|
||
<pre><code class="language-rust"># fn calculate_length(s: &String) -> usize {
|
||
# let length = s.len();
|
||
#
|
||
# length
|
||
# }
|
||
let s1 = String::from("hello");
|
||
|
||
let len = calculate_length(&s1);
|
||
</code></pre>
|
||
<p>The <code>&s1</code> syntax lets us create a reference which <em>refers</em> to the value of <code>s1</code>
|
||
but does not own it. Because it does not own it, the value it points to will
|
||
not be dropped when the reference goes out of scope.</p>
|
||
<p>Likewise, the signature of the function uses <code>&</code> to indicate that it takes
|
||
a reference as an argument. Let’s add some explanatory annotations:</p>
|
||
<pre><code class="language-rust">fn calculate_length(s: &String) -> usize { // s is a reference to a String
|
||
let length = s.len();
|
||
|
||
length
|
||
} // Here, s goes out of scope. But since it does not have ownership of what
|
||
// it refers to, nothing happens.
|
||
</code></pre>
|
||
<p>It’s the same process as before, but we don’t drop what the reference points to
|
||
when it goes out of scope because we don't have ownership. This lets us write
|
||
functions which take references as arguments instead of the values themselves,
|
||
so that we won’t need to return them to give back ownership.</p>
|
||
<p>We call this process <em>borrowing</em>. Just like with real life, if a person owns
|
||
something, you can borrow it from them, and when you’re done, you have to give
|
||
it back.</p>
|
||
<p>So what happens if we try to modify something we're borrowing? Try this code
|
||
out. Spoiler alert: it doesn’t work!</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let s = String::from("hello");
|
||
|
||
change(&s);
|
||
}
|
||
|
||
fn change(some_string: &String) {
|
||
some_string.push_str(", world");
|
||
}
|
||
</code></pre>
|
||
<p>Here’s the error:</p>
|
||
<pre><code class="language-bash">error: cannot borrow immutable borrowed content `*some_string` as mutable
|
||
--> error.rs:8:5
|
||
|
|
||
8 | some_string.push_str(", world");
|
||
| ^^^^^^^^^^^
|
||
</code></pre>
|
||
<p>Just as bindings are immutable by default, so are references. We’re not allowed
|
||
to modify something we have a reference to.</p>
|
||
<h3>Mutable References</h3>
|
||
<p>We can fix this error with just a small tweak:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let mut s = String::from("hello");
|
||
|
||
change(&mut s);
|
||
}
|
||
|
||
fn change(some_string: &mut String) {
|
||
some_string.push_str(", world");
|
||
}
|
||
</code></pre>
|
||
<p>First, we had to change <code>s</code> to be <code>mut</code>. Then we had to create a mutable
|
||
reference with <code>&mut s</code> and accept a mutable reference with <code>some_string: &mut String</code>.</p>
|
||
<p>Mutable references have one big restriction, though: you can only have one
|
||
mutable reference to a particular piece of data in a particular scope. This
|
||
code will fail:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">let mut s = String::from("hello");
|
||
|
||
let r1 = &mut s;
|
||
let r2 = &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
|
||
--> borrow_twice.rs:5:19
|
||
|
|
||
4 | let r1 = &mut s;
|
||
| - first mutable borrow occurs here
|
||
5 | let r2 = &mut s;
|
||
| ^ second mutable borrow occurs here
|
||
6 | }
|
||
| - first borrow ends here
|
||
</code></pre>
|
||
<p>This restriction allows for mutation but in a very controlled fashion. It is
|
||
something that new Rustaceans struggle with, because most languages let you
|
||
mutate whenever you’d like. The benefit of having this restriction is that Rust
|
||
can prevent data races at compile time. A <em>data race</em> is a particular type of
|
||
race condition where two or more pointers access the same data at the same
|
||
time, at least one of the pointers is being used to write to the data, and
|
||
there's no mechanism being used to synchronize access to the data. Data races
|
||
cause undefined behavior and can be difficult to diagnose and fix when trying
|
||
to track them down at runtime; Rust prevents this problem from happening since
|
||
it won't even compile code with data races!</p>
|
||
<p>As always, we can use <code>{}</code>s to create a new scope, allowing for multiple mutable
|
||
references, just not <em>simultaneous</em> ones:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("hello");
|
||
|
||
{
|
||
let r1 = &mut s;
|
||
|
||
} // r1 goes out of scope here, so we can make a new reference with no problems.
|
||
|
||
let r2 = &mut s;
|
||
</code></pre>
|
||
<p>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("hello");
|
||
|
||
let r1 = &s; // no problem
|
||
let r2 = &s; // no problem
|
||
let r3 = &mut s; // BIG PROBLEM
|
||
</code></pre>
|
||
<p>Here’s the error:</p>
|
||
<pre><code class="language-bash">error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
|
||
--> borrow_thrice.rs:6:19
|
||
|
|
||
4 | let r1 = &s; // no problem
|
||
| - immutable borrow occurs here
|
||
5 | let r2 = &s; // no problem
|
||
6 | let r3 = &mut s; // BIG PROBLEM
|
||
| ^ mutable borrow occurs here
|
||
7 | }
|
||
| - immutable borrow ends here
|
||
</code></pre>
|
||
<p>Whew! We <em>also</em> cannot have a mutable reference while we have an immutable one.
|
||
Users of an immutable reference don’t expect the values to suddenly change out
|
||
from under them! Multiple immutable references are okay, however, since no one
|
||
who is just reading the data has the ability to affect anyone else's reading of
|
||
the data.</p>
|
||
<p>Even though these errors may be frustrating at times, remember that it's the
|
||
Rust compiler pointing out a potential bug earlier (at compile time rather than
|
||
at runtime) and showing you exactly where the problem is instead of you having
|
||
to track down why sometimes your data isn't what you thought it should be.</p>
|
||
<h3>Dangling References</h3>
|
||
<p>In languages with pointers, it's easy to make the error of creating a <em>dangling
|
||
pointer</em>, a pointer referencing a location in memory that may have been given
|
||
to someone else, by freeing some memory while keeping around a pointer to that
|
||
memory. In Rust, by contrast, the compiler guarantees that references will
|
||
never be dangling: if we have a reference to some data, the compiler will
|
||
ensure that the data will not go out of scope before the reference to the data
|
||
does.</p>
|
||
<p>Let’s try to create a dangling reference:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let reference_to_nothing = dangle();
|
||
}
|
||
|
||
fn dangle() -> &String {
|
||
let s = String::from("hello");
|
||
|
||
&s
|
||
}
|
||
</code></pre>
|
||
<p>Here’s the error:</p>
|
||
<pre><code class="language-bash">error[E0106]: missing lifetime specifier
|
||
--> dangle.rs:5:16
|
||
|
|
||
5 | fn dangle() -> &String {
|
||
| ^^^^^^^
|
||
|
|
||
= help: this function's return type contains a borrowed value, but there is no
|
||
value for it to be borrowed from
|
||
= help: consider giving it a 'static lifetime
|
||
|
||
error: aborting due to previous error
|
||
</code></pre>
|
||
<p>This error message refers to a feature we haven’t learned about yet:
|
||
<em>lifetimes</em>. We'll discuss lifetimes in detail in Chapter XX, but, disregarding
|
||
the parts about lifetimes, the message does contain the key to why this code is
|
||
a problem: <code>this function’s return type contains a borrowed value, but there is no value for it to be borrowed from</code>.</p>
|
||
<p>Let’s have a closer look at exactly what's happenening at each stage of our
|
||
<code>dangle</code> code:</p>
|
||
<pre><code class="language-rust,ignore">fn dangle() -> &String { // dangle returns a reference to a String
|
||
|
||
let s = String::from("hello"); // s is a new String
|
||
|
||
&s // we return a reference to the String, s
|
||
} // Here, s goes out of scope, and is dropped. Its memory goes away.
|
||
// Danger!
|
||
</code></pre>
|
||
<p>Because <code>s</code> is created inside 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() -> String {
|
||
let s = String::from("hello");
|
||
|
||
s
|
||
}
|
||
</code></pre>
|
||
<p>This works, no problem. Ownership is moved out, nothing is deallocated.</p>
|
||
<h3>The Rules of References</h3>
|
||
<p>Here’s a recap of what we’ve talked about:</p>
|
||
<ol>
|
||
<li>At any given time, you may have <em>either</em>, but not both of:
|
||
<ol>
|
||
<li>One mutable reference.</li>
|
||
<li>Any number of immutable references.</li>
|
||
</ol>
|
||
</li>
|
||
<li>References must always be valid.</li>
|
||
</ol>
|
||
<p>Next, let's look at a different kind of reference: slices.</p>
|
||
<h2>Slices</h2>
|
||
<p>There is another data type which does not have ownership: slices. Slices let
|
||
you reference a contiguous sequence of elements in a collection rather than the
|
||
whole collection itself.</p>
|
||
<p>Here’s a small programming problem: write a function which takes a string and
|
||
returns the first word it finds in that string. If it doesn’t find a space in
|
||
the string, it means the whole string is one word, so the whole thing should be
|
||
returned.</p>
|
||
<p>Let’s think about the signature of this function:</p>
|
||
<pre><code class="language-rust,ignore">fn first_word(s: &String) -> ?
|
||
</code></pre>
|
||
<p>This function, <code>first_word</code>, takes a <code>&String</code> as an argument. We don’t want
|
||
ownership, so this is fine. But what should we return? We don’t really have a
|
||
way to talk about <em>part</em> of a string. We could return the index of the end of
|
||
the word, though. Let’s try that:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn first_word(s: &String) -> usize {
|
||
let bytes = s.as_bytes();
|
||
|
||
for (i, &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, &item) in bytes.iter().enumerate() {
|
||
</code></pre>
|
||
<p>We will be discussing iterators in more detail in Chapter XX, but for now, know
|
||
that <code>iter</code> is a method that returns each element in a collection, and
|
||
<code>enumerate</code> modifies the result of <code>iter</code> and returns each element as part
|
||
of a tuple instead, where the first element of the tuple is the index, and the
|
||
second element is a reference to the element itself. This is a bit nicer than
|
||
calculating the index ourselves.</p>
|
||
<p>Since it’s a tuple, we can use patterns, just like elsewhere in Rust. So we
|
||
match against the tuple with <code>i</code> for the index and <code>&item</code> for a single byte.
|
||
Since we get a reference from <code>.iter().enumerate()</code>, we use <code>&</code> in the pattern.</p>
|
||
<pre><code class="language-rust,ignore"> if item == b' ' {
|
||
return i;
|
||
}
|
||
}
|
||
s.len()
|
||
</code></pre>
|
||
<p>We search for the byte that represents the space, using the byte literal
|
||
syntax. If we find a space, we return the position. Otherwise, we return the
|
||
length of the string, using <code>s.len()</code>.</p>
|
||
<p>We now have a way to find out the index of the end of the first word in the
|
||
string, but there’s a problem. We’re returning a <code>usize</code> on its own, but it’s
|
||
only a meaningful number in the context of the <code>&String</code>. In other words,
|
||
because it’s a separate value from the <code>String</code>, there’s no guarantee that it
|
||
will still be valid in the future. Consider this program that uses this
|
||
<code>first_word</code> function:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust"># fn first_word(s: &String) -> usize {
|
||
# let bytes = s.as_bytes();
|
||
#
|
||
# for (i, &item) in bytes.iter().enumerate() {
|
||
# if item == b' ' {
|
||
# return i;
|
||
# }
|
||
# }
|
||
#
|
||
# s.len()
|
||
# }
|
||
#
|
||
fn main() {
|
||
let mut s = String::from("hello world");
|
||
|
||
let word = first_word(&s); // word will get the value 5.
|
||
|
||
s.clear(); // This empties the String, making it equal to "".
|
||
|
||
// word still has the value 5 here, but there's no more string that
|
||
// we could meaningfully use the value 5 with. word is now totally invalid!
|
||
}
|
||
</code></pre>
|
||
<p>This program compiles without any errors, and also would if we used <code>word</code>
|
||
after calling <code>s.clear()</code>. <code>word</code> isn't connected to the state of <code>s</code> at all,
|
||
so <code>word</code> still contains the value <code>5</code>. We could use that <code>5</code> with <code>s</code> to try
|
||
to extract the first word out, but this would be a bug since the contents of
|
||
<code>s</code> have changed since we saved <code>5</code> in <code>word</code>.</p>
|
||
<p>This is bad! It’s even worse if we wanted to write a <code>second_word</code>
|
||
function. Its signature would have to look like this:</p>
|
||
<pre><code class="language-rust,ignore">fn second_word(s: &String) -> (usize, usize) {
|
||
</code></pre>
|
||
<p>Now we’re tracking both a start <em>and</em> an ending index, and we have even more
|
||
values that were calculated from data in a particular state but aren't tied to
|
||
that state at all. We now have three unrelated variable bindings floating
|
||
around which need to be kept in sync.</p>
|
||
<p>Luckily, Rust has a solution to this problem: string slices.</p>
|
||
<h3>String Slices</h3>
|
||
<p>A string slice is a reference to part of a <code>String</code>, and looks like this:</p>
|
||
<pre><code class="language-rust">let s = String::from("hello world");
|
||
|
||
let hello = &s[0..5];
|
||
let world = &s[6..11];
|
||
</code></pre>
|
||
<p>This is similar to taking a reference to the whole <code>String</code>, but with the
|
||
extra <code>[0..5]</code> bit. Rather than a reference to the entire <code>String</code>, it’s a
|
||
reference to an internal position in the <code>String</code> and the number of elements
|
||
that it refers to.</p>
|
||
<p>We create slices with a range of <code>[starting_index..ending_index]</code>, but the
|
||
slice data structure actually stores the starting position and the length of the
|
||
slice. So in the case of <code>let world = &s[6..11];</code>, <code>world</code> would be a slice that
|
||
contains a pointer to the 6th byte of <code>s</code> and a length value of 5.</p>
|
||
<p>Figure 4-6 shows this in a diagram:</p>
|
||
<p><img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" /></p>
|
||
<p>Figure 4-6: Two string slices referring to parts of a <code>String</code></p>
|
||
<p>With Rust’s <code>..</code> range syntax, if you want to start at the first index (zero),
|
||
you can drop the value before the <code>..</code>. In other words, these are equal:</p>
|
||
<pre><code class="language-rust">let s = String::from("hello");
|
||
|
||
let slice = &s[0..2];
|
||
let slice = &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("hello");
|
||
|
||
let len = s.len();
|
||
|
||
let slice = &s[3..len];
|
||
let slice = &s[3..];
|
||
</code></pre>
|
||
<p>You can also drop both values to take a slice of the entire string. So these
|
||
are equal:</p>
|
||
<pre><code class="language-rust">let s = String::from("hello");
|
||
|
||
let len = s.len();
|
||
|
||
let slice = &s[0..len];
|
||
let slice = &s[..];
|
||
</code></pre>
|
||
<p>With this in mind, let’s re-write <code>first_word</code> to return a slice. The type
|
||
that signifies "string slice" is written as <code>&str</code>:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn first_word(s: &String) -> &str {
|
||
let bytes = s.as_bytes();
|
||
|
||
for (i, &item) in bytes.iter().enumerate() {
|
||
if item == b' ' {
|
||
return &s[0..i];
|
||
}
|
||
}
|
||
|
||
&s[..]
|
||
}
|
||
</code></pre>
|
||
<p>We get the index for the end of the word in the same way as before, by looking
|
||
for the first occurrence of a space. When we find a space, we return a string
|
||
slice using the start of the string and the index of the space as the starting
|
||
and ending indices.</p>
|
||
<p>Now when we call <code>first_word</code>, we get back a single value that is tied to the
|
||
underlying data. The value is made up of a reference to the starting point of
|
||
the slice and the number of elements in the slice.</p>
|
||
<p>Returning a slice would also work for a <code>second_word</code> function:</p>
|
||
<pre><code class="language-rust,ignore">fn second_word(s: &String) -> &str {
|
||
</code></pre>
|
||
<p>We now have a straightforward API that’s much harder to mess up. Remember our
|
||
bug from before, when we got the first word but then cleared the string so that
|
||
our first word was invalid? That code was logically incorrect but didn't show
|
||
any immediate errors. The problems would show up later, if we kept trying to
|
||
use the first word index with an emptied string. Slices make this bug
|
||
impossible, and let us know we have a problem with our code much sooner. Using
|
||
the slice version of <code>first_word</code> will throw a compile time error:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">fn main() {
|
||
let mut s = String::from("hello world");
|
||
|
||
let word = first_word(&s);
|
||
|
||
s.clear(); // Error!
|
||
}
|
||
</code></pre>
|
||
<p>Here’s the compiler error:</p>
|
||
<pre><code class="language-bash">17:6 error: cannot borrow `s` as mutable because it is also borrowed as
|
||
immutable [E0502]
|
||
s.clear(); // Error!
|
||
^
|
||
15:29 note: previous borrow of `s` occurs here; the immutable borrow prevents
|
||
subsequent moves or mutable borrows of `s` until the borrow ends
|
||
let word = first_word(&s);
|
||
^
|
||
18:2 note: previous borrow ends here
|
||
fn main() {
|
||
|
||
}
|
||
^
|
||
</code></pre>
|
||
<p>Remember from the borrowing rules that if we have an immutable reference to
|
||
something, we cannot also take a mutable reference. Since <code>clear</code> needs to
|
||
truncate the <code>String</code>, it tries to take a mutable reference, which fails. Not
|
||
only has Rust made our API easier to use, but it’s also eliminated an entire
|
||
class of errors at compile time!</p>
|
||
<h4>String Literals are Slices</h4>
|
||
<p>Remember how we talked about string literals being stored inside of the binary
|
||
itself? Now that we know about slices, we can now properly understand string
|
||
literals.</p>
|
||
<pre><code class="language-rust">let s = "Hello, world!";
|
||
</code></pre>
|
||
<p>The type of <code>s</code> here is <code>&str</code>: It’s a slice, pointing to that specific point
|
||
of the binary. This is also why string literals are immutable; <code>&str</code> is an
|
||
immutable reference.</p>
|
||
<h4>String Slices as Arguments</h4>
|
||
<p>Knowing that you can take slices of 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: &String) -> &str {
|
||
</code></pre>
|
||
<p>A more experienced Rustacean would write this one instead because it allows us
|
||
to use the same function on both <code>String</code>s and <code>&str</code>s:</p>
|
||
<pre><code class="language-rust,ignore">fn first_word(s: &str) -> &str {
|
||
</code></pre>
|
||
<p>If we have a string slice, we can pass that as the argument directly. If we
|
||
have a <code>String</code>, we can pass a slice of the entire <code>String</code>. This makes our API
|
||
more general and useful without losing any functionality:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust"># fn first_word(s: &str) -> &str {
|
||
# let bytes = s.as_bytes();
|
||
#
|
||
# for (i, &item) in bytes.iter().enumerate() {
|
||
# if item == b' ' {
|
||
# return &s[0..i];
|
||
# }
|
||
# }
|
||
#
|
||
# &s[..]
|
||
# }
|
||
fn main() {
|
||
let my_string = String::from("hello world");
|
||
|
||
// first_word works on slices of `String`s
|
||
let word = first_word(&my_string[..]);
|
||
|
||
let my_string_literal = "hello world";
|
||
|
||
// first_word works on slices of string literals
|
||
let word = first_word(&my_string_literal[..]);
|
||
|
||
// since string literals *are* string slices already,
|
||
// this works too, without the slice syntax!
|
||
let word = first_word(my_string_literal);
|
||
}
|
||
</code></pre>
|
||
<h3>Other Slices</h3>
|
||
<p>String slices, as you might imagine, are specific to strings. But there’s a more
|
||
general slice type, too. Consider this array:</p>
|
||
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
|
||
</code></pre>
|
||
<p>Just like we may want to refer to a part of a string, we may want to refer to
|
||
part of an array, and would do so like this:</p>
|
||
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
|
||
|
||
let slice = &a[1..3];
|
||
</code></pre>
|
||
<p>This slice has the type <code>&[i32]</code>. It works the exact same way as string slices
|
||
do, by storing a reference to the first element and a length. You’ll use this
|
||
kind of slice for all sorts of other collections. We’ll discuss these in detail
|
||
when we talk about vectors in Chapter XX.</p>
|
||
<h2>Summary</h2>
|
||
<p>The concepts of ownership, borrowing, and slices are what ensure memory safety
|
||
in Rust programs at compile time. Rust is a language that gives you control
|
||
over your memory usage like other systems programming languages, but having the
|
||
owner of data automatically clean up that data when the owner goes out of scope
|
||
means you don't have to write and debug extra code to get this control.</p>
|
||
<p>Ownership affects how lots of other parts of Rust work, so we will be talking
|
||
about these concepts further throughout the rest of the book. Let's move on to
|
||
the next chapter where we'll look at grouping pieces of data together in a
|
||
<code>struct</code>.</p>
|
||
<h1>Structs</h1>
|
||
<p>A <code>struct</code>, short for "structure", 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 called <code>points</code>. Here’s a short program
|
||
which calculates the distance between two points to put into this project's
|
||
<code>src/main.rs</code>:</p>
|
||
<p>Filename: src/main.rs</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!("Point 1: ({}, {})", x1, y1);
|
||
println!("Point 2: ({}, {})", x2, y2);
|
||
println!("Distance: {}", answer);
|
||
}
|
||
|
||
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> 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 "x" direction)</li>
|
||
<li>squaring the distance between the points vertically (the "y" 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) -> 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>
|
||
<p>Filename: src/main.rs</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!("Point 1: {:?}", p1);
|
||
println!("Point 2: {:?}", p2);
|
||
println!("Distance: {}", answer);
|
||
}
|
||
|
||
fn distance(p1: (f64, f64), p2: (f64, f64)) -> 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>
|
||
<p>Filename: src/main.rs</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!("Point 1: {:?}", p1);
|
||
println!("Point 2: {:?}", p2);
|
||
println!("Distance: {}", answer);
|
||
}
|
||
|
||
fn distance(p1: Point, p2: Point) -> 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>
|
||
<p>Filename: src/main.rs</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!("Point 1: {}", 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]
|
||
--> src/main.rs:8:29
|
||
8 |> println!("Point 1: {}", p1);
|
||
|> ^^
|
||
<std macros>:2:27: 2:58: note: in this expansion of format_args!
|
||
<std macros>:3:1: 3:54: note: in this expansion of print! (defined in <std macros>)
|
||
src/main.rs:8:5: 8:33: note: in this expansion of println! (defined in <std macros>)
|
||
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>
|
||
<p>Filename: src/main.rs</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!("Point 1: {:?}", 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 = "hello";
|
||
|
||
// call a method on s1
|
||
let s2 = s1.clone();
|
||
|
||
println!("{}", 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(&self, other: &Point) -> f64 {
|
||
let x_squared = f64::powi(other.x - self.x, 2);
|
||
let y_squared = f64::powi(other.y - self.y, 2);
|
||
|
||
f64::sqrt(x_squared + y_squared)
|
||
}
|
||
}
|
||
|
||
let p1 = Point { x: 0.0, y: 0.0 };
|
||
let p2 = Point { x: 5.0, y: 6.5 };
|
||
|
||
assert_eq!(8.200609733428363, p1.distance(&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(&self, other: &Point) -> 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) -> f64 {
|
||
// ...
|
||
}
|
||
</code></pre>
|
||
<p>The first difference is in the first argument. Instead of a name and a type, we
|
||
have written <code>&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>&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: &Point)
|
||
fn foo(&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(&self) // take self by reference
|
||
fn foo(&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(&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>&</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>&</code>s
|
||
or <code>&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(&self, other: &Point) -> f64 {
|
||
# let x_squared = f64::powi(other.x - self.x, 2);
|
||
# let y_squared = f64::powi(other.y - self.y, 2);
|
||
#
|
||
# f64::sqrt(x_squared + y_squared)
|
||
# }
|
||
# }
|
||
# let p1 = Point { x: 0.0, y: 0.0 };
|
||
# let p2 = Point { x: 5.0, y: 6.5 };
|
||
p1.distance(&p2);
|
||
(&p1).distance(&p2);
|
||
</code></pre>
|
||
<p>The first one looks much, much cleaner. Here’s another example:</p>
|
||
<pre><code class="language-rust">let mut s = String::from("Hello,");
|
||
|
||
s.push_str(" world!");
|
||
|
||
// The above is the same as:
|
||
// (&mut s).push_str(" world!");
|
||
|
||
assert_eq!("Hello, world!", s);
|
||
</code></pre>
|
||
<p>Because [<code>push_str()</code>][pushstr]<!-- ignore --> has the following signature:</p>
|
||
<pre><code class="language-rust,ignore">fn push_str(&mut self, string: &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>&self</code>), mutating (so
|
||
<code>&mut self</code>), or consuming (so <code>self</code>). The fact that Rust makes borrowing
|
||
implicit for method receivers is a big part of making ownership ergonomic in
|
||
practice.</p>
|
||
<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 "enums", 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 "algebraic data types" 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("127.0.0.1"),
|
||
};
|
||
|
||
let loopback = IpAddr {
|
||
kind: IpAddrKind::V6,
|
||
address: String::from("::1"),
|
||
};
|
||
</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("127.0.0.1"));
|
||
|
||
let loopback = IpAddr::V6(String::from("::1"));
|
||
</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("::1"));
|
||
</code></pre>
|
||
<p>You can put any kind of data inside of an enum variant, including another enum!
|
||
The <code>IpAddr</code> enum is <a href="../std/net/enum.IpAddr.html">in the standard library</a><!-- ignore -->, but it
|
||
embeds two different structs inside of its variants:</p>
|
||
<pre><code class="language-rust">struct Ipv4Addr {
|
||
// details elided
|
||
}
|
||
|
||
struct Ipv6Addr {
|
||
// details elided
|
||
}
|
||
|
||
enum IpAddr {
|
||
V4(Ipv4Addr),
|
||
V6(Ipv6Addr),
|
||
}
|
||
</code></pre>
|
||
<p>Here’s an enum with a variety of types embedded in its variants:</p>
|
||
<pre><code class="language-rust">enum Message {
|
||
Quit,
|
||
Move { x: i32, y: i32 },
|
||
Write(String),
|
||
ChangeColor(i32, i32, i32),
|
||
}
|
||
</code></pre>
|
||
<ul>
|
||
<li><code>Quit</code> has no data associated with it at all.</li>
|
||
<li><code>Move</code> includes an anonymous struct inside of it.</li>
|
||
<li><code>Write</code> includes a single <code>String</code>.</li>
|
||
<li><code>ChangeColor</code> includes three <code>i32</code>s.</li>
|
||
</ul>
|
||
<p>This might seem overwhelming, but another way to look at the different enum
|
||
possibilities is that they are just like different kinds of struct definitions
|
||
that you already know, except without the <code>struct</code> keyword and they are grouped
|
||
together under the <code>Message</code> type. These structs could hold the same data that
|
||
these enum variants hold:</p>
|
||
<pre><code class="language-rust">struct QuitMessage; // unit struct
|
||
struct MoveMessage {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
struct WriteMessage(String); // tuple struct
|
||
struct ChangeColorMessage(i32, i32, i32); // tuple struct
|
||
</code></pre>
|
||
<p>Let's look at another enum in the standard library that is very common and
|
||
useful: <code>Option</code>.</p>
|
||
<h2>Option</h2>
|
||
<p>Now that we have had an introduction to enums, let's combine them with a
|
||
feature that we talked a little bit about in the previous chapter: generics.</p>
|
||
<p>Programming language design is often thought of as which features you include,
|
||
but it's also about which features you leave out. Rust does not have a feature
|
||
that is in many other languages: <em>null</em>. In languages with this feature,
|
||
variables can have two states: null or not-null.</p>
|
||
<p>The inventor of this concept has this to say:</p>
|
||
<blockquote>
|
||
<p>I call it my billion-dollar mistake. At that time, I was designing the first
|
||
comprehensive type system for references in an object-oriented language. My
|
||
goal was to ensure that all use of references should be absolutely safe, with
|
||
checking performed automatically by the compiler. But I couldn't resist the
|
||
temptation to put in a null reference, simply because it was so easy to
|
||
implement. This has led to innumerable errors, vulnerabilities, and system
|
||
crashes, which have probably caused a billion dollars of pain and damage in
|
||
the last forty years.</p>
|
||
<ul>
|
||
<li>Tony Hoare "Null References: The Billion Dollar Mistake"</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<T></code>, and it looks like this:</p>
|
||
<pre><code class="language-rust">enum Option<T> {
|
||
Some(T),
|
||
None,
|
||
}
|
||
</code></pre>
|
||
<p>This enum is <a href="../std/option/enum.Option.html">provided by the standard library</a><!-- ignore -->, and is
|
||
so useful that it's even in the prelude; you don't need to import it
|
||
explicitly. Furthermore, so are its variants: you can say <code>Some</code> and <code>None</code>
|
||
directly, without prefixing them with <code>Option::</code>.</p>
|
||
<p>Here's an example of using <code>Option<T></code>:</p>
|
||
<pre><code class="language-rust">let some_number = Some(5);
|
||
let some_string = Some("a string");
|
||
|
||
// If we only say None, we need to tell Rust what type of Option<T> we have.
|
||
let absent_number: Option<i32> = None;
|
||
</code></pre>
|
||
<p>Let's dig in. First, you'll notice that we used the <code><T></code> syntax when defining
|
||
<code>Option<T></code>: it's a generic enum. <code>Option<T></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 "null", and <code>Some</code> means "not null". So why is this any
|
||
better than null?</p>
|
||
<p>In short, because <code>Option<T></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<i8> = 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<std::option::Option<i8>>` 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<T></code> and a <code>T</code>. They're different types! This
|
||
shows one of the big advantages of an <code>Option<T></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<T></code> to a <code>T</code> before you
|
||
can do <code>T</code> stuff with it. This helps catch one of the most common issues with
|
||
null, generally: assuming that something isn't null when it actually is.</p>
|
||
<p>This is pretty powerful: in order to have a value that can possibly be null,
|
||
you have to explicitly opt in by making the type of that value an <code>Option<T></code>.
|
||
Then, when you use that value, you are required to explicitly handle the case
|
||
when the value is null. Everywhere that a value has a type that isn't an
|
||
<code>Option<T></code>, you <em>can</em> safely assume that the value isn't null. This was a
|
||
deliberate design decision for Rust to limit null's pervasiveness and increase
|
||
the safety of Rust code.</p>
|
||
<p>So, how <em>do</em> you get a <code>T</code> from an <code>Option<T></code>? The <code>Option<T></code> enum has a
|
||
large number of methods that you can check out in
|
||
<a href="../std/option/enum.Option.html">its documentation</a><!-- ignore -->, and becoming familiar with them will
|
||
be extremely useful in your journey with Rust.</p>
|
||
<p>But we want a deeper understanding than that. If we didn't have those methods
|
||
defined for us already, what would we do? And more generally, how do we get
|
||
the inner values out of any enum variant? We need a new feature: <code>match</code>.</p>
|
||
<h2>Match</h2>
|
||
<p>Rust has an extremely powerful control-flow operator: <code>match</code>. It allows us to
|
||
compare a value against a series of patterns and then execute code based on
|
||
how they compare.</p>
|
||
<p>Think of a <code>match</code> expression kind of like a coin sorting machine. Coins slide
|
||
down a track that has variously sized holes along it, and each coin falls
|
||
through the first hole it encounters that it fits into. In the same way, values
|
||
go through each pattern in a <code>match</code>, and for the first pattern that the value
|
||
"fits", the value will fall into the associated code block to be used during
|
||
execution.</p>
|
||
<p>Since we're already talking about coins, let's use them for an example using
|
||
<code>match</code>. We can write a function that can take an unknown American coin and, in
|
||
a similar way as the 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) -> i32 {
|
||
match coin {
|
||
Coin::Penny => 1,
|
||
Coin::Nickel => 5,
|
||
Coin::Dime => 10,
|
||
Coin::Quarter => 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 => 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 "match arm". That's the part that looks like <code>pattern => 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 "Lucky penny!" every time the method was called with a <code>Coin::Penny</code>,
|
||
but would still return the last value of the block, <code>1</code>:</p>
|
||
<pre><code class="language-rust"># enum Coin {
|
||
# Penny,
|
||
# Nickel,
|
||
# Dime,
|
||
# Quarter,
|
||
# }
|
||
#
|
||
fn value_in_cents(coin: Coin) -> i32 {
|
||
match coin {
|
||
Coin::Penny => {
|
||
println!("Lucky penny!");
|
||
1
|
||
},
|
||
Coin::Nickel => 5,
|
||
Coin::Dime => 10,
|
||
Coin::Quarter => 25,
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Another useful feature of match arms is that they can create bindings to parts
|
||
of the values that match the pattern. From 1999 through 2008, the U.S. printed
|
||
quarters with different designs for each of the 50 states on one side. The other
|
||
coins did not get state designs, so only quarters have this extra attribute. We
|
||
can add this information to our <code>enum</code> by changing the <code>Quarter</code> variant to have
|
||
a <code>State</code> value:</p>
|
||
<pre><code class="language-rust">#[derive(Debug)] // So we can inspect the state in a minute
|
||
enum UsState {
|
||
Alabama,
|
||
Alaska,
|
||
// ... etc
|
||
}
|
||
|
||
enum Coin {
|
||
Penny,
|
||
Nickel,
|
||
Dime,
|
||
Quarter(UsState),
|
||
}
|
||
</code></pre>
|
||
<p>Let's imagine that a friend of ours is trying to collect all 50 state quarters.
|
||
While we sort our loose change by coin type in order to count it, we're going
|
||
to call out the name of the state so that if it's one our friend doesn't have
|
||
yet, they can add it to their collection.</p>
|
||
<p>In the match statement to do this, the quarter case now has a binding, <code>state</code>,
|
||
that contains the value of the state of that quarter. The binding will only get
|
||
created if the coin matches the <code>Quarter</code> pattern. Then we can use the binding
|
||
in the code for that arm:</p>
|
||
<pre><code class="language-rust"># #[derive(Debug)]
|
||
# enum UsState {
|
||
# Alabama,
|
||
# Alaska,
|
||
# }
|
||
#
|
||
# enum Coin {
|
||
# Penny,
|
||
# Nickel,
|
||
# Dime,
|
||
# Quarter(UsState),
|
||
# }
|
||
#
|
||
fn value_in_cents(coin: Coin) -> i32 {
|
||
match coin {
|
||
Coin::Penny => 1,
|
||
Coin::Nickel => 5,
|
||
Coin::Dime => 10,
|
||
Coin::Quarter(state) => {
|
||
println!("State quarter from {:?}!", state);
|
||
25
|
||
},
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>If we were to call <code>value_in_cents(Coin::Quarter(UsState::Alaska))</code>, <code>coin</code> will
|
||
be <code>Coin::Quarter(UsState::Alaska)</code>. When we compare that value with each of the
|
||
match arms, none of them match until we reach <code>Coin::Quarter(state)</code>. At that
|
||
point, the binding for <code>state</code> will be the value <code>UsState::Alaska</code>. We can then
|
||
use that binding in the <code>println!</code>, thus getting the inner state value out of
|
||
the <code>Coin</code> enum variant for <code>Quarter</code> and enabling us to print "State quarter
|
||
from Alaska!".</p>
|
||
<p>Remember the <code>Option<T></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<i32></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<i32>) -> Option<i32> {
|
||
match x {
|
||
None => None,
|
||
Some(i) => Some(i + 1),
|
||
}
|
||
}
|
||
|
||
let five = Some(5);
|
||
let six = plus_one(five);
|
||
let none = plus_one(None);
|
||
</code></pre>
|
||
<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 => 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) => 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 => 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>=></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<i32>) -> Option<i32> {
|
||
match x {
|
||
Some(i) => 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) => 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 "exhaustive": we must exhaust
|
||
every last option possible in order to be valid. Especially in the case of
|
||
<code>Option<T></code>, when Rust prevents us from forgetting to explicitly handle the
|
||
<code>None</code> case, it protects us from assuming that we have a value when we might
|
||
have null and thus making the billion-dollar mistake 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 => println!("one"),
|
||
3 => println!("three"),
|
||
5 => println!("five"),
|
||
7 => println!("seven"),
|
||
_ => (),
|
||
}
|
||
</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) => {
|
||
// do something with x
|
||
},
|
||
None => {},
|
||
}
|
||
</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>_ => {}</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 "Do something with this one case; I don't care about the
|
||
others."</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 => body,
|
||
_ => {}
|
||
}
|
||
</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 => body,
|
||
_ => else_body,
|
||
}
|
||
</code></pre>
|
||
<p>In other words, it's the high-level construct we were originally looking for:
|
||
do something special with only one pattern.</p>
|
||
<h1>Modules</h1>
|
||
<p>When you write a program in Rust, your code might start off living solely in
|
||
the <code>main</code> function. As your code grows, you eventually move functionality out
|
||
into functions, both for re-use and for nicer organization. By splitting your
|
||
code up into smaller chunks, each chunk is easier to understand on its own. So
|
||
what happens when you start having too many functions? Rust has a module system
|
||
that tackles both the problem of wanting to be able to re-use code and the
|
||
problem of keeping your code organized.</p>
|
||
<p>In the same way that you extract lines of code into a function, you can extract
|
||
functions (and other code like structs and enums too) into different modules. A
|
||
<em>module</em> is a namespace that contains definitions of functions or types, and
|
||
those definitions can be visible outside their module or not. Here's an
|
||
overview of how the bits fit together:</p>
|
||
<ul>
|
||
<li><code>mod</code> declares a new module.</li>
|
||
<li>Everything starts off as private, but the <code>pub</code> keyword makes it public.</li>
|
||
<li>The <code>use</code> keyword allows you to bring modules, or definitions inside of them,
|
||
into scope so that it's easier to refer to them.</li>
|
||
</ul>
|
||
<p>We'll take a look at each of these parts and see how they fit into the whole.</p>
|
||
<h2><code>mod</code> and the Filesystem</h2>
|
||
<p>Every module in Rust starts with the <code>mod</code> keyword. In this next example, we'll
|
||
start again by making a new project with Cargo. This time, instead of a binary,
|
||
we're going to make a library: a project that other people would pull into their
|
||
projects as a dependency. We saw this with the <code>rand</code> crate in Chapter 2.</p>
|
||
<p>Imagine that we're creating a library to provide some general networking
|
||
functionality, and we decide to call our library <code>communicator</code>. To create this
|
||
library, we won't use the <code>--bin</code> option like we have before. This is because
|
||
by default cargo will create a library:</p>
|
||
<pre><code class="language-bash">$ cargo new communicator
|
||
$ cd communicator
|
||
</code></pre>
|
||
<p>Notice that Cargo generated <code>src/lib.rs</code> instead of <code>src/main.rs</code> for us, and
|
||
inside it we'll find this:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>This is an empty test to help us get our library started, instead of the binary
|
||
that says "Hello, world!" that we get with the <code>--bin</code> option. Let's ignore the
|
||
<code>#[]</code> stuff and <code>mod tests</code> for a little bit, but we'll make sure to leave it
|
||
in <code>src/lib.rs</code> for later.</p>
|
||
<p>We're going to look at different ways we could choose to organize our library's
|
||
code, any of which could make sense depending on exactly what we were trying to
|
||
do. To start, add this code at the beginning of the file:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust">mod network {
|
||
fn connect() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>This is our first module declaration. We use the <code>mod</code> keyword, followed by the
|
||
name of the module, and then a block of code in curly braces. Everything inside
|
||
this block is inside the namespace <code>network</code>. In this case, we have a single
|
||
function, <code>connect</code>. If we wanted to try and call this function from outside
|
||
the <code>network</code> module, we would say <code>network::connect()</code> rather than <code>connect()</code>.</p>
|
||
<p>We could have multiple modules, side-by-side. For example, if we wanted a
|
||
<code>client</code> module:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust">mod network {
|
||
fn connect() {
|
||
}
|
||
}
|
||
|
||
mod client {
|
||
fn connect() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Now we have a <code>network::connect</code> function and a <code>client::connect</code> function.</p>
|
||
<p>And we can put modules inside of modules. If we wanted to have <code>client</code> be
|
||
within <code>network</code>:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust">mod network {
|
||
fn connect() {
|
||
}
|
||
|
||
mod client {
|
||
fn connect() {
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>This gives us <code>network::connect</code> and <code>network::client::connect</code>.</p>
|
||
<p>In this way, modules form a tree. The contents of <code>src/lib.rs</code> are at the root
|
||
of the project's tree, and the submodules form the leaves. Here's what our
|
||
first example looks like when thought of this way:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── network
|
||
└── client
|
||
</code></pre>
|
||
<p>And here's the second:</p>
|
||
<pre><code class="language-text">communicator
|
||
└── network
|
||
└── client
|
||
</code></pre>
|
||
<p>More complicated projects can have a lot of modules.</p>
|
||
<h3>Putting Modules in Another File</h3>
|
||
<p>Modules form a hierarchical, tree-like structure. So does another thing:
|
||
file systems! The module system is the way that we split larger Rust projects up
|
||
into multiple files. Let's imagine we have a module layout like this:</p>
|
||
<p>File: src/lib.rs</p>
|
||
<pre><code class="language-rust">mod client {
|
||
fn connect() {
|
||
}
|
||
}
|
||
|
||
mod network {
|
||
fn connect() {
|
||
}
|
||
|
||
mod server {
|
||
fn connect() {
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Let's extract the <code>client</code> module into another file. First, we need to change
|
||
our code in <code>src/lib.rs</code>:</p>
|
||
<p>File: src/lib.rs</p>
|
||
<pre><code class="language-rust,ignore">mod client;
|
||
|
||
mod network {
|
||
fn connect() {
|
||
}
|
||
|
||
mod server {
|
||
fn connect() {
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We still say <code>mod client</code>, but instead of curly braces, we have a semicolon.
|
||
This lets Rust know that we have a module, but it's in another file with that
|
||
module's name. Open up <code>src/client.rs</code> and put this in it:</p>
|
||
<p>File: src/client.rs</p>
|
||
<pre><code class="language-rust">fn connect() {
|
||
}
|
||
</code></pre>
|
||
<p>Note that we don't need a <code>mod</code> declaration in this file. <code>mod</code> is for
|
||
declaring a new module, and we've already declared this module in <code>src/lib.rs</code>.
|
||
This file provides the <em>contents</em> of the <code>client</code> module. If we put a <code>mod client</code> here, we'd be giving the <code>client</code> module its own submodule named
|
||
<code>client</code>!</p>
|
||
<p>Now, everything should compile successfully, but with a few warnings:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/client.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/lib.rs:4:5
|
||
|
|
||
4 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/lib.rs:8:9
|
||
|
|
||
8 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Don't worry about those warnings for now; we'll clear them up in a future
|
||
section. They're just warnings, we've built things successfully!</p>
|
||
<p>Let's extract the <code>network</code> module into its own file next, using the same
|
||
pattern. Change <code>src/lib.rs</code> to look like this:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust,ignore">mod client;
|
||
|
||
mod network;
|
||
</code></pre>
|
||
<p>And then put this in <code>src/network.rs</code></p>
|
||
<p>Filename: src/network.rs</p>
|
||
<pre><code class="language-rust">fn connect() {
|
||
}
|
||
|
||
mod server {
|
||
fn connect() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>And then run <code>cargo build</code> again. Success! We have one more module to extract:
|
||
<code>server</code>. Unfortunately, our current tactic of extracting a module into a file
|
||
named after that module won't work. Let's try it anyway. Modify
|
||
<code>src/network.rs</code> to look like this:</p>
|
||
<p>Filename: src/network.rs</p>
|
||
<pre><code class="language-rust,ignore">fn connect() {
|
||
}
|
||
|
||
mod server;
|
||
</code></pre>
|
||
<p>Put this in <code>src/server.rs</code></p>
|
||
<p>Filename: src/server.rs</p>
|
||
<pre><code class="language-rust">fn connect() {
|
||
}
|
||
</code></pre>
|
||
<p>When we try to <code>cargo build</code>, we'll get an error:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
error: cannot declare a new module at this location
|
||
--> src/network.rs:4:5
|
||
|
|
||
4 | mod server;
|
||
| ^^^^^^
|
||
|
|
||
note: maybe move this module `network` to its own directory via `network/mod.rs`
|
||
--> src/network.rs:4:5
|
||
|
|
||
4 | mod server;
|
||
| ^^^^^^
|
||
note: ... or maybe `use` the module `server` instead of possibly redeclaring it
|
||
--> src/network.rs:4:5
|
||
|
|
||
4 | mod server;
|
||
| ^^^^^^
|
||
</code></pre>
|
||
<p>This error is actually pretty helpful. It points out something we didn't know
|
||
that we could do yet:</p>
|
||
<blockquote>
|
||
<p>note: maybe move this module <code>network</code> to its own directory via
|
||
<code>network/mod.rs</code></p>
|
||
</blockquote>
|
||
<p>Here's the problem: in our case, we have different names for our modules:
|
||
<code>client</code> and <code>network::server</code>. But what if we had <code>client</code> and
|
||
<code>network::client</code>, or <code>server</code> and <code>network::server</code>? Having two modules at
|
||
different places in the module hierarchy have the same name is completely
|
||
valid, but then which module would the files <code>src/client.rs</code> and
|
||
<code>src/server.rs</code>, respectively, be for?</p>
|
||
<p>Instead of continuing to follow the same file naming pattern we used
|
||
previously, we can do what the error suggests. We'll make a new <em>directory</em>,
|
||
move <code>src/server.rs</code> into it, and change <code>src/network.rs</code> to
|
||
<code>src/network/mod.rs</code>. Then, when we try to build:</p>
|
||
<pre><code class="language-bash">$ mkdir src/network
|
||
$ mv src/server.rs src/network
|
||
$ mv src/network.rs src/network/mod.rs
|
||
$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
<warnings>
|
||
$
|
||
</code></pre>
|
||
<p>It works! So now our module layout looks like this:</p>
|
||
<pre><code class="language-text">communicator
|
||
├── client
|
||
└── network
|
||
└── server
|
||
</code></pre>
|
||
<p>And the corresponding file layout looks like this:</p>
|
||
<pre><code class="language-text">├── src
|
||
│ ├── client.rs
|
||
│ ├── lib.rs
|
||
│ └── network
|
||
│ ├── mod.rs
|
||
│ └── server.rs
|
||
</code></pre>
|
||
<p>In summary, these are the rules of modules with regards to files:</p>
|
||
<ul>
|
||
<li>
|
||
<p>If a module named <code>foo</code> has no submodules, you should put the declarations in
|
||
the <code>foo</code> module in a file named <code>foo.rs</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p>If a module named <code>foo</code> does have submodules, you should put the declarations
|
||
for <code>foo</code> in a file named <code>foo/mod.rs</code>.</p>
|
||
</li>
|
||
<li>
|
||
<p>The first two rules apply recursively, so that if a module named <code>foo</code> has a
|
||
submodule named <code>bar</code> and <code>bar</code> does not have submodules, you should have the
|
||
following files in your <code>src</code> directory:</p>
|
||
<pre><code class="language-text">├── foo
|
||
│ ├── bar.rs (contains the declarations in `foo::bar`)
|
||
│ └── mod.rs (contains the declarations in `foo`, including `mod bar`)
|
||
</code></pre>
|
||
</li>
|
||
<li>
|
||
<p>The modules themselves should be declared in their parent module's file using
|
||
the <code>mod</code> keyword.</p>
|
||
</li>
|
||
</ul>
|
||
<p>Next, we'll talk about the <code>pub</code> keyword, and get rid of those warnings!</p>
|
||
<h2>Controlling Visibility with <code>pub</code></h2>
|
||
<p>At the end of the last section, we had a project, <code>communicator</code>, and when we compiled it, we got some strange warnings:</p>
|
||
<pre><code class="language-bash"> Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/client.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/mod.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Why does this happen? After all, we're building a library. What if these three
|
||
functions are the public interface that we want our <em>users</em> to use? We won't
|
||
necessarily be using them within our own project, but the point of creating them
|
||
is that they <em>will</em> be used by another project. Let's try using them as if we
|
||
were another project using our library to see what happens and understand why
|
||
we're getting these unused function warnings. Create a <code>src/main.rs</code> file with
|
||
this code:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust,ignore">extern crate communicator;
|
||
|
||
fn main() {
|
||
communicator::client::connect();
|
||
}
|
||
</code></pre>
|
||
<p>We need the <code>extern crate</code> line to bring our <code>communicator</code> library crate into
|
||
scope, because our package actually now contains <em>two</em> crates. Cargo treats
|
||
src/main.rs as the crate root of a binary crate, and we also have our existing
|
||
library crate. This pattern is quite common for executable crates: most
|
||
functionality is in a library crate, and the executable crate uses that
|
||
library. This way, other programs can also use the library crate, and it’s a
|
||
nice separation of concerns.</p>
|
||
<p>Our binary crate right now just calls our library's <code>connect</code> function from
|
||
the <code>client</code> module; we picked that one since it's the first warning in our
|
||
build output above. Invoking <code>cargo build</code> will now give us an error after the
|
||
warnings:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
error: module `client` is private
|
||
--> src/main.rs:4:5
|
||
|
|
||
4 | communicator::client::connect();
|
||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||
</code></pre>
|
||
<p>Ah ha! The <code>client</code> module is private. This is the first time we've run into
|
||
the concepts of 'public' and 'private' in the context of Rust. There's no
|
||
keyword to make something private; that's the default state. In this default
|
||
state, no one else could possibly use it, so if we don't use it within our
|
||
library crate, Rust will warn us that it's unused. Once we tell Rust something
|
||
is public, Rust knows that we intend for code external to our crate to use it,
|
||
and Rust considers theoretical external usage that is now possible to count as
|
||
being used. Thus, when something is marked as public, Rust will stop warning us
|
||
that it is unused.</p>
|
||
<p>To tell Rust we want to make something public, we add the <code>pub</code> keyword. This
|
||
keyword goes before the declaration of the item we want to make public. Let's
|
||
modify <code>src/lib.rs</code> to make the <code>client</code> module public to fix the error we got:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust,ignore">pub mod client;
|
||
|
||
mod network;
|
||
</code></pre>
|
||
<p>The <code>pub</code> goes right before <code>mod</code>. Let's try building again:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
<warnings>
|
||
error: function `connect` is private
|
||
--> src/main.rs:4:5
|
||
|
|
||
4 | communicator::client::connect();
|
||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||
</code></pre>
|
||
<p>Hooray! We have a different error! Yes, different error messages are a cause
|
||
for celebration. The new error says "function <code>connect</code> is private", so let's
|
||
edit <code>src/client.rs</code> to make <code>client::connect</code> public:</p>
|
||
<p>Filename: src/client.rs</p>
|
||
<pre><code class="language-rust">pub fn connect() {
|
||
}
|
||
</code></pre>
|
||
<p>And run <code>cargo build</code> again:</p>
|
||
<pre><code class="language-bash"> cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/mod.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>It compiled! And the warning about <code>client::connect</code> not being used is gone!</p>
|
||
<p>Making functions public isn't the only way to fix unused code warnings: if
|
||
we <em>didn't</em> want these functions to be part of our public API and we got these
|
||
warnings, the warnings could be alerting us to code we no longer needed and
|
||
could safely delete. They could also be alerting us to a bug, if we
|
||
had just accidentally removed all places within our library where we called
|
||
this function.</p>
|
||
<p>However, we <em>do</em> want the other two functions to be part of our crate's public
|
||
API, so let's mark them as <code>pub</code> as well to get rid of the remaining warnings.
|
||
Modify <code>src/network/mod.rs</code> to be:</p>
|
||
<p>Filename: src/network/mod.rs</p>
|
||
<pre><code class="language-rust,ignore">pub fn connect() {
|
||
}
|
||
|
||
mod server;
|
||
</code></pre>
|
||
<p>And compile:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/mod.rs:1:1
|
||
|
|
||
1 | pub fn connect() {
|
||
| ^
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Hmmm, it says this is still dead, even though it's <code>pub</code>. While the function is
|
||
public within the module, the <code>network</code> module it's in is not public. We're
|
||
working from the interior of the library out this time, as opposed to with
|
||
<code>client</code> where we worked from the outside in. Let's change <code>src/lib.rs</code> to add
|
||
the same fix though, by making <code>network</code> public like <code>client</code> is:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust,ignore">pub mod client;
|
||
|
||
pub mod network;
|
||
</code></pre>
|
||
<p>Now if we compile, that warning is gone:</p>
|
||
<pre><code class="language-bash">$ cargo build
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Only one last warning! Try to fix this one on your own!</p>
|
||
<h3>Privacy Rules</h3>
|
||
<p>Overall, these are the rules for item visibility:</p>
|
||
<ol>
|
||
<li>If an item is public, then it can be accessed through any of its
|
||
parent modules.</li>
|
||
<li>If an item is private, it may be accessed by the current module and its
|
||
child modules.</li>
|
||
</ol>
|
||
<p>Let's look at a few more examples to get some practice. What if we had this
|
||
code in a new project's <code>src/lib.rs</code>:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust,ignore">mod outermost {
|
||
pub fn middle_function() {}
|
||
|
||
fn middle_secret_function() {}
|
||
|
||
mod inside {
|
||
pub fn inner_function() {}
|
||
|
||
fn secret_function() {}
|
||
}
|
||
}
|
||
|
||
fn try_me() {
|
||
outermost::middle_function();
|
||
outermost::middle_secret_function();
|
||
outermost::inside::inner_function();
|
||
outermost::inside::secret_function();
|
||
}
|
||
</code></pre>
|
||
<p>Before you try to compile this code, make a guess about which lines in
|
||
<code>try_me</code> will have errors.</p>
|
||
<p>Ready? Let's talk through them!</p>
|
||
<p>The <code>try_me</code> function is in the root module of our project. The module named
|
||
<code>outermost</code> is private, but the second rule says we're allowed to access it
|
||
since <code>outermost</code> is in our current, root module.</p>
|
||
<p>The function call <code>outermost::middle_function()</code> will work. <code>middle_function</code>
|
||
is public, and we are accessing it through its parent module, <code>outermost</code>,
|
||
which we just determined we can access in the previous paragraph.</p>
|
||
<p><code>outermost::middle_secret_function()</code> will cause a compilation error.
|
||
<code>middle_secret_function</code> is private, so the second rule applies. Our current
|
||
root module is neither the current module of <code>middle_secret_function</code>
|
||
(<code>outermost</code> is), nor is it a child module of the current module of
|
||
<code>middle_secret_function</code>.</p>
|
||
<p>The module named <code>inside</code> is private and has no child modules, so it can only
|
||
be accessed by its current module, <code>outermost</code>. That means the <code>try_me</code>
|
||
function is not allowed to call <code>outermost::inside::inner_function()</code> or
|
||
<code>outermost::inside::secret_function()</code>.</p>
|
||
<p>Here are some changes to try making with this code. Try each one, make a guess
|
||
about what will be allowed or not, compile to see if you're right, and use the
|
||
rules to understand why.</p>
|
||
<ul>
|
||
<li>What if the <code>inside</code> module was public?</li>
|
||
<li>What if <code>outside</code> was public and <code>inside</code> was private?</li>
|
||
<li>What if, in the body of <code>inner_function</code>, we called
|
||
<code>::outermost::middle_secret_function()</code>? (The two colons at the beginning
|
||
mean that we want to refer to the namespaces starting from the root
|
||
namespace.)</li>
|
||
</ul>
|
||
<p>Feel free to design more experiments and try them out!</p>
|
||
<p>Next, let's talk about bringing items into a scope with the <code>use</code> keyword.</p>
|
||
<h2>Importing Names with <code>use</code></h2>
|
||
<p>We've seen how we can call functions defined within a module by using the
|
||
module name as part of the call, like this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">pub mod a {
|
||
pub mod series {
|
||
pub mod of {
|
||
pub fn namespaces() {}
|
||
}
|
||
}
|
||
}
|
||
|
||
fn main() {
|
||
a::series::of::namespaces();
|
||
}
|
||
</code></pre>
|
||
<p>However, referring to the fully qualified name can get quite lengthy, as we see
|
||
in that example. To solve this issue, Rust has a keyword, <code>use</code>. It works like
|
||
this:</p>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">pub mod a {
|
||
pub mod series {
|
||
pub mod of {
|
||
pub fn namespaces() {}
|
||
}
|
||
}
|
||
}
|
||
|
||
use a::series::of;
|
||
|
||
fn main() {
|
||
of::namespaces();
|
||
}
|
||
</code></pre>
|
||
<p>We can <code>use</code> a module, and that will bring its name into scope. This allows us
|
||
to shorten our function call, only requiring us to type the final module name,
|
||
not the entire chain of them. <code>use</code> is quite powerful and can bring all kinds
|
||
of things into scope. For example, we could <code>use</code> the function itself:</p>
|
||
<pre><code class="language-rust">pub mod a {
|
||
pub mod series {
|
||
pub mod of {
|
||
pub fn namespaces() {}
|
||
}
|
||
}
|
||
}
|
||
|
||
use a::series::of::namespaces;
|
||
|
||
fn main() {
|
||
namespaces();
|
||
}
|
||
</code></pre>
|
||
<p>Enums also form this kind of namespace; we can import an enum's variants with
|
||
<code>use</code> as well. For any kind of <code>use</code> statement, if you are importing multiple
|
||
items from one namespace, you can list them using curly braces and commas in
|
||
the last position, like so:</p>
|
||
<pre><code class="language-rust">enum TrafficLight {
|
||
Red,
|
||
Yellow,
|
||
Green,
|
||
}
|
||
|
||
use TrafficLight::{Red, Yellow};
|
||
|
||
fn main() {
|
||
let red = Red;
|
||
let yellow = Yellow;
|
||
let green = TrafficLight::Green; // because we didn't use TrafficLight::Green
|
||
}
|
||
</code></pre>
|
||
<h3>Glob Imports with <code>*</code></h3>
|
||
<p>If you'd like to import all the items in a namespace at once, you can use <code>*</code>:</p>
|
||
<pre><code class="language-rust">enum TrafficLight {
|
||
Red,
|
||
Yellow,
|
||
Green,
|
||
}
|
||
|
||
use TrafficLight::*;
|
||
|
||
fn main() {
|
||
let red = Red;
|
||
let yellow = Yellow;
|
||
let green = Green;
|
||
}
|
||
</code></pre>
|
||
<p>The <code>*</code> is called a 'glob', and it will import everything that's visible inside
|
||
of the namespace. Globs should be used sparingly: they are convenient, but you
|
||
might also pull in more things than you expected and cause naming conflicts.</p>
|
||
<h3>Using <code>super</code> to Access a Parent Module</h3>
|
||
<p>Remember when we created our crate that Cargo made a <code>tests</code> module for us?
|
||
Let's talk about that now. It was in <code>src/lib.rs</code>:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust,ignore">pub mod client;
|
||
|
||
pub mod network;
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We'll explain more about testing in Chapter XX, but parts of this should make
|
||
sense now: we have a module named <code>tests</code> that lives next to our other modules
|
||
and contains one function named <code>it_works</code>. Even though there are special
|
||
annotations, the <code>tests</code> module is just another module!</p>
|
||
<p>Since tests are for exercising the code within our library, let's try to call
|
||
our <code>client::connect</code> function from this <code>it_works</code> function, even though
|
||
we're not going to be checking any functionality right now:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
#[test]
|
||
fn it_works() {
|
||
client::connect();
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Run the tests by invoking the <code>cargo test</code> command:</p>
|
||
<pre><code class="language-bash">$ cargo test
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
error[E0433]: failed to resolve. Use of undeclared type or module `client`
|
||
--> src/lib.rs:9:9
|
||
|
|
||
9 | client::connect();
|
||
| ^^^^^^^^^^^^^^^ Use of undeclared type or module `client`
|
||
|
||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||
--> src/network/server.rs:1:1
|
||
|
|
||
1 | fn connect() {
|
||
| ^
|
||
</code></pre>
|
||
<p>Why doesn't this compile? It's not because we don't have <code>communicator::</code> in
|
||
front of the function like we had in <code>src/main.rs</code>: we are definitely within
|
||
the <code>communicator</code> library crate here. The reason is that paths anywhere except
|
||
in a <code>use</code> statement are relative to the current module (In a <code>use</code> statement,
|
||
they're relative to the crate root by default). Our <code>tests</code> module doesn't have
|
||
a <code>client</code> module in its scope!</p>
|
||
<p>So how do we get back up one module? We can either use leading colons to say
|
||
that we want to start from the root and list the whole path:</p>
|
||
<pre><code class="language-rust,ignore">::client::connect();
|
||
</code></pre>
|
||
<p>Or we can use <code>super</code> to move up one module in the hierarchy:</p>
|
||
<pre><code class="language-rust,ignore">super::client::connect();
|
||
</code></pre>
|
||
<p>If we were deep in the module hierarchy, starting from the root every time
|
||
would get long. Plus, if we rearrange our modules by moving a subtree to
|
||
another place, there might be a lot of places the path would need to be updated
|
||
if we always used the path from the root.</p>
|
||
<p>It would also be annoying to have to type <code>super::</code> all the time in each test,
|
||
but we now have a tool for that solution: <code>use</code>! <code>super::</code> is special and
|
||
changes the path we give to <code>use</code> so that it is relative to the parent module
|
||
instead of to the root module.</p>
|
||
<p>For these reasons, in the <code>tests</code> module especially, <code>use super::something</code> is
|
||
usually the way to go. So now our test looks like this:</p>
|
||
<p>Filename: src/lib.rs</p>
|
||
<pre><code class="language-rust">#[cfg(test)]
|
||
mod tests {
|
||
use super::client;
|
||
|
||
#[test]
|
||
fn it_works() {
|
||
client::connect();
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>If we run <code>cargo test</code> again, the test will pass and the first part of the test
|
||
result output will be:</p>
|
||
<pre><code class="language-bash">$ cargo test
|
||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||
Running target/debug/communicator-92007ddb5330fa5a
|
||
|
||
running 1 test
|
||
test tests::it_works ... ok
|
||
|
||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
|
||
</code></pre>
|
||
<p>Now you know techniques for organizing your code! Use these to group related
|
||
functionality together, keep files from getting too long, and present a tidy
|
||
public API to users of your library.</p>
|
||
<h1>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<T> {
|
||
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<T> {
|
||
# x: T,
|
||
# y: T,
|
||
# }
|
||
</code></pre>
|
||
<p>Our previous definition said, "We are defining a struct named Point." This
|
||
definition says something slightly different: "We are defining a struct named
|
||
Point with one type parameter <code>T</code>."</p>
|
||
<p>Let's talk about this term <em>type parameter</em>. We've already seen one other thing
|
||
called a "parameter" in Rust: function parameters:</p>
|
||
<pre><code class="language-rust">fn plus_one(x: i32) -> 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) -> 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<T> {
|
||
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<T> {
|
||
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<T, OtherT> {
|
||
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 "type", 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<T>(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<T> {
|
||
x: T,
|
||
y: T,
|
||
}
|
||
|
||
impl<T> Point<T> {
|
||
fn some_method(&self) {
|
||
// ...
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We also need the <code><T></code> after <code>impl</code>. This line reads, "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>." In a sense, the <code>impl<T></code> says "we will be using a type
|
||
<code>T</code>" and the <code>Point<T></code> says "that <code>T</code> is used for <code>Point</code>." 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<T>(x: T) {
|
||
println!("x is: {}", 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!("x is: {}", 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><></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>
|
||
<p>Filename: src/main.rs</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let (x, y) = (5, 6);
|
||
|
||
println!("The value of x is: {}", x);
|
||
println!("The value of y is: {}", y);
|
||
}
|
||
</code></pre>
|
||
<p>And run it with <code>cargo run</code>:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling bindings v0.1.0 (file:///projects/bindings)
|
||
Running `target/debug/bindings`
|
||
The value of x is: 5
|
||
The value of y is: 6
|
||
</code></pre>
|
||
<p>We’ve created two bindings with one <code>let</code>! Here’s our pattern:</p>
|
||
<pre><code class="language-text">(x, y)
|
||
</code></pre>
|
||
<p>And here’s the value:</p>
|
||
<pre><code class="language-text">(5, 6)
|
||
</code></pre>
|
||
<p>As you can see, the two line up visually, and so <code>let</code> binds <code>5</code> to <code>x</code> and <code>6</code>
|
||
to <code>y</code>. We could have used two <code>let</code> statements as well:</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 5;
|
||
let y = 6;
|
||
}
|
||
</code></pre>
|
||
<p>In simple cases like this, two <code>let</code>s may be clearer, but in others, creating
|
||
multiple bindings at once is nice. As we become more proficient in Rust, we’ll
|
||
figure out which style is better, but it’s mostly a judgement call.</p>
|
||
<h2>Type annotations</h2>
|
||
<p>Most of the time, Rust uses <em>type inference</em>, meaning that it attempts to infer
|
||
the types of your bindings rather than you having to declare them explicitly
|
||
even though Rust is a statically typed language. Occasionally, Rust won't have
|
||
enough information to infer the type of your value, and you will need to add a
|
||
type annotation in with the pattern.</p>
|
||
<p>Here’s what a <code>let</code> statement with a <em>type annotation</em> looks like:</p>
|
||
<pre><code class="language-rust">let x: i32 = 5;
|
||
</code></pre>
|
||
<p>We can add a colon, followed by the type name. Here’s the structure of a <code>let</code>
|
||
statement with a type annotation:</p>
|
||
<pre><code class="language-text">let PATTERN: TYPE = VALUE;
|
||
</code></pre>
|
||
<p>Note that the colon and the <code>TYPE</code> go <em>after</em> the <code>PATTERN</code>, not in the pattern
|
||
itself. As an example, here’s our more complex pattern with two bindings:</p>
|
||
<pre><code class="language-rust">let (x, y): (i32, i32) = (5, 6);
|
||
</code></pre>
|
||
<p>Just like we match up the <code>VALUE</code> with the <code>PATTERN</code>, we match up the <code>TYPE</code>
|
||
with the <code>PATTERN</code>.</p>
|
||
<h2>Literals & _</h2>
|
||
<p>You can match against literals directly, and <code>_</code> acts as an any case:</p>
|
||
<pre><code class="language-rust">let x = 1;
|
||
|
||
match x {
|
||
1 => println!("one"),
|
||
2 => println!("two"),
|
||
3 => println!("three"),
|
||
_ => println!("anything"),
|
||
}
|
||
</code></pre>
|
||
<p>This prints <code>one</code>.</p>
|
||
<h1>Multiple patterns</h1>
|
||
<p>You can match multiple patterns with <code>|</code>:</p>
|
||
<pre><code class="language-rust">let x = 1;
|
||
|
||
match x {
|
||
1 | 2 => println!("one or two"),
|
||
3 => println!("three"),
|
||
_ => println!("anything"),
|
||
}
|
||
</code></pre>
|
||
<p>This prints <code>one or two</code>.</p>
|
||
<h2>ref and ref mut</h2>
|
||
<p>Usually, when you match against a pattern, 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("Bors"));
|
||
|
||
match name {
|
||
Some(name) => println!("Found a name: {}", name),
|
||
None => (),
|
||
}
|
||
|
||
// name is moved here. This line will fail to compile:
|
||
println!("name is: {:?}", name);
|
||
</code></pre>
|
||
<p>If you'd prefer to bind <code>name</code> by reference, use the <code>ref</code> keyword:</p>
|
||
<pre><code class="language-rust">let name = Some(String::from("Bors"));
|
||
|
||
match name {
|
||
Some(ref name) => println!("Found a name: {}", name),
|
||
None => (),
|
||
}
|
||
|
||
// name is not moved here; the match only took a reference to its data rather
|
||
// than moving it. This will work:
|
||
println!("name is: {:?}", name);
|
||
</code></pre>
|
||
<p>And for a mutable reference, <code>ref mut</code>:</p>
|
||
<pre><code class="language-rust">let mut name = Some(String::from("Bors"));
|
||
|
||
match name {
|
||
Some(ref mut name) => *name = String::from("Another name"),
|
||
None => (),
|
||
}
|
||
|
||
// name is not moved here; the match only took a reference to its data rather
|
||
// than moving it
|
||
println!("name is: {:?}", name);
|
||
</code></pre>
|
||
<h2>Destructuring</h2>
|
||
<p>Patterns can be used to destructure structs and enums:</p>
|
||
<pre><code class="language-rust">struct Point {
|
||
x: i32,
|
||
y: i32,
|
||
}
|
||
|
||
let origin = Point { x: 0, y: 0 };
|
||
|
||
let Point { x, y } = origin;
|
||
</code></pre>
|
||
<p>This brings 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 } => { }, // 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) => { }, // x is an i32 here, not an Option<i32>
|
||
None => (),
|
||
}
|
||
</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(_) => println!("got a Some and I don't care what's inside"),
|
||
None => (),
|
||
}
|
||
</code></pre>
|
||
<p>Or like this:</p>
|
||
<pre><code class="language-rust">let numbers = (2, 4, 8, 16, 32);
|
||
|
||
match numbers {
|
||
(first, _, third, _, fifth) => println!("Some numbers: {}, {}, {}", first, third, fifth),
|
||
}
|
||
</code></pre>
|
||
<p>If you want, you can use <code>..</code> to ignore all of the parts you haven't defined:</p>
|
||
<pre><code class="language-rust">struct Point {
|
||
x: i32,
|
||
y: i32,
|
||
z: i32,
|
||
}
|
||
|
||
let origin = Point { x: 0, y: 0, z: 0 };
|
||
|
||
match origin {
|
||
Point { x, .. } => { }, // y and z are ignored
|
||
}
|
||
</code></pre>
|
||
<h2>Ranges</h2>
|
||
<p>You can match a range of values with <code>...</code>:</p>
|
||
<pre><code class="language-rust">let x = 5;
|
||
|
||
match x {
|
||
1 ... 5 => println!("one through five"),
|
||
_ => println!("something else"),
|
||
}
|
||
</code></pre>
|
||
<p>Ranges are usually used with integers or <code>char</code>s:</p>
|
||
<pre><code class="language-rust">let x = 'c';
|
||
|
||
match x {
|
||
'a' ... 'j' => println!("early ASCII letter"),
|
||
'k' ... 'z' => println!("late ASCII letter"),
|
||
_ => println!("something else"),
|
||
}
|
||
</code></pre>
|
||
<h2>Guards</h2>
|
||
<p>You can introduce match guards with <code>if</code>:</p>
|
||
<pre><code class="language-rust">let x = Some(5);
|
||
|
||
match x {
|
||
Some(x) if x < 5 => println!("less than five: {}", x),
|
||
Some(x) => println!("{}", x),
|
||
None => (),
|
||
}
|
||
</code></pre>
|
||
<p>If youre using if with multiple patterns, the if applies to both sides:</p>
|
||
<pre><code class="language-rust">let x = 4;
|
||
let y = false;
|
||
|
||
match x {
|
||
4 | 5 if y => println!("yes"),
|
||
_ => println!("no"),
|
||
}
|
||
</code></pre>
|
||
<p>This prints <code>no</code>, because the if applies to the whole of <code>4 | 5</code>, and not to only
|
||
the <code>5</code>. In other words, the precedence of if behaves like this:</p>
|
||
<pre><code class="language-text">(4 | 5) if y => ...
|
||
</code></pre>
|
||
<p>not this:</p>
|
||
<pre><code class="language-text">4 | (5 if y) => ...
|
||
</code></pre>
|
||
<h2>Bindings</h2>
|
||
<p>You can bind values to names with <code>@</code>:</p>
|
||
<h2>Organizing your Public API</h2>
|
||
<p>Here, we will describe the properties that a good public API in Rust has in
|
||
order to be pleasant for others to use.</p>
|
||
<h3>Re-exports with <code>pub use</code></h3>
|
||
<p>If your internal code organization doesn't match your desired public API
|
||
organization, you can re-export items in the way you want them to be organized.</p>
|
||
<p>To re-export a name, combine the <code>pub</code> keyword with <code>use</code>:</p>
|
||
<pre><code class="language-rust"># fn main() {} // this ex needs to be outside main
|
||
mod a {
|
||
pub mod namespace {
|
||
pub fn function() {}
|
||
}
|
||
}
|
||
|
||
pub use a::namespace::function;
|
||
</code></pre>
|
||
<p>Here, the <code>a</code> module is not public to users of our library, so neither are its
|
||
children, even though <code>namespace</code> and <code>function</code> are public <em>within</em> our
|
||
library. So users of our library couldn't call <code>a::namespace::function()</code>
|
||
themselves. However, since we've re-exported <code>function</code> with <code>pub use</code>,
|
||
<code>function</code> will be public. Users can just call <code>function</code> themselves,
|
||
directly. This allows us to organize our code internally however we'd like,
|
||
while presenting a different external interface.</p>
|
||
<h2>Documentation</h2>
|
||
<!-- Insert why documentation is important here, who your audience is for documentation -->
|
||
<h3>Documentation comments</h3>
|
||
<p>Rust has another kind of comment: a documentation comment. These
|
||
comments don’t affect the way that the code works, but they do work with Rust’s
|
||
tools. More specifically, the <code>rustdoc</code> tool that comes with Rust reads
|
||
documentation comments and produces HTML documentation from them.</p>
|
||
<p>Documentation comments use an extra slash:</p>
|
||
<pre><code class="language-rust">/// The foo function doesn’t really do much.
|
||
fn foo() {
|
||
}
|
||
|
||
/// We also can use
|
||
/// multiple comments here too,
|
||
/// like we did before
|
||
fn bar() {
|
||
}
|
||
</code></pre>
|
||
<p>This comment would then be interpreted by <code>rustdoc</code> as documenting the thing
|
||
that follows it: <code>foo</code> and <code>bar</code>.</p>
|
||
<p>Because documentation comments have semantic meaning to <code>rustdoc</code>, the compiler
|
||
will pay attention to the placement of your documentation comments. For
|
||
example, a program with only this:</p>
|
||
<pre><code class="language-rust,ignore">/// What am I documenting?
|
||
</code></pre>
|
||
<p>Will give a compiler error:</p>
|
||
<pre><code class="language-bash">src/main.rs:1:1: 1:27 error: expected item after doc comment
|
||
src/main.rs:1 /// What am I documenting?
|
||
^~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
</code></pre>
|
||
<h3>Generating HTML documentation</h3>
|
||
<h3>Documentation examples</h3>
|
||
<p>Another special part about documentation comments is that code examples in
|
||
documentation comments are run as part of your tests, so that they're less
|
||
likely to go out of date! To use this feature:</p>
|
||
<ul>
|
||
<li>TODO: insert a documentation example, preferably one that demonstrates a
|
||
<code>use</code> statement including parts of the current crate, not just stdlib.</li>
|
||
</ul>
|
||
<h2>Workspaces and Multiple Related Crates</h2>
|
||
<p>Projects can define a workspace which is a set of crates that will all share
|
||
the same Cargo.lock and output directory.</p>
|
||
<p>We weren't technically precise about the difference between a <em>package</em> and a
|
||
<em>crate</em> until now, and casually people will use the words <em>package</em> and <em>crate</em>
|
||
interchangeably and everyone will understand.</p>
|
||
<p>But there are cases when it makes sense to have multiple crates in one project
|
||
because (insert reasons here). For example, (insert examples here, maybe
|
||
log/env_log in rust-lang-nursery?)</p>
|
||
<p>So let's get more precise now. Earlier, we said:</p>
|
||
<blockquote>
|
||
<p>A <em>crate</em> is what we call a package of Rust code.</p>
|
||
</blockquote>
|
||
<p>This definition is problematic because "package" 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 "compilation unit" is the definition we use in Rust.
|
||
This comes from C and C++, which has three phases of going from "here's my
|
||
source" to "here's something I run":</p>
|
||
<ol>
|
||
<li><strong>Preprocessing</strong>: this is where <code>cpp</code> (the c preprocessor, not "c plus
|
||
plus") 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 "translation unit", even though most people say
|
||
"compilation unit."</p>
|
||
<p>In some sense, a crate is "that pile of source code you pass the root of to
|
||
<code>rustc</code>", but that feels too circular to be good. "compilation unit" is
|
||
technically precise, but is gibberish to a lot of people. And a "package" is
|
||
"one or more crates", 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>
|