mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:44:32 -06:00
rebuild pages at 57811c0
This commit is contained in:
+1
-1
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Appendix</h1>
|
||||
<a class="header" href="#appendix" name="appendix"><h1>Appendix</h1></a>
|
||||
<p>The following sections contain reference material you may find useful in your
|
||||
Rust journey.</p>
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Keywords</h2>
|
||||
<a class="header" href="#keywords" name="keywords"><h2>Keywords</h2></a>
|
||||
<p>The following keywords are reserved by the Rust language and may not be used as
|
||||
names of functions, variables, macros, modules, crates, constants, static
|
||||
values, attributes, struct fields, or parameters.</p>
|
||||
|
||||
+11
-11
@@ -67,8 +67,8 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Operators</h2>
|
||||
<h3>Unary operator expressions</h3>
|
||||
<a class="header" href="#operators" name="operators"><h2>Operators</h2></a>
|
||||
<a class="header" href="#unary-operator-expressions" name="unary-operator-expressions"><h3>Unary operator expressions</h3></a>
|
||||
<p>Rust defines the following unary operators. They are all written as prefix
|
||||
operators, before the expression they apply to.</p>
|
||||
<ul>
|
||||
@@ -96,9 +96,9 @@ borrow (<code>&</code>), this implies that the value may not be mutated, but
|
||||
it may be read or shared again. For a mutable borrow (<code>&mut</code>), the
|
||||
value may not be accessed in any way until the borrow expires.</li>
|
||||
</ul>
|
||||
<h3>Binary operator expressions</h3>
|
||||
<a class="header" href="#binary-operator-expressions" name="binary-operator-expressions"><h3>Binary operator expressions</h3></a>
|
||||
<p>Binary operators expressions are given in order of operator precedence.</p>
|
||||
<h4>Arithmetic operators</h4>
|
||||
<a class="header" href="#arithmetic-operators" name="arithmetic-operators"><h4>Arithmetic operators</h4></a>
|
||||
<p>Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
|
||||
defined in the <code>std::ops</code> module of the <code>std</code> library. This means arithmetic
|
||||
operators can be overridden for user-defined types. The default meaning of the
|
||||
@@ -122,7 +122,7 @@ Calls the <code>rem</code> method on the <code>std::ops::Rem</code> trait.</li>
|
||||
</ul>
|
||||
<p>Note that Rust does not have a built-in operator for exponential (power)
|
||||
calculation; see the <code>pow</code> method on the numeric types.</p>
|
||||
<h4>Bitwise operators</h4>
|
||||
<a class="header" href="#bitwise-operators" name="bitwise-operators"><h4>Bitwise operators</h4></a>
|
||||
<p>Like the arithmetic operators, bitwise operators are syntactic sugar for calls
|
||||
to methods of built-in traits. This means bitwise operators can be overridden
|
||||
for user-defined types. The default meaning of the operators on standard types
|
||||
@@ -145,7 +145,7 @@ Calls the <code>shl</code> method of the <code>std::ops::Shl</code> trait.</li>
|
||||
: Right shift (arithmetic).
|
||||
Calls the <code>shr</code> method of the <code>std::ops::Shr</code> trait.</li>
|
||||
</ul>
|
||||
<h4>Lazy boolean operators</h4>
|
||||
<a class="header" href="#lazy-boolean-operators" name="lazy-boolean-operators"><h4>Lazy boolean operators</h4></a>
|
||||
<p>The operators <code>||</code> and <code>&&</code> may be applied to operands of boolean type. The
|
||||
<code>||</code> operator denotes logical 'or', and the <code>&&</code> operator denotes logical
|
||||
'and'. They differ from <code>|</code> and <code>&</code> in that the right-hand operand is only
|
||||
@@ -153,7 +153,7 @@ evaluated when the left-hand operand does not already determine the result of
|
||||
the expression. That is, <code>||</code> only evaluates its right-hand operand when the
|
||||
left-hand operand evaluates to <code>false</code>, and <code>&&</code> only when it evaluates to
|
||||
<code>true</code>.</p>
|
||||
<h4>Comparison operators</h4>
|
||||
<a class="header" href="#comparison-operators" name="comparison-operators"><h4>Comparison operators</h4></a>
|
||||
<p>Comparison operators are, like the arithmetic operators and bitwise operators,
|
||||
syntactic sugar for calls to built-in traits. This means that comparison
|
||||
operators can be overridden for user-defined types. The default meaning of the
|
||||
@@ -178,7 +178,7 @@ Calls the <code>le</code> method on the <code>std::cmp::PartialOrd</code> trait.
|
||||
: Greater than or equal.
|
||||
Calls the <code>ge</code> method on the <code>std::cmp::PartialOrd</code> trait.</li>
|
||||
</ul>
|
||||
<h4>Type cast expressions</h4>
|
||||
<a class="header" href="#type-cast-expressions" name="type-cast-expressions"><h4>Type cast expressions</h4></a>
|
||||
<p>A type cast expression is denoted with the binary operator <code>as</code>.</p>
|
||||
<p>Executing an <code>as</code> expression casts the value on the left-hand side to the type
|
||||
on the right-hand side.</p>
|
||||
@@ -198,7 +198,7 @@ argument passing and assignment to a <code>let</code> binding with an explicit
|
||||
type. Implicit conversions are limited to "harmless" conversions that
|
||||
do not lose information and which have minimal or no risk of
|
||||
surprising side-effects on the dynamic execution semantics.</p>
|
||||
<h4>Assignment expressions</h4>
|
||||
<a class="header" href="#assignment-expressions" name="assignment-expressions"><h4>Assignment expressions</h4></a>
|
||||
<p>An <em>assignment expression</em> consists of a pattern followed by an equals
|
||||
sign (<code>=</code>) and an expression.</p>
|
||||
<p>Evaluating an assignment expression either copies or
|
||||
@@ -208,12 +208,12 @@ operand.</p>
|
||||
# let y = 0;
|
||||
x = y;
|
||||
</code></pre>
|
||||
<h4>Compound assignment expressions</h4>
|
||||
<a class="header" href="#compound-assignment-expressions" name="compound-assignment-expressions"><h4>Compound assignment expressions</h4></a>
|
||||
<p>The <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>&</code>, <code>|</code>, <code>^</code>, <code><<</code>, and <code>>></code> operators may be
|
||||
composed with the <code>=</code> operator. The expression <code>lval OP= val</code> is equivalent to
|
||||
<code>lval = lval OP val</code>. For example, <code>x = x + 1</code> may be written as <code>x += 1</code>.</p>
|
||||
<p>Any such expression always has the <code>unit</code> type.</p>
|
||||
<h4>Operator precedence</h4>
|
||||
<a class="header" href="#operator-precedence" name="operator-precedence"><h4>Operator precedence</h4></a>
|
||||
<p>The precedence of Rust binary operators is ordered as follows, going from
|
||||
strong to weak:</p>
|
||||
<pre><code class="language-text">as :
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Derivable Traits</h2>
|
||||
<a class="header" href="#derivable-traits" name="derivable-traits"><h2>Derivable Traits</h2></a>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Nightly Rust</h1>
|
||||
<a class="header" href="#nightly-rust" name="nightly-rust"><h1>Nightly Rust</h1></a>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
@@ -67,9 +67,9 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Macros</h1>
|
||||
<h2>Basics of writing your own macros</h2>
|
||||
<h2>Macros are changing, go see X for more info</h2>
|
||||
<a class="header" href="#macros" name="macros"><h1>Macros</h1></a>
|
||||
<a class="header" href="#basics-of-writing-your-own-macros" name="basics-of-writing-your-own-macros"><h2>Basics of writing your own macros</h2></a>
|
||||
<a class="header" href="#macros-are-changing-go-see-x-for-more-info" name="macros-are-changing-go-see-x-for-more-info"><h2>Macros are changing, go see X for more info</h2></a>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
@@ -55,20 +55,6 @@ $( document ).ready(function() {
|
||||
var page_wrapper = $("#page-wrapper");
|
||||
var content = $("#content");
|
||||
|
||||
|
||||
// Add anchors for all content headers
|
||||
content.find("h1, h2, h3, h4, h5").wrap(function(){
|
||||
var wrapper = $("<a class=\"header\">");
|
||||
var header_name = $(this).text().trim().replace(/\W/g, '-')
|
||||
wrapper.attr("name", header_name);
|
||||
// Add so that when you click the link actually shows up in the url bar...
|
||||
// Remove any existing anchor then append the new one
|
||||
// ensuring eg. no spaces are present within it ie. they become %20
|
||||
wrapper.attr("href", $(location).attr('href').split("#")[0] + "#" + header_name );
|
||||
return wrapper;
|
||||
});
|
||||
|
||||
|
||||
// Toggle sidebar
|
||||
$("#sidebar-toggle").click(function(event){
|
||||
if ( html.hasClass("sidebar-hidden") ) {
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Introduction</h1>
|
||||
<a class="header" href="#introduction" name="introduction"><h1>Introduction</h1></a>
|
||||
<p>Welcome to “The Rust Programming Language,” an introductory book about Rust.
|
||||
Rust is a programming language that’s focused on safety, speed, and
|
||||
concurrency. Its design lets you create programs that have the performance and
|
||||
@@ -88,7 +88,7 @@ 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>
|
||||
<a class="header" href="#contributing-to-the-book" name="contributing-to-the-book"><h2>Contributing to the book</h2></a>
|
||||
<p>This book is open source. If you find an error, please don’t hesitate to file an
|
||||
issue or send a pull request <a href="https://github.com/rust-lang/book">on GitHub</a>.</p>
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Installation</h2>
|
||||
<a class="header" href="#installation" name="installation"><h2>Installation</h2></a>
|
||||
<p>The first step to using Rust is to install it. You’ll need an internet
|
||||
connection to run the commands in this chapter, as we’ll be downloading Rust
|
||||
from the internet.</p>
|
||||
@@ -77,7 +77,7 @@ the start of each command. You’ll see many tutorials and examples around the w
|
||||
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>
|
||||
<a class="header" href="#installing-on-linux-or-mac" name="installing-on-linux-or-mac"><h3>Installing on Linux or Mac</h3></a>
|
||||
<p>If you're on Linux or a Mac, all you need to do is open a terminal and type
|
||||
this:</p>
|
||||
<pre><code class="language-text">$ curl https://sh.rustup.rs -sSf | sh
|
||||
@@ -88,7 +88,7 @@ your password. If it all goes well, you’ll see this appear:</p>
|
||||
</code></pre>
|
||||
<p>Of course, if you disapprove of the <code>curl | sh</code> pattern, you can download, inspect
|
||||
and run the script however you like.</p>
|
||||
<h3>Installing on Windows</h3>
|
||||
<a class="header" href="#installing-on-windows" name="installing-on-windows"><h3>Installing on Windows</h3></a>
|
||||
<p>On Windows, go to <a href="https://rustup.rs/">https://rustup.rs</a><!-- ignore --> and
|
||||
follow the instructions to download rustup-init.exe. Run that and follow the
|
||||
rest of the instructions it gives you.</p>
|
||||
@@ -96,15 +96,15 @@ rest of the instructions it gives you.</p>
|
||||
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>
|
||||
<a class="header" href="#custom-installations" name="custom-installations"><h3>Custom installations</h3></a>
|
||||
<p>If you have reasons for preferring not to use rustup.rs, please see <a href="https://www.rust-lang.org/install.html">the Rust
|
||||
installation page</a> for other options.</p>
|
||||
<h3>Uninstalling</h3>
|
||||
<a class="header" href="#uninstalling" name="uninstalling"><h3>Uninstalling</h3></a>
|
||||
<p>Uninstalling Rust is as easy as installing it. From your shell, run
|
||||
the uninstall script:</p>
|
||||
<pre><code class="language-text">$ rustup self uninstall
|
||||
</code></pre>
|
||||
<h3>Troubleshooting</h3>
|
||||
<a class="header" href="#troubleshooting" name="troubleshooting"><h3>Troubleshooting</h3></a>
|
||||
<p>If you've got Rust installed, you can open up a shell, and type this:</p>
|
||||
<pre><code class="language-text">$ rustc --version
|
||||
</code></pre>
|
||||
@@ -122,7 +122,7 @@ which you can access through <a href="http://chat.mibbit.com/?server=irc.mozilla
|
||||
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>
|
||||
<a class="header" href="#local-documentation" name="local-documentation"><h3>Local documentation</h3></a>
|
||||
<p>The installer also includes a copy of the documentation locally, so you can
|
||||
read it offline. Run <code>rustup doc</code> to open the local documentation in your
|
||||
browser.</p>
|
||||
|
||||
+10
-10
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Hello, World!</h2>
|
||||
<a class="header" href="#hello-world" name="hello-world"><h2>Hello, World!</h2></a>
|
||||
<p>Now that you have Rust installed, let’s write your first Rust program. It's
|
||||
traditional when learning a new language to write a little program to print the
|
||||
text “Hello, world!” to the screen, and in this section, we'll follow that
|
||||
@@ -78,7 +78,7 @@ 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 Directory</h3>
|
||||
<a class="header" href="#creating-a-project-directory" name="creating-a-project-directory"><h3>Creating a Project Directory</h3></a>
|
||||
<p>First, make a directory to put your Rust code in. Rust doesn't care where your code
|
||||
lives, but for this book, we'd suggest making a <em>projects</em> directory in your
|
||||
home directory and keeping all your projects there. Open a terminal and enter
|
||||
@@ -95,7 +95,7 @@ $ cd hello_world
|
||||
> mkdir hello_world
|
||||
> cd hello_world
|
||||
</code></pre>
|
||||
<h3>Writing and Running a Rust Program</h3>
|
||||
<a class="header" href="#writing-and-running-a-rust-program" name="writing-and-running-a-rust-program"><h3>Writing and Running a Rust Program</h3></a>
|
||||
<p>Next, make a new source file and call it <em>main.rs</em>. Rust files always end with
|
||||
the <em>.rs</em> extension. If you’re using more than one word in your filename, use
|
||||
an underscore to separate them. For example, you'd use <em>hello_world.rs</em> rather
|
||||
@@ -116,7 +116,7 @@ Hello, world!
|
||||
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>
|
||||
<a class="header" href="#anatomy-of-a-rust-program" name="anatomy-of-a-rust-program"><h3>Anatomy of a Rust Program</h3></a>
|
||||
<p>Now, let’s go over what just happened in your "Hello, world!" program in
|
||||
detail. Here's the first piece of the puzzle:</p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
@@ -149,7 +149,7 @@ argument to <code>println!</code>, which prints the string to the screen. Easy e
|
||||
<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>
|
||||
<a class="header" href="#compiling-and-running-are-separate-steps" name="compiling-and-running-are-separate-steps"><h3>Compiling and Running Are Separate Steps</h3></a>
|
||||
<p>In "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
|
||||
@@ -188,7 +188,7 @@ 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>
|
||||
<a class="header" href="#hello-cargo" name="hello-cargo"><h2>Hello, Cargo!</h2></a>
|
||||
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
|
||||
manage their Rust projects because it makes a lot of tasks easier. For example,
|
||||
Cargo takes care of building your code, downloading the libraries your code
|
||||
@@ -208,7 +208,7 @@ have Cargo installed by typing the following into your terminal:</p>
|
||||
</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>
|
||||
<a class="header" href="#creating-a-project-with-cargo" name="creating-a-project-with-cargo"><h3>Creating a Project with Cargo</h3></a>
|
||||
<p>Let's create a new project using Cargo and look at how it differs from our
|
||||
project in <code>hello_world</code>. Go back to your projects directory (or wherever you
|
||||
decided to put your code):</p>
|
||||
@@ -281,7 +281,7 @@ everything, and everything is in its place.</p>
|
||||
the <em>hello_world</em> directory, you can convert it to a project that does use
|
||||
Cargo by moving your code into the <em>src</em> directory and creating an appropriate
|
||||
<em>Cargo.toml</em>.</p>
|
||||
<h3>Building and Running a Cargo Project</h3>
|
||||
<a class="header" href="#building-and-running-a-cargo-project" name="building-and-running-a-cargo-project"><h3>Building and Running a Cargo Project</h3></a>
|
||||
<p>Now let's look at what's different about building and running your Hello World
|
||||
program through Cargo! To do so, enter the following commands:</p>
|
||||
<pre><code class="language-text">$ cargo build
|
||||
@@ -331,7 +331,7 @@ code, Cargo will put it in the <em>target/debug</em> directory.</li>
|
||||
<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>
|
||||
<a class="header" href="#building-for-release" name="building-for-release"><h3>Building for Release</h3></a>
|
||||
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. This will create an
|
||||
executable in <em>target/release</em> instead of <em>target/debug</em>. These optimizations
|
||||
make your Rust code run faster, but turning them on makes your program take
|
||||
@@ -341,7 +341,7 @@ building the final program you’ll give to a user that won't be rebuilt and
|
||||
that we want to run as fast as possible. If you're benchmarking the running
|
||||
time of your code, be sure to run <code>cargo build --release</code> and benchmark with
|
||||
the executable in <em>target/release</em>.</p>
|
||||
<h3>Cargo as Convention</h3>
|
||||
<a class="header" href="#cargo-as-convention" name="cargo-as-convention"><h3>Cargo as Convention</h3></a>
|
||||
<p>With simple projects, Cargo doesn't provide a whole lot of value over just
|
||||
using <code>rustc</code>, but it will prove its worth as you continue. With complex
|
||||
projects composed of multiple crates, it’s much easier to let Cargo coordinate
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Guessing Game</h1>
|
||||
<a class="header" href="#guessing-game" name="guessing-game"><h1>Guessing Game</h1></a>
|
||||
<p>Let’s jump into Rust by working through a hands-on project together! This
|
||||
chapter introduces you to a few common Rust concepts by showing you how to use
|
||||
them in a real program. You’ll learn about <code>let</code>, <code>match</code>, methods, associated
|
||||
@@ -78,7 +78,7 @@ how it works: the program will generate a random integer between 1 and 100. It
|
||||
will then prompt the player to enter a guess. After entering a guess, it will
|
||||
indicate whether the guess is too low or too high. If the guess is correct, the
|
||||
game will print congratulations and exit.</p>
|
||||
<h2>Setting Up a New Project</h2>
|
||||
<a class="header" href="#setting-up-a-new-project" name="setting-up-a-new-project"><h2>Setting Up a New Project</h2></a>
|
||||
<p>To set up a new project, go to the <em>projects</em> directory that you created in
|
||||
Chapter 1, and make a new project using Cargo, like so:</p>
|
||||
<pre><code class="language-text">$ cargo new guessing_game --bin
|
||||
@@ -117,7 +117,7 @@ Hello, world!
|
||||
and this game is such a project: we want to quickly test each iteration
|
||||
before moving on to the next one.</p>
|
||||
<p>Reopen the <em>src/main.rs</em> file. You’ll be writing all the code in this file.</p>
|
||||
<h2>Processing a Guess</h2>
|
||||
<a class="header" href="#processing-a-guess" name="processing-a-guess"><h2>Processing a Guess</h2></a>
|
||||
<p>The first part of the program will ask for user input, process that input, and
|
||||
check that the input is in the expected form. To start, we’ll allow the player
|
||||
to input a guess. Enter the code in Listing 2-1 into <em>src/main.rs</em>.</p>
|
||||
@@ -166,7 +166,7 @@ println!("Please input your guess.");
|
||||
</code></pre>
|
||||
<p>This code is just printing a prompt stating what the game is and requesting
|
||||
input from the user.</p>
|
||||
<h3>Storing Values with Variables</h3>
|
||||
<a class="header" href="#storing-values-with-variables" name="storing-values-with-variables"><h3>Storing Values with Variables</h3></a>
|
||||
<p>Next, we’ll create a place to store the user input, like this:</p>
|
||||
<pre><code class="language-rust,ignore">let mut guess = String::new();
|
||||
</code></pre>
|
||||
@@ -237,7 +237,7 @@ written this code as:</p>
|
||||
</code></pre>
|
||||
<p>However, one long line is difficult to read, so it’s best to divide it, two
|
||||
lines for two method calls. Now let’s discuss what this line does.</p>
|
||||
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
|
||||
<a class="header" href="#handling-potential-failure-with-the-result-type" name="handling-potential-failure-with-the-result-type"><h3>Handling Potential Failure with the <code>Result</code> Type</h3></a>
|
||||
<p>As mentioned earlier, <code>read_line</code> puts what the user types into the string we’re
|
||||
passing it, but it also returns a value—in this case, an
|
||||
<a href="../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
|
||||
@@ -275,7 +275,7 @@ indicating that the program hasn’t handled a possible error. The right way to
|
||||
suppress the warning is to actually write error handling, but since we just
|
||||
want to crash this program when a problem occurs, we can use <code>expect</code>. You’ll
|
||||
learn about recovering from errors in Chapter 9.</p>
|
||||
<h3>Printing Values with <code>println!</code> Placeholders</h3>
|
||||
<a class="header" href="#printing-values-with-println-placeholders" name="printing-values-with-println-placeholders"><h3>Printing Values with <code>println!</code> Placeholders</h3></a>
|
||||
<p>Aside from the closing curly brace, there’s only one more line to discuss in
|
||||
the code added so far, which is the following:</p>
|
||||
<pre><code class="language-rust,ignore">println!("You guessed: {}", guess);
|
||||
@@ -291,7 +291,7 @@ let y = 10;
|
||||
println!("x = {} and y = {}", x, y);
|
||||
</code></pre>
|
||||
<p>This code would print out <code>x = 5 and y = 10</code>.</p>
|
||||
<h3>Testing the First Part</h3>
|
||||
<a class="header" href="#testing-the-first-part" name="testing-the-first-part"><h3>Testing the First Part</h3></a>
|
||||
<p>Let’s test the first part of the guessing game. You can run it using <code>cargo run</code>:</p>
|
||||
<pre><code class="language-text">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
@@ -303,13 +303,13 @@ You guessed: 6
|
||||
</code></pre>
|
||||
<p>At this point, the first part of the game is done: we’re getting input from the
|
||||
keyboard and then printing it.</p>
|
||||
<h2>Generating a Secret Number</h2>
|
||||
<a class="header" href="#generating-a-secret-number" name="generating-a-secret-number"><h2>Generating a Secret Number</h2></a>
|
||||
<p>Next, we need to generate a secret number that the user will try to guess. The
|
||||
secret number should be different every time so the game is fun to play more
|
||||
than once. Let’s use a random number between 1 and 100 so the game isn’t too
|
||||
difficult. Rust doesn’t yet include random number functionality in its standard
|
||||
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
|
||||
<h3>Using a Crate to Get More Functionality</h3>
|
||||
<a class="header" href="#using-a-crate-to-get-more-functionality" name="using-a-crate-to-get-more-functionality"><h3>Using a Crate to Get More Functionality</h3></a>
|
||||
<p>Remember that a <em>crate</em> is a package of Rust code. The project we’ve been
|
||||
building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is a
|
||||
<em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||||
@@ -373,7 +373,7 @@ you’ll only see one line of output:</p>
|
||||
<em>src/main.rs</em> file. Your dependencies haven't changed, so Cargo knows it can
|
||||
reuse what it has already downloaded and compiled for those. It just rebuilds
|
||||
your part of the code.</p>
|
||||
<h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4>
|
||||
<a class="header" href="#the-cargolock-file-ensures-reproducible-builds" name="the-cargolock-file-ensures-reproducible-builds"><h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4></a>
|
||||
<p>Cargo has a mechanism that ensures you can rebuild the same artifact every time
|
||||
you or anyone else builds your code: Cargo will use only the versions of the
|
||||
dependencies you specified until you indicate otherwise. For example, what
|
||||
@@ -390,7 +390,7 @@ rather than doing all the work of figuring out versions again. This lets you
|
||||
have a reproducible build automatically. In other words, your project will
|
||||
remain at <code>0.3.14</code> until you explicitly upgrade, thanks to the <em>Cargo.lock</em>
|
||||
file.</p>
|
||||
<h4>Updating a Crate to Get a New Version</h4>
|
||||
<a class="header" href="#updating-a-crate-to-get-a-new-version" name="updating-a-crate-to-get-a-new-version"><h4>Updating a Crate to Get a New Version</h4></a>
|
||||
<p>When you <em>do</em> want to update a crate, Cargo provides another command, <code>update</code>,
|
||||
which will:</p>
|
||||
<ol>
|
||||
@@ -421,7 +421,7 @@ ecosystem</a><!-- ignore --> that Chapter 14 will discuss, but for
|
||||
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
|
||||
so Rustaceans are able to write smaller projects that are assembled from a
|
||||
number of packages.</p>
|
||||
<h3>Generating a Random Number</h3>
|
||||
<a class="header" href="#generating-a-random-number" name="generating-a-random-number"><h3>Generating a Random Number</h3></a>
|
||||
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <em>src/main.rs</em>, as shown
|
||||
in Listing 2-3:</p>
|
||||
<figure>
|
||||
@@ -496,7 +496,7 @@ You guessed: 5
|
||||
</code></pre>
|
||||
<p>You should get different random numbers, and they should all be numbers between
|
||||
1 and 100. Great job!</p>
|
||||
<h2>Comparing the Guess to the Secret Number</h2>
|
||||
<a class="header" href="#comparing-the-guess-to-the-secret-number" name="comparing-the-guess-to-the-secret-number"><h2>Comparing the Guess to the Secret Number</h2></a>
|
||||
<p>Now that we have user input and a random number, we can compare them. That
|
||||
step is shown in Listing 2-4:</p>
|
||||
<figure>
|
||||
@@ -689,7 +689,7 @@ different behavior with different kinds of input: guess the number correctly,
|
||||
guess a number that is too high, and guess a number that is too low.</p>
|
||||
<p>We have most of the game working now, but the user can make only one guess.
|
||||
Let’s change that by adding a loop!</p>
|
||||
<h2>Allowing Multiple Guesses with Looping</h2>
|
||||
<a class="header" href="#allowing-multiple-guesses-with-looping" name="allowing-multiple-guesses-with-looping"><h2>Allowing Multiple Guesses with Looping</h2></a>
|
||||
<p>The <code>loop</code> keyword gives us an infinite loop. Add that now to give users more
|
||||
chances at guessing the number:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
@@ -763,7 +763,7 @@ error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
|
||||
<p>Typing <code>quit</code> actually quits the game, but so will any other non-number input.
|
||||
However, this is suboptimal to say the least. We want the game to automatically
|
||||
stop when the correct number is guessed.</p>
|
||||
<h3>Quitting After a Correct Guess</h3>
|
||||
<a class="header" href="#quitting-after-a-correct-guess" name="quitting-after-a-correct-guess"><h3>Quitting After a Correct Guess</h3></a>
|
||||
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
@@ -806,7 +806,7 @@ fn main() {
|
||||
<p>By adding the <code>break</code> line after <code>You win!</code>, the program will exit the loop
|
||||
when the user guesses the secret number correctly. Exiting the loop also means
|
||||
exiting the program, because the loop is the last part of <code>main</code>.</p>
|
||||
<h3>Handling Invalid Input</h3>
|
||||
<a class="header" href="#handling-invalid-input" name="handling-invalid-input"><h3>Handling Invalid Input</h3></a>
|
||||
<p>To further refine the game’s behavior, rather than crashing the program when
|
||||
the user inputs a non-number, let’s make the game ignore a non-number so the
|
||||
user can continue guessing. We can do that by altering the line where <code>guess</code> is
|
||||
@@ -904,7 +904,7 @@ fn main() {
|
||||
<p>Listing 2-5: Complete code of the guessing game</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
|
||||
<p>This project was a hands-on way to introduce you to many new Rust concepts:
|
||||
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Common Programming Concepts</h1>
|
||||
<a class="header" href="#common-programming-concepts" name="common-programming-concepts"><h1>Common Programming Concepts</h1></a>
|
||||
<p>This chapter covers concepts that appear in almost every programming language
|
||||
and how they work in Rust. Many programming languages have much in common at
|
||||
their core. None of the concepts presented in this chapter are unique to Rust,
|
||||
@@ -77,7 +77,7 @@ and control flow. These foundations will be in every Rust program, and learning
|
||||
them early will give you a strong core to start from.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<blockquote>
|
||||
<h3>Keywords</h3>
|
||||
<a class="header" href="#keywords" name="keywords"><h3>Keywords</h3></a>
|
||||
<p>The Rust language has a set of <em>keywords</em> that have been reserved for use by
|
||||
the language only, much like other languages do. Keep in mind that you cannot
|
||||
use these words as names of variables or functions. Most of the keywords have
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Variables and Mutability</h2>
|
||||
<a class="header" href="#variables-and-mutability" name="variables-and-mutability"><h2>Variables and Mutability</h2></a>
|
||||
<p>As mentioned in Chapter 2, by default variables are <em>immutable</em>. This is one of
|
||||
many nudges in Rust that encourages you to write your code in a way that takes
|
||||
advantage of the safety and easy concurrency that Rust offers. However, you
|
||||
@@ -147,7 +147,7 @@ an instance in place may be faster than copying and returning newly allocated
|
||||
instances. With smaller data structures, always creating new instances and
|
||||
writing in a more functional programming style may be easier to reason about,
|
||||
so the lower performance penalty might be worth it to gain that clarity.</p>
|
||||
<h3>Differences Between Variables and Constants</h3>
|
||||
<a class="header" href="#differences-between-variables-and-constants" name="differences-between-variables-and-constants"><h3>Differences Between Variables and Constants</h3></a>
|
||||
<p>Not being able to change the value of a variable might have reminded you of
|
||||
another programming concept that most languages have: <em>constants</em>. Constants
|
||||
are also values bound to a name that are not allowed to change, but there are a
|
||||
@@ -175,7 +175,7 @@ of seconds in a year.</p>
|
||||
constants is useful to convey the meaning of that value to future maintainers
|
||||
of the code. It also helps to have only one place in your code that you would
|
||||
need to change if the hardcoded value needed to be updated in the future.</p>
|
||||
<h3>Shadowing</h3>
|
||||
<a class="header" href="#shadowing" name="shadowing"><h3>Shadowing</h3></a>
|
||||
<p>As we saw in the guessing game tutorial in Chapter 2, we can declare new
|
||||
variables with the same name as a previous variables, and the new variable
|
||||
<em>shadows</em> the previous variable. Rustaceans say that the first variable is
|
||||
|
||||
+12
-12
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Data Types</h2>
|
||||
<a class="header" href="#data-types" name="data-types"><h2>Data Types</h2></a>
|
||||
<p>Every value in Rust is of a certain <em>type</em>, which tells Rust what kind of data
|
||||
is being specified so it knows how to work with that data. In this section,
|
||||
we’ll look at a number of types that are built into the language. We split the
|
||||
@@ -92,12 +92,12 @@ possible type we want to use:</p>
|
||||
= note: type annotations or generic parameter binding required
|
||||
</code></pre>
|
||||
<p>You’ll see different type annotations as we discuss the various data types.</p>
|
||||
<h3>Scalar Types</h3>
|
||||
<a class="header" href="#scalar-types" name="scalar-types"><h3>Scalar Types</h3></a>
|
||||
<p>A <em>scalar</em> type represents a single value. Rust has four primary scalar types:
|
||||
integers, floating-point numbers, booleans, and characters. You’ll likely
|
||||
recognize these from other programming languages, but let’s jump into how they
|
||||
work in Rust.</p>
|
||||
<h4>Integer Types</h4>
|
||||
<a class="header" href="#integer-types" name="integer-types"><h4>Integer Types</h4></a>
|
||||
<p>An <em>integer</em> is a number without a fractional component. We used one integer
|
||||
type earlier in this chapter, the <code>i32</code> type. This type declaration indicates
|
||||
that the value it’s associated with should be a signed integer (hence the <code>i</code>,
|
||||
@@ -153,7 +153,7 @@ that all number literals except the byte literal allow a type suffix, such as
|
||||
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>
|
||||
<a class="header" href="#floating-point-types" name="floating-point-types"><h4>Floating-Point Types</h4></a>
|
||||
<p>Rust also has two primitive types for <em>floating-point numbers</em>, which are
|
||||
numbers with decimal points. Rust’s floating-point types are <code>f32</code> and <code>f64</code>,
|
||||
which are 32 bits and 64 bits in size, respectively. The default type is <code>f64</code>
|
||||
@@ -173,7 +173,7 @@ your situation.</p>
|
||||
</code></pre>
|
||||
<p>Floating-point numbers are represented according to the IEEE-754 standard. The
|
||||
<code>f32</code> type is a single-precision float, and <code>f64</code> has double precision.</p>
|
||||
<h4>Numeric Operations</h4>
|
||||
<a class="header" href="#numeric-operations" name="numeric-operations"><h4>Numeric Operations</h4></a>
|
||||
<p>Rust supports the usual basic mathematic operations you’d expect for all of the
|
||||
number types: addition, subtraction, multiplication, division, and remainder.
|
||||
The following code shows how you’d use each one in a <code>let</code> statement:</p>
|
||||
@@ -198,7 +198,7 @@ The following code shows how you’d use each one in a <code>let</code> statemen
|
||||
<p>Each expression in these statements uses a mathematical operator and evaluates
|
||||
to a single value, which is then bound to a variable. Appendix B contains a
|
||||
list of all operators that Rust provides.</p>
|
||||
<h4>The Boolean Type</h4>
|
||||
<a class="header" href="#the-boolean-type" name="the-boolean-type"><h4>The Boolean Type</h4></a>
|
||||
<p>As in most other programming languages, a boolean type in Rust has two possible
|
||||
values: <code>true</code> and <code>false</code>. The boolean type in Rust is specified using <code>bool</code>.
|
||||
For example:</p>
|
||||
@@ -212,7 +212,7 @@ For example:</p>
|
||||
<p>The main way to consume boolean values is through conditionals, such as an <code>if</code>
|
||||
statement. We’ll cover how <code>if</code> statements work in Rust in the “Control Flow”
|
||||
section.</p>
|
||||
<h4>The Character Type</h4>
|
||||
<a class="header" href="#the-character-type" name="the-character-type"><h4>The Character Type</h4></a>
|
||||
<p>So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
|
||||
<code>char</code> type is the language’s most primitive alphabetic type, and the following
|
||||
code shows one way to use it:</p>
|
||||
@@ -231,10 +231,10 @@ Unicode Scalar Values range from <code>U+0000</code> to <code>U+D7FF</code> and
|
||||
so your human intuition for what a “character” is may not match up with what a
|
||||
<code>char</code> is in Rust. We’ll discuss this topic in detail in the “Strings” section
|
||||
in Chapter 8.</p>
|
||||
<h3>Compound Types</h3>
|
||||
<a class="header" href="#compound-types" name="compound-types"><h3>Compound Types</h3></a>
|
||||
<p><em>Compound types</em> can group multiple values of other types into one type. Rust
|
||||
has two primitive compound types: tuples and arrays.</p>
|
||||
<h4>Grouping Values into Tuples</h4>
|
||||
<a class="header" href="#grouping-values-into-tuples" name="grouping-values-into-tuples"><h4>Grouping Values into Tuples</h4></a>
|
||||
<p>A tuple is a general way of grouping together some number of other values with
|
||||
a variety of types into one compound type.</p>
|
||||
<p>We create a tuple by writing a comma-separated list of values inside
|
||||
@@ -280,7 +280,7 @@ value we want to access. For example:</p>
|
||||
<p>This program creates a tuple, <code>x</code>, and then makes new variables for each
|
||||
element by using their index. As with most programming languages, the first
|
||||
index in a tuple is 0.</p>
|
||||
<h4>Arrays</h4>
|
||||
<a class="header" href="#arrays" name="arrays"><h4>Arrays</h4></a>
|
||||
<p>Another way to have a collection of multiple values is with an <em>array</em>. Unlike
|
||||
a tuple, every element of an array must have the same type. Arrays in Rust are
|
||||
different than arrays in some other languages because arrays in Rust have a
|
||||
@@ -306,7 +306,7 @@ an array because you know it will always contain 12 items:</p>
|
||||
<pre><code class="language-rust">let months = ["January", "February", "March", "April", "May", "June", "July",
|
||||
"August", "September", "October", "November", "December"];
|
||||
</code></pre>
|
||||
<h5>Accessing Array Elements</h5>
|
||||
<a class="header" href="#accessing-array-elements" name="accessing-array-elements"><h5>Accessing Array Elements</h5></a>
|
||||
<p>An array is a single chunk of memory allocated on the stack. We can access
|
||||
elements of an array using indexing, like this:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
@@ -320,7 +320,7 @@ elements of an array using indexing, like this:</p>
|
||||
<p>In this example, the variable named <code>first</code> will get the value <code>1</code>, because
|
||||
that is the value at index <code>[0]</code> in the array. The variable named <code>second</code> will
|
||||
get the value <code>2</code> from index <code>[1]</code> in the array.</p>
|
||||
<h5>Invalid Array Element Access</h5>
|
||||
<a class="header" href="#invalid-array-element-access" name="invalid-array-element-access"><h5>Invalid Array Element Access</h5></a>
|
||||
<p>What happens if we try to access an element of an array that is past the end of
|
||||
the array? Say we change the example to the following:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>How Functions Work</h2>
|
||||
<a class="header" href="#how-functions-work" name="how-functions-work"><h2>How Functions Work</h2></a>
|
||||
<p>Functions are pervasive in Rust code. You’ve already seen one of the most
|
||||
important functions in the language: the <code>main</code> function, which is the entry
|
||||
point of many programs. You’ve also seen the <code>fn</code> keyword, which allows you to
|
||||
@@ -107,7 +107,7 @@ Another function.
|
||||
<p>The lines execute in the order in which they appear in the <code>main</code> function.
|
||||
First, the “Hello, world!” message prints, and then <code>another_function</code> is
|
||||
called and its message is printed.</p>
|
||||
<h3>Function Parameters</h3>
|
||||
<a class="header" href="#function-parameters" name="function-parameters"><h3>Function Parameters</h3></a>
|
||||
<p>Functions can also be defined to have <em>parameters</em>, which are special variables
|
||||
that are part of a function's signature. When a function has parameters, we can
|
||||
provide it with concrete values for those parameters. Technically, the concrete
|
||||
@@ -167,7 +167,7 @@ The value of y is: 6
|
||||
</code></pre>
|
||||
<p>Because we called the function with <code>5</code> as the value for <code>x</code> and <code>6</code> as the
|
||||
value for <code>y</code>, the two strings are printed using those values.</p>
|
||||
<h3>Function Bodies</h3>
|
||||
<a class="header" href="#function-bodies" name="function-bodies"><h3>Function Bodies</h3></a>
|
||||
<p>Function bodies are made up of a series of statements optionally ending in an
|
||||
expression. So far, we’ve only covered functions without an ending expression,
|
||||
but we have seen expressions as parts of statements. Because Rust is an
|
||||
@@ -175,7 +175,7 @@ expression-based language, this is an important distinction to understand.
|
||||
Other languages don’t have the same distinctions, so let’s look at what
|
||||
statements and expressions are and how their differences affect the bodies of
|
||||
functions.</p>
|
||||
<h3>Statements and Expressions</h3>
|
||||
<a class="header" href="#statements-and-expressions" name="statements-and-expressions"><h3>Statements and Expressions</h3></a>
|
||||
<p>We’ve actually already used statements and expressions. <em>Statements</em> are
|
||||
instructions that perform some action and do not return a value. <em>Expressions</em>
|
||||
evaluate to a resulting value. Let’s look at some examples.</p>
|
||||
@@ -247,7 +247,7 @@ unlike most of the lines you’ve seen so far. Expressions do not include ending
|
||||
semicolons. If you add a semicolon to the end of an expression, you turn it
|
||||
into a statement, which will then not return a value. Keep this in mind as you
|
||||
explore function return values and expressions next.</p>
|
||||
<h3>Functions with Return Values</h3>
|
||||
<a class="header" href="#functions-with-return-values" name="functions-with-return-values"><h3>Functions with Return Values</h3></a>
|
||||
<p>Functions can return values to the code that calls them. We don’t name return
|
||||
values, but we do declare their type after an arrow (<code>-></code>). In Rust, the return
|
||||
value of the function is synonymous with the value of the final expression in
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Comments</h2>
|
||||
<a class="header" href="#comments" name="comments"><h2>Comments</h2></a>
|
||||
<p>All programmers strive to make their code easy to understand, but sometimes
|
||||
extra explanation is warranted. In these cases, programmers leave notes, or
|
||||
<em>comments</em>, in their source code that the compiler will ignore but people
|
||||
|
||||
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Control Flow</h2>
|
||||
<a class="header" href="#control-flow" name="control-flow"><h2>Control Flow</h2></a>
|
||||
<p>Deciding whether or not to run some code depending on if a condition is true or
|
||||
deciding to run some code repeatedly while a condition is true are basic
|
||||
building blocks in most programming languages. The most common constructs that
|
||||
let you control the flow of execution of Rust code are <code>if</code> expressions and
|
||||
loops.</p>
|
||||
<h3><code>if</code> Expressions</h3>
|
||||
<a class="header" href="#if-expressions" name="if-expressions"><h3><code>if</code> Expressions</h3></a>
|
||||
<p>An <code>if</code> expression allows us to branch our code depending on conditions. We
|
||||
provide a condition and then state, “If this condition is met, run this block
|
||||
of code. If the condition is not met, do not run this block of code.”</p>
|
||||
@@ -161,7 +161,7 @@ expression to the following:</p>
|
||||
}
|
||||
</code></pre>
|
||||
<p>Running this code will print <code>number was something other than zero</code>.</p>
|
||||
<h4>Multiple Conditions with <code>else if</code></h4>
|
||||
<a class="header" href="#multiple-conditions-with-else-if" name="multiple-conditions-with-else-if"><h4>Multiple Conditions with <code>else if</code></h4></a>
|
||||
<p>We can have multiple conditions by combining <code>if</code> and <code>else</code> in an <code>else if</code>
|
||||
expression. For example:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
@@ -195,7 +195,7 @@ and once it finds one, it won’t even check the rest.</p>
|
||||
<p>Using too many <code>else if</code> expressions can clutter your code, so if you have more
|
||||
than one, you might want to refactor your code. Chapter 6 describes a powerful
|
||||
Rust branching construct called <code>match</code> for these cases.</p>
|
||||
<h4>Using <code>if</code> in a <code>let</code> statement</h4>
|
||||
<a class="header" href="#using-if-in-a-let-statement" name="using-if-in-a-let-statement"><h4>Using <code>if</code> in a <code>let</code> statement</h4></a>
|
||||
<p>Because <code>if</code> is an expression, we can use it on the right side of a <code>let</code>
|
||||
statement, for instance in Listing 3-4:</p>
|
||||
<figure>
|
||||
@@ -263,13 +263,13 @@ valid everywhere we use <code>number</code>. Rust wouldn’t be able to do that
|
||||
of <code>number</code> was only determined at runtime; the compiler would be more complex
|
||||
and would make fewer guarantees about the code if it had to keep track of
|
||||
multiple hypothetical types for any variable.</p>
|
||||
<h3>Repetition with Loops</h3>
|
||||
<a class="header" href="#repetition-with-loops" name="repetition-with-loops"><h3>Repetition with Loops</h3></a>
|
||||
<p>It’s often useful to execute a block of code more than once. For this task,
|
||||
Rust provides several <em>loops</em>. A loop runs through the code inside the loop
|
||||
body to the end and then starts immediately back at the beginning. To
|
||||
experiment with loops, let’s make a new project called <em>loops</em>.</p>
|
||||
<p>Rust has three kinds of loops: <code>loop</code>, <code>while</code>, and <code>for</code>. Let’s try each one.</p>
|
||||
<h4>Repeating Code with <code>loop</code></h4>
|
||||
<a class="header" href="#repeating-code-with-loop" name="repeating-code-with-loop"><h4>Repeating Code with <code>loop</code></h4></a>
|
||||
<p>The <code>loop</code> keyword tells Rust to execute a block of code over and over again
|
||||
forever or until you explicitly tell it to stop.</p>
|
||||
<p>As an example, change the <em>src/main.rs</em> file in your <em>loops</em> directory to look
|
||||
@@ -301,7 +301,7 @@ You can place the <code>break</code> keyword within the loop to tell the program
|
||||
stop executing the loop. Recall that we did this in the guessing game in the
|
||||
“Quitting After a Correct Guess” section of Chapter 2 to exit the
|
||||
program when the user won the game by guessing the correct number.</p>
|
||||
<h4>Conditional Loops with <code>while</code></h4>
|
||||
<a class="header" href="#conditional-loops-with-while" name="conditional-loops-with-while"><h4>Conditional Loops with <code>while</code></h4></a>
|
||||
<p>It’s often useful for a program to evaluate a condition within a loop. While
|
||||
the condition is true, the loop runs. When the condition ceases to be true, you
|
||||
call <code>break</code>, stopping the loop. This loop type could be implemented using a
|
||||
@@ -327,7 +327,7 @@ prints another message and exits:</p>
|
||||
<p>This construct eliminates a lot of nesting that would be necessary if you used
|
||||
<code>loop</code>, <code>if</code>, <code>else</code>, and <code>break</code>, and it’s clearer. While a condition holds
|
||||
true, the code runs; otherwise, it exits the loop.</p>
|
||||
<h4>Looping Through a Collection with <code>for</code></h4>
|
||||
<a class="header" href="#looping-through-a-collection-with-for" name="looping-through-a-collection-with-for"><h4>Looping Through a Collection with <code>for</code></h4></a>
|
||||
<p>You could use the <code>while</code> construct to loop over the elements of a collection,
|
||||
such as an array. For example:</p>
|
||||
<figure>
|
||||
@@ -409,7 +409,7 @@ we’ve not yet talked about, <code>rev</code>, to reverse the range:</p>
|
||||
}
|
||||
</code></pre>
|
||||
<p>This code is a bit nicer, isn’t it?</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>You made it! That was a sizable chapter: you learned about variables, scalar
|
||||
and<code>if</code> expressions, and loops! If you want to practice with the concepts
|
||||
discussed in this chapter, try building programs to do the following:</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Understanding Ownership</h1>
|
||||
<a class="header" href="#understanding-ownership" name="understanding-ownership"><h1>Understanding Ownership</h1></a>
|
||||
<p>Ownership is Rust’s most unique feature, and it enables Rust to make memory
|
||||
safety guarantees without needing a garbage collector. Therefore, it’s
|
||||
important to understand how ownership works in Rust. In this chapter we’ll talk
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>What Is Ownership?</h2>
|
||||
<a class="header" href="#what-is-ownership" name="what-is-ownership"><h2>What Is Ownership?</h2></a>
|
||||
<p>Rust’s central feature is <em>ownership</em>. Although the feature is straightforward
|
||||
to explain, it has deep implications for the rest of the language.</p>
|
||||
<p>All programs have to manage the way they use a computer’s memory while running.
|
||||
@@ -86,7 +86,7 @@ working through some examples that focus on a very common data structure:
|
||||
strings.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<blockquote>
|
||||
<h3>The Stack and the Heap</h3>
|
||||
<a class="header" href="#the-stack-and-the-heap" name="the-stack-and-the-heap"><h3>The Stack and the Heap</h3></a>
|
||||
<p>In many programming languages, we don’t have to think about the stack and the
|
||||
heap very often. But in a systems programming language like Rust, whether a
|
||||
value is on the stack or the heap has more of an effect on how the language
|
||||
@@ -140,7 +140,7 @@ heap very often, but knowing that managing heap data is why ownership exists
|
||||
can help explain why it works the way it does.</p>
|
||||
</blockquote>
|
||||
<!-- PROD: END BOX -->
|
||||
<h3>Ownership Rules</h3>
|
||||
<a class="header" href="#ownership-rules" name="ownership-rules"><h3>Ownership Rules</h3></a>
|
||||
<p>First, let’s take a look at the ownership rules. Keep these rules in mind as we
|
||||
work through the examples that illustrate the rules:</p>
|
||||
<blockquote>
|
||||
@@ -150,7 +150,7 @@ work through the examples that illustrate the rules:</p>
|
||||
<li>When the owner goes out of scope, the value will be dropped.</li>
|
||||
</ol>
|
||||
</blockquote>
|
||||
<h3>Variable Scope</h3>
|
||||
<a class="header" href="#variable-scope" name="variable-scope"><h3>Variable Scope</h3></a>
|
||||
<p>We’ve walked through an example of a Rust program already in Chapter 2. Now
|
||||
that we’re past basic syntax, we won’t include all the <code>fn main() {</code> code in
|
||||
examples, so if you’re following along, you’ll have to put the following
|
||||
@@ -185,7 +185,7 @@ comments annotating where the variable <code>s</code> is valid:</p>
|
||||
<p>At this point, the relationship between scopes and when variables are valid is
|
||||
similar to other programming languages. Now we’ll build on top of this
|
||||
understanding by introducing the <code>String</code> type.</p>
|
||||
<h3>The <code>String</code> Type</h3>
|
||||
<a class="header" href="#the-string-type" name="the-string-type"><h3>The <code>String</code> Type</h3></a>
|
||||
<p>To illustrate the rules of ownership, we need a data type that is more complex
|
||||
than the ones we covered in Chapter 3. All the data types we’ve looked at
|
||||
previously are stored on the stack and popped off the stack when their scope is
|
||||
@@ -220,7 +220,7 @@ println!("{}", s); // This will print `hello, world!`
|
||||
</code></pre>
|
||||
<p>So, what’s the difference here? Why can <code>String</code> be mutated but literals
|
||||
cannot? The difference is how these two types deal with memory.</p>
|
||||
<h3>Memory and Allocation</h3>
|
||||
<a class="header" href="#memory-and-allocation" name="memory-and-allocation"><h3>Memory and Allocation</h3></a>
|
||||
<p>In the case of a string literal, we know the contents at compile time so the
|
||||
text is hardcoded directly into the final executable, making string literals
|
||||
fast and efficient. But these properties only come from its immutability.
|
||||
@@ -272,7 +272,7 @@ patterns.</p>
|
||||
simple right now, but the behavior of code can be unexpected in more
|
||||
complicated situations when we want to have multiple variables use the data
|
||||
we’ve allocated on the heap. Let’s explore some of those situations now.</p>
|
||||
<h4>Ways Variables and Data Interact: Move</h4>
|
||||
<a class="header" href="#ways-variables-and-data-interact-move" name="ways-variables-and-data-interact-move"><h4>Ways Variables and Data Interact: Move</h4></a>
|
||||
<p>Multiple variables can interact with the same data in different ways in Rust.
|
||||
Let’s look at an example using an integer in Listing 4-2:</p>
|
||||
<figure>
|
||||
@@ -381,7 +381,7 @@ alone will free the memory, and we’re done.</p>
|
||||
<p>In addition, there’s a design choice that’s implied by this: Rust will never
|
||||
automatically create “deep” copies of your data. Therefore, any <em>automatic</em>
|
||||
copying can be assumed to be inexpensive in terms of runtime performance.</p>
|
||||
<h4>Ways Variables and Data Interact: Clone</h4>
|
||||
<a class="header" href="#ways-variables-and-data-interact-clone" name="ways-variables-and-data-interact-clone"><h4>Ways Variables and Data Interact: Clone</h4></a>
|
||||
<p>If we <em>do</em> want to deeply copy the heap data of the <code>String</code>, not just the
|
||||
stack data, we can use a common method called <code>clone</code>. We’ll discuss method
|
||||
syntax in Chapter 5, but because methods are a common feature in many
|
||||
@@ -397,7 +397,7 @@ in Figure 4-5, where the heap data <em>does</em> get copied.</p>
|
||||
<p>When you see a call to <code>clone</code>, you know that some arbitrary code is being
|
||||
executed and that code may be expensive. It’s a visual indicator that something
|
||||
different is going on.</p>
|
||||
<h4>Stack-Only Data: Copy</h4>
|
||||
<a class="header" href="#stack-only-data-copy" name="stack-only-data-copy"><h4>Stack-Only Data: Copy</h4></a>
|
||||
<p>There’s another wrinkle we haven’t talked about yet. This code using integers,
|
||||
part of which was shown earlier in Listing 4-2, works and is valid:</p>
|
||||
<pre><code class="language-rust">let x = 5;
|
||||
@@ -431,7 +431,7 @@ be sure, but as a general rule, any group of simple scalar values can be
|
||||
<li>Tuples, but only if they contain types that are also <code>Copy</code>. <code>(i32, i32)</code> is
|
||||
<code>Copy</code>, but <code>(i32, String)</code> is not.</li>
|
||||
</ul>
|
||||
<h3>Ownership and Functions</h3>
|
||||
<a class="header" href="#ownership-and-functions" name="ownership-and-functions"><h3>Ownership and Functions</h3></a>
|
||||
<p>The semantics for passing a value to a function are similar to assigning a
|
||||
value to a variable. Passing a variable to a function will move or copy, just
|
||||
like assignment. Listing 4-7 has an example with some annotations showing where
|
||||
@@ -469,7 +469,7 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope.
|
||||
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>
|
||||
<a class="header" href="#return-values-and-scope" name="return-values-and-scope"><h3>Return Values and Scope</h3></a>
|
||||
<p>Returning values can also transfer ownership. Here’s an example with similar
|
||||
annotations to those in Listing 4-7:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>References and Borrowing</h2>
|
||||
<a class="header" href="#references-and-borrowing" name="references-and-borrowing"><h2>References and Borrowing</h2></a>
|
||||
<p>The issue with the tuple code at the end of the preceding section is that we
|
||||
have to return the <code>String</code> to the calling function so we can still use the
|
||||
<code>String</code> after the call to <code>calculate_length</code>, because the <code>String</code> was moved
|
||||
@@ -153,7 +153,7 @@ fn change(some_string: &String) {
|
||||
</code></pre>
|
||||
<p>Just as variables are immutable by default, so are references. We’re not
|
||||
allowed to modify something we have a reference to.</p>
|
||||
<h3>Mutable References</h3>
|
||||
<a class="header" href="#mutable-references" name="mutable-references"><h3>Mutable References</h3></a>
|
||||
<p>We can fix the error in the code from Listing 4-9 with just a small tweak:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
@@ -243,7 +243,7 @@ the data.</p>
|
||||
Rust compiler pointing out a potential bug early (at compile time rather than
|
||||
at runtime) and showing you exactly where the problem is instead of you having
|
||||
to track down why sometimes your data isn’t what you thought it should be.</p>
|
||||
<h3>Dangling References</h3>
|
||||
<a class="header" href="#dangling-references" name="dangling-references"><h3>Dangling References</h3></a>
|
||||
<p>In languages with pointers, it’s easy to erroneously create a <em>dangling
|
||||
pointer</em>, a pointer that references a location in memory that may have been
|
||||
given to someone else, by freeing some memory while preserving a pointer to
|
||||
@@ -306,7 +306,7 @@ won’t let us do this.</p>
|
||||
</code></pre>
|
||||
<p>This works without any problems. Ownership is moved out, and nothing is
|
||||
deallocated.</p>
|
||||
<h3>The Rules of References</h3>
|
||||
<a class="header" href="#the-rules-of-references" name="the-rules-of-references"><h3>The Rules of References</h3></a>
|
||||
<p>Let’s recap what we’ve discussed about references:</p>
|
||||
<ol>
|
||||
<li>At any given time, you can have <em>either</em> but not both of:</li>
|
||||
|
||||
+6
-6
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Slices</h2>
|
||||
<a class="header" href="#slices" name="slices"><h2>Slices</h2></a>
|
||||
<p>Another data type that does not have ownership is the <em>slice</em>. Slices let you
|
||||
reference a contiguous sequence of elements in a collection rather than the
|
||||
whole collection.</p>
|
||||
@@ -180,7 +180,7 @@ that were calculated from data in a particular state but aren’t tied to that
|
||||
state at all. We now have three unrelated variables floating around that need
|
||||
to be kept in sync.</p>
|
||||
<p>Luckily, Rust has a solution to this problem: string slices.</p>
|
||||
<h3>String Slices</h3>
|
||||
<a class="header" href="#string-slices" name="string-slices"><h3>String Slices</h3></a>
|
||||
<p>A <em>string slice</em> is a reference to part of a <code>String</code>, and looks like this:</p>
|
||||
<pre><code class="language-rust">let s = String::from("hello world");
|
||||
|
||||
@@ -290,7 +290,7 @@ something, we cannot also take a mutable reference. Because <code>clear</code> n
|
||||
truncate the <code>String</code>, it tries to take a mutable reference, which fails. Not
|
||||
only has Rust made our API easier to use, but it has also eliminated an entire
|
||||
class of errors at compile time!</p>
|
||||
<h4>String Literals Are Slices</h4>
|
||||
<a class="header" href="#string-literals-are-slices" name="string-literals-are-slices"><h4>String Literals Are Slices</h4></a>
|
||||
<p>Recall that we talked about string literals being stored inside the binary. Now
|
||||
that we know about slices, we can properly understand string literals:</p>
|
||||
<pre><code class="language-rust">let s = "Hello, world!";
|
||||
@@ -298,7 +298,7 @@ that we know about slices, we can properly understand string literals:</p>
|
||||
<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 Parameters</h4>
|
||||
<a class="header" href="#string-slices-as-parameters" name="string-slices-as-parameters"><h4>String Slices as Parameters</h4></a>
|
||||
<p>Knowing that you can take slices of literals and <code>String</code>s leads us to one more
|
||||
improvement on <code>first_word</code>, and that’s its signature:</p>
|
||||
<pre><code class="language-rust,ignore">fn first_word(s: &String) -> &str {
|
||||
@@ -339,7 +339,7 @@ fn main() {
|
||||
let word = first_word(my_string_literal);
|
||||
}
|
||||
</code></pre>
|
||||
<h3>Other Slices</h3>
|
||||
<a class="header" href="#other-slices" name="other-slices"><h3>Other Slices</h3></a>
|
||||
<p>String slices, as you might imagine, are specific to strings. But there’s a
|
||||
more general slice type, too. Consider this array:</p>
|
||||
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
|
||||
@@ -354,7 +354,7 @@ let slice = &a[1..3];
|
||||
storing a reference to the first element and a length. You’ll use this kind of
|
||||
slice for all sorts of other collections. We’ll discuss these collections in
|
||||
detail when we talk about vectors in Chapter 8.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>The concepts of ownership, borrowing, and slices are what ensure memory safety
|
||||
in Rust programs at compile time. The Rust language gives you control over your
|
||||
memory usage like other systems programming languages, but having the owner of
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Structs</h1>
|
||||
<a class="header" href="#structs" name="structs"><h1>Structs</h1></a>
|
||||
<p>A <code>struct</code>, short for <em>structure</em>, is a custom data type that lets us name and
|
||||
package together multiple related values that make up a meaningful group. If
|
||||
you come from an object-oriented language, a <code>struct</code> is like an object’s data
|
||||
@@ -126,7 +126,7 @@ let user1 = User {
|
||||
</code></pre>
|
||||
<p>To get a particular value out of a struct, we can use dot notation. If we
|
||||
wanted just this user’s email address, we can say <code>user1.email</code>.</p>
|
||||
<h2>Ownership of Struct Data</h2>
|
||||
<a class="header" href="#ownership-of-struct-data" name="ownership-of-struct-data"><h2>Ownership of Struct Data</h2></a>
|
||||
<p>In the <code>User</code> struct definition in Listing 5-1, we used the owned <code>String</code> type
|
||||
rather than the <code>&str</code> string slice type. This is a deliberate choice because
|
||||
we want instances of this struct to own all of its data, and for that data to
|
||||
@@ -169,7 +169,7 @@ error[E0106]: missing lifetime specifier
|
||||
<p>We will talk about how to fix these errors in order to store references in
|
||||
structs in Chapter 10, but for now, fix errors like these by switching to owned
|
||||
types like <code>String</code> instead of references like <code>&str</code>.</p>
|
||||
<h2>An Example Program</h2>
|
||||
<a class="header" href="#an-example-program" name="an-example-program"><h2>An Example Program</h2></a>
|
||||
<p>To understand when we might want to use structs, let’s write a program that
|
||||
calculates the area of a rectangle. We’ll start off with single variables, then
|
||||
refactor our program until we’re using structs instead.</p>
|
||||
@@ -201,7 +201,7 @@ width in separate variables</p>
|
||||
<p>Let’s try running this program with <code>cargo run</code>:</p>
|
||||
<pre><code class="language-text">The area of the rectangle is 1500 square pixels.
|
||||
</code></pre>
|
||||
<h3>Refactoring with Tuples</h3>
|
||||
<a class="header" href="#refactoring-with-tuples" name="refactoring-with-tuples"><h3>Refactoring with Tuples</h3></a>
|
||||
<p>Our little program works okay; it figures out the area of the rectangle by
|
||||
calling the <code>area</code> function with each dimension. But we can do better. The
|
||||
length and the width are related to each other since together they describe one
|
||||
@@ -251,7 +251,7 @@ index <code>1</code>. If someone else was to work on this code, they would have
|
||||
this out and remember it as well. It would be easy to forget or mix these
|
||||
values up and cause errors, since we haven’t conveyed the meaning of our data
|
||||
in our code.</p>
|
||||
<h3>Refactoring with Structs: Adding More Meaning</h3>
|
||||
<a class="header" href="#refactoring-with-structs-adding-more-meaning" name="refactoring-with-structs-adding-more-meaning"><h3>Refactoring with Structs: Adding More Meaning</h3></a>
|
||||
<p>Here is where we bring in structs. We can transform our tuple into a data type
|
||||
with a name for the whole as well as names for the parts, as shown in Listing
|
||||
5-4:</p>
|
||||
@@ -296,7 +296,7 @@ calculate the area of a <code>Rectangle</code>, using its <code>length</code> an
|
||||
This conveys that the length and width are related to each other, and gives
|
||||
descriptive names to the values rather than using the tuple index values of <code>0</code>
|
||||
and <code>1</code>. This is a win for clarity.</p>
|
||||
<h3>Adding Useful Functionality with Derived Traits</h3>
|
||||
<a class="header" href="#adding-useful-functionality-with-derived-traits" name="adding-useful-functionality-with-derived-traits"><h3>Adding Useful Functionality with Derived Traits</h3></a>
|
||||
<p>It’d be nice to be able to print out an instance of our <code>Rectangle</code> while we’re
|
||||
debugging our program and see the values for all its fields. Listing 5-5 tries
|
||||
using the <code>println!</code> macro as we have been:</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Method Syntax</h2>
|
||||
<a class="header" href="#method-syntax" name="method-syntax"><h2>Method Syntax</h2></a>
|
||||
<p><em>Methods</em> are similar to functions: they’re declared with the <code>fn</code> keyword and
|
||||
their name, they can have parameters and return values, and they contain some
|
||||
code that gets run when they’re called from somewhere else. Methods are
|
||||
@@ -75,7 +75,7 @@ different from functions, however, because they’re defined within the context
|
||||
of a struct (or an enum or a trait object, which we will cover in Chapters 6
|
||||
and 13, respectively), and their first parameter is always <code>self</code>, which
|
||||
represents the instance of the struct that the method is being called on.</p>
|
||||
<h3>Defining Methods</h3>
|
||||
<a class="header" href="#defining-methods" name="defining-methods"><h3>Defining Methods</h3></a>
|
||||
<p>Let’s change our <code>area</code> function that has a <code>Rectangle</code> instance as a parameter
|
||||
and instead make an <code>area</code> method defined on the <code>Rectangle</code> struct, as shown
|
||||
in Listing 5-7:</p>
|
||||
@@ -136,7 +136,7 @@ instance of a type together in one <code>impl</code> block, rather than make fut
|
||||
of our code search for capabilities of <code>Rectangle</code> all over the place.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<blockquote>
|
||||
<h3>Where’s the <code>-></code> operator?</h3>
|
||||
<a class="header" href="#wheres-the---operator" name="wheres-the---operator"><h3>Where’s the <code>-></code> operator?</h3></a>
|
||||
<p>In languages like C++, there are two different operators for calling methods:
|
||||
<code>.</code> if you’re calling a method on the object directly, and <code>-></code> if you’re
|
||||
calling the method on a pointer to the object and thus need to dereference the
|
||||
@@ -175,7 +175,7 @@ consuming (so <code>self</code>). The fact that Rust makes borrowing implicit fo
|
||||
receivers is a big part of making ownership ergonomic in practice.</p>
|
||||
</blockquote>
|
||||
<!-- PROD: END BOX -->
|
||||
<h3>Methods with More Parameters</h3>
|
||||
<a class="header" href="#methods-with-more-parameters" name="methods-with-more-parameters"><h3>Methods with More Parameters</h3></a>
|
||||
<p>Let’s practice some more with methods by implementing a second method on our
|
||||
<code>Rectangle</code> struct. This time, we’d like for an instance of <code>Rectangle</code> to take
|
||||
another instance of <code>Rectangle</code> and return <code>true</code> if the second rectangle could
|
||||
@@ -235,7 +235,7 @@ impl Rectangle {
|
||||
Methods can have multiple parameters that we add to the signature after the
|
||||
<code>self</code> parameter, and those parameters work just like parameters in functions
|
||||
do.</p>
|
||||
<h3>Associated Functions</h3>
|
||||
<a class="header" href="#associated-functions" name="associated-functions"><h3>Associated Functions</h3></a>
|
||||
<p>One more useful feature of <code>impl</code> blocks: we’re allowed to define functions
|
||||
within <code>impl</code> blocks that <em>don’t</em> take <code>self</code> as a parameter. These are called
|
||||
<em>associated functions</em>, since they’re associated with the struct. They’re still
|
||||
@@ -263,7 +263,7 @@ impl Rectangle {
|
||||
<code>let sq = Rectangle::square(3);</code>, for example. This function is namespaced by
|
||||
the struct: the <code>::</code> syntax is used for both associated functions and
|
||||
namespaces created by modules, which we’ll learn about in Chapter 7.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Structs let us create custom types that are meaningful for our domain. By using
|
||||
structs, we can keep associated pieces of data connected to each other and name
|
||||
each piece to make our code clear. Methods let us specify the behavior that
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Enums and Pattern Matching</h1>
|
||||
<a class="header" href="#enums-and-pattern-matching" name="enums-and-pattern-matching"><h1>Enums and Pattern Matching</h1></a>
|
||||
<p>In this chapter we’ll look at <em>enumerations</em>, also referred to as <em>enums</em>.
|
||||
Enums allow you to define a type by enumerating its possible values. First,
|
||||
we’ll define and use an enum to show how an enum can encode meaning along with
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Defining an Enum</h2>
|
||||
<a class="header" href="#defining-an-enum" name="defining-an-enum"><h2>Defining an Enum</h2></a>
|
||||
<p>Let’s look at a situation we might want to express in code and see why enums
|
||||
are useful and more appropriate than structs in this case. Say we need to work
|
||||
with IP addresses. Currently, two major standards are used for IP addresses:
|
||||
@@ -89,7 +89,7 @@ as the <em>variants</em> of the enum:</p>
|
||||
}
|
||||
</code></pre>
|
||||
<p><code>IpAddrKind</code> is now a custom data type that we can use elsewhere in our code.</p>
|
||||
<h3>Enum Values</h3>
|
||||
<a class="header" href="#enum-values" name="enum-values"><h3>Enum Values</h3></a>
|
||||
<p>We can create instances of each of the two variants of <code>IpAddrKind</code> like this:</p>
|
||||
<pre><code class="language-rust"># enum IpAddrKind {
|
||||
# V4,
|
||||
@@ -283,7 +283,7 @@ method on. In this example, we’ve created a variable <code>m</code> that has t
|
||||
<code>call</code> method when <code>m.call()</code> runs.</p>
|
||||
<p>Let’s look at another enum in the standard library that is very common and
|
||||
useful: <code>Option</code>.</p>
|
||||
<h3>The <code>Option</code> Enum and Its Advantages Over Null Values</h3>
|
||||
<a class="header" href="#the-option-enum-and-its-advantages-over-null-values" name="the-option-enum-and-its-advantages-over-null-values"><h3>The <code>Option</code> Enum and Its Advantages Over Null Values</h3></a>
|
||||
<p>In the previous section, we looked at how the <code>IpAddr</code> enum let us use Rust’s
|
||||
type system to encode more information than just the data into our program.
|
||||
This section explores a case study of <code>Option</code>, which is another enum defined
|
||||
|
||||
+7
-7
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>The <code>match</code> Control Flow Operator</h2>
|
||||
<a class="header" href="#the-match-control-flow-operator" name="the-match-control-flow-operator"><h2>The <code>match</code> Control Flow Operator</h2></a>
|
||||
<p>Rust has an extremely powerful control-flow operator called <code>match</code> that allows
|
||||
us to compare a value against a series of patterns and then execute code based
|
||||
on which pattern matches. Patterns can be made up of literal values, variable
|
||||
@@ -148,7 +148,7 @@ fn value_in_cents(coin: Coin) -> i32 {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<h3>Patterns that Bind to Values</h3>
|
||||
<a class="header" href="#patterns-that-bind-to-values" name="patterns-that-bind-to-values"><h3>Patterns that Bind to Values</h3></a>
|
||||
<p>Another useful feature of match arms is that they can bind to parts of the
|
||||
values that match the pattern. This is how we can extract values out of enum
|
||||
variants.</p>
|
||||
@@ -217,7 +217,7 @@ of the match arms, none of them match until we reach <code>Coin::Quarter(state)<
|
||||
that point, the binding for <code>state</code> will be the value <code>UsState::Alaska</code>. We can
|
||||
then use that binding in the <code>println!</code> expression, thus getting the inner
|
||||
state value out of the <code>Coin</code> enum variant for <code>Quarter</code>.</p>
|
||||
<h3>Matching with <code>Option<T></code></h3>
|
||||
<a class="header" href="#matching-with-optiont" name="matching-with-optiont"><h3>Matching with <code>Option<T></code></h3></a>
|
||||
<p>In the previous section we wanted to get the inner <code>T</code> value out of the <code>Some</code>
|
||||
case when using <code>Option<T></code>; we can also handle <code>Option<T></code> using <code>match</code> as we
|
||||
did with the <code>Coin</code> enum! Instead of comparing coins, we’ll compare the
|
||||
@@ -245,7 +245,7 @@ let none = plus_one(None);
|
||||
<p>Listing 6-5: A function that uses a <code>match</code> expression on an <code>Option<i32></code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<h4>Matching <code>Some(T)</code></h4>
|
||||
<a class="header" href="#matching-somet" name="matching-somet"><h4>Matching <code>Some(T)</code></h4></a>
|
||||
<p>Let’s examine the first execution of <code>plus_one</code> in more detail. When we call
|
||||
<code>plus_one(five)</code>, the variable <code>x</code> in the body of <code>plus_one</code> will have the
|
||||
value <code>Some(5)</code>. We then compare that against each match arm.</p>
|
||||
@@ -259,7 +259,7 @@ next arm.</p>
|
||||
The <code>i</code> binds to the value contained in <code>Some</code>, so <code>i</code> takes the value <code>5</code>. The
|
||||
code in the match arm is then executed, so we add one to the value of <code>i</code> and
|
||||
create a new <code>Some</code> value with our total <code>6</code> inside.</p>
|
||||
<h4>Matching <code>None</code></h4>
|
||||
<a class="header" href="#matching-none" name="matching-none"><h4>Matching <code>None</code></h4></a>
|
||||
<p>Now let’s consider the second call of <code>plus_one</code> in Listing 6-5 where <code>x</code> is
|
||||
<code>None</code>. We enter the <code>match</code> and compare to the first arm.</p>
|
||||
<pre><code class="language-rust,ignore">None => None,
|
||||
@@ -272,7 +272,7 @@ pattern a lot in Rust code: <code>match</code> against an enum, bind a variable
|
||||
data inside, and then execute code based on it. It’s a bit tricky at first, but
|
||||
once you get used to it, you’ll wish you had it in all languages. It’s
|
||||
consistently a user favorite.</p>
|
||||
<h3>Matches Are Exhaustive</h3>
|
||||
<a class="header" href="#matches-are-exhaustive" name="matches-are-exhaustive"><h3>Matches Are Exhaustive</h3></a>
|
||||
<p>There’s one other aspect of <code>match</code> we need to discuss. Consider this version
|
||||
of our <code>plus_one</code> function:</p>
|
||||
<pre><code class="language-rust,ignore">fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
@@ -296,7 +296,7 @@ possibility in order for the code 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, thus making the billion dollar mistake discussed earlier.</p>
|
||||
<h3>The <code>_</code> Placeholder</h3>
|
||||
<a class="header" href="#the-_-placeholder" name="the-_-placeholder"><h3>The <code>_</code> Placeholder</h3></a>
|
||||
<p>Rust also has a pattern we can use in situations when we don’t want to list all
|
||||
possible values. For example, a <code>u8</code> can have valid values of 0 through 255. If
|
||||
we only care about the values 1, 3, 5, and 7, we don’t want to have to list out
|
||||
|
||||
+2
-2
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Concise Control Flow with <code>if let</code></h2>
|
||||
<a class="header" href="#concise-control-flow-with-if-let" name="concise-control-flow-with-if-let"><h2>Concise Control Flow with <code>if let</code></h2></a>
|
||||
<p>The <code>if let</code> syntax lets you combine <code>if</code> and <code>let</code> into a less verbose way to
|
||||
handle values that match one pattern and ignore the rest. Consider the program
|
||||
in Listing 6-6 that matches on an <code>Option<u8></code> value but only wants to execute
|
||||
@@ -154,7 +154,7 @@ if let Coin::Quarter(state) = coin {
|
||||
</code></pre>
|
||||
<p>If you have a situation in which your program has logic that is too verbose to
|
||||
express using a <code>match</code>, remember that <code>if let</code> is in your Rust toolbox as well.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>We’ve now covered how to use enums to create custom types that can be one of a
|
||||
set of enumerated values. We’ve shown how the standard library’s <code>Option<T></code>
|
||||
type helps you use the type system to prevent errors. When enum values have
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Modules</h1>
|
||||
<a class="header" href="#modules" name="modules"><h1>Modules</h1></a>
|
||||
<p>When you start writing programs in Rust, your code might live solely in the
|
||||
<code>main</code> function. As your code grows, you’ll eventually move functionality out
|
||||
into other functions, both for re-use and for better organization. By splitting
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2><code>mod</code> and the Filesystem</h2>
|
||||
<a class="header" href="#mod-and-the-filesystem" name="mod-and-the-filesystem"><h2><code>mod</code> and the Filesystem</h2></a>
|
||||
<p>We’ll start our module example by making a new project with Cargo, but instead
|
||||
of creating a binary crate, we’re going to make a library crate: a project that
|
||||
other people can pull into their projects as a dependency. We saw this with the
|
||||
@@ -101,7 +101,7 @@ to only compile our library crate’s code.</p>
|
||||
<p>We’re going to look at different options for organizing your library’s code
|
||||
which will be suitable in a variety of situations, depending on the intentions
|
||||
you have for your code.</p>
|
||||
<h3>Module Definitions</h3>
|
||||
<a class="header" href="#module-definitions" name="module-definitions"><h3>Module Definitions</h3></a>
|
||||
<p>For our <code>communicator</code> networking library, we’re first going to define a module
|
||||
named <code>network</code> that contains the definition of a function called <code>connect</code>.
|
||||
Every module definition in Rust starts with the <code>mod</code> keyword. Add this code to
|
||||
@@ -190,7 +190,7 @@ they’ll need to be organized logically in order to keep track of them. What
|
||||
of your library think about your project’s domain. Use the techniques we’ve
|
||||
shown here to create side-by-side modules and nested modules in whatever
|
||||
structure you would like.</p>
|
||||
<h3>Moving Modules to Other Files</h3>
|
||||
<a class="header" href="#moving-modules-to-other-files" name="moving-modules-to-other-files"><h3>Moving Modules to Other Files</h3></a>
|
||||
<p>Modules form a hierarchical structure, much like another structure in computing
|
||||
that you’re used to: file systems! We can use Rust’s module system along with
|
||||
multiple files to split Rust projects up so that not everything lives in
|
||||
@@ -422,7 +422,7 @@ module then goes into the <em>src/network/mod.rs</em> file, and the submodule
|
||||
<code>network::client</code> can have its own <em>src/network/client.rs</em> file. Now the
|
||||
top-level <em>src/client.rs</em> is unambiguously the code that belongs to the
|
||||
<code>client</code> module.</p>
|
||||
<h3>Rules of Module File Systems</h3>
|
||||
<a class="header" href="#rules-of-module-file-systems" name="rules-of-module-file-systems"><h3>Rules of Module File Systems</h3></a>
|
||||
<p>In summary, these are the rules of modules with regards to files:</p>
|
||||
<ul>
|
||||
<li>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Controlling Visibility with <code>pub</code></h2>
|
||||
<a class="header" href="#controlling-visibility-with-pub" name="controlling-visibility-with-pub"><h2>Controlling Visibility with <code>pub</code></h2></a>
|
||||
<p>We resolved the error messages shown in Listing 7-4 by moving the <code>network</code> and
|
||||
<code>network::server</code> code into the <em>src/network/mod.rs</em> and
|
||||
<em>src/network/server.rs</em> files, respectively. At that point, <code>cargo build</code> was
|
||||
@@ -139,7 +139,7 @@ considers the theoretical external usage that’s now possible as the function
|
||||
“being used.” Thus, when something is marked as public, Rust will not require
|
||||
that it’s used in our own program and will stop warning that the item is
|
||||
unused.</p>
|
||||
<h3>Making a Function Public</h3>
|
||||
<a class="header" href="#making-a-function-public" name="making-a-function-public"><h3>Making a Function Public</h3></a>
|
||||
<p>To tell Rust to make something public, we add the <code>pub</code> keyword to the start of
|
||||
the declaration of the item we want to make public. We’ll focus on fixing the
|
||||
warning that tells us that <code>client::connect</code> has gone unused for now, as well
|
||||
@@ -226,7 +226,7 @@ pub mod network;
|
||||
| ^
|
||||
</code></pre>
|
||||
<p>Only one warning left! Try to fix this one on your own!</p>
|
||||
<h3>Privacy Rules</h3>
|
||||
<a class="header" href="#privacy-rules" name="privacy-rules"><h3>Privacy Rules</h3></a>
|
||||
<p>Overall, these are the rules for item visibility:</p>
|
||||
<ol>
|
||||
<li>If an item is public, it can be accessed through any of its
|
||||
@@ -234,7 +234,7 @@ parent modules.</li>
|
||||
<li>If an item is private, it may be accessed only by the current module and its
|
||||
child modules.</li>
|
||||
</ol>
|
||||
<h3>Privacy Examples</h3>
|
||||
<a class="header" href="#privacy-examples" name="privacy-examples"><h3>Privacy Examples</h3></a>
|
||||
<p>Let’s look at a few more examples to get some practice. Create a new library
|
||||
project and enter the code in Listing 7-5 into your new project’s <em>src/lib.rs</em>:</p>
|
||||
<figure>
|
||||
@@ -266,7 +266,7 @@ incorrect</p>
|
||||
<p>Before you try to compile this code, make a guess about which lines in <code>try_me</code>
|
||||
function will have errors. Then try compiling to see if you were right, and read
|
||||
on for discussion of the errors!</p>
|
||||
<h4>Looking at the Errors</h4>
|
||||
<a class="header" href="#looking-at-the-errors" name="looking-at-the-errors"><h4>Looking at the Errors</h4></a>
|
||||
<p>The <code>try_me</code> function is in the root module of our project. The module named
|
||||
<code>outermost</code> is private, but the second privacy rule says the <code>try_me</code> function
|
||||
is allowed to access the <code>outermost</code> module since <code>outermost</code> is in the current
|
||||
@@ -283,7 +283,7 @@ is), nor is it a child module of the current module of <code>middle_secret_funct
|
||||
be accessed by its current module, <code>outermost</code>. That means the <code>try_me</code>
|
||||
function is not allowed to call <code>outermost::inside::inner_function</code> or
|
||||
<code>outermost::inside::secret_function</code> either.</p>
|
||||
<h4>Fixing the Errors</h4>
|
||||
<a class="header" href="#fixing-the-errors" name="fixing-the-errors"><h4>Fixing the Errors</h4></a>
|
||||
<p>Here are some suggestions for changing the code in an attempt to fix the
|
||||
errors. Before you try each one, make a guess as to whether it will fix the
|
||||
errors, then compile to see if you’re right and use the privacy rules to
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Importing Names</h2>
|
||||
<a class="header" href="#importing-names" name="importing-names"><h2>Importing Names</h2></a>
|
||||
<p>We’ve covered how to call functions defined within a module using the module
|
||||
name as part of the call, as in the call to the <code>namespaces</code> function shown
|
||||
here in Listing 7-6.</p>
|
||||
@@ -92,7 +92,7 @@ namespaces</p>
|
||||
</figure>
|
||||
<p>As you can see, referring to the fully qualified name can get quite lengthy.
|
||||
Luckily, Rust has a keyword to make these calls more concise.</p>
|
||||
<h3>Concise Imports with <code>use</code></h3>
|
||||
<a class="header" href="#concise-imports-with-use" name="concise-imports-with-use"><h3>Concise Imports with <code>use</code></h3></a>
|
||||
<p>Rust’s <code>use</code> keyword works to shorten lengthy function calls by bringing the
|
||||
modules of the function you want to call into a scope. Here’s an example of
|
||||
bringing the <code>a::series::of</code> namespace into a binary crate’s root scope:</p>
|
||||
@@ -153,7 +153,7 @@ fn main() {
|
||||
let green = TrafficLight::Green; // because we didn’t `use` TrafficLight::Green
|
||||
}
|
||||
</code></pre>
|
||||
<h3>Glob Imports with <code>*</code></h3>
|
||||
<a class="header" href="#glob-imports-with-" name="glob-imports-with-"><h3>Glob Imports with <code>*</code></h3></a>
|
||||
<p>To import all the items in a namespace at once, we can use the <code>*</code> syntax. For
|
||||
example:</p>
|
||||
<pre><code class="language-rust">enum TrafficLight {
|
||||
@@ -173,7 +173,7 @@ fn main() {
|
||||
<p>The <code>*</code> is called a <em>glob</em>, and it will import everything that’s visible inside
|
||||
of the namespace. Globs should be used sparingly: they are convenient, but you
|
||||
might also pull in more things than you expected and cause naming conflicts.</p>
|
||||
<h3>Using <code>super</code> to Access a Parent Module</h3>
|
||||
<a class="header" href="#using-super-to-access-a-parent-module" name="using-super-to-access-a-parent-module"><h3>Using <code>super</code> to Access a Parent Module</h3></a>
|
||||
<p>As you now know, when you create a library crate, Cargo makes a <code>tests</code> module
|
||||
for you. Let’s go into more detail about that now. In your <code>communicator</code>
|
||||
project, open <em>src/lib.rs</em>.</p>
|
||||
@@ -278,7 +278,7 @@ test tests::it_works ... ok
|
||||
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
|
||||
</code></pre>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Now you know techniques for organizing your code! Use these to group related
|
||||
functionality together, keep files from getting too long, and present a tidy
|
||||
public API to users of your library.</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Fundamental Collections</h1>
|
||||
<a class="header" href="#fundamental-collections" name="fundamental-collections"><h1>Fundamental Collections</h1></a>
|
||||
<p>Rust's standard library includes a number of really useful data structures
|
||||
called <em>collections</em>. Most other data types represent one specific value, but
|
||||
collections can contain multiple values. Unlike the built-in array and tuple
|
||||
|
||||
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Vectors</h2>
|
||||
<a class="header" href="#vectors" name="vectors"><h2>Vectors</h2></a>
|
||||
<p>The first type we'll look at is <code>Vec<T></code>, also known as a <em>vector</em>. Vectors
|
||||
allow us to store more than one value in a single data structure that puts all
|
||||
the values next to each other in memory. Vectors can only store values of the
|
||||
same type. They are useful in situations where you have a list of items, such
|
||||
as the lines of text in a file or the prices of items in a shopping cart.</p>
|
||||
<h3>Creating a New Vector</h3>
|
||||
<a class="header" href="#creating-a-new-vector" name="creating-a-new-vector"><h3>Creating a New Vector</h3></a>
|
||||
<p>To create a new, empty vector, we can call the <code>Vec::new</code> function:</p>
|
||||
<pre><code class="language-rust">let v: Vec<i32> = Vec::new();
|
||||
</code></pre>
|
||||
@@ -96,7 +96,7 @@ it. This will create a new <code>Vec<i32></code> that holds the values <co
|
||||
<p>Because we've given initial <code>i32</code> values, Rust can infer that the type of <code>v</code>
|
||||
is <code>Vec<i32></code>, and the type annotation isn't necessary. Let's look at how to
|
||||
modify a vector next.</p>
|
||||
<h3>Updating a Vector</h3>
|
||||
<a class="header" href="#updating-a-vector" name="updating-a-vector"><h3>Updating a Vector</h3></a>
|
||||
<p>To create a vector then add elements to it, we can use the <code>push</code> method:</p>
|
||||
<pre><code class="language-rust">let mut v = Vec::new();
|
||||
|
||||
@@ -109,7 +109,7 @@ v.push(8);
|
||||
change its value, we need to make it mutable with the <code>mut</code> keyword. The
|
||||
numbers we place inside are all <code>i32</code>s, and Rust infers this from the data, so
|
||||
we don't need the <code>Vec<i32></code> annotation.</p>
|
||||
<h3>Dropping a Vector Drops its Elements</h3>
|
||||
<a class="header" href="#dropping-a-vector-drops-its-elements" name="dropping-a-vector-drops-its-elements"><h3>Dropping a Vector Drops its Elements</h3></a>
|
||||
<p>Like any other <code>struct</code>, a vector will be freed when it goes out of scope:</p>
|
||||
<pre><code class="language-rust">{
|
||||
let v = vec![1, 2, 3, 4];
|
||||
@@ -122,7 +122,7 @@ we don't need the <code>Vec<i32></code> annotation.</p>
|
||||
those integers it holds will be cleaned up. This may seem like a
|
||||
straightforward point, but can get a little more complicated once we start to
|
||||
introduce references to the elements of the vector. Let's tackle that next!</p>
|
||||
<h3>Reading Elements of Vectors</h3>
|
||||
<a class="header" href="#reading-elements-of-vectors" name="reading-elements-of-vectors"><h3>Reading Elements of Vectors</h3></a>
|
||||
<p>Now that you know how to create, update, and destroy vectors, knowing how to
|
||||
read their contents is a good next step. There are two ways to reference a
|
||||
value stored in a vector. In the examples, we've annotated the types of the
|
||||
@@ -164,7 +164,7 @@ enter a number that's too large and your program gets a <code>None</code> value,
|
||||
tell the user how many items are in the current <code>Vec</code> and give them another
|
||||
chance to enter a valid value. That would be more user-friendly than crashing
|
||||
the program for a typo!</p>
|
||||
<h4>Invalid References</h4>
|
||||
<a class="header" href="#invalid-references" name="invalid-references"><h4>Invalid References</h4></a>
|
||||
<p>Once the program has a valid reference, the borrow checker will enforce the
|
||||
ownership and borrowing rules covered in Chapter 4 to ensure this reference and
|
||||
any other references to the contents of the vector stay valid. Recall the rule
|
||||
@@ -199,7 +199,7 @@ memory. The borrowing rules prevent programs from ending up in that situation.</
|
||||
<blockquote>
|
||||
<p>Note: For more on this, see <a href="https://doc.rust-lang.org/stable/nomicon/vec.html">The Nomicon</a>.</p>
|
||||
</blockquote>
|
||||
<h3>Using an Enum to Store Multiple Types</h3>
|
||||
<a class="header" href="#using-an-enum-to-store-multiple-types" name="using-an-enum-to-store-multiple-types"><h3>Using an Enum to Store Multiple Types</h3></a>
|
||||
<p>At the beginning of this chapter, we said that vectors can only store values
|
||||
that are all the same type. This can be inconvenient; there are definitely use
|
||||
cases for needing to store a list of things of different types. Luckily, the
|
||||
|
||||
+12
-12
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Strings</h2>
|
||||
<a class="header" href="#strings" name="strings"><h2>Strings</h2></a>
|
||||
<p>We've already talked about strings a bunch in Chapter 4, but let's take a more
|
||||
in-depth look at them now. Strings are an area that new Rustaceans commonly get
|
||||
stuck on. This is due to a combination of three things: Rust's propensity for
|
||||
@@ -82,7 +82,7 @@ creating, updating, and reading. We'll also discuss the ways in which <code>Stri
|
||||
is different than the other collections, namely how indexing into a <code>String</code> is
|
||||
complicated by the differences in which people and computers interpret <code>String</code>
|
||||
data.</p>
|
||||
<h3>What is a String?</h3>
|
||||
<a class="header" href="#what-is-a-string" name="what-is-a-string"><h3>What is a String?</h3></a>
|
||||
<p>Before we can dig into those aspects, we need to talk about what exactly we
|
||||
mean by the term 'string'. Rust actually only has one string type in the core
|
||||
language itself: <code>str</code>, the string slice, which is usually seen in its borrowed
|
||||
@@ -104,7 +104,7 @@ These string types may store different encodings or be represented in memory in
|
||||
a different way, for example. We won't be talking about these other string
|
||||
types in this chapter; see their API documentation for more about how to use
|
||||
them and when each is appropriate.</p>
|
||||
<h3>Creating a New String</h3>
|
||||
<a class="header" href="#creating-a-new-string" name="creating-a-new-string"><h3>Creating a New String</h3></a>
|
||||
<p>Many of the same operations available with <code>Vec</code> are available with <code>String</code> as
|
||||
well, starting with the <code>new</code> function to create a string, like so:</p>
|
||||
<pre><code class="language-rust">let s = String::new();
|
||||
@@ -144,11 +144,11 @@ let hello = "Olá";
|
||||
let hello = "Здравствуйте";
|
||||
let hello = "Hola";
|
||||
</code></pre>
|
||||
<h3>Updating a String</h3>
|
||||
<a class="header" href="#updating-a-string" name="updating-a-string"><h3>Updating a String</h3></a>
|
||||
<p>A <code>String</code> can grow in size and its contents can change just like the
|
||||
contents of a <code>Vec</code>, by pushing more data into it. In addition, <code>String</code> has
|
||||
concatenation operations implemented with the <code>+</code> operator for convenience.</p>
|
||||
<h4>Appending to a String with Push</h4>
|
||||
<a class="header" href="#appending-to-a-string-with-push" name="appending-to-a-string-with-push"><h4>Appending to a String with Push</h4></a>
|
||||
<p>We can grow a <code>String</code> by using the <code>push_str</code> method to append a string slice:</p>
|
||||
<pre><code class="language-rust">let mut s = String::from("foo");
|
||||
s.push_str("bar");
|
||||
@@ -167,7 +167,7 @@ it to the <code>String</code>:</p>
|
||||
s.push('l');
|
||||
</code></pre>
|
||||
<p>After this, <code>s</code> will contain "lol".</p>
|
||||
<h4>Concatenation with the + Operator or the <code>format!</code> Macro</h4>
|
||||
<a class="header" href="#concatenation-with-the--operator-or-the-format-macro" name="concatenation-with-the--operator-or-the-format-macro"><h4>Concatenation with the + Operator or the <code>format!</code> Macro</h4></a>
|
||||
<p>Often, we'll want to combine two existing strings together. One way is to use
|
||||
the <code>+</code> operator like this:</p>
|
||||
<pre><code class="language-rust">let s1 = String::from("Hello, ");
|
||||
@@ -234,7 +234,7 @@ have in the next paragraph without repeating the `println!` content too much?
|
||||
same way as <code>println!</code>, but instead of printing the output to the screen, it
|
||||
returns a <code>String</code> with the contents. This version is much easier to read, and
|
||||
also does not take ownership of any of its parameters.</p>
|
||||
<h3>Indexing into Strings</h3>
|
||||
<a class="header" href="#indexing-into-strings" name="indexing-into-strings"><h3>Indexing into Strings</h3></a>
|
||||
<p>In many other languages, accessing individual characters in a string by
|
||||
referencing them by index is a valid and common operation. In Rust, however, if
|
||||
we try to access parts of a <code>String</code> using indexing syntax, we'll get an error.
|
||||
@@ -253,7 +253,7 @@ note: the type `std::string::String` cannot be indexed by `_`
|
||||
<p>The error and the note tell the story: Rust strings don't support indexing. So
|
||||
the follow-up question is, why not? In order to answer that, we have to talk a
|
||||
bit about how Rust stores strings in memory.</p>
|
||||
<h4>Internal Representation</h4>
|
||||
<a class="header" href="#internal-representation" name="internal-representation"><h4>Internal Representation</h4></a>
|
||||
<p>A <code>String</code> is a wrapper over a <code>Vec<u8></code>. Let's take a look at some of our
|
||||
properly-encoded UTF-8 example strings from before. First, this one:</p>
|
||||
<pre><code class="language-rust">let len = String::from("Hola").len();
|
||||
@@ -281,7 +281,7 @@ only Latin letters: <code>&"hello"[0]</code> would return <code>10
|
||||
returning an unexpected value and causing bugs that might not be discovered
|
||||
immediately, Rust chooses to not compile this code at all and prevent
|
||||
misunderstandings earlier.</p>
|
||||
<h4>Bytes and Scalar Values and Grapheme Clusters! Oh my!</h4>
|
||||
<a class="header" href="#bytes-and-scalar-values-and-grapheme-clusters-oh-my" name="bytes-and-scalar-values-and-grapheme-clusters-oh-my"><h4>Bytes and Scalar Values and Grapheme Clusters! Oh my!</h4></a>
|
||||
<p>This leads to another point about UTF-8: there are really three relevant ways
|
||||
to look at strings, from Rust's perspective: as bytes, scalar values, and
|
||||
grapheme clusters (the closest thing to what people would call 'letters').</p>
|
||||
@@ -310,7 +310,7 @@ though, since Rust would have to walk through the contents from the beginning
|
||||
to the index to determine how many valid characters there were.</p>
|
||||
<p>All of these problems mean that Rust does not implement <code>[]</code> for <code>String</code>, so
|
||||
we cannot directly do this.</p>
|
||||
<h3>Slicing Strings</h3>
|
||||
<a class="header" href="#slicing-strings" name="slicing-strings"><h3>Slicing Strings</h3></a>
|
||||
<p>However, indexing the <em>bytes</em> of a string is very useful, and is not expected
|
||||
to be fast. While we can't use <code>[]</code> with a single number, we <em>can</em> use <code>[]</code>
|
||||
with a range to create a string slice containing particular bytes:</p>
|
||||
@@ -327,7 +327,7 @@ runtime, in the same way that accessing an invalid index in a vector does:</p>
|
||||
character boundary', ../src/libcore/str/mod.rs:1694
|
||||
</code></pre>
|
||||
<p>You should use this with caution, since it can cause your program to crash.</p>
|
||||
<h3>Methods for Iterating Over Strings</h3>
|
||||
<a class="header" href="#methods-for-iterating-over-strings" name="methods-for-iterating-over-strings"><h3>Methods for Iterating Over Strings</h3></a>
|
||||
<p>Luckily, there are other ways we can access elements in a String.</p>
|
||||
<p>If we need to perform operations on individual characters, the best way to do
|
||||
so is to use the <code>chars</code> method. Calling <code>chars</code> on "नमस्ते" separates out and
|
||||
@@ -369,7 +369,7 @@ method here, ie it's complicated and therefore best to use a crate? -->
|
||||
provided by the community, so we don't want to mention some and not others and
|
||||
seem biased towards certain crates, plus crates can change more quickly (and
|
||||
new crates can be created) than the language and this book will. /Carol -->
|
||||
<h3>Strings are Not so Simple</h3>
|
||||
<a class="header" href="#strings-are-not-so-simple" name="strings-are-not-so-simple"><h3>Strings are Not so Simple</h3></a>
|
||||
<p>To summarize, strings are complicated. Different programming languages make
|
||||
different choices about how to present this complexity to the programmer. Rust
|
||||
has chosen to make the correct handling of <code>String</code> data the default behavior
|
||||
|
||||
+10
-10
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Hash Maps</h2>
|
||||
<a class="header" href="#hash-maps" name="hash-maps"><h2>Hash Maps</h2></a>
|
||||
<p>The last of our fundamental collections is the <em>hash map</em>. The type <code>HashMap<K, V></code> stores a mapping of keys of type <code>K</code> to values of type <code>V</code>. It does this
|
||||
via a <em>hashing function</em>, which determines how it places these keys and values
|
||||
into memory. Many different programming languages support this kind of data
|
||||
@@ -82,7 +82,7 @@ team name, you can retrieve their score.</p>
|
||||
more goodies hiding in the functions defined on <code>HashMap</code> by the standard
|
||||
library. As always, check the standard library documentation for more
|
||||
information.</p>
|
||||
<h3>Creating a New Hash Map</h3>
|
||||
<a class="header" href="#creating-a-new-hash-map" name="creating-a-new-hash-map"><h3>Creating a New Hash Map</h3></a>
|
||||
<p>We can create an empty <code>HashMap</code> with <code>new</code>, and add elements with <code>insert</code>.
|
||||
Here we're keeping track of the scores of two teams whose names are Blue and
|
||||
Yellow. The Blue team will start with 10 points and the Yellow team starts with
|
||||
@@ -122,7 +122,7 @@ let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collec
|
||||
want unless you specify. For the type parameters for the key and value types,
|
||||
however, we use underscores and Rust can infer the types that the hash map
|
||||
contains based on the types of the data in the vector.</p>
|
||||
<h3>Hash Maps and Ownership</h3>
|
||||
<a class="header" href="#hash-maps-and-ownership" name="hash-maps-and-ownership"><h3>Hash Maps and Ownership</h3></a>
|
||||
<p>For types that implement the <code>Copy</code> trait, like <code>i32</code>, the values are copied
|
||||
into the hash map. For owned values like <code>String</code>, the values will be moved and
|
||||
the hash map will be the owner of those values:</p>
|
||||
@@ -141,7 +141,7 @@ they have been moved into the hash map with the call to <code>insert</code>.</p>
|
||||
not be moved into the hash map. The values that the references point to must be
|
||||
valid for at least as long as the hash map is valid, though. We will talk more
|
||||
about these issues in the Lifetimes section of Chapter 10.</p>
|
||||
<h3>Accessing Values in a Hash Map</h3>
|
||||
<a class="header" href="#accessing-values-in-a-hash-map" name="accessing-values-in-a-hash-map"><h3>Accessing Values in a Hash Map</h3></a>
|
||||
<p>We can get a value out of the hash map by providing its key to the <code>get</code> method:</p>
|
||||
<pre><code class="language-rust">use std::collections::HashMap;
|
||||
|
||||
@@ -175,7 +175,7 @@ for (key, value) in &scores {
|
||||
<pre><code class="language-text">Yellow: 50
|
||||
Blue: 10
|
||||
</code></pre>
|
||||
<h3>Updating a Hash Map</h3>
|
||||
<a class="header" href="#updating-a-hash-map" name="updating-a-hash-map"><h3>Updating a Hash Map</h3></a>
|
||||
<!-- So the quantity of keys must be defined up front, that's not growable?
|
||||
That could be worthy saying -->
|
||||
<!-- No, the number of keys is growable, it's just that for EACH individual
|
||||
@@ -188,7 +188,7 @@ completely disregarding the old value. We could choose to keep the old value
|
||||
and ignore the new value, and only add the new value if the key <em>doesn't</em>
|
||||
already have a value. Or we could combine the old value and the new value.
|
||||
Let's look at how to do each of these!</p>
|
||||
<h4>Overwriting a Value</h4>
|
||||
<a class="header" href="#overwriting-a-value" name="overwriting-a-value"><h4>Overwriting a Value</h4></a>
|
||||
<p>If we insert a key and a value into a hash map, then insert that same key with a
|
||||
different value, the value associated with that key will be replaced. Even
|
||||
though this following code calls <code>insert</code> twice, the hash map will only contain
|
||||
@@ -204,7 +204,7 @@ scores.insert(String::from("Blue"), 25);
|
||||
println!("{:?}", scores);
|
||||
</code></pre>
|
||||
<p>This will print <code>{"Blue": 25}</code>. The original value of 10 has been overwritten.</p>
|
||||
<h4>Only Insert If the Key Has No Value</h4>
|
||||
<a class="header" href="#only-insert-if-the-key-has-no-value" name="only-insert-if-the-key-has-no-value"><h4>Only Insert If the Key Has No Value</h4></a>
|
||||
<p>It's common to want to check if a particular key has a value and, if it does
|
||||
not, insert a value for it. Hash maps have a special API for this, called
|
||||
<code>entry</code>, that takes the key we want to check as an argument. The return value
|
||||
@@ -231,7 +231,7 @@ addition, plays more nicely with the borrow checker.</p>
|
||||
will insert the key for the Yellow team with the value 50, since the Yellow
|
||||
team doesn't have a value already. The second call to <code>entry</code> will not change
|
||||
the hash map since the Blue team already has the value 10.</p>
|
||||
<h4>Update a Value Based on the Old Value</h4>
|
||||
<a class="header" href="#update-a-value-based-on-the-old-value" name="update-a-value-based-on-the-old-value"><h4>Update a Value Based on the Old Value</h4></a>
|
||||
<p>Another common use case for hash maps is to look up a key's value then update
|
||||
it, based on the old value. For instance, if we wanted to count how many times
|
||||
each word appeared in some text, we could use a hash map with the words as keys
|
||||
@@ -256,7 +256,7 @@ key. Here we store that mutable reference in the <code>count</code> variable, so
|
||||
to assign to that value we must first dereference <code>count</code> using the asterisk
|
||||
(<code>*</code>). The mutable reference goes out of scope at the end of the <code>for</code> loop, so
|
||||
all of these changes are safe and allowed by the borrowing rules.</p>
|
||||
<h3>Hashing Function</h3>
|
||||
<a class="header" href="#hashing-function" name="hashing-function"><h3>Hashing Function</h3></a>
|
||||
<p>By default, <code>HashMap</code> uses a cryptographically secure hashing function that can
|
||||
provide resistance to Denial of Service (DoS) attacks. This is not the fastest
|
||||
hashing algorithm out there, but the tradeoff for better security that comes
|
||||
@@ -265,7 +265,7 @@ that the default hash function is too slow for your purposes, you can switch to
|
||||
another function by specifying a different <em>hasher</em>. A hasher is a type that
|
||||
implements the <code>BuildHasher</code> trait. We'll be talking about traits and how to
|
||||
implement them in Chapter 10.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Vectors, strings, and hash maps will take you far in programs where you need to
|
||||
store, access, and modify data. Here are some exercises you should now be
|
||||
equipped to solve:</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Error Handling</h1>
|
||||
<a class="header" href="#error-handling" name="error-handling"><h1>Error Handling</h1></a>
|
||||
<p>Rust's commitment to reliability extends to error handling. Errors are a fact
|
||||
of life in software, so Rust has a number of features for handling situations
|
||||
in which something goes wrong. In many cases, Rust will require you to
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Unrecoverable Errors with <code>panic!</code></h2>
|
||||
<a class="header" href="#unrecoverable-errors-with-panic" name="unrecoverable-errors-with-panic"><h2>Unrecoverable Errors with <code>panic!</code></h2></a>
|
||||
<p>Sometimes, bad things happen, and there's nothing that you can do about it. For
|
||||
these cases, Rust has the <code>panic!</code> macro. When this macro executes, your
|
||||
program will print a failure message, unwind and clean up the stack, and then
|
||||
@@ -75,7 +75,7 @@ quit. The most common situation this occurs in is when a bug of some kind has
|
||||
been detected and it's not clear to the programmer how to handle the error.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<blockquote>
|
||||
<h4>Unwinding</h4>
|
||||
<a class="header" href="#unwinding" name="unwinding"><h4>Unwinding</h4></a>
|
||||
<p>By default, when a <code>panic!</code> occurs, the program starts
|
||||
<em>unwinding</em>, which means Rust walks back up the stack and cleans up the data
|
||||
from each function it encounters, but this walking and cleanup is a lot of
|
||||
@@ -116,7 +116,7 @@ code that our code calls. The filename and line number reported by the error
|
||||
message will be someone else's code where the <code>panic!</code> macro is called, not the
|
||||
line of our code that eventually led to the <code>panic!</code>. We can use the backtrace
|
||||
of the functions the <code>panic!</code> call came from to figure this out.</p>
|
||||
<h3>Using a <code>panic!</code> Backtrace</h3>
|
||||
<a class="header" href="#using-a-panic-backtrace" name="using-a-panic-backtrace"><h3>Using a <code>panic!</code> Backtrace</h3></a>
|
||||
<p>Let's look at another example to see what it's like when a <code>panic!</code> call comes
|
||||
from a library because of a bug in our code instead of from our code calling
|
||||
the macro directly:</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Recoverable Errors with <code>Result</code></h2>
|
||||
<a class="header" href="#recoverable-errors-with-result" name="recoverable-errors-with-result"><h2>Recoverable Errors with <code>Result</code></h2></a>
|
||||
<p>Most errors aren't serious enough to require the program to stop entirely.
|
||||
Sometimes, when a function fails, it's for a reason that we can easily
|
||||
interpret and respond to. For example, if we try to open a file and that
|
||||
@@ -207,7 +207,7 @@ Os { code: 2, message: "No such file or directory" } }', src/main.rs:8
|
||||
run the program? -->
|
||||
<!-- No, the `panic!` macro prints what we give to it, which we covered in the
|
||||
section previous to this one. /Carol -->
|
||||
<h3>Matching on Different Errors</h3>
|
||||
<a class="header" href="#matching-on-different-errors" name="matching-on-different-errors"><h3>Matching on Different Errors</h3></a>
|
||||
<p>The code in Listing 9-3 will <code>panic!</code> no matter the reason that <code>File::open</code>
|
||||
failed. What we'd really like to do instead is take different actions for
|
||||
different failure reasons: if <code>File::open</code> failed because the file doesn't
|
||||
@@ -265,7 +265,7 @@ could also fail, we need to add an inner <code>match</code> statement as well! W
|
||||
file can't be opened, a different error message will be printed. The last arm
|
||||
of the outer <code>match</code> stays the same so that the program panics on any error
|
||||
besides the missing file error.</p>
|
||||
<h3>Shortcuts for Panic on Error: <code>unwrap</code> and <code>expect</code></h3>
|
||||
<a class="header" href="#shortcuts-for-panic-on-error-unwrap-and-expect" name="shortcuts-for-panic-on-error-unwrap-and-expect"><h3>Shortcuts for Panic on Error: <code>unwrap</code> and <code>expect</code></h3></a>
|
||||
<p>Using <code>match</code> works well enough, but it can be a bit verbose and doesn't always
|
||||
communicate intent well. The <code>Result<T, E></code> type has many helper methods
|
||||
defined on it to do various things. One of those methods, called <code>unwrap</code>, is
|
||||
@@ -334,7 +334,7 @@ goes over the criteria the reader should use to decide if they're in a
|
||||
situation that's recoverable or not. I've actually moved the text that was here
|
||||
into that section to keep that whole discussion together. /Carol
|
||||
-->
|
||||
<h3>Propagating Errors</h3>
|
||||
<a class="header" href="#propagating-errors" name="propagating-errors"><h3>Propagating Errors</h3></a>
|
||||
<p>When writing a function whose implementation calls something that might fail,
|
||||
instead of handling the error within this function, you can choose to let your
|
||||
caller know about the error so they can decide what to do. This is known as
|
||||
@@ -412,7 +412,7 @@ to do, so we propagate all the success or error information upwards for them to
|
||||
handle as they see fit.</p>
|
||||
<p>This pattern of propagating errors is so common in Rust that there is dedicated
|
||||
syntax to make this easier: <code>?</code>.</p>
|
||||
<h3>A Shortcut for Propagating Errors: <code>?</code></h3>
|
||||
<a class="header" href="#a-shortcut-for-propagating-errors-" name="a-shortcut-for-propagating-errors-"><h3>A Shortcut for Propagating Errors: <code>?</code></h3></a>
|
||||
<!-- The `?` ended up stabilizing in 1.13 and is quickly becoming preferred over
|
||||
`try!`, so we decided to only cover `?`. /Carol -->
|
||||
<p>Listing 9-6 shows an implementation of <code>read_username_from_file</code> that has the
|
||||
@@ -476,7 +476,7 @@ chained the call to <code>read_to_string</code> directly onto the result of
|
||||
username in <code>s</code> when both <code>File::open</code> and <code>read_to_string</code> succeed rather than
|
||||
returning errors. The functionality is again the same as in Listing 9-5 and
|
||||
Listing 9-6, this is just a different, more ergonomic way to write it.</p>
|
||||
<h4><code>?</code> Can Only Be Used in Functions That Return <code>Result</code></h4>
|
||||
<a class="header" href="#-can-only-be-used-in-functions-that-return-result" name="-can-only-be-used-in-functions-that-return-result"><h4><code>?</code> Can Only Be Used in Functions That Return <code>Result</code></h4></a>
|
||||
<!-- I think we need a new heading here, could you suggest something? I'm sure
|
||||
there's a better way to phrase this!-->
|
||||
<!-- I've tried, but I'm not really sure how to say it any more succinctly than
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>To <code>panic!</code> or Not To <code>panic!</code></h2>
|
||||
<a class="header" href="#to-panic-or-not-to-panic" name="to-panic-or-not-to-panic"><h2>To <code>panic!</code> or Not To <code>panic!</code></h2></a>
|
||||
<p>So how do you decide when you should <code>panic!</code> and when you should return
|
||||
<code>Result</code>? When code panics, there's no way to recover. You could choose to call
|
||||
<code>panic!</code> for any error situation, whether there's a possible way to recover or
|
||||
@@ -85,7 +85,7 @@ why it's appropriate to panic in examples, prototype code, and tests, then
|
||||
situations where you as a human can know a method won't fail that the compiler
|
||||
can't reason about, and conclude with some general guidelines on how to decide
|
||||
whether to panic in library code.</p>
|
||||
<h3>Examples, Prototype Code, and Tests: Perfectly Fine to Panic</h3>
|
||||
<a class="header" href="#examples-prototype-code-and-tests-perfectly-fine-to-panic" name="examples-prototype-code-and-tests-perfectly-fine-to-panic"><h3>Examples, Prototype Code, and Tests: Perfectly Fine to Panic</h3></a>
|
||||
<p>When you're writing an example to illustrate some concept, having robust error
|
||||
handling code in the example as well can make the example less clear. In
|
||||
examples, it's understood that a call to a method like <code>unwrap</code> that could
|
||||
@@ -99,7 +99,7 @@ your code for when you're ready to make your program more robust.</p>
|
||||
method isn't the functionality under test. Because <code>panic!</code> is how a test gets
|
||||
marked as a failure, calling <code>unwrap</code> or <code>expect</code> is exactly what makes sense to
|
||||
do.</p>
|
||||
<h3>Cases When You Have More Information Than The Compiler</h3>
|
||||
<a class="header" href="#cases-when-you-have-more-information-than-the-compiler" name="cases-when-you-have-more-information-than-the-compiler"><h3>Cases When You Have More Information Than The Compiler</h3></a>
|
||||
<p>It would also be appropriate to call <code>unwrap</code> when you have some other logic
|
||||
that ensures the <code>Result</code> will have an <code>Ok</code> value, but the logic isn't
|
||||
something the compiler understands. You'll still have a <code>Result</code> value that you
|
||||
@@ -126,7 +126,7 @@ since the compiler isn't smart enough to see that this string is always a
|
||||
valid IP address. If the IP address string came from a user instead of being
|
||||
hardcoded into the program, and therefore <em>did</em> have a possibility of failure,
|
||||
we'd definitely want to handle the <code>Result</code> in a more robust way instead.</p>
|
||||
<h3>Guidelines for Error Handling</h3>
|
||||
<a class="header" href="#guidelines-for-error-handling" name="guidelines-for-error-handling"><h3>Guidelines for Error Handling</h3></a>
|
||||
<p>It's advisable to have your code <code>panic!</code> when it's possible that you could end
|
||||
up in a <em>bad state</em>—in this context, <em>bad state</em> is when some assumption,
|
||||
guarantee, contract, or invariant has been broken, such as when invalid values,
|
||||
@@ -181,7 +181,7 @@ better to use than an Option?-->
|
||||
<!-- I tried to reword, but I'm not sure if I made it any clearer. You don't
|
||||
have to have extra checks, so your code is simpler; I'm not sure why it's not
|
||||
clear that simpler is better. /Carol -->
|
||||
<h3>Creating Custom Types for Validation</h3>
|
||||
<a class="header" href="#creating-custom-types-for-validation" name="creating-custom-types-for-validation"><h3>Creating Custom Types for Validation</h3></a>
|
||||
<p>Let's take the idea of using Rust's type system to ensure we have a valid value
|
||||
one step further, and look at creating a custom type for validation. Recall the
|
||||
guessing game in Chapter 2, where our code asked the user to guess a number
|
||||
@@ -289,7 +289,7 @@ hasn't been checked by the conditions in the constructor.</p>
|
||||
<p>A function that has a parameter or returns only numbers between 1 and 100 could
|
||||
then declare in its signature that it takes or returns a <code>Guess</code> rather than a
|
||||
<code>u32</code>, and wouldn't need to do any additional checks in its body.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Rust's error handling features are designed to help you write more robust code.
|
||||
The <code>panic!</code> macro signals that your program is in a state it can't handle, and
|
||||
lets you tell the process to stop instead of trying to proceed with invalid or
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Generics</h1>
|
||||
<a class="header" href="#generics" name="generics"><h1>Generics</h1></a>
|
||||
<p>One of the core tools a programming language gives you is the ability to deal
|
||||
effectively with duplication of code. It's important to minimize the amount of
|
||||
code that is duplicated throughout a program to make maintenance easier and
|
||||
@@ -80,7 +80,7 @@ hard to track down. Rust has the concept of <em>generics</em> as one way to elim
|
||||
duplicate code. Generics come in the form of generic types, traits that those
|
||||
generic types have, and generic lifetimes. We'll cover how to use all of these
|
||||
in this chapter.</p>
|
||||
<h2>Removing Duplication by Extracting a Function</h2>
|
||||
<a class="header" href="#removing-duplication-by-extracting-a-function" name="removing-duplication-by-extracting-a-function"><h2>Removing Duplication by Extracting a Function</h2></a>
|
||||
<p>Let's first go through a technique for dealing with duplication that you're
|
||||
probably familiar with: extracting a function. Consider a small program that
|
||||
finds the largest number in a list, shown in Listing 10-1:</p>
|
||||
|
||||
+7
-7
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Generics Syntax</h2>
|
||||
<a class="header" href="#generics-syntax" name="generics-syntax"><h2>Generics Syntax</h2></a>
|
||||
<p>We've already hinted at the idea of generics in previous chapters, but we
|
||||
never dug into what exactly they are or how to use them. In places where we
|
||||
specify a type, like function signatures or structs, instead we can use
|
||||
@@ -82,7 +82,7 @@ with a concrete type, and that determines how the overall type works. In the
|
||||
same way that a function like <code>foo(x: i32)</code> can be called with a specific value
|
||||
such as <code>foo(5)</code>, a <code>Vec<T></code> can be created with a specific type, like
|
||||
<code>Vec<i32></code>.</p>
|
||||
<h3>Duplicated Enum Definitions</h3>
|
||||
<a class="header" href="#duplicated-enum-definitions" name="duplicated-enum-definitions"><h3>Duplicated Enum Definitions</h3></a>
|
||||
<p>Let's dive into generic data types in more detail. We learned about how to use
|
||||
the <code>Option<T></code> enum in Chapter 6, but we never examined its definition. Let's
|
||||
try to imagine how we'd write it! We'll start from duplicated code like we did
|
||||
@@ -122,7 +122,7 @@ what we currently know how to do in Rust, we would have to write a unique type
|
||||
for every single kind of value we wanted to have either <code>Some</code> or <code>None</code> of. In
|
||||
other words, the idea of "an optional value" is a more abstract concept than one
|
||||
specific type. We want it to work for any type at all.</p>
|
||||
<h3>Removing Duplication by Extracting a Generic Data Type</h3>
|
||||
<a class="header" href="#removing-duplication-by-extracting-a-generic-data-type" name="removing-duplication-by-extracting-a-generic-data-type"><h3>Removing Duplication by Extracting a Generic Data Type</h3></a>
|
||||
<p>Let's see how to get from duplicated types to the generic type. Here are the
|
||||
definitions of our two enums side-by-side:</p>
|
||||
<pre><code class="language-text">enum OptionalNumber { enum OptionalFloatingPointNumber {
|
||||
@@ -180,7 +180,7 @@ let float = Some(5.0);
|
||||
</code></pre>
|
||||
<p>When you recognize situations with almost-duplicate types like this in your
|
||||
code, you can follow this process to reduce duplication using generics.</p>
|
||||
<h3>Monomorphization at Compile Time</h3>
|
||||
<a class="header" href="#monomorphization-at-compile-time" name="monomorphization-at-compile-time"><h3>Monomorphization at Compile Time</h3></a>
|
||||
<p>Understanding this refactoring process is also useful in understanding how
|
||||
generics work behind the scenes: the compiler does the exact opposite of this
|
||||
process when compiling your code. <em>Monomorphization</em> means taking code that
|
||||
@@ -217,7 +217,7 @@ fn main() {
|
||||
code, but Rust will compile that into code that acts as though we wrote the
|
||||
specific type out in each instance. This means we pay no runtime cost for using
|
||||
generics; it's just like we duplicated each particular definition.</p>
|
||||
<h3>Generic Structs</h3>
|
||||
<a class="header" href="#generic-structs" name="generic-structs"><h3>Generic Structs</h3></a>
|
||||
<p>In a similar fashion as we did with enums, we can use <code><></code>s with structs as
|
||||
well in order to define structs that have a generic type parameter in one or
|
||||
more of their fields. Generic structs also get monomorphized into specialized
|
||||
@@ -242,7 +242,7 @@ fn main() {
|
||||
<p>The syntax is the same with structs: add a <code><T></code> after the name of the struct,
|
||||
then use <code>T</code> in the definition where you want to use that generic type instead
|
||||
of a specific type.</p>
|
||||
<h3>Multiple Type Parameters</h3>
|
||||
<a class="header" href="#multiple-type-parameters" name="multiple-type-parameters"><h3>Multiple Type Parameters</h3></a>
|
||||
<p>Note that in the <code>Point</code> definition in Listing 10-2, we've used the same <code>T</code>
|
||||
parameter for both fields. This means <code>x</code> and <code>y</code> must always be values of the
|
||||
same type. Trying to instantiate a <code>Point</code> that uses an <code>i32</code> for <code>x</code> and an
|
||||
@@ -296,7 +296,7 @@ definition:</p>
|
||||
values in function signatures, if you have a lot of parameters, the code can
|
||||
get quite confusing, so try to keep the number of parameters defined in any one
|
||||
type small if you can.</p>
|
||||
<h3>Generic Functions and Methods</h3>
|
||||
<a class="header" href="#generic-functions-and-methods" name="generic-functions-and-methods"><h3>Generic Functions and Methods</h3></a>
|
||||
<p>In a similar way to data structures, we can use the <code><></code> syntax in function or
|
||||
method definitions. The angle brackets for type parameters go after the
|
||||
function or method name and before the parameter list in parentheses:</p>
|
||||
|
||||
+3
-3
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Traits</h2>
|
||||
<a class="header" href="#traits" name="traits"><h2>Traits</h2></a>
|
||||
<p><em>Traits</em> are similar to a feature often called 'interfaces' in other languages,
|
||||
but are also different. Traits let us do another kind of abstraction: they let
|
||||
us abstract over <em>behavior</em> that types can have in common.</p>
|
||||
@@ -162,7 +162,7 @@ wanted to call the <code>print</code> method. This is because it's possible to h
|
||||
traits that both define a method named <code>print</code>, and our <code>Temperature</code> enum might
|
||||
implement both. Rust wouldn't know which <code>print</code> method we wanted unless we
|
||||
brought the trait we wanted into our current scope with <code>use</code>.</p>
|
||||
<h3>Trait Bounds</h3>
|
||||
<a class="header" href="#trait-bounds" name="trait-bounds"><h3>Trait Bounds</h3></a>
|
||||
<p>Defining traits with methods and implementing the trait methods on a particular
|
||||
type gives Rust more information than just defining methods on a type directly.
|
||||
The information Rust gets is that the type that implements the trait can be
|
||||
@@ -266,7 +266,7 @@ fn show_anything<T: Display>(value: T) {
|
||||
</figure>
|
||||
<p>Now that this function specifies that <code>T</code> can be any type as long as that type
|
||||
implements the <code>Display</code> trait, this code will compile.</p>
|
||||
<h3>Multiple Trait Bounds and <code>where</code> Syntax</h3>
|
||||
<a class="header" href="#multiple-trait-bounds-and-where-syntax" name="multiple-trait-bounds-and-where-syntax"><h3>Multiple Trait Bounds and <code>where</code> Syntax</h3></a>
|
||||
<p>Each generic type can have its own trait bounds. The signature for a function
|
||||
that takes a type <code>T</code> that implements <code>Display</code> and a type <code>U</code> that implements
|
||||
<code>Printable</code> looks like:</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Lifetime Syntax</h2>
|
||||
<a class="header" href="#lifetime-syntax" name="lifetime-syntax"><h2>Lifetime Syntax</h2></a>
|
||||
<p>Generic type parameters let us abstract over types, and traits let us abstract
|
||||
over behavior. There's one more way that Rust allows us to do something
|
||||
similar: <em>lifetimes</em> allow us to be generic over scopes of code.</p>
|
||||
@@ -78,7 +78,7 @@ to cover everything about them in this chapter. What we <em>are</em> going to do
|
||||
talk about the very basics of lifetimes, so that when you see the syntax in
|
||||
documentation or other places, you'll be familiar with the concepts. Chapter 20
|
||||
will contain more advanced information about everything lifetimes can do.</p>
|
||||
<h3>Core Syntax</h3>
|
||||
<a class="header" href="#core-syntax" name="core-syntax"><h3>Core Syntax</h3></a>
|
||||
<p>We talked about references in Chapter 4, but we left out an important detail.
|
||||
As it turns out, every reference in Rust has a <em>lifetime</em>, which is the scope
|
||||
for which that reference is valid. Most of the time, lifetimes are implicit,
|
||||
@@ -104,7 +104,7 @@ declaration and a generic type declaration:</p>
|
||||
reference has the lifetime <code>'a</code>. In the same way that we parameterize functions
|
||||
that take generic types, we parameterize references with lifetimes.</p>
|
||||
<p>So, that's the syntax, but <em>why</em>? What does a lifetime do, anyway?</p>
|
||||
<h3>Lifetimes Prevent Dangling References</h3>
|
||||
<a class="header" href="#lifetimes-prevent-dangling-references" name="lifetimes-prevent-dangling-references"><h3>Lifetimes Prevent Dangling References</h3></a>
|
||||
<p>Consider the program in listing 10-8. There's an outer scope and an inner
|
||||
scope. The outer scope declares a variable named <code>r</code> with no initial value, and
|
||||
the inner scope declares a variable named <code>x</code> with the initial value of 5.
|
||||
@@ -188,7 +188,7 @@ it out for us. One situation in which Rust can't figure out the lifetimes is
|
||||
for a function or method when one of the parameters or return values is a
|
||||
reference, except for a few scenarios we'll discuss in the lifetime elision
|
||||
section.</p>
|
||||
<h3>Lifetime Annotations in Struct Definitions</h3>
|
||||
<a class="header" href="#lifetime-annotations-in-struct-definitions" name="lifetime-annotations-in-struct-definitions"><h3>Lifetime Annotations in Struct Definitions</h3></a>
|
||||
<p>Another time that Rust can't figure out the lifetimes is when structs have a
|
||||
field that holds a reference. In that case, naming the lifetimes looks like
|
||||
this:</p>
|
||||
@@ -208,7 +208,7 @@ function that has a parameter of a generic type: we don't know what type the
|
||||
values will actually end up being when the function gets called. Lifetimes are
|
||||
the same idea, but they are generic over the scope of a reference, rather than
|
||||
a type.</p>
|
||||
<h3>Lifetime Annotations in Function Signatures</h3>
|
||||
<a class="header" href="#lifetime-annotations-in-function-signatures" name="lifetime-annotations-in-function-signatures"><h3>Lifetime Annotations in Function Signatures</h3></a>
|
||||
<p>Lifetime annotations for functions go on the function signature, but we don't
|
||||
have to annotate any of the code in the function body with lifetimes. That's
|
||||
because Rust can analyze the specific code inside the function without any
|
||||
@@ -353,7 +353,7 @@ cleaning up the value.</p>
|
||||
parameters and return values of functions. Once they're connected, Rust has
|
||||
enough information to allow memory-safe operations and disallow operations that
|
||||
would create dangling pointers or otherwise violate memory safety.</p>
|
||||
<h3>Lifetime Elision</h3>
|
||||
<a class="header" href="#lifetime-elision" name="lifetime-elision"><h3>Lifetime Elision</h3></a>
|
||||
<p>If every reference has a lifetime, and we need to provide them for functions
|
||||
that use references as parameters or return values, then why did this function
|
||||
from the "String Slices" section of Chapter 4 compile? We haven't annotated any
|
||||
@@ -411,7 +411,7 @@ code without needing to specify explicit lifetimes. However, Rust is always
|
||||
checking these rules and the lifetimes in your program, and cases in which the
|
||||
lifetime elision rules do not apply are cases where you'll need to add lifetime
|
||||
parameters to help Rust understand the contracts of your code.</p>
|
||||
<h3>Lifetime Annotations in Method Definitions</h3>
|
||||
<a class="header" href="#lifetime-annotations-in-method-definitions" name="lifetime-annotations-in-method-definitions"><h3>Lifetime Annotations in Method Definitions</h3></a>
|
||||
<p>Now that we've gone over the lifetime elision rules, defining methods on
|
||||
structs that hold references will make more sense. The lifetime name needs to
|
||||
be declared after the <code>impl</code> keyword and then used after the struct's name,
|
||||
@@ -437,7 +437,7 @@ impl<'a> App<'a> {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<h3>The Static Lifetime</h3>
|
||||
<a class="header" href="#the-static-lifetime" name="the-static-lifetime"><h3>The Static Lifetime</h3></a>
|
||||
<p>There is <em>one</em> special lifetime that Rust knows about: <code>'static</code>. The <code>'static</code>
|
||||
lifetime is the entire duration of the program. All string literals have the
|
||||
<code>'static</code> lifetime:</p>
|
||||
@@ -452,7 +452,7 @@ program or not (or even if you want it to live that long, if it could). Most of
|
||||
the time, the problem in the code is an attempt to create a dangling reference
|
||||
or a mismatch of the available lifetimes, and the solution is fixing those
|
||||
problems, not specifying the <code>'static</code> lifetime.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>We've covered the basics of Rust's system of generics. Generics are the core to
|
||||
building good abstractions, and can be used in a number of ways. There's more
|
||||
to learn about them, particularly lifetimes, but we'll cover those in later
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Testing</h1>
|
||||
<a class="header" href="#testing" name="testing"><h1>Testing</h1></a>
|
||||
<blockquote>
|
||||
<p>Program testing can be a very effective way to show the presence of bugs, but
|
||||
it is hopelessly inadequate for showing their absence.</p>
|
||||
|
||||
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Writing Tests</h2>
|
||||
<a class="header" href="#writing-tests" name="writing-tests"><h2>Writing Tests</h2></a>
|
||||
<p>Tests are Rust functions that use particular features and are written in such a
|
||||
way as to verify that non-test code is functioning in the expected manner.
|
||||
Everything we've discussed about Rust code applies to Rust tests as well! Let's
|
||||
look at the features Rust provides specifically for writing tests: the <code>test</code>
|
||||
attribute, a few macros, and the <code>should_panic</code> attribute.</p>
|
||||
<h3>The <code>test</code> attribute</h3>
|
||||
<a class="header" href="#the-test-attribute" name="the-test-attribute"><h3>The <code>test</code> attribute</h3></a>
|
||||
<p>At its simplest, a test in Rust is a function that's annotated with the <code>test</code>
|
||||
attribute. Let's make a new library project with Cargo called <code>adder</code>:</p>
|
||||
<pre><code class="language-text">$ cargo new adder
|
||||
@@ -121,7 +121,7 @@ this line:</p>
|
||||
tests that we have:</p>
|
||||
<pre><code class="language-text">test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
|
||||
</code></pre>
|
||||
<h3>The <code>assert!</code> macro</h3>
|
||||
<a class="header" href="#the-assert-macro" name="the-assert-macro"><h3>The <code>assert!</code> macro</h3></a>
|
||||
<p>The empty test function passes because any test which doesn't <code>panic!</code> passes,
|
||||
and any test that does <code>panic!</code> fails. Let's make the test fail by using the
|
||||
<code>assert!</code> macro:</p>
|
||||
@@ -166,7 +166,7 @@ line 5 got a <code>false</code> value:</p>
|
||||
<p>The test failure is also reflected in the summary line:</p>
|
||||
<pre><code class="language-text">test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
|
||||
</code></pre>
|
||||
<h3>Testing equality with the <code>assert_eq!</code> and <code>assert_ne!</code> macros</h3>
|
||||
<a class="header" href="#testing-equality-with-the-assert_eq-and-assert_ne-macros" name="testing-equality-with-the-assert_eq-and-assert_ne-macros"><h3>Testing equality with the <code>assert_eq!</code> and <code>assert_ne!</code> macros</h3></a>
|
||||
<p>A common way to test functionality is to compare the result of the code under
|
||||
test to the value you expect it to be, and check that they're equal. You can do
|
||||
this using the <code>assert!</code> macro by passing it an expression using the <code>==</code>
|
||||
@@ -237,7 +237,7 @@ order to be able to print out the values in the case that the assertion fails.
|
||||
Because both of these traits are derivable traits that we mentioned in Chapter
|
||||
5, usually this is as straightforward as adding the <code>#[derive(PartialEq, Debug)]</code> annotation to your struct or enum definition. See Appendix C for more
|
||||
details about these and other derivable traits.</p>
|
||||
<h2>Test for failure with <code>should_panic</code></h2>
|
||||
<a class="header" href="#test-for-failure-with-should_panic" name="test-for-failure-with-should_panic"><h2>Test for failure with <code>should_panic</code></h2></a>
|
||||
<p>We can invert our test's failure with another attribute: <code>should_panic</code>. This
|
||||
is useful when we want to test that calling a particular function will cause an
|
||||
error. For example, let's test something that we know will panic from Chapter
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Running tests</h2>
|
||||
<a class="header" href="#running-tests" name="running-tests"><h2>Running tests</h2></a>
|
||||
<p>Just like <code>cargo run</code> compiles your code and then runs the resulting binary,
|
||||
<code>cargo test</code> compiles your code in test mode and runs the resulting test
|
||||
binary. The default behavior of the binary that <code>cargo test</code> produces is to run
|
||||
@@ -79,7 +79,7 @@ be passed instead to the resulting test binary. The way to separate these
|
||||
arguments is with <code>--</code>: after <code>cargo test</code>, list the arguments that go to
|
||||
<code>cargo test</code>, then the separator <code>--</code>, and then the arguments that go to the
|
||||
test binary.</p>
|
||||
<h3>Tests Run in Parallel</h3>
|
||||
<a class="header" href="#tests-run-in-parallel" name="tests-run-in-parallel"><h3>Tests Run in Parallel</h3></a>
|
||||
<p>Tests are run in parallel using threads. For this reason, you should take care
|
||||
that your tests are written in such a way as to not depend on each other or on
|
||||
any shared state. Shared state can also include the environment, such as the
|
||||
@@ -90,7 +90,7 @@ number of threads to the test binary. Setting the number of test threads to 1
|
||||
means to not use any parallelism:</p>
|
||||
<pre><code class="language-text">$ cargo test -- --test-threads=1
|
||||
</code></pre>
|
||||
<h3>Tests Capture Output</h3>
|
||||
<a class="header" href="#tests-capture-output" name="tests-capture-output"><h3>Tests Capture Output</h3></a>
|
||||
<p>By default, Rust's test library captures and discards output to standard out
|
||||
and standard error, unless the test fails. For example, if you call <code>println!</code>
|
||||
in a test and the test passes, you won't see the <code>println!</code> output in your
|
||||
@@ -98,7 +98,7 @@ terminal. This behavior can be disabled by sending the <code>--nocapture</code>
|
||||
the test binary:</p>
|
||||
<pre><code class="language-text">$ cargo test -- --nocapture
|
||||
</code></pre>
|
||||
<h3>Running a Subset of Tests by Name</h3>
|
||||
<a class="header" href="#running-a-subset-of-tests-by-name" name="running-a-subset-of-tests-by-name"><h3>Running a Subset of Tests by Name</h3></a>
|
||||
<p>Sometimes, running a full test suite can take a long time. If you're only
|
||||
working on code in a particular area, you might want to only run the tests
|
||||
having to do with that code. <code>cargo test</code> takes an argument that allows you to
|
||||
@@ -218,7 +218,7 @@ test adding::add_two_and_two ... ok
|
||||
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured
|
||||
</code></pre>
|
||||
<h3>Ignore Some Tests Unless Specifically Requested</h3>
|
||||
<a class="header" href="#ignore-some-tests-unless-specifically-requested" name="ignore-some-tests-unless-specifically-requested"><h3>Ignore Some Tests Unless Specifically Requested</h3></a>
|
||||
<p>Sometimes a few specific tests can be very time-consuming to execute, so during
|
||||
most runs of <code>cargo test</code>, we'd like to exclude them. Instead of having to
|
||||
construct an argument to <code>cargo test</code> to run all tests except these and
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Test Organization</h2>
|
||||
<a class="header" href="#test-organization" name="test-organization"><h2>Test Organization</h2></a>
|
||||
<p>As mentioned before, testing is a large discipline, and different people
|
||||
sometimes use different terminology and organization. The Rust community tends
|
||||
to think about tests in terms of two main categories: <em>unit tests</em> and
|
||||
@@ -78,13 +78,13 @@ the same way any other code would, using only the public interface and
|
||||
exercising multiple modules per test. Both kinds of tests are important to
|
||||
ensure that the pieces of your library are doing what you expect them to
|
||||
separately and together.</p>
|
||||
<h3>Unit Tests</h3>
|
||||
<a class="header" href="#unit-tests" name="unit-tests"><h3>Unit Tests</h3></a>
|
||||
<p>The purpose of unit tests is to test each unit of code in isolation from the
|
||||
rest of the code, in order to be able to quickly pinpoint where code is working
|
||||
as expected or not. Unit tests live in the <em>src</em> directory, in the same files
|
||||
as the code they are testing. They are separated into their own <code>tests</code> module
|
||||
in each file.</p>
|
||||
<h4>The Tests Module and <code>cfg(test)</code></h4>
|
||||
<a class="header" href="#the-tests-module-and-cfgtest" name="the-tests-module-and-cfgtest"><h4>The Tests Module and <code>cfg(test)</code></h4></a>
|
||||
<p>By placing tests in their own module and using the <code>cfg</code> annotation on the
|
||||
module, we can tell Rust to only compile and run the test code when we run
|
||||
<code>cargo test</code>. This saves compile time when we only want to build the library
|
||||
@@ -160,7 +160,7 @@ unresolved name error since the <code>tests</code> module wouldn't know anything
|
||||
to list everything in the <code>use</code> statement in the tests. It's common instead to
|
||||
put <code>use super::*;</code> within a module's <code>test</code> submodule in order to bring
|
||||
everything into the <code>test</code> module scope at once.</p>
|
||||
<h4>Testing Private Functions</h4>
|
||||
<a class="header" href="#testing-private-functions" name="testing-private-functions"><h4>Testing Private Functions</h4></a>
|
||||
<p>There's controversy within the testing community about whether you should write
|
||||
unit tests for private functions or not. Regardless of which testing ideology
|
||||
you adhere to, Rust does allow you to test private functions due to the way
|
||||
@@ -194,13 +194,13 @@ mod tests {
|
||||
we can import and call <code>internal_adder</code> in a test just fine. If you don't think
|
||||
private functions should be tested, there's nothing in Rust that will compel
|
||||
you to do so.</p>
|
||||
<h3>Integration Tests</h3>
|
||||
<a class="header" href="#integration-tests" name="integration-tests"><h3>Integration Tests</h3></a>
|
||||
<p>In Rust, integration tests are tests that are entirely external to your
|
||||
library. They use your library in the same way any other code would. Their
|
||||
purpose is to test that many parts of your library work correctly together.
|
||||
Units of code that work correctly by themselves could have problems when
|
||||
integrated, so test coverage of the integrated code is important as well.</p>
|
||||
<h4>The <em>tests</em> Directory</h4>
|
||||
<a class="header" href="#the-tests-directory" name="the-tests-directory"><h4>The <em>tests</em> Directory</h4></a>
|
||||
<p>Cargo has support for integration tests in the <em>tests</em> directory. If you make
|
||||
one and put Rust files inside, Cargo will compile each of the files as an
|
||||
individual crate. Let's give it a try!</p>
|
||||
@@ -272,7 +272,7 @@ test it_adds_two ... ok
|
||||
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
|
||||
</code></pre>
|
||||
<h4>Submodules in Integration Tests</h4>
|
||||
<a class="header" href="#submodules-in-integration-tests" name="submodules-in-integration-tests"><h4>Submodules in Integration Tests</h4></a>
|
||||
<p>As you add more integration tests, you may want to make more than one file in
|
||||
the <code>tests</code> directory in order to group the test functions by the functionality
|
||||
they're testing, for example. As we mentioned before, that will work fine,
|
||||
@@ -287,7 +287,7 @@ what you want, it's recommended to instead use a <em>mod.rs</em> file in a
|
||||
subdirectory, like <em>tests/common/mod.rs</em>, for helper functions. Files in
|
||||
subdirectories of the <em>tests</em> directory do not get compiled as separate crates
|
||||
or have sections in the test output.</p>
|
||||
<h4>Integration Tests for Binary Crates</h4>
|
||||
<a class="header" href="#integration-tests-for-binary-crates" name="integration-tests-for-binary-crates"><h4>Integration Tests for Binary Crates</h4></a>
|
||||
<p>If your project is a binary crate that only contains a <em>src/main.rs</em> and does
|
||||
not have a <em>src/lib.rs</em>, it is not possible to create integration tests in the
|
||||
<em>tests</em> directory and use <code>extern crate</code> to import the functions in
|
||||
@@ -297,7 +297,7 @@ have a straightforward <em>src/main.rs</em> that calls logic that lives in
|
||||
crate by using <code>extern crate</code> to cover the important functionality, and if that
|
||||
works, the small amount of code in <em>src/main.rs</em> will work as well and does not
|
||||
need to be tested.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Rust's testing features provide a way to specify how code should function to
|
||||
ensure the code continues to work in the specified ways even as we make
|
||||
changes. Unit tests exercise different parts of a library separately and can
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>An I/O Project</h1>
|
||||
<a class="header" href="#an-io-project" name="an-io-project"><h1>An I/O Project</h1></a>
|
||||
<p>We've learned a lot over the last few chapters. Let's take that new knowledge
|
||||
and apply it by building a project together. Along the way, we'll learn a bit
|
||||
more about Rust's standard library.</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Accepting Command Line Arguments</h2>
|
||||
<a class="header" href="#accepting-command-line-arguments" name="accepting-command-line-arguments"><h2>Accepting Command Line Arguments</h2></a>
|
||||
<p>Our first task is to have <code>greprs</code> accept its two command line arguments. There
|
||||
are some existing libraries on crates.io that can help us do this, but since
|
||||
we're learning, we'll implement this ourselves.</p>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Reading a File</h2>
|
||||
<a class="header" href="#reading-a-file" name="reading-a-file"><h2>Reading a File</h2></a>
|
||||
<p>Now that we have some variables containing the information that we need, let's
|
||||
try using them. The next step is to open the file that we want to search. To do
|
||||
that, we need a file. Create one called <code>poem.txt</code> at the root level of your
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Improving Error Handling and Modularity</h2>
|
||||
<a class="header" href="#improving-error-handling-and-modularity" name="improving-error-handling-and-modularity"><h2>Improving Error Handling and Modularity</h2></a>
|
||||
<p>There are four problems that we'd like to fix to improve our program, and they
|
||||
all have to do with potential errors and the way the program is structured. The
|
||||
first problem is where we open the file: we've used <code>expect</code> to print out an
|
||||
@@ -94,7 +94,7 @@ harder it is to keep track of which ones we need for which purpose. It would be
|
||||
better if we grouped the configuration variables into one structure to make
|
||||
their purpose clear.</p>
|
||||
<p>Let's address these problems by restructuring our project.</p>
|
||||
<h3>Separation of Concerns for Binary Projects</h3>
|
||||
<a class="header" href="#separation-of-concerns-for-binary-projects" name="separation-of-concerns-for-binary-projects"><h3>Separation of Concerns for Binary Projects</h3></a>
|
||||
<p>These kinds of organizational problems are common to many similar kinds of
|
||||
projects, so the Rust community has developed a pattern for organizing the
|
||||
separate concerns. This pattern is useful for organizing any binary project
|
||||
@@ -160,7 +160,7 @@ fn parse_config(args: &[String]) -> (&str, &str) {
|
||||
this change, run the program again to verify that the argument parsing still
|
||||
works. It's good to check your progress often, so that you have a better idea
|
||||
of which change caused a problem, should you encounter one.</p>
|
||||
<h3>Grouping Configuration Values</h3>
|
||||
<a class="header" href="#grouping-configuration-values" name="grouping-configuration-values"><h3>Grouping Configuration Values</h3></a>
|
||||
<p>Now that we have a function, let's improve it. Our code still has an indication
|
||||
that there's a better design possible: we return a tuple, but then immediately
|
||||
break that tuple up into individual parts again. This code isn't bad on its
|
||||
@@ -235,7 +235,7 @@ than storing a reference to the string data, but cloning the data makes our
|
||||
code very straightforward.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<blockquote>
|
||||
<h4>The Tradeoffs of Using <code>clone</code></h4>
|
||||
<a class="header" href="#the-tradeoffs-of-using-clone" name="the-tradeoffs-of-using-clone"><h4>The Tradeoffs of Using <code>clone</code></h4></a>
|
||||
<p>There's a tendency amongst many Rustaceans to prefer not to use <code>clone</code> to fix
|
||||
ownership problems due to its runtime cost. In Chapter XX on iterators, we'll
|
||||
learn how to make this situation more efficient. For now, it's okay to copy a
|
||||
@@ -251,7 +251,7 @@ call <code>clone</code>.</p>
|
||||
returns in a variable named <code>config</code>, and we've updated the code that was using
|
||||
the separate <code>search</code> and <code>filename</code> variables to use the fields on the
|
||||
<code>Config</code> struct instead.</p>
|
||||
<h3>Creating a Constructor for <code>Config</code></h3>
|
||||
<a class="header" href="#creating-a-constructor-for-config" name="creating-a-constructor-for-config"><h3>Creating a Constructor for <code>Config</code></h3></a>
|
||||
<p>Let's now think about the purpose of <code>parse_config</code>: it's a function that
|
||||
creates a <code>Config</code> instance. We've already seen a convention for functions that
|
||||
create instances: a <code>new</code> function, like <code>String::new</code>. Listing 12-6 shows the
|
||||
@@ -309,7 +309,7 @@ impl Config {
|
||||
<p>We've changed the name of <code>parse_config</code> to <code>new</code> and moved it within an <code>impl</code>
|
||||
block. We've also updated the callsite in <code>main</code>. Try compiling this again to
|
||||
make sure it works.</p>
|
||||
<h3>Returning a <code>Result</code> from the Constructor</h3>
|
||||
<a class="header" href="#returning-a-result-from-the-constructor" name="returning-a-result-from-the-constructor"><h3>Returning a <code>Result</code> from the Constructor</h3></a>
|
||||
<p>Here's our last refactoring of this method: remember how accessing the vector
|
||||
with indices 1 and 2 panics when it contains fewer than 3 items and gives a bad
|
||||
error message? Let's fix that! Listing 12-7 shows how we can check that our
|
||||
@@ -438,7 +438,7 @@ literals, which is what our error message is for now.</p>
|
||||
<code>panic!</code> if there aren't enough arguments, we now return an <code>Err</code> value. We
|
||||
wrapped the <code>Config</code> return value in an <code>Ok</code>. These changes make the function
|
||||
conform to its new type signature.</p>
|
||||
<h3>Calling <code>Config::new</code> and Handling Errors</h3>
|
||||
<a class="header" href="#calling-confignew-and-handling-errors" name="calling-confignew-and-handling-errors"><h3>Calling <code>Config::new</code> and Handling Errors</h3></a>
|
||||
<p>Now we need to make some changes to <code>main</code> as shown in Listing 12-9:</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
@@ -522,7 +522,7 @@ but we no longer get all the extra output. Let's try it:</p>
|
||||
Problem parsing arguments: not enough arguments
|
||||
</code></pre>
|
||||
<p>Great! This output is much friendlier for our users.</p>
|
||||
<h3>Handling Errors from the <code>run</code> Function</h3>
|
||||
<a class="header" href="#handling-errors-from-the-run-function" name="handling-errors-from-the-run-function"><h3>Handling Errors from the <code>run</code> Function</h3></a>
|
||||
<p>Now that we're done refactoring our configuration parsing, let's improve our
|
||||
program's logic. Listing 12-10 shows the code after extracting a function named
|
||||
<code>run</code> that we'll call from <code>main</code>. The <code>run</code> function contains the code that
|
||||
@@ -724,7 +724,7 @@ we care about is the first case: detecting an error. If we used
|
||||
very useful.</p>
|
||||
<p>The bodies of the <code>if let</code> and of the <code>unwrap_or_else</code> are the same in both
|
||||
cases though: we print out an error and exit.</p>
|
||||
<h3>Split Code into a Library Crate</h3>
|
||||
<a class="header" href="#split-code-into-a-library-crate" name="split-code-into-a-library-crate"><h3>Split Code into a Library Crate</h3></a>
|
||||
<p>This is looking pretty good! There's one more thing we haven't done yet: split
|
||||
the <em>src/main.rs</em> up and put some code into <em>src/lib.rs</em> Let's do that now:
|
||||
move the <code>run</code> function from <em>src/main.rs</em> to a new file, <em>src/lib.rs</em>. You'll
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Testing the Library's Functionality</h2>
|
||||
<a class="header" href="#testing-the-librarys-functionality" name="testing-the-librarys-functionality"><h2>Testing the Library's Functionality</h2></a>
|
||||
<p>Writing tests for the core functionality of our code is now easier since we
|
||||
extracted the logic into <em>src/lib.rs</em> and left all the argument parsing and
|
||||
error handling in <em>src/main.rs</em>. We can now call our code directly with various
|
||||
|
||||
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Working with Environment Variables</h2>
|
||||
<a class="header" href="#working-with-environment-variables" name="working-with-environment-variables"><h2>Working with Environment Variables</h2></a>
|
||||
<p>Let's add one more feature: case insensitive searching. In addition, this
|
||||
setting won't be a command line option: it'll be an environment variable
|
||||
instead. We could choose to make case insensitivity a command line option, but
|
||||
our users have requested an environment variable that they could set once and
|
||||
make all their searches case insensitive in that terminal session.</p>
|
||||
<h3>Implement and Test a Case-Insensitive <code>grep</code> Function</h3>
|
||||
<a class="header" href="#implement-and-test-a-case-insensitive-grep-function" name="implement-and-test-a-case-insensitive-grep-function"><h3>Implement and Test a Case-Insensitive <code>grep</code> Function</h3></a>
|
||||
<p>First, let's add a new function that we will call when the environment variable
|
||||
is on. Let's start by adding a new test and re-naming our existing one:</p>
|
||||
<pre><code class="language-rust,ignore">#[cfg(test)]
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Write to <code>stderr</code> Instead of <code>stdout</code></h2>
|
||||
<a class="header" href="#write-to-stderr-instead-of-stdout" name="write-to-stderr-instead-of-stdout"><h2>Write to <code>stderr</code> Instead of <code>stdout</code></h2></a>
|
||||
<p>Right now, we're writing all of our output to the terminal with <code>println!</code>.
|
||||
This works, but most terminals provide two kinds of output: "standard out" is
|
||||
used for most information, but "standard error" is used for error messages. This
|
||||
@@ -150,7 +150,7 @@ our results:</p>
|
||||
<pre><code class="language-text">Are you nobody, too?
|
||||
How dreary to be somebody!
|
||||
</code></pre>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>In this chapter, we've covered how to do common I/O operations in a Rust
|
||||
context. By using command line arguments, files, environment variables, and the
|
||||
ability to write to <code>stderr</code>, you're now prepared to write command line
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Functional Language features in Rust - Iterators and Closures</h1>
|
||||
<a class="header" href="#functional-language-features-in-rust---iterators-and-closures" name="functional-language-features-in-rust---iterators-and-closures"><h1>Functional Language features in Rust - Iterators and Closures</h1></a>
|
||||
<p>Rust's design has taken inspiration from a lot of previous work. One of Rust's
|
||||
influences is functional programming, where functions are values that can be
|
||||
used as arguments or return values to other functions, assigned to variables,
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Closures</h2>
|
||||
<a class="header" href="#closures" name="closures"><h2>Closures</h2></a>
|
||||
<p>Rust gives you the ability to define <em>closures</em>, which are similar to
|
||||
functions. Instead of starting with a technical definition, let's see what
|
||||
closures look like, syntactically, and then we'll return to defining what they
|
||||
@@ -171,7 +171,7 @@ let three = add_one(2i32);
|
||||
it would be tedious if we were required to annotate their types.</p>
|
||||
<p>Another reason to have a different syntax from functions for closures is that
|
||||
they have different behavior than functions: closures possess an <em>environment</em>.</p>
|
||||
<h3>Closures Can Reference Their Environment</h3>
|
||||
<a class="header" href="#closures-can-reference-their-environment" name="closures-can-reference-their-environment"><h3>Closures Can Reference Their Environment</h3></a>
|
||||
<p>We've learned that functions can only use variables that are in scope, either
|
||||
by being <code>const</code> or being declared as parameters. Closures can do more: they're
|
||||
allowed to access variables from their enclosing scope. Listing 13-4 has an
|
||||
@@ -222,7 +222,7 @@ closure form instead
|
||||
the context of starting new threads. We'll show some more examples and explain
|
||||
more detail about this feature of closures in Chapter 16 when we talk about
|
||||
concurrency.</p>
|
||||
<h3>Closures as Function Parameters Using the <code>Fn</code> Traits</h3>
|
||||
<a class="header" href="#closures-as-function-parameters-using-the-fn-traits" name="closures-as-function-parameters-using-the-fn-traits"><h3>Closures as Function Parameters Using the <code>Fn</code> Traits</h3></a>
|
||||
<p>While we can bind closures to variables, that's not the most useful thing we
|
||||
can do with them. We can also define functions that have closures as parameters
|
||||
by using the <code>Fn</code> traits. Here's an example of a function named <code>call_with_one</code>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Iterators</h2>
|
||||
<a class="header" href="#iterators" name="iterators"><h2>Iterators</h2></a>
|
||||
<p>Iterators are a pattern in Rust that allows you to do some processing on a
|
||||
sequence of items. For example, the code in Listing 13-5 adds one to each
|
||||
number in a vector:</p>
|
||||
@@ -105,7 +105,7 @@ the closure it's passed to create the new sequence of values.</p>
|
||||
<p>That's how we end up with <code>[2, 3, 4]</code>. As you can see, closures are a very
|
||||
important part of using iterators: they provide a way of customizing the
|
||||
behavior of an iterator adaptor like <code>map</code>.</p>
|
||||
<h3>Iterators are Lazy</h3>
|
||||
<a class="header" href="#iterators-are-lazy" name="iterators-are-lazy"><h3>Iterators are Lazy</h3></a>
|
||||
<p>In the previous section, you may have noticed a subtle difference in wording:
|
||||
we said that <code>map</code> <em>adapts</em> an iterator, but <code>collect</code> <em>consumes</em> one. That was
|
||||
intentional. By themselves, iterators won't do anything; they're lazy. That is,
|
||||
@@ -128,7 +128,7 @@ chain to evaluate. We call those <em>consuming adaptors</em>, and <code>collect<
|
||||
them.</p>
|
||||
<p>So how do we tell which iterator methods consume the iterator or not? And what
|
||||
adaptors are available? For that, let's look at the <code>Iterator</code> trait.</p>
|
||||
<h3>The <code>Iterator</code> trait</h3>
|
||||
<a class="header" href="#the-iterator-trait" name="the-iterator-trait"><h3>The <code>Iterator</code> trait</h3></a>
|
||||
<p>Iterators all implement a trait named <code>Iterator</code> that is defined in the standard
|
||||
library. The definition of the trait looks like this:</p>
|
||||
<pre><code class="language-rust">trait Iterator {
|
||||
@@ -241,7 +241,7 @@ println!("{:?}", x);
|
||||
</code></pre>
|
||||
<p>This will print <code>Some(1)</code> through <code>Some(5)</code> and then <code>None</code>, each on their own
|
||||
line.</p>
|
||||
<h3>All Sorts of <code>Iterator</code> Adaptors</h3>
|
||||
<a class="header" href="#all-sorts-of-iterator-adaptors" name="all-sorts-of-iterator-adaptors"><h3>All Sorts of <code>Iterator</code> Adaptors</h3></a>
|
||||
<p>In Listing 13-5, we had iterators and we called methods like <code>map</code> and
|
||||
<code>collect</code> on them. In Listing 13-6, however, we only implemented the <code>next</code>
|
||||
method on our <code>Counter</code>. How do we get methods like <code>map</code> and <code>collect</code> on our
|
||||
|
||||
@@ -67,12 +67,12 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Improving our I/O Project</h2>
|
||||
<a class="header" href="#improving-our-io-project" name="improving-our-io-project"><h2>Improving our I/O Project</h2></a>
|
||||
<p>In our I/O project implementing <code>grep</code> in the last chapter, there are some
|
||||
places where the code could be made clearer and more concise using iterators.
|
||||
Let's take a look at how iterators can improve our implementation of the
|
||||
<code>Config::new</code> function and the <code>grep</code> function.</p>
|
||||
<h3>Removing a <code>clone</code> by Using an Iterator</h3>
|
||||
<a class="header" href="#removing-a-clone-by-using-an-iterator" name="removing-a-clone-by-using-an-iterator"><h3>Removing a <code>clone</code> by Using an Iterator</h3></a>
|
||||
<p>Back in listing 12-8, we had this code that took a slice of <code>String</code> values and
|
||||
created an instance of the <code>Config</code> struct by checking for the right number of
|
||||
arguments, indexing into the slice, and cloning the values so that the <code>Config</code>
|
||||
@@ -167,7 +167,7 @@ nice if we could use <code>?</code> on the <code>Option</code> returned from <co
|
||||
works with <code>Result</code> values currently. Even if we could use <code>?</code> on <code>Option</code> like
|
||||
we can on <code>Result</code>, the value we would get would be borrowed, and we want to
|
||||
move the <code>String</code> from the iterator into <code>Config</code>.</p>
|
||||
<h3>Making Code Clearer with Iterator Adaptors</h3>
|
||||
<a class="header" href="#making-code-clearer-with-iterator-adaptors" name="making-code-clearer-with-iterator-adaptors"><h3>Making Code Clearer with Iterator Adaptors</h3></a>
|
||||
<p>The other bit of code where we could take advantage of iterators was in the
|
||||
<code>grep</code> function as implemented in Listing 12-15:</p>
|
||||
<!-- We hadn't had a listing number for this code sample when we submitted
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Performance</h2>
|
||||
<a class="header" href="#performance" name="performance"><h2>Performance</h2></a>
|
||||
<p>Which version of our <code>grep</code> functions is faster: the version with an explicit
|
||||
<code>for</code> loop or the version with iterators? We ran a benchmark by loading the
|
||||
entire contents of "The Adventures of Sherlock Holmes" by Sir Arthur Conan
|
||||
@@ -133,7 +133,7 @@ access. It's extremely efficient.</p>
|
||||
<p>Now that you know this, go use iterators and closures without fear! They make
|
||||
code feel higher-level, but don't impose a runtime performance penalty for
|
||||
doing so.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Closures and iterators are Rust features inspired by functional programming
|
||||
language ideas. They contribute to Rust's ability to clearly express high-level
|
||||
ideas. The implementations of closures and iterators, as well as other zero-cost
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>More about Cargo and Crates.io</h1>
|
||||
<a class="header" href="#more-about-cargo-and-cratesio" name="more-about-cargo-and-cratesio"><h1>More about Cargo and Crates.io</h1></a>
|
||||
<p>We've used some features of Cargo in this book so far, but only the most basic
|
||||
ones. We've used Cargo to build, run, and test our code, but it can do a lot
|
||||
more. Let's go over some of its other features now. Cargo can do even more than
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Release profiles</h2>
|
||||
<a class="header" href="#release-profiles" name="release-profiles"><h2>Release profiles</h2></a>
|
||||
<p>Cargo supports a notion of <em>release profiles</em>. These profiles control various
|
||||
options for compiling your code and let you configure each profile
|
||||
independently of the others. You've seen a hint of this feature in the output
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Publishing a Crate to Crates.io</h2>
|
||||
<a class="header" href="#publishing-a-crate-to-cratesio" name="publishing-a-crate-to-cratesio"><h2>Publishing a Crate to Crates.io</h2></a>
|
||||
<p>We've added crates from crates.io as dependencies of our project. We can choose
|
||||
to share our code for other people to use as well. Crates.io distributes the
|
||||
source code of your packages, so it is primarily used to distribute code that's
|
||||
@@ -75,7 +75,7 @@ open source.</p>
|
||||
<p>Rust and Cargo have some features that can make your published package easier
|
||||
for people to find and use. We'll talk about some of those features, then cover
|
||||
how to publish a package.</p>
|
||||
<h3>Documentation Comments</h3>
|
||||
<a class="header" href="#documentation-comments" name="documentation-comments"><h3>Documentation Comments</h3></a>
|
||||
<p>In Chapter 3, we saw comments in Rust that start with <code>//</code>. Rust also has a
|
||||
second kind of comment: the <em>documentation comment</em>. While comments can be
|
||||
useful if someone is reading your code, you can generate HTML documentation
|
||||
@@ -142,7 +142,7 @@ library:</p>
|
||||
//! The Rust Standard Library provides the essential runtime
|
||||
//! functionality for building portable Rust software.
|
||||
</code></pre>
|
||||
<h3>Exporting a Convenient Public API with <code>pub use</code></h3>
|
||||
<a class="header" href="#exporting-a-convenient-public-api-with-pub-use" name="exporting-a-convenient-public-api-with-pub-use"><h3>Exporting a Convenient Public API with <code>pub use</code></h3></a>
|
||||
<p>In Chapter 7, we covered how to organize our code into modules with the <code>mod</code>
|
||||
keyword, how to make items public with the <code>pub</code> keyword, and how to bring
|
||||
items into a scope with the <code>use</code> keyword. When publishing a crate for people
|
||||
@@ -268,7 +268,7 @@ fn main() {
|
||||
Choosing <code>pub use</code> gives you flexibility in how you expose your crate's
|
||||
internal structure to users. Take a look at some of the code of crates you've
|
||||
installed to see if their internal structure differs from their public API.</p>
|
||||
<h3>Before Your First Publish</h3>
|
||||
<a class="header" href="#before-your-first-publish" name="before-your-first-publish"><h3>Before Your First Publish</h3></a>
|
||||
<p>Before being able to publish any crates, you'll need to create an account on
|
||||
<a href="https://crates.io">crates.io</a> and get an API token. To do so, <a href="https://crates.io">visit the home page</a>
|
||||
and log in via a GitHub account. A GitHub account is a requirement for now, but
|
||||
@@ -282,7 +282,7 @@ this:</p>
|
||||
<em>~/.cargo/config</em>. Note that this token is a <strong>secret</strong> and should not be
|
||||
shared with anyone else. If it gets shared with anyone for any reason, you
|
||||
should regenerate it immediately.</p>
|
||||
<h3>Before Publishing a New Crate</h3>
|
||||
<a class="header" href="#before-publishing-a-new-crate" name="before-publishing-a-new-crate"><h3>Before Publishing a New Crate</h3></a>
|
||||
<p>First, your crate will need a unique name. While you're working on a crate
|
||||
locally, you may name a crate whatever you'd like, but crate names on
|
||||
<a href="https://crates.io">crates.io</a> are allocated on a first-come-first- serve basis. Once a crate name
|
||||
@@ -328,7 +328,7 @@ license = "MIT/Apache-2.0"
|
||||
<p>Be sure to check out the <a href="http://doc.crates.io/manifest.html#package-metadata">documentation on crates.io</a> that
|
||||
describes other metadata you can specify to ensure your crate can be discovered
|
||||
and used more easily!</p>
|
||||
<h3>Publishing to Crates.io</h3>
|
||||
<a class="header" href="#publishing-to-cratesio" name="publishing-to-cratesio"><h3>Publishing to Crates.io</h3></a>
|
||||
<p>Now that we've created an account, saved our API token, chosen a name for our
|
||||
crate, and specified the required metadata, we're ready to publish! Publishing
|
||||
a crate is when a specific version is uploaded to be hosted on crates.io.</p>
|
||||
@@ -348,13 +348,13 @@ Uploading guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
</code></pre>
|
||||
<p>Congratulations! You've now shared your code with the Rust community, and
|
||||
anyone can easily add your crate as a dependency to their project.</p>
|
||||
<h3>Publishing a New Version of an Existing Crate</h3>
|
||||
<a class="header" href="#publishing-a-new-version-of-an-existing-crate" name="publishing-a-new-version-of-an-existing-crate"><h3>Publishing a New Version of an Existing Crate</h3></a>
|
||||
<p>When you've made changes to your crate and are ready to release a new version,
|
||||
change the <code>version</code> value specified in your <em>Cargo.toml</em>. Use the <a href="http://semver.org/">Semantic
|
||||
Versioning rules</a> to decide what an appropriate next version number is
|
||||
based on the kinds of changes you've made. Then run <code>cargo publish</code> to upload
|
||||
the new version.</p>
|
||||
<h3>Removing Versions from Crates.io with <code>cargo yank</code></h3>
|
||||
<a class="header" href="#removing-versions-from-cratesio-with-cargo-yank" name="removing-versions-from-cratesio-with-cargo-yank"><h3>Removing Versions from Crates.io with <code>cargo yank</code></h3></a>
|
||||
<p>Occasions may arise where you publish a version of a crate that actually ends
|
||||
up being broken for one reason or another, such as a syntax error or forgetting
|
||||
to include a file. For situations such as this, Cargo supports <em>yanking</em> a
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Cargo Workspaces</h2>
|
||||
<a class="header" href="#cargo-workspaces" name="cargo-workspaces"><h2>Cargo Workspaces</h2></a>
|
||||
<p>In Chapter 12, we built a package that included both a binary crate and a
|
||||
library crate. But what if the library crate continues to get bigger and we
|
||||
want to split our package up further into multiple library crates? As packages
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Installing Binaries from Crates.io with <code>cargo install</code></h2>
|
||||
<a class="header" href="#installing-binaries-from-cratesio-with-cargo-install" name="installing-binaries-from-cratesio-with-cargo-install"><h2>Installing Binaries from Crates.io with <code>cargo install</code></h2></a>
|
||||
<p>The <code>cargo install</code> command allows you to install and use binary crates
|
||||
locally. This isn't intended to replace system packages; it's meant to be a
|
||||
convenient way for Rust developers to install tools that others have shared on
|
||||
|
||||
@@ -67,14 +67,14 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h2>Extending Cargo with Custom Commands</h2>
|
||||
<a class="header" href="#extending-cargo-with-custom-commands" name="extending-cargo-with-custom-commands"><h2>Extending Cargo with Custom Commands</h2></a>
|
||||
<p>Cargo is designed to be extensible with new subcommands without having to
|
||||
modify Cargo itself. If a binary in your <code>$PATH</code> is named <code>cargo-something</code>,
|
||||
you can run it as if it were a Cargo subcommand by running <code>cargo something</code>.
|
||||
Custom commands like this are also listed when you run <code>cargo --list</code>. It's
|
||||
convenient to <code>cargo install</code> extensions to Cargo then be able to run them just
|
||||
like the built-in Cargo tools!</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>Sharing code with Cargo and crates.io is part of what makes the Rust ecosystem
|
||||
useful for many different tasks. Rust's standard library is small and stable,
|
||||
but crates are easy to share, use, and improve on a different timeline than the
|
||||
|
||||
+11
-11
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Smart Pointers</h1>
|
||||
<a class="header" href="#smart-pointers" name="smart-pointers"><h1>Smart Pointers</h1></a>
|
||||
<p>By smart pointers we mean a reference with more characteristics.</p>
|
||||
<p>Example of something that doesn't work</p>
|
||||
<p>Surprise! Vec and String are technically smart pointers too!</p>
|
||||
<p>This chapter is not a comprehensive list, but will give some examples of the
|
||||
ones in the standard library.</p>
|
||||
<h2><code>Box<T></code></h2>
|
||||
<a class="header" href="#boxt" name="boxt"><h2><code>Box<T></code></h2></a>
|
||||
<p>Don't use very often in your own code
|
||||
Heap allocated
|
||||
Express Ownership of a heap allocated thing</p>
|
||||
@@ -84,7 +84,7 @@ Express Ownership of a heap allocated thing</p>
|
||||
<li>Extend the lifetime of something</li>
|
||||
</ol>
|
||||
<p>How this interacts with the Drop trait</p>
|
||||
<h2><code>Rc<T></code></h2>
|
||||
<a class="header" href="#rct" name="rct"><h2><code>Rc<T></code></h2></a>
|
||||
<p>Reference counted. Rc is for <em>multiple ownership</em> - this thing should get
|
||||
deallocated when all of the owners go out of scope.</p>
|
||||
<p>Show the data structure:</p>
|
||||
@@ -98,23 +98,23 @@ deallocated when all of the owners go out of scope.</p>
|
||||
<p>This only works if the data is immutable.</p>
|
||||
<p>What happens when you clone an Rc: data isn't cloned, increase the strong count.
|
||||
When an Rc clone goes out of scope, the count goes down.</p>
|
||||
<h3>Rc Cycles</h3>
|
||||
<a class="header" href="#rc-cycles" name="rc-cycles"><h3>Rc Cycles</h3></a>
|
||||
<p>This is how you leak memory in rust, which btw is totally safe.</p>
|
||||
<p>Is this garbage collecting? Well it's not tracing GC... if you use Rc and had
|
||||
a cycle detector, it would be functionally equivalent to a tracing GC. Different
|
||||
runtime characteristics tho.</p>
|
||||
<h4>Solution: turn an Rc into a <code>Weak<T></code></h4>
|
||||
<a class="header" href="#solution-turn-an-rc-into-a-weakt" name="solution-turn-an-rc-into-a-weakt"><h4>Solution: turn an Rc into a <code>Weak<T></code></h4></a>
|
||||
<p>Same as Rc, but doesn't count towards the strong ref count. When you do this, the
|
||||
strong ref count goes down and the weak count goes up.</p>
|
||||
<p>Data gets cleaned up when the strong count is 0, no matter what the weak count is.
|
||||
However, Rc structure is kept until weak reference count also goes to zero, so weak pointers do not become dangling pointers.
|
||||
At this point, attempt to upgrade Weak pointer will result into None.
|
||||
Only when weak reference counter also reduces to zero, Rc structure is freed.</p>
|
||||
<h2><code>RefCell<T></code></h2>
|
||||
<a class="header" href="#refcellt" name="refcellt"><h2><code>RefCell<T></code></h2></a>
|
||||
<p>Single owner of mutable data</p>
|
||||
<p>The ownership rules checked at runtime instead of compile time.</p>
|
||||
<p>Only single threaded. See next chapter.</p>
|
||||
<h3><code>borrow</code> and <code>borrow_mut</code> methods</h3>
|
||||
<a class="header" href="#borrow-and-borrow_mut-methods" name="borrow-and-borrow_mut-methods"><h3><code>borrow</code> and <code>borrow_mut</code> methods</h3></a>
|
||||
<p>Checks all the rules and panics at runtime if the code violates them.</p>
|
||||
<ol>
|
||||
<li>
|
||||
@@ -126,20 +126,20 @@ don't, but if you really want to go back to debugging segfaults, feel free)</p>
|
||||
but you need to be able to mutate the underlying data.</p>
|
||||
</li>
|
||||
</ol>
|
||||
<h2><code>Cell<T></code></h2>
|
||||
<a class="header" href="#cellt" name="cellt"><h2><code>Cell<T></code></h2></a>
|
||||
<p>Same thing as RefCell but for types that are Copy. No borrow checking rules here
|
||||
anyway. So just reason #2 above.</p>
|
||||
<h2>Is this really safe? Yes!</h2>
|
||||
<a class="header" href="#is-this-really-safe-yes" name="is-this-really-safe-yes"><h2>Is this really safe? Yes!</h2></a>
|
||||
<p>RefCell is still doing the checks, just at runtime
|
||||
Cell is safe bc Copy types don't need the ownership rules anyway</p>
|
||||
<h3>The Interior Mutability Pattern</h3>
|
||||
<a class="header" href="#the-interior-mutability-pattern" name="the-interior-mutability-pattern"><h3>The Interior Mutability Pattern</h3></a>
|
||||
<p>The Interior Mutability Pattern is super unsafe internally but safe to use
|
||||
from the outside and is totally safe, totally, trust us, seriously, it's safe.</p>
|
||||
<p>Allude to <code>UnsafeCell<T></code> maybe. Affects optimizations since &mut T is unique.
|
||||
UnsafeCell turns off those optimizations so that everything doesn't break.</p>
|
||||
<p>This is how you can opt-out of the default of Rust's ownership rules and opt
|
||||
in to different guarantees.</p>
|
||||
<h2>Summary</h2>
|
||||
<a class="header" href="#summary" name="summary"><h2>Summary</h2></a>
|
||||
<p>If you want to implement your own smart pointer, go read the Nomicon.</p>
|
||||
<p>Now let's talk about concurrency, and some smart pointers that can be used
|
||||
with multiple threads.</p>
|
||||
|
||||
+16
-16
@@ -67,7 +67,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Fearless Concurrency</h1>
|
||||
<a class="header" href="#fearless-concurrency" name="fearless-concurrency"><h1>Fearless Concurrency</h1></a>
|
||||
<p>So, with Rust, it's more subtle than that. That is, while threading proper
|
||||
isn't part of the language itself, Rust's type system is structured in such a
|
||||
way as to make it possible to build those kinds of libraries. In other words,
|
||||
@@ -77,8 +77,8 @@ Rust's focus on aliasability ends up solving these problems.</p>
|
||||
mutability.</p>
|
||||
<p>Ownership rules (that tame the "shared" aspect) enable fearless concurrency: the
|
||||
compiler is making sure you don't shoot yourself in your foot.</p>
|
||||
<h2>What are threads</h2>
|
||||
<h2>Rust's concurrency tradeoffs</h2>
|
||||
<a class="header" href="#what-are-threads" name="what-are-threads"><h2>What are threads</h2></a>
|
||||
<a class="header" href="#rusts-concurrency-tradeoffs" name="rusts-concurrency-tradeoffs"><h2>Rust's concurrency tradeoffs</h2></a>
|
||||
<p>Lots of different languages tackle this problem in different ways. We are not
|
||||
going to talk about that: exercise for the reader is investigate other languages
|
||||
and compare and contrast with Rust's approach.</p>
|
||||
@@ -89,10 +89,10 @@ should integrate with your system.</p>
|
||||
to not have a heavy runtime.</p>
|
||||
<p>These are the reasons Rust's concurrency model is this way as opposed to other
|
||||
language's ways, which are optimizing for different things.</p>
|
||||
<h2>Let's get a thread: <code>thread::spawn</code></h2>
|
||||
<a class="header" href="#lets-get-a-thread-threadspawn" name="lets-get-a-thread-threadspawn"><h2>Let's get a thread: <code>thread::spawn</code></h2></a>
|
||||
<p>Code examples - just print stuff, no data sharing</p>
|
||||
<h2>Communicating between threads</h2>
|
||||
<h3>Closures, Ownership, and Borrowing</h3>
|
||||
<a class="header" href="#communicating-between-threads" name="communicating-between-threads"><h2>Communicating between threads</h2></a>
|
||||
<a class="header" href="#closures-ownership-and-borrowing" name="closures-ownership-and-borrowing"><h3>Closures, Ownership, and Borrowing</h3></a>
|
||||
<p>The property of being allowed to use variables from the surrounding scope is
|
||||
also subject to all of the usual rules around ownership and borrowing. Since
|
||||
closures attempt to infer the types of their parameters, they also infer how
|
||||
@@ -146,7 +146,7 @@ be <code>&mut Foo</code>, and so on. If we try to use <code>f3</code> after
|
||||
<code>closure_that_moves</code> in the last line of <code>main</code>, we'll get a compiler error
|
||||
since ownership of <code>f3</code> was transferred to <code>closure_that_moves</code>, which
|
||||
transferred ownership to the function <code>moves</code>.</p>
|
||||
<h3>Overriding Inferred Borrowing with the <code>move</code> Keyword</h3>
|
||||
<a class="header" href="#overriding-inferred-borrowing-with-the-move-keyword" name="overriding-inferred-borrowing-with-the-move-keyword"><h3>Overriding Inferred Borrowing with the <code>move</code> Keyword</h3></a>
|
||||
<p>Rust will allow you to override the borrowing inference by using the <code>move</code>
|
||||
keyword. This will cause all of the closure's parameters to be taken by
|
||||
ownership, instead of whatever they were inferred as. Consider this example:</p>
|
||||
@@ -182,7 +182,7 @@ assert_eq!(4, num);
|
||||
threads, since it's important that one thread is no longer allowed to use a
|
||||
value once the value has been transferred to another thread through a closure
|
||||
in order to prevent data races. We'll talk more about that in Chapter XX.</p>
|
||||
<h3>Closures and Lifetimes</h3>
|
||||
<a class="header" href="#closures-and-lifetimes" name="closures-and-lifetimes"><h3>Closures and Lifetimes</h3></a>
|
||||
<p>Remember Listing 10-8 from the Lifetime Syntax section of Chapter 10? It looked
|
||||
like this:</p>
|
||||
<pre><code class="language-rust,ignore">{
|
||||
@@ -278,29 +278,29 @@ defining <code>calculation</code>, we declare a new variable <code>r</code> that
|
||||
in the body of the <code>calculation</code> closure, we use <code>r</code> instead of using <code>s1</code>
|
||||
directly. The closure takes ownership of <code>r</code>, but <code>r</code> is a reference, so the
|
||||
closure hasn't taken ownership of <code>s1</code> even though <code>calculation</code> uses <code>move</code>.</p>
|
||||
<h3><code>Channels</code></h3>
|
||||
<a class="header" href="#channels" name="channels"><h3><code>Channels</code></h3></a>
|
||||
<p>Look up examples of cases where channels are useful</p>
|
||||
<p>Can match modeling of certain problems</p>
|
||||
<h4><code>Send</code></h4>
|
||||
<a class="header" href="#send" name="send"><h4><code>Send</code></h4></a>
|
||||
<p>Send is a trait that means i'm allowed to transfer ownership to another thread
|
||||
down a channel</p>
|
||||
<p>What things can be send and what can't?</p>
|
||||
<h2>Sharing data between threads</h2>
|
||||
<a class="header" href="#sharing-data-between-threads" name="sharing-data-between-threads"><h2>Sharing data between threads</h2></a>
|
||||
<p>Try to share data and get an error about which trait it doesn't implement</p>
|
||||
<h3><code>Sync</code></h3>
|
||||
<a class="header" href="#sync" name="sync"><h3><code>Sync</code></h3></a>
|
||||
<p>It's ok to access a thing from multiple threads at once</p>
|
||||
<p>Immutable things can be sync easily.</p>
|
||||
<h3><code>Arc<T></code></h3>
|
||||
<a class="header" href="#arct" name="arct"><h3><code>Arc<T></code></h3></a>
|
||||
<p>Atomic Reference Counting. Inner data still has to be immutable.</p>
|
||||
<p>Steve knows the motivating code that goes here.</p>
|
||||
<h3><code>Mutex<T></code></h3>
|
||||
<a class="header" href="#mutext" name="mutext"><h3><code>Mutex<T></code></h3></a>
|
||||
<p>For mutable data.</p>
|
||||
<p><code>lock</code> method, you get a Mutex guard. Change, then unlock, which usually happens
|
||||
automatically when the Mutex guard goes out of scope. If you do this wrong, your
|
||||
code will hang.</p>
|
||||
<p>Deadlocks are safe, you have to manage that yourself. Deadlock bugs usually
|
||||
happen bc you forget to unlock, but drop unlocks automatically.</p>
|
||||
<h2>Maybe make the I/O project concurrent?</h2>
|
||||
<a class="header" href="#maybe-make-the-io-project-concurrent" name="maybe-make-the-io-project-concurrent"><h2>Maybe make the I/O project concurrent?</h2></a>
|
||||
<p>Might be a lot of boilerplate without scoped threads, maybe just allude.</p>
|
||||
<p>This is a really rough sketch of some ideas that this chapter might cover.</p>
|
||||
<p>From a comment of steveklabnik's on <a href="https://news.ycombinator.com/item?id=13078384">the definitely not orange website</a>. "that paper" refers to <a href="http://www.hpl.hp.com/techreports/2004/HPL-2004-209.pdf">Boehm 2004</a>.</p>
|
||||
@@ -357,7 +357,7 @@ change a call from iter() to par_iter() and you're done).</p>
|
||||
kind of reasoning, but since aliasing and concurrency are so tightly related, I
|
||||
would argue that the language could understand only aliasing, not concurrency,
|
||||
and then library abstractions are sufficient.</p>
|
||||
<h2>Arc</h2>
|
||||
<a class="header" href="#arc" name="arc"><h2>Arc</h2></a>
|
||||
<p>Check out <a href="http://stackoverflow.com/a/40985661/51683">this awesome explanation of <code>Arc</code></a>.</p>
|
||||
|
||||
</div>
|
||||
|
||||
+9
-9
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Is Rust OOP?</h1>
|
||||
<a class="header" href="#is-rust-oop" name="is-rust-oop"><h1>Is Rust OOP?</h1></a>
|
||||
<p>Aphorism: DRY</p>
|
||||
<p>So how do you share code?</p>
|
||||
<p>I'm used to doing things to solve problems, what do i do instead?
|
||||
Why do i need to do different things in Rust? Let's look at an example
|
||||
with the Command pattern.</p>
|
||||
<h2>Command pattern</h2>
|
||||
<a class="header" href="#command-pattern" name="command-pattern"><h2>Command pattern</h2></a>
|
||||
<p>Look up official def</p>
|
||||
<p>Want caller to be able to customize what gets done</p>
|
||||
<p>Method takes command object, calls a run fn</p>
|
||||
@@ -81,12 +81,12 @@ with the Command pattern.</p>
|
||||
<p>where T: Run</p>
|
||||
<p>This is the definition of the Fn trait! So we wouldn't implement this, we'd just
|
||||
pass closures in</p>
|
||||
<h2>Supertraits</h2>
|
||||
<a class="header" href="#supertraits" name="supertraits"><h2>Supertraits</h2></a>
|
||||
<p>Trait constraints that use other traits</p>
|
||||
<p>Copy requires Clone because Copy is a subset of Clone's behavior, since if you
|
||||
have one, you can trivially implement the other.</p>
|
||||
<p>Traits that need behavior of another trait in a default method or something.</p>
|
||||
<h2>Trait objects</h2>
|
||||
<a class="header" href="#trait-objects" name="trait-objects"><h2>Trait objects</h2></a>
|
||||
<p>Runtime decisions about deciding what shared code we use</p>
|
||||
<p>Give example code</p>
|
||||
<p>With traits, libraries are extensible. This is why trait objects are different
|
||||
@@ -96,21 +96,21 @@ new things to the set of possible things</p>
|
||||
<p>T: trait is a compile time decision, monomorphization == static dispatch</p>
|
||||
<p>when you implement this trait, you get this other shared behavior</p>
|
||||
<p>dynamic dispatch (C++)</p>
|
||||
<h3>Implementation details</h3>
|
||||
<a class="header" href="#implementation-details" name="implementation-details"><h3>Implementation details</h3></a>
|
||||
<ul>
|
||||
<li>Like how other languages implement oo.</li>
|
||||
</ul>
|
||||
<h3>How to use it</h3>
|
||||
<a class="header" href="#how-to-use-it" name="how-to-use-it"><h3>How to use it</h3></a>
|
||||
<ul>
|
||||
<li>Statically checked duck typing</li>
|
||||
</ul>
|
||||
<h2>Builder pattern</h2>
|
||||
<a class="header" href="#builder-pattern" name="builder-pattern"><h2>Builder pattern</h2></a>
|
||||
<p>When you don't know how many arguments you're going to have</p>
|
||||
<h2>Delegation</h2>
|
||||
<a class="header" href="#delegation" name="delegation"><h2>Delegation</h2></a>
|
||||
<p>Deref - be mad</p>
|
||||
<p>Deref is a way to delegate everything, if you don't want that, then write
|
||||
boilerplate. Sending messages to your components.</p>
|
||||
<h2>How do you share data?</h2>
|
||||
<a class="header" href="#how-do-you-share-data" name="how-do-you-share-data"><h2>How do you share data?</h2></a>
|
||||
<p>Answer: get and set methods, this is awkward and might get better someday.</p>
|
||||
|
||||
</div>
|
||||
|
||||
+12
-12
@@ -67,13 +67,13 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Patterns</h1>
|
||||
<a class="header" href="#patterns" name="patterns"><h1>Patterns</h1></a>
|
||||
<p>We've actually used patterns a few times so far: they're used in <code>let</code>
|
||||
statements, in function parameters, and in the <code>match</code> expression. Patterns have
|
||||
a lot more abilities than we have demonstrated so far, so we'll cover some of
|
||||
the most commonly used ones in this section. Any of these abilities work in any
|
||||
place where a pattern is used.</p>
|
||||
<h2><code>let</code> statements</h2>
|
||||
<a class="header" href="#let-statements" name="let-statements"><h2><code>let</code> statements</h2></a>
|
||||
<p>A basic <code>let</code> statement has this form:</p>
|
||||
<pre><code class="language-text">let PATTERN = EXPRESSION;
|
||||
</code></pre>
|
||||
@@ -112,7 +112,7 @@ well:</p>
|
||||
<p>In simple cases like this, two <code>let</code>s may be clearer, but in others, creating
|
||||
multiple variables at once is nice. As we become more proficient in Rust, we’ll
|
||||
figure out which style is better, but it’s mostly a judgment call.</p>
|
||||
<h2>Type annotations</h2>
|
||||
<a class="header" href="#type-annotations" name="type-annotations"><h2>Type annotations</h2></a>
|
||||
<p>Most of the time, Rust uses <em>type inference</em>, meaning that it attempts to infer
|
||||
the types of your variables rather than you having to declare them explicitly
|
||||
even though Rust is a statically typed language. Occasionally, Rust won't have
|
||||
@@ -131,7 +131,7 @@ itself. As an example, here’s our more complex pattern with two variables:</p>
|
||||
</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>
|
||||
<a class="header" href="#literals--_" name="literals--_"><h2>Literals & _</h2></a>
|
||||
<p>You can match against literals directly, and <code>_</code> acts as an any case:</p>
|
||||
<pre><code class="language-rust">let x = 1;
|
||||
|
||||
@@ -143,7 +143,7 @@ match x {
|
||||
}
|
||||
</code></pre>
|
||||
<p>This prints <code>one</code>.</p>
|
||||
<h1>Multiple patterns</h1>
|
||||
<a class="header" href="#multiple-patterns" name="multiple-patterns"><h1>Multiple patterns</h1></a>
|
||||
<p>You can match multiple patterns with <code>|</code>:</p>
|
||||
<pre><code class="language-rust">let x = 1;
|
||||
|
||||
@@ -154,7 +154,7 @@ match x {
|
||||
}
|
||||
</code></pre>
|
||||
<p>This prints <code>one or two</code>.</p>
|
||||
<h2>ref and ref mut</h2>
|
||||
<a class="header" href="#ref-and-ref-mut" name="ref-and-ref-mut"><h2>ref and ref mut</h2></a>
|
||||
<p>Usually, when you match against a pattern, variables are bound to a value.
|
||||
This means you'll end up moving the value into the <code>match</code>:</p>
|
||||
<pre><code class="language-rust,ignore">let name = Some(String::from("Bors"));
|
||||
@@ -191,7 +191,7 @@ match name {
|
||||
// than moving it
|
||||
println!("name is: {:?}", name);
|
||||
</code></pre>
|
||||
<h2>Destructuring</h2>
|
||||
<a class="header" href="#destructuring" name="destructuring"><h2>Destructuring</h2></a>
|
||||
<p>Patterns can be used to destructure structs and enums:</p>
|
||||
<pre><code class="language-rust">struct Point {
|
||||
x: i32,
|
||||
@@ -216,7 +216,7 @@ match origin {
|
||||
Point { x, y } => { }, // variables x and y are created here
|
||||
}
|
||||
</code></pre>
|
||||
<h2>Shadowing</h2>
|
||||
<a class="header" href="#shadowing" name="shadowing"><h2>Shadowing</h2></a>
|
||||
<p>As with all variables, those declared by a pattern will shadow variables
|
||||
outside of the <code>match</code> construct:</p>
|
||||
<pre><code class="language-rust">let x = Some(5);
|
||||
@@ -226,7 +226,7 @@ match x {
|
||||
None => (),
|
||||
}
|
||||
</code></pre>
|
||||
<h2>Ignoring values</h2>
|
||||
<a class="header" href="#ignoring-values" name="ignoring-values"><h2>Ignoring values</h2></a>
|
||||
<p>We discussed using <code>_</code> as a whole pattern to ignore it above, but you can
|
||||
also use <code>_</code> inside of another pattern to ignore just part of it:</p>
|
||||
<pre><code class="language-rust">let x = Some(5);
|
||||
@@ -256,7 +256,7 @@ match origin {
|
||||
Point { x, .. } => { }, // y and z are ignored
|
||||
}
|
||||
</code></pre>
|
||||
<h2>Ranges</h2>
|
||||
<a class="header" href="#ranges" name="ranges"><h2>Ranges</h2></a>
|
||||
<p>You can match a range of values with <code>...</code>:</p>
|
||||
<pre><code class="language-rust">let x = 5;
|
||||
|
||||
@@ -274,7 +274,7 @@ match x {
|
||||
_ => println!("something else"),
|
||||
}
|
||||
</code></pre>
|
||||
<h2>Guards</h2>
|
||||
<a class="header" href="#guards" name="guards"><h2>Guards</h2></a>
|
||||
<p>You can introduce match guards with <code>if</code>:</p>
|
||||
<pre><code class="language-rust">let x = Some(5);
|
||||
|
||||
@@ -300,7 +300,7 @@ the <code>5</code>. In other words, the precedence of if behaves like this:</p>
|
||||
<p>not this:</p>
|
||||
<pre><code class="language-text">4 | (5 if y) => ...
|
||||
</code></pre>
|
||||
<h2>Bindings</h2>
|
||||
<a class="header" href="#bindings" name="bindings"><h2>Bindings</h2></a>
|
||||
<p>You can bind values to names with <code>@</code>:</p>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -67,10 +67,10 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>More Lifetimes</h1>
|
||||
<h2>Lifetimes that depend on other lifetimes</h2>
|
||||
<a class="header" href="#more-lifetimes" name="more-lifetimes"><h1>More Lifetimes</h1></a>
|
||||
<a class="header" href="#lifetimes-that-depend-on-other-lifetimes" name="lifetimes-that-depend-on-other-lifetimes"><h2>Lifetimes that depend on other lifetimes</h2></a>
|
||||
<p>'a: 'b stuff: subtyping</p>
|
||||
<h2>Higher ranked trait bounds</h2>
|
||||
<a class="header" href="#higher-ranked-trait-bounds" name="higher-ranked-trait-bounds"><h2>Higher ranked trait bounds</h2></a>
|
||||
<p>for<'a></p>
|
||||
<p>Needed for closures</p>
|
||||
|
||||
|
||||
+11
-11
@@ -67,8 +67,8 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Advanced Type System Features</h1>
|
||||
<h2>Unsafe Rust</h2>
|
||||
<a class="header" href="#advanced-type-system-features" name="advanced-type-system-features"><h1>Advanced Type System Features</h1></a>
|
||||
<a class="header" href="#unsafe-rust" name="unsafe-rust"><h2>Unsafe Rust</h2></a>
|
||||
<p>Things you may do in an unsafe block that you may not in safe rust</p>
|
||||
<ul>
|
||||
<li>deref a raw pointer</li>
|
||||
@@ -80,22 +80,22 @@
|
||||
<p>Here's the syntax tho</p>
|
||||
<p>You know unsafe blocks are the cause of any crashes</p>
|
||||
<p>wrap all the unsafe, make it as small as possible, present a safe public API</p>
|
||||
<h3>Raw Pointers</h3>
|
||||
<h3>Unsafe Functions</h3>
|
||||
<h4><code>transmute</code></h4>
|
||||
<a class="header" href="#raw-pointers" name="raw-pointers"><h3>Raw Pointers</h3></a>
|
||||
<a class="header" href="#unsafe-functions" name="unsafe-functions"><h3>Unsafe Functions</h3></a>
|
||||
<a class="header" href="#transmute" name="transmute"><h4><code>transmute</code></h4></a>
|
||||
<p>never ever. don't. stop.</p>
|
||||
<h4><code>extern fn</code></h4>
|
||||
<a class="header" href="#extern-fn" name="extern-fn"><h4><code>extern fn</code></h4></a>
|
||||
<p>You have to write unsafe code to FFI</p>
|
||||
<h3><code>static</code></h3>
|
||||
<h3>Unsafe Traits</h3>
|
||||
<h2>Associated Types</h2>
|
||||
<a class="header" href="#static" name="static"><h3><code>static</code></h3></a>
|
||||
<a class="header" href="#unsafe-traits" name="unsafe-traits"><h3>Unsafe Traits</h3></a>
|
||||
<a class="header" href="#associated-types" name="associated-types"><h2>Associated Types</h2></a>
|
||||
<p>More common than the other things, less common than the rest of the book</p>
|
||||
<p>why this is a thing instead of a generic</p>
|
||||
<h2>The Thing Formerly Known as UFCS</h2>
|
||||
<a class="header" href="#the-thing-formerly-known-as-ufcs" name="the-thing-formerly-known-as-ufcs"><h2>The Thing Formerly Known as UFCS</h2></a>
|
||||
<p>Only needed when implementing super generic code</p>
|
||||
<p>Lots of things are syntax sugar for this</p>
|
||||
<p>Two traits that impl the same method - how to disambiguate</p>
|
||||
<h2>Coherence</h2>
|
||||
<a class="header" href="#coherence" name="coherence"><h2>Coherence</h2></a>
|
||||
<p>Show examples of when you control traits and types or not</p>
|
||||
<p>Ex: Cannot impl Debug on someone else's type</p>
|
||||
<p>Solution: newtype</p>
|
||||
|
||||
+2
-2
@@ -66,7 +66,7 @@
|
||||
</div>
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Introduction</h1>
|
||||
<a class="header" href="#introduction" name="introduction"><h1>Introduction</h1></a>
|
||||
<p>Welcome to “The Rust Programming Language,” an introductory book about Rust.
|
||||
Rust is a programming language that’s focused on safety, speed, and
|
||||
concurrency. Its design lets you create programs that have the performance and
|
||||
@@ -87,7 +87,7 @@ 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>
|
||||
<a class="header" href="#contributing-to-the-book" name="contributing-to-the-book"><h2>Contributing to the book</h2></a>
|
||||
<p>This book is open source. If you find an error, please don’t hesitate to file an
|
||||
issue or send a pull request <a href="https://github.com/rust-lang/book">on GitHub</a>.</p>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user