mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:34:52 -06:00
rebuild pages at a307b7f
This commit is contained in:
+394
-380
@@ -68,25 +68,29 @@
|
||||
|
||||
<div id="content" class="content">
|
||||
<h1>Guessing Game</h1>
|
||||
<p>Let's jump into Rust with a hands-on project! This chapter will introduce you to
|
||||
a few common Rust concepts by showing how you would use them in a real program.
|
||||
You'll learn about <code>let</code>, <code>match</code>, methods, associated functions, using
|
||||
external crates, and more! Following chapters will explore these ideas in more
|
||||
detail; this chapter will get you practicing the fundamentals.</p>
|
||||
<p>We’re going to implement a classic beginner programming problem: the guessing
|
||||
game. Here’s how it works: Our program will generate a random integer between
|
||||
one and a hundred. It will then prompt us to enter a guess. Upon entering our
|
||||
guess, it will tell us if we’re too low or too high. Once we guess correctly,
|
||||
it will congratulate us.</p>
|
||||
<p>Let’s jump into Rust by working through a hands-on project together! This
|
||||
chapter introduces you to a few common Rust concepts by showing you how to use
|
||||
them in a real program. You’ll learn about <code>let</code>, <code>match</code>, methods, associated
|
||||
functions, using external crates, and more! The following chapters will explore
|
||||
these ideas in more detail. In this chapter, you’ll practice the fundamentals.</p>
|
||||
<p>We’ll implement a classic beginner programming problem: a guessing game.
|
||||
Here’s how it works: the program will generate a random integer between 1 and</p>
|
||||
<ol start="100">
|
||||
<li>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.</li>
|
||||
</ol>
|
||||
<h2>Setting Up a New Project</h2>
|
||||
<p>Let’s set up a new project. Go to your projects directory from the previous
|
||||
chapter, and create a new project using Cargo, like so:</p>
|
||||
<p>To set up a new project, go to the projects directory that you created in
|
||||
Chapter 1, and make a new project using Cargo, like so:</p>
|
||||
<pre><code class="language-bash">$ cargo new guessing_game --bin
|
||||
$ cd guessing_game
|
||||
</code></pre>
|
||||
<p>We pass the name of our project to <code>cargo new</code> and pass the <code>--bin</code> flag, since
|
||||
we’re going to be making another binary like in Chapter 1.</p>
|
||||
<p>Take a look at the generated <code>Cargo.toml</code>:</p>
|
||||
<p>The first command, <code>cargo new</code>, takes the name of the project (<code>guessing_game</code>)
|
||||
as the first argument. The <code>--bin</code> flag tells Cargo to make a binary project,
|
||||
similar to the one in Chapter 1. The second command changes to the new
|
||||
project's directory.</p>
|
||||
<p>Look at the generated <code>Cargo.toml</code> file:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<pre><code class="language-toml">[package]
|
||||
name = "guessing_game"
|
||||
@@ -95,32 +99,30 @@ authors = ["Your Name <you@example.com>"]
|
||||
|
||||
[dependencies]
|
||||
</code></pre>
|
||||
<p>If the author information that Cargo got from your environment is not correct,
|
||||
go ahead and fix that in the file and save it again.</p>
|
||||
<p>As we saw in the last chapter, cargo new generates a “Hello, world!” program
|
||||
for us. Check out src/main.rs:</p>
|
||||
<p>If the author information that Cargo obtained from your environment is not
|
||||
correct, fix that in the file and save it again.</p>
|
||||
<p>As you saw in Chapter 1, <code>cargo new</code> generates a “Hello, world!” program for
|
||||
you. Check out the <code>src/main.rs</code> file:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
</code></pre>
|
||||
<p>Let’s try compiling what Cargo gave us and running it in the same step, using
|
||||
the <code>cargo run</code> command:</p>
|
||||
<p>Now let’s compile this "Hello, world!" program and run it in the same step
|
||||
using the <code>cargo run</code> command:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/debug/guessing_game`
|
||||
Hello, world!
|
||||
</code></pre>
|
||||
<p>Great! The <code>run</code> command comes in handy when you need to rapidly iterate on a
|
||||
project. Our game is such a project: we want to quickly test each
|
||||
iteration before moving on to the next one.</p>
|
||||
<p>Now open up your <code>src/main.rs</code> again. We’ll be writing all of our code in this
|
||||
file.</p>
|
||||
<p>The <code>run</code> command comes in handy when you need to rapidly iterate on a project,
|
||||
and this game is such a project: we want to quickly test each iteration
|
||||
before moving on to the next one.</p>
|
||||
<p>Reopen the <code>src/main.rs</code> file. You’ll be writing all the code in this file.</p>
|
||||
<h2>Processing a Guess</h2>
|
||||
<p>Let’s get to it! We'll split the development of this game up into parts. This
|
||||
first part will ask for input from a user and process the input, checking that
|
||||
the input is in the form we expect. First we need to allow our player to input
|
||||
a guess. Enter this in your <code>src/main.rs</code>:</p>
|
||||
<p>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 <code>src/main.rs</code>.</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">use std::io;
|
||||
|
||||
@@ -137,129 +139,130 @@ fn main() {
|
||||
println!("You guessed: {}", guess);
|
||||
}
|
||||
</code></pre>
|
||||
<p>There’s a lot here! Let’s go over it, bit by bit.</p>
|
||||
<caption>
|
||||
Listing 2-1: Code to get a guess from the user and print it out
|
||||
</caption>
|
||||
<p>This code contains a lot of information, so let’s go over it bit by bit. To
|
||||
obtain user input and then print the result as output, we need to import the
|
||||
<code>io</code> (input/output) library from the standard library (which is known as <code>std</code>):</p>
|
||||
<pre><code class="language-rust,ignore">use std::io;
|
||||
</code></pre>
|
||||
<p>We’ll need to take user input and then print the result as output, and for that
|
||||
functionality we need to import the <code>io</code> (input/output) library from the
|
||||
standard library (which is known as <code>std</code>).</p>
|
||||
<p>By default, Rust only imports a few things into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
|
||||
<em>prelude</em></a><!-- ignore -->. If it’s not in the prelude, you’ll have to
|
||||
import it into your program explicitly with a <code>use</code> statement. Using the
|
||||
<code>std::io</code> library gets you a number of useful <code>io</code>-related things, including
|
||||
the functionality to accept user input.</p>
|
||||
<p>By default, Rust imports only a few types into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
|
||||
<em>prelude</em></a><!-- ignore -->. If a type you want to use isn’t in the
|
||||
prelude, you have to import that type into your program explicitly with a <code>use</code>
|
||||
statement. Using the <code>std::io</code> library provides you with a number of useful
|
||||
<code>io</code>-related features, including the functionality to accept user input.</p>
|
||||
<p>As you saw in Chapter 1, the <code>main</code> function is the entry point into the
|
||||
program:</p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
</code></pre>
|
||||
<p>As you’ve seen in Chapter 1, the <code>main</code> function is the entry point into the
|
||||
program. The <code>fn</code> syntax declares a new function, the <code>()</code>s indicate that
|
||||
there are no arguments, and <code>{</code> starts the body of the function.</p>
|
||||
<p>The <code>fn</code> syntax declares a new function, the <code>()</code> indicate there are no
|
||||
arguments, and <code>{</code> starts the body of the function.</p>
|
||||
<p>As you also learned in Chapter 1, <code>println!</code> is a macro that prints a string to
|
||||
the screen:</p>
|
||||
<pre><code class="language-rust,ignore">println!("Guess the number!");
|
||||
|
||||
println!("Please input your guess.");
|
||||
</code></pre>
|
||||
<p>As we learned in Chapter 1, <code>println!</code> is a macro that prints a string to the
|
||||
screen. This is just a prompt stating what the game is and requesting input from
|
||||
the user.</p>
|
||||
<p>This code is just printing a prompt stating what the game is and requesting
|
||||
input from the user.</p>
|
||||
<h3>Storing Values with Variables</h3>
|
||||
<p>Next we need to store the user input.</p>
|
||||
<p>Next, we'll create a place to store the user input, like this:</p>
|
||||
<pre><code class="language-rust,ignore">let mut guess = String::new();
|
||||
</code></pre>
|
||||
<p>Now we’re getting interesting! There’s a lot going on in this little line.
|
||||
The first thing to notice is that this is a <code>let</code> statement, which is
|
||||
used to create <em>variables</em>. Here's another example:</p>
|
||||
<p>Now the program is getting interesting! There’s a lot going on in this little
|
||||
line. Notice that this is a <code>let</code> statement, which is used to create
|
||||
<em>variables</em>. Here’s another example:</p>
|
||||
<pre><code class="language-rust,ignore">let foo = bar;
|
||||
</code></pre>
|
||||
<p>This will create a new variable named <code>foo</code>, and bind this name to the value
|
||||
<code>bar</code>. In Rust, variables are immutable by default. To make a variable mutable,
|
||||
use <code>mut</code> before the variable name:</p>
|
||||
<pre><code class="language-rust">let foo = 5; // immutable.
|
||||
<p>This line will create a new variable named <code>foo</code> and bind it to the value
|
||||
<code>bar</code>. In Rust, variables are immutable by default. The following example shows
|
||||
how to use <code>mut</code> before the variable name to make a variable mutable:</p>
|
||||
<pre><code class="language-rust">let foo = 5; // immutable
|
||||
let mut bar = 5; // mutable
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>Note: The <code>//</code> syntax will start a comment that continues until the end of the
|
||||
<p>Note: The <code>//</code> syntax starts a comment that continues until the end of the
|
||||
line. Rust ignores everything in comments.</p>
|
||||
</blockquote>
|
||||
<p>So now we know that <code>let mut guess</code> will introduce a mutable variable named
|
||||
<code>guess</code>, but we have to look at the other side of the <code>=</code> for the value it’s
|
||||
bound to: <code>String::new</code>. <code>String</code> is a string type, provided by the standard
|
||||
library. A <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a growable, UTF-8 encoded bit
|
||||
of text.</p>
|
||||
<p>Now you know that <code>let mut guess</code> will introduce a mutable variable named
|
||||
<code>guess</code>. On the other side of the equal sign (<code>=</code>) is the value that <code>guess</code> is
|
||||
bound to, which is the result of calling <code>String::new</code>, a function that returns
|
||||
a new instance of a <code>String</code>. <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a string
|
||||
type provided by the standard library that is a growable, UTF-8 encoded bit of
|
||||
text.</p>
|
||||
<p>The <code>::</code> syntax in the <code>::new</code> line indicates that <code>new</code> is an <em>associated
|
||||
function</em> of a particular type. An associated function is a function that is
|
||||
associated with a type, in this case <code>String</code>, rather than a particular
|
||||
instance of a <code>String</code>. Some languages call this a <em>static method</em>.</p>
|
||||
<p>This <code>new</code> function creates a new, empty <code>String</code>.
|
||||
You’ll find a <code>new</code> function on many types, as it’s a common name for making
|
||||
a new value of some kind.</p>
|
||||
<p>So to summarize, the <code>let mut guess = String::new();</code> line has created a
|
||||
mutable variable that is currently bound to a new, empty instance of a <code>String</code>.
|
||||
Whew!</p>
|
||||
<p>Let’s move forward:</p>
|
||||
function</em> of the <code>String</code> type. An associated function is implemented on a type,
|
||||
in this case <code>String</code>, rather than on a particular instance of a <code>String</code>. Some
|
||||
languages call this a <em>static method</em>.</p>
|
||||
<p>This <code>new</code> function creates a new, empty <code>String</code>. You’ll find a <code>new</code> function
|
||||
on many types, because it’s a common name for a function that makes a new value
|
||||
of some kind.</p>
|
||||
<p>To summarize, the <code>let mut guess = String::new();</code> line has created a mutable
|
||||
variable that is currently bound to a new, empty instance of a <code>String</code>. Whew!</p>
|
||||
<p>Recall that we included the input/output functionality from the standard
|
||||
library with <code>use std::io;</code> on the first line of the program. Now we'll call an
|
||||
associated function, <code>stdin</code>, on <code>io</code>:</p>
|
||||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess)
|
||||
.expect("Failed to read line");
|
||||
</code></pre>
|
||||
<p>We included the input/output functionality from the standard library with use
|
||||
std::io; on the first line of the program. We are now calling an associated
|
||||
function, stdin(), on io. If we didn’t have the use std::io line at the
|
||||
beginning of the program, we could have written this function call as
|
||||
std::io::stdin(). The stdin() function returns an instance of std::io::Stdin,
|
||||
which is a type that represents a handle to the standard input for your
|
||||
terminal.</p>
|
||||
<p>The next part, <code>.read_line(&mut guess)</code>, calls the
|
||||
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle
|
||||
to get input from the user. We’re also passing one argument to <code>read_line</code>:
|
||||
<code>&mut guess</code>.</p>
|
||||
<p>If we didn’t have the <code>use std::io</code> line at the beginning of the program, we
|
||||
could have written this function call as <code>std::io::stdin</code>. The <code>stdin</code> function
|
||||
returns an instance of <a href="../std/io/struct.Stdin.html"><code>std::io::Stdin</code></a><!-- ignore -->, which is a
|
||||
type that represents a handle to the standard input for your terminal.</p>
|
||||
<p>The next part of the code, <code>.read_line(&mut guess)</code>, calls the
|
||||
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle to
|
||||
get input from the user. We’re also passing one argument to <code>read_line</code>: <code>&mut guess</code>.</p>
|
||||
<p>The job of <code>read_line</code> is to take whatever the user types into standard input
|
||||
and place that into a string, so it takes that string as an argument. The
|
||||
string argument needs to be mutable so that the method can change the string's
|
||||
string argument needs to be mutable so the method can change the string’s
|
||||
content by adding the user input.</p>
|
||||
<p>The <code>&</code> indicates that this argument is a <em>reference</em>, which gives you a way to
|
||||
let multiple parts of your code access one piece of data without needing to
|
||||
copy that data into memory multiple times. References are a complex feature,
|
||||
and one of Rust’s major advantages is how safe and easy it is to use
|
||||
references. We don’t need to know a lot of those details to finish our program
|
||||
right now, though; Chapter XX will cover references in more detail. For now,
|
||||
all we need to know is that like variables, references are immutable by
|
||||
default. Hence, we need to write <code>&mut guess</code>, rather than <code>&guess</code>, to make it
|
||||
mutable.</p>
|
||||
<p>We’re not quite done with this line of code. While it’s a single line of text,
|
||||
it’s only the first part of the single logical line of code. The second part is
|
||||
this method:</p>
|
||||
references. You don’t need to know a lot of those details to finish this
|
||||
program: Chapter 4 will explain references more thoroughly. For now, all you
|
||||
need to know is that like variables, references are immutable by default.
|
||||
Hence, we need to write <code>&mut guess</code> rather than <code>&guess</code> to make it mutable.</p>
|
||||
<p>We’re not quite done with this line of code. Although it’s a single line of
|
||||
text, it’s only the first part of the single logical line of code. The second
|
||||
part is this method:</p>
|
||||
<pre><code class="language-rust,ignore">.expect("Failed to read line");
|
||||
</code></pre>
|
||||
<p>When you call a method with the <code>.foo()</code> syntax, it's often wise to introduce a
|
||||
newline and other whitespace. This helps you split up long lines. We could have
|
||||
<p>When you call a method with the <code>.foo()</code> syntax, it’s often wise to introduce a
|
||||
newline and other whitespace to help break up long lines. We could have
|
||||
written this code as:</p>
|
||||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess).expect("failed to read line");
|
||||
</code></pre>
|
||||
<p>But that gets hard to read. So we’ve split it up, two lines for two method
|
||||
calls. Now let's see what this line does.</p>
|
||||
<p>However, one long line is difficult to read, so it’s best to divide it, two
|
||||
lines for two method calls. Now let’s discuss what this line does.</p>
|
||||
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
|
||||
<p>We mentioned that <code>read_line</code> puts what the user types into the string we
|
||||
pass it, but it also returns a value: in this case, an
|
||||
<p>As mentioned earlier, <code>read_line</code> puts what the user types into the string we're
|
||||
passing it, but it also returns a value—in this case, an
|
||||
<a href="../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
|
||||
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore -->,
|
||||
and then specific versions for sub-libraries, like <code>io::Result</code>.</p>
|
||||
<p>The <code>Result</code> types are <a href="ch06-00-enums.html">enums</a><!-- ignore -->, which is short for
|
||||
<em>enumerations</em>. An enumeration is a type that can have a fixed set of values,
|
||||
which are called the enum's <em>variants</em>. We will be covering enums in more
|
||||
detail in Chapter XX.</p>
|
||||
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore --> as
|
||||
well as specific versions for submodules, such as <code>io::Result</code>.</p>
|
||||
<p>The <code>Result</code> types are <a href="ch06-00-enums.html"><em>enumerations</em></a><!-- ignore -->, often referred
|
||||
to as <em>enums</em>. An enumeration is a type that can have a fixed set of values,
|
||||
and those values are called the enum’s <em>variants</em>. Chapter 6 will cover enums
|
||||
in more detail.</p>
|
||||
<p>For <code>Result</code>, the variants are <code>Ok</code> or <code>Err</code>. <code>Ok</code> indicates the operation was
|
||||
successful, and inside the <code>Ok</code> variant is the successfully generated value.
|
||||
<code>Err</code> means the operation failed, and the <code>Err</code> contains information about how
|
||||
or why the operation failed.</p>
|
||||
<code>Err</code> means the operation failed, and <code>Err</code> contains information about how or
|
||||
why the operation failed.</p>
|
||||
<p>The purpose of these <code>Result</code> types is to encode error handling information.
|
||||
Values of the <code>Result</code> type, like any type, have methods defined on them.
|
||||
<code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that we can call.
|
||||
If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will cause our
|
||||
program to crash and display the message that we passed as an argument to
|
||||
<code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would likely be the
|
||||
result of an error coming from the underlying operating system. If this
|
||||
instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the return value
|
||||
that <code>Ok</code> is holding and return just that value to us so that we could use it.
|
||||
In this case, that value is the number of characters the user entered into
|
||||
standard input.</p>
|
||||
<p>If we don't call <code>expect</code>, our program will compile, but we’ll get a warning:</p>
|
||||
Values of the <code>Result</code> type, like any type, have methods defined on them. An
|
||||
instance of <code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that
|
||||
you can call. If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will
|
||||
cause the program to crash and display the message that you passed as an
|
||||
argument to <code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would
|
||||
likely be the result of an error coming from the underlying operating system.
|
||||
If this instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the
|
||||
return value that <code>Ok</code> is holding and return just that value to you so you
|
||||
could use it. In this case, that value is the number of characters the user
|
||||
entered into standard input.</p>
|
||||
<p>If we don’t call <code>expect</code>, the program will compile, but we’ll get a warning:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||||
@@ -267,30 +270,29 @@ src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||||
src/main.rs:10 io::stdin().read_line(&mut guess);
|
||||
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
</code></pre>
|
||||
<p>Rust warns that we haven’t used the <code>Result</code> value, telling us that we
|
||||
haven’t handled a possible error. The right way to suppress the warning is to
|
||||
actually write error handling, but if we just want to crash the program when a
|
||||
problem occurs, we can use <code>expect</code>. We’ll save recovering from errors for a
|
||||
future project.</p>
|
||||
<p>Rust warns that we haven’t used the <code>Result</code> value returned from <code>read_line</code>,
|
||||
indicating that the program hasn’t handled a possible error. The right way to
|
||||
suppress the warning is to actually write error handling, but since we just
|
||||
want to crash this program when a problem occurs, we can use <code>expect</code>. You’ll
|
||||
learn about recovering from errors in Chapter 9.</p>
|
||||
<h3>Printing Values with <code>println!</code> Placeholders</h3>
|
||||
<p>There’s only one line of this first example left, aside from the closing curly
|
||||
brace:</p>
|
||||
<pre><code class="language-rust,ignore"> println!("You guessed: {}", guess);
|
||||
<p>Aside from the closing curly brace, there’s only one more line to discuss in
|
||||
the code added so far, which is the following:</p>
|
||||
<pre><code class="language-rust,ignore">println!("You guessed: {}", guess);
|
||||
</code></pre>
|
||||
<p>This prints out the string we saved our input in. The <code>{}</code>s are a placeholder:
|
||||
think of <code>{}</code> as little crab pincers, holding a value in place. You can print
|
||||
more than one value this way: the first <code>{}</code> holds the first value listed after
|
||||
the format string, the second set holds the second value, and so on. Printing
|
||||
out multiple values in one call to <code>println!</code> would then look like this:</p>
|
||||
<p>This line prints out the string we saved the user’s input in. The set of <code>{}</code>
|
||||
is a placeholder that holds a value in place. You can print more than one value
|
||||
using <code>{}</code>: the first set of <code>{}</code> holds the first value listed after the format
|
||||
string, the second set holds the second value, and so on. Printing out multiple
|
||||
values in one call to <code>println!</code> would look like this:</p>
|
||||
<pre><code class="language-rust">let x = 5;
|
||||
let y = 10;
|
||||
|
||||
println!("x = {} and y = {}", x, y);
|
||||
</code></pre>
|
||||
<p>Which would print out "x = 5 and y = 10".</p>
|
||||
<p>This code would print out <code>x = 5 and y = 10</code>.</p>
|
||||
<h3>Testing the First Part</h3>
|
||||
<p>Back to our guessing game, let's test what we have so far. We can run it with
|
||||
<code>cargo run</code>:</p>
|
||||
<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-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/debug/guessing_game`
|
||||
@@ -299,38 +301,39 @@ Please input your guess.
|
||||
6
|
||||
You guessed: 6
|
||||
</code></pre>
|
||||
<p>All right! Our first part is done: we can get input from the keyboard and then
|
||||
print it back out.</p>
|
||||
<p>At this point, the first part of the game is done: we're getting input from the
|
||||
keyboard and then printing it.</p>
|
||||
<h2>Generating a Secret Number</h2>
|
||||
<p>Next, we need to generate a secret number that the user will try to guess. The
|
||||
secret number should be different every time so that the game is fun to play
|
||||
more than once, and we'd like to have a random number between 1 and 100 so the
|
||||
game isn’t too difficult. Rust does not yet include random number functionality
|
||||
in its standard library. The Rust team does, however, provide a <a href="https://crates.io/crates/rand"><code>rand</code>
|
||||
crate</a>.</p>
|
||||
secret number should be different every time so the game is fun to play more
|
||||
than once. Let’s use a random number between 1 and 100 so the game isn’t too
|
||||
difficult. Rust doesn’t yet include random number functionality in its standard
|
||||
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
|
||||
<h3>Using a Crate to Get More Functionality</h3>
|
||||
<p>Remember that <em>crate</em> is what we call a package of Rust code. The project we’ve
|
||||
been building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is
|
||||
a <em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||||
<p>Cargo's use of external crates is where it really shines. Before we can write
|
||||
the code using <code>rand</code>, we need to modify our <code>Cargo.toml</code> to include the <code>rand</code>
|
||||
crate as a dependency. Open it up, and add this line at the bottom beneath the
|
||||
<code>[dependencies]</code> section header that Cargo created for you:</p>
|
||||
<p>Remember that a <em>crate</em> is a package of Rust code. The project we’ve been
|
||||
building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is a
|
||||
<em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||||
<p>Cargo’s use of external crates is where it really shines. Before we can write
|
||||
code that uses <code>rand</code>, we need to modify the <code>Cargo.toml</code> file to include the
|
||||
<code>rand</code> crate as a dependency. Open that file now and add the following line to
|
||||
the bottom beneath the <code>[dependencies]</code> section header that Cargo created for
|
||||
you:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<pre><code class="language-toml">[dependencies]
|
||||
|
||||
rand = "0.3.14"
|
||||
</code></pre>
|
||||
<p>In the <code>Cargo.toml</code> file, everything that follows a header is part of a section
|
||||
that goes until another section starts. Cargo uses the <code>[dependencies]</code> section
|
||||
to know what external crates your project depends on and what versions of those
|
||||
crates you require. In this case, we’ve specified the <code>rand</code> crate with the
|
||||
semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
|
||||
Versioning</a><!-- ignore --> (sometimes called <em>semver</em>), which is a
|
||||
standard for writing version numbers. A bare number like above is actually
|
||||
shorthand for <code>^0.3.14</code>, which means "any version that has a public API
|
||||
compatible with version 0.3.14".</p>
|
||||
<p>Now, without changing any of our code, let’s build our project:</p>
|
||||
that continues until another section starts. The <code>[dependencies]</code> section is
|
||||
where you tell Cargo which external crates your project depends on and which
|
||||
versions of those crates you require. In this case, we’ll specify the <code>rand</code>
|
||||
crate with the semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
|
||||
Versioning</a><!-- ignore --> (sometimes called <em>SemVer</em>), which is a
|
||||
standard for writing version numbers. The number <code>0.3.14</code> is actually shorthand
|
||||
for <code>^0.3.14</code>, which means “any version that has a public API compatible with
|
||||
version <code>0.3.14</code>.”</p>
|
||||
<p>Now, without changing any of the code, let’s build the project, as shown in
|
||||
Listing 2-2:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||||
Downloading rand v0.3.14
|
||||
@@ -339,80 +342,86 @@ compatible with version 0.3.14".</p>
|
||||
Compiling rand v0.3.14
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-2: The output from running cargo build after adding the rand crate as
|
||||
a dependency
|
||||
</caption>
|
||||
<p>You may see different version numbers (but they will all be compatible with
|
||||
your code, thanks to semver!) and the lines may be in a different order.</p>
|
||||
<p>Lots of new output! Now that we have an external dependency, Cargo fetches the
|
||||
latest versions of everything from the <em>registry</em>, which is a copy of data from
|
||||
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem
|
||||
post their open source Rust projects for others to use.</p>
|
||||
<p>After updating the registry, Cargo checks our <code>[dependencies]</code> and downloads
|
||||
any we don’t have yet. In this case, while we only listed <code>rand</code> as a
|
||||
dependency, we’ve also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
|
||||
the code, thanks to SemVer!), and the lines may be in a different order.</p>
|
||||
<p>Now that we have an external dependency, Cargo fetches the latest versions of
|
||||
everything from the <em>registry</em>, which is a copy of data from
|
||||
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem post
|
||||
their open source Rust projects for others to use.</p>
|
||||
<p>After updating the registry, Cargo checks the <code>[dependencies]</code> section and
|
||||
downloads any you don’t have yet. In this case, although we only listed <code>rand</code>
|
||||
as a dependency, Cargo also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
|
||||
<code>libc</code> to work. After downloading them, Rust compiles them and then compiles
|
||||
our project with our dependencies available.</p>
|
||||
<p>If we immediately run <code>cargo build</code> again without making any changes, we won't
|
||||
get any output. Cargo knows it has already downloaded and compiled our
|
||||
dependencies, and we haven't changed anything about them in our <code>Cargo.toml</code>
|
||||
file. Cargo also knows that we haven't changed anything about our code, so it
|
||||
doesn't recompile that either. With nothing to do, it simply exits. If we open
|
||||
up <code>src/main.rs</code>, make a trivial change, then save it again, we’ll only see one
|
||||
line:</p>
|
||||
the project with the dependencies available.</p>
|
||||
<p>If you immediately run <code>cargo build</code> again without making any changes, you won’t
|
||||
get any output. Cargo knows it has already downloaded and compiled the
|
||||
dependencies, and you haven't changed anything about them in your <code>Cargo.toml</code>
|
||||
file. Cargo also knows that you haven't changed anything about your code, so it
|
||||
doesn't recompile that either. With nothing to do, it simply exits. If you open
|
||||
up the <code>src/main.rs</code> file, make a trivial change, then save it and build again,
|
||||
you’ll only see one line of output:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
</code></pre>
|
||||
<p>This just updates the build with your tiny change to the <code>main.rs</code> file. Our
|
||||
dependencies haven't changed, so Cargo knows it can reuse what it has already
|
||||
downloaded and compiled for those. It just rebuilds our part of the code.</p>
|
||||
<h4>The Cargo.lock File that Ensures Reproducible Builds</h4>
|
||||
<p>Cargo has a mechanism to make sure we can rebuild the exact same artifact every
|
||||
time we or anyone else builds our code: Cargo will only use the versions of the
|
||||
dependencies you specified until you say otherwise. For example, what happens
|
||||
if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out, containing an
|
||||
important bugfix, but that also contains a regression that will break our code?</p>
|
||||
<p>The answer to this problem is the <code>Cargo.lock</code> file created the first time we
|
||||
ran <code>cargo build</code> that is now in your project directory. When you build your
|
||||
project for the first time, Cargo figures out all of the versions of your
|
||||
dependencies that fit your criteria then writes them to the <code>Cargo.lock</code> file.
|
||||
When you build your project in the future, Cargo will see that the <code>Cargo.lock</code>
|
||||
file exists and use the versions specified there rather than doing all the work
|
||||
of figuring out versions again. This lets you have a reproducible build
|
||||
automatically. In other words, our project will stay at <code>0.3.14</code> until we
|
||||
explicitly upgrade, thanks to the lock file.</p>
|
||||
<p>This line shows Cargo only updates the build with your tiny change to the
|
||||
<code>src/main.rs</code> 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 Cargo.lock File Ensures Reproducible Builds</h4>
|
||||
<p>Cargo has a mechanism that ensures you can rebuild the same artifact every time
|
||||
you or anyone else builds your code: Cargo will use only the versions of the
|
||||
dependencies you specified until you indicate otherwise. For example, what
|
||||
happens if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out and
|
||||
contains an important bug fix but also contains a regression that will break
|
||||
your code?</p>
|
||||
<p>The answer to this problem is the <code>Cargo.lock</code> file, which was created the
|
||||
first time you ran <code>cargo build</code> and is now in your <code>guessing_game</code> directory.
|
||||
When you build a project for the first time, Cargo figures out all the
|
||||
versions of the dependencies that fit the criteria and then writes them to
|
||||
the <code>Cargo.lock</code> file. When you build your project in the future, Cargo will
|
||||
see that the <code>Cargo.lock</code> file exists and use the versions specified there
|
||||
rather than doing all the work of figuring out versions again. This lets you
|
||||
have a reproducible build automatically. In other words, your project will
|
||||
remain at <code>0.3.14</code> until you explicitly upgrade, thanks to the <code>Cargo.lock</code>
|
||||
file.</p>
|
||||
<h4>Updating a Crate to Get a New Version</h4>
|
||||
<p>When we <em>do</em> want to update a crate, Cargo has another command,
|
||||
<code>update</code>, which will:</p>
|
||||
<ul>
|
||||
<p>When you <em>do</em> want to update a crate, Cargo provides another command, <code>update</code>,
|
||||
which will:</p>
|
||||
<ol>
|
||||
<li>Ignore the <code>Cargo.lock</code> file and figure out all the latest versions that fit
|
||||
our specifications in <code>Cargo.toml</code>.</li>
|
||||
<li>If that works, write those versions out to the lock file.</li>
|
||||
</ul>
|
||||
your specifications in <code>Cargo.toml</code>.</li>
|
||||
<li>If that works, Cargo will write those versions to the <code>Cargo.lock</code> file.</li>
|
||||
</ol>
|
||||
<p>But by default, Cargo will only look for versions larger than <code>0.3.0</code> and
|
||||
smaller than <code>0.4.0</code>. If the <code>rand</code> crate has released two new versions,
|
||||
<code>0.3.15</code> and <code>0.4.0</code>, this is what we would see if we ran <code>cargo update</code>:</p>
|
||||
<code>0.3.15</code> and <code>0.4.0</code>, you would see the following if you ran <code>cargo update</code>:</p>
|
||||
<pre><code class="language-bash">$ cargo update
|
||||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||||
Updating rand v0.3.14 -> v0.3.15
|
||||
</code></pre>
|
||||
<p>At this point, you would also notice a change in your <code>Cargo.lock</code> file noting
|
||||
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</p>
|
||||
<p>If we wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
|
||||
series, we’d have to update what is in the <code>Cargo.toml</code> file to look like this
|
||||
instead:</p>
|
||||
<p>If you wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
|
||||
series, you’d have to update the <code>Cargo.toml</code> file to look like this instead:</p>
|
||||
<pre><code class="language-toml">[dependencies]
|
||||
|
||||
rand = "0.4.0"
|
||||
</code></pre>
|
||||
<p>The next time we <code>cargo build</code>, assuming that the <code>rand</code> crate version <code>0.4.0</code>
|
||||
has been released, Cargo will update the crates index and re-evaluate our
|
||||
<code>rand</code> requirements according to the new version we have specified.</p>
|
||||
<p>The next time you run <code>cargo build</code>, Cargo will update the registry of crates
|
||||
available and reevaluate your <code>rand</code> requirements according to the new version
|
||||
you specified.</p>
|
||||
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a><!-- ignore --> and <a href="http://doc.crates.io/crates-io.html">its
|
||||
ecosystem</a><!-- ignore --> that we will get into in Chapter XX, but
|
||||
for now, that’s all we need to know. Cargo makes it really easy to re-use
|
||||
libraries, so Rustaceans are able to write smaller projects which are assembled
|
||||
out of a number of sub-packages.</p>
|
||||
ecosystem</a><!-- ignore --> that Chapter XX will discuss, but for
|
||||
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
|
||||
so Rustaceans are able to write smaller projects that are assembled from a
|
||||
number of packages.</p>
|
||||
<h3>Generating a Random Number</h3>
|
||||
<p>Let’s get on to actually <em>using</em> <code>rand</code>. Our next step is to update our
|
||||
<code>main.rs</code> code as follows:</p>
|
||||
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <code>src/main.rs</code>, as shown
|
||||
in Listing 2-3:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -436,39 +445,33 @@ fn main() {
|
||||
println!("You guessed: {}", guess);
|
||||
}
|
||||
</code></pre>
|
||||
<p>First we've added a line to the top, <code>extern crate rand</code>, that lets Rust know
|
||||
we’ll be making use of that external dependency. This also does the equivalent
|
||||
of calling <code>use rand</code>, so we can now call anything in the <code>rand</code> crate by
|
||||
prefixing it with <code>rand::</code>.</p>
|
||||
<p>Next, we added another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
|
||||
<p>Listing 2-3: Code changes needed in order to generate a random number</p>
|
||||
<p>We're adding a <code>extern crate rand;</code> line to the top that lets Rust know we’ll be
|
||||
using that external dependency. This also does the equivalent of calling <code>use rand</code>, so now we can call anything in the <code>rand</code> crate by prefixing it with
|
||||
<code>rand::</code>.</p>
|
||||
<p>Next, we're adding another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
|
||||
defines methods that random number generators implement, and this trait must be
|
||||
in scope for us to use those methods. We'll cover traits in detail in the
|
||||
Traits section in Chapter XX.</p>
|
||||
<p>We also added two more lines in the middle:</p>
|
||||
<pre><code class="language-rust,ignore">let secret_number = rand::thread_rng().gen_range(1, 101);
|
||||
|
||||
println!("The secret number is: {}", secret_number);
|
||||
</code></pre>
|
||||
<p>The <code>rand::thread_rng</code> function will give us the particular random number
|
||||
generator that we're going to use: one that is local to our current thread of
|
||||
execution and seeded by the operating system. Next, we call the <code>gen_range</code>
|
||||
method on our random number generator. This method is defined by the <code>Rng</code>
|
||||
trait that we brought into scope with the <code>use rand::Rng</code> statement above. The
|
||||
<code>gen_range</code> method takes two numbers as arguments and generates a random
|
||||
number between them. It's inclusive on the lower bound but exclusive on the
|
||||
upper bound, so we need <code>1</code> and <code>101</code> to ask for a number ranging from one to a
|
||||
hundred.</p>
|
||||
<p>Knowing what traits to import and what functions and methods to use from a
|
||||
crate isn't something that you'll just <em>know</em>. Instructions for using a crate
|
||||
are in each crate's documentation. Another neat feature of Cargo is that you
|
||||
can run the <code>cargo doc --open</code> command to build documentation provided by all
|
||||
of your dependencies locally and then open it in your browser. If you're
|
||||
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> then click on "rand" in the sidebar on the left.</p>
|
||||
<p>The second line that we added to our code prints out the secret number. This is
|
||||
useful while we’re developing our program to let us easily test it out, but
|
||||
we’ll be deleting it for the final version. It’s not much of a game if it
|
||||
prints out the answer when you start it up!</p>
|
||||
<p>Try running our new program a few times:</p>
|
||||
in scope for us to use those methods. Chapter 10 will cover traits in detail.</p>
|
||||
<p>Also, we're adding two more lines in the middle. The <code>rand::thread_rng</code> function
|
||||
will give us the particular random number generator that we’re going to use:
|
||||
one that is local to the current thread of execution and seeded by the
|
||||
operating system. Next, we call the <code>gen_range</code> method on the random number
|
||||
generator. This method is defined by the <code>Rng</code> trait that we brought into
|
||||
scope with the <code>use rand::Rng</code> statement. The <code>gen_range</code> method takes two
|
||||
numbers as arguments and generates a random number between them. It’s inclusive
|
||||
on the lower bound but exclusive on the upper bound, so we need to specify <code>1</code>
|
||||
and <code>101</code> to request a number between 1 and 100.</p>
|
||||
<p>Knowing which traits to import and which functions and methods to use from a
|
||||
crate isn’t something that you’ll just <em>know</em>. Instructions for using a crate
|
||||
are in each crate’s documentation. Another neat feature of Cargo is that you
|
||||
can run the <code>cargo doc --open</code> command that will build documentation provided
|
||||
by all of your dependencies locally and open it in your browser. If you’re
|
||||
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> and click <code>rand</code> in the sidebar on the left.</p>
|
||||
<p>The second line that we added to the code prints the secret number. This is
|
||||
useful while we’re developing the program to be able to test it, but we’ll
|
||||
delete it from the final version. It’s not much of a game if the program prints
|
||||
the answer as soon as it starts!</p>
|
||||
<p>Try running the program a few times:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/debug/guessing_game`
|
||||
@@ -487,9 +490,9 @@ You guessed: 5
|
||||
</code></pre>
|
||||
<p>You should get different random numbers, and they should all be numbers between
|
||||
1 and 100. Great job!</p>
|
||||
<h2>Comparing Our Guesses</h2>
|
||||
<p>Now that we’ve got user input, let’s compare our guess to the secret number.
|
||||
Here’s that part of our next step:</p>
|
||||
<h2>Comparing the Guess to the Secret Number</h2>
|
||||
<p>Now that we have user input and a random number, we can compare them. That
|
||||
step is shown in Listing 2-4:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -520,8 +523,9 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>There are a few new bits here. The first is another <code>use</code>, bringing a type
|
||||
called <code>std::cmp::Ordering</code> into scope from the standard crate. <code>Ordering</code> is
|
||||
<p>Listing 2-4: Handling the possible return values of comparing two numbers</p>
|
||||
<p>The first new bit here is another <code>use</code>, bringing a type called
|
||||
<code>std::cmp::Ordering</code> into scope from the standard library. <code>Ordering</code> is
|
||||
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
|
||||
<code>Greater</code>, and <code>Equal</code>. These are the three outcomes that are possible when you
|
||||
compare two values.</p>
|
||||
@@ -532,56 +536,59 @@ compare two values.</p>
|
||||
Ordering::Equal => println!("You win!"),
|
||||
}
|
||||
</code></pre>
|
||||
<p>The <code>cmp</code> method compares two values, and can be called on anything that can
|
||||
be compared. It takes a reference to whatever you want to compare with, so here
|
||||
it's comparing our <code>guess</code> to our <code>secret_number</code>. <code>cmp</code> returns a variant of
|
||||
the <code>Ordering</code> enum we imported with the <code>use</code> statement earlier. We use a
|
||||
<a href="match.html"><code>match</code></a><!-- ignore --> statement to decide what to do next based on
|
||||
which variant of <code>Ordering</code> we got back from our call to <code>cmp</code> with the values
|
||||
<p>The <code>cmp</code> method compares two values and can be called on anything that can be
|
||||
compared. It takes a reference to whatever you want to compare with: here it’s
|
||||
comparing the <code>guess</code> to the <code>secret_number</code>. <code>cmp</code> returns a variant of the
|
||||
<code>Ordering</code> enum we imported with the <code>use</code> statement. We use a
|
||||
<a href="ch06-02-match.html"><code>match</code></a><!-- ignore --> expression to decide what to do next based on
|
||||
which variant of <code>Ordering</code> was returned from the call to <code>cmp</code> with the values
|
||||
in <code>guess</code> and <code>secret_number</code>.</p>
|
||||
<p><code>match</code> statements are made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
|
||||
the code that we should run if the value given to the beginning of the <code>match</code>
|
||||
statement fits that arm's pattern. Rust takes the value given to <code>match</code> and
|
||||
looks through each arm's pattern in turn. The <code>match</code> construct and patterns
|
||||
are powerful features in Rust that will be covered in detail in Chapter XX and
|
||||
Chapter XX, respectively.</p>
|
||||
<p>Let's walk through an example of what would happen with our <code>match</code>. Say that
|
||||
the user has guessed 50, and the randomly-generated secret number this time
|
||||
is 38. So when we compare 50 to 38, the <code>cmp</code> method will return
|
||||
<code>Ordering::Greater</code>, since 50 is greater than 38. <code>Ordering::Greater</code> is the
|
||||
value that the <code>match</code> statement gets. It looks at the first arm's pattern,
|
||||
<code>Ordering::Less</code>, and says nope, the value we have (<code>Ordering::Greater</code>) does
|
||||
not match <code>Ordering::Less</code>. So it ignores the code in that arm and moves on to
|
||||
the next arm. The next arm's pattern, <code>Ordering::Greater</code>, <strong>does</strong> match
|
||||
<code>Ordering::Greater</code>! The associated code in that arm will get executed, which
|
||||
prints "Too big!" to the screen. Then we're done with the <code>match</code> statement; we
|
||||
don't look at the last arm at all in this particular scenario.</p>
|
||||
<p>However, this code won’t quite compile yet. Let’s try it:</p>
|
||||
<p>A <code>match</code> expression is made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
|
||||
the code that should be run if the value given to the beginning of the <code>match</code>
|
||||
expression fits that arm’s pattern. Rust takes the value given to <code>match</code> and
|
||||
looks through each arm’s pattern in turn. The <code>match</code> construct and patterns
|
||||
are powerful features in Rust that let you express a variety of situations your
|
||||
code might encounter and helps ensure that you handle them all. These features
|
||||
will be covered in detail in Chapter 6 and Chapter XX, respectively.</p>
|
||||
<p>Let’s walk through an example of what would happen with the <code>match</code> expression
|
||||
used here. Say that the user has guessed 50, and the randomly generated secret
|
||||
number this time is 38. When the code compares 50 to 38, the <code>cmp</code> method will
|
||||
return <code>Ordering::Greater</code>, because 50 is greater than 38. <code>Ordering::Greater</code>
|
||||
is the value that the <code>match</code> expression gets. It looks at the first arm’s
|
||||
pattern, <code>Ordering::Less</code>, but the value <code>Ordering::Greater</code> does not match
|
||||
<code>Ordering::Les</code>s. So it ignores the code in that arm and moves to the next arm.
|
||||
The next arm’s pattern, <code>Ordering::Greater</code>, <strong>does</strong> match
|
||||
<code>Ordering::Greater</code>! The associated code in that arm will execute and print
|
||||
<code>Too big!</code> to the screen. The <code>match</code> expression ends because it has no need to
|
||||
look at the last arm in this particular scenario.</p>
|
||||
<p>However, the code in Listing 2-4 won’t compile yet. Let’s try it:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
src/main.rs:23:21: 23:35 error: mismatched types [E0308]
|
||||
src/main.rs:23 match guess.cmp(&secret_number) {
|
||||
^~~~~~~~~~~~~~
|
||||
src/main.rs:23:21: 23:35 help: run `rustc --explain E0308` to see a detailed explanation
|
||||
src/main.rs:23:21: 23:35 note: expected type `&std::string::String`
|
||||
src/main.rs:23:21: 23:35 note: found type `&_`
|
||||
error[E0308]: mismatched types
|
||||
--> src/main.rs:23:21
|
||||
|
|
||||
23 | match guess.cmp(&secret_number) {
|
||||
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integral variable
|
||||
|
|
||||
= note: expected type `&std::string::String`
|
||||
= note: found type `&{integer}`
|
||||
|
||||
error: aborting due to previous error
|
||||
Could not compile `guessing_game`.
|
||||
</code></pre>
|
||||
<p>Whew! This is a big error. The core of the error says that we have <em>mismatched
|
||||
types</em>. Rust has a strong, static type system. However, it also has type
|
||||
inference. When we wrote <code>let guess = String::new()</code>, Rust was able to infer
|
||||
that <code>guess</code> should be a <code>String</code> and didn’t make us write the type out. Our
|
||||
<code>secret_number</code> on the other hand is a number type. There are a few number
|
||||
types which can have a value between one and a hundred: <code>i32</code>, a thirty-two-bit
|
||||
number; <code>u32</code>, an unsigned thirty-two-bit number; <code>i64</code>, a sixty-four-bit
|
||||
number; or others. Rust defaults to an <code>i32</code>, so that's the type of
|
||||
<p>The core of the error states that there are <em>mismatched types</em>. Rust has a
|
||||
strong, static type system. However, it also has type inference. When we wrote
|
||||
<code>let guess = String::new()</code>, Rust was able to infer that <code>guess</code> should be a
|
||||
<code>String</code> and didn’t make us write the type. The <code>secret_number</code>, on the other
|
||||
hand, is a number type. A few number types can have a value between 1 and 100:
|
||||
<code>i32</code>, a 32-bit number; <code>u32</code>, an unsigned 32-bit number; <code>i64</code>, a 64-bit
|
||||
number; as well as others. Rust defaults to an <code>i32</code>, which is the type of
|
||||
<code>secret_number</code> unless we add type information elsewhere that would cause Rust
|
||||
to infer a different numerical type. The error is because Rust will not compare
|
||||
a string and a number type.</p>
|
||||
<p>Ultimately, we want to convert the <code>String</code> we read as input into a real number
|
||||
type so that we can compare it to the guess numerically. We can do that with
|
||||
two more lines; to your <code>main</code> function body, add the following two lines:</p>
|
||||
to infer a different numerical type. The reason for the error is that Rust will
|
||||
not compare a string and a number type.</p>
|
||||
<p>Ultimately, we want to convert the <code>String</code> the program reads as input into a
|
||||
real number type so we can compare it to the guess numerically. We can do
|
||||
that by adding the following two lines to the <code>main</code> function body:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -619,43 +626,43 @@ fn main() {
|
||||
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
|
||||
.expect("Please type a number!");
|
||||
</code></pre>
|
||||
<p>We create a variable <code>guess</code>. But wait a minute, don't we already have
|
||||
a variable named <code>guess</code>? We do, but Rust allows us to <em>shadow</em> the
|
||||
previous value of <code>guess</code> with a new one. This is often used in this exact
|
||||
situation, where we want to convert a value from one type into another type.
|
||||
Shadowing lets us re-use the <code>guess</code> variable name rather than forcing us to
|
||||
come up with two unique variables, like <code>guess_str</code> and <code>guess</code> or something
|
||||
(we'll cover shadowing in more detail in Chapter 3).</p>
|
||||
<p>We bind the second <code>guess</code> variable (a number of type <code>u32</code>) to the result
|
||||
of calling <code>.trim().parse()</code> on the first <code>guess</code> variable (a <code>String</code>).
|
||||
The <code>trim</code> method on <code>String</code>s will eliminate any whitespace at the
|
||||
beginning and end. Our <code>u32</code> can only contain numerical characters, but we have
|
||||
to press the return key to satisfy <code>read_line</code>. When we press the return
|
||||
key, it introduces a newline character. For example, if we type <code>5</code> and hit
|
||||
return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents "newline", the
|
||||
return key. The <code>trim</code> method gets rid of this, leaving our string with only
|
||||
the <code>5</code>.</p>
|
||||
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into
|
||||
some kind of number. Since this method can parse a variety of number types, we
|
||||
need to tell Rust the exact type of number we want with <code>let guess: u32</code>. The
|
||||
colon (<code>:</code>) after <code>guess</code> tells Rust we’re going to annotate its type. Rust has
|
||||
a few built-in number types, but we’ve chosen <code>u32</code>, an unsigned, thirty-two
|
||||
bit integer. It’s a good default choice for a small positive number. You'll see
|
||||
the other number types in Chapter XX. Additionally, our <code>u32</code> annotation here
|
||||
and the comparison with <code>secret_number</code> means that Rust will infer that
|
||||
<code>secret_number</code> should be a <code>u32</code> as well. So now the comparison will be
|
||||
between two values of the same type!</p>
|
||||
<p>Our call to <code>parse</code> could quite easily cause an error. If, for example, our
|
||||
string contained <code>A👍%</code>, there’d be no way to convert that to a number. Because
|
||||
it might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
|
||||
<code>read_line</code> method does that we discussed earlier. We're going to treat this
|
||||
<code>Result</code> the same way by using the <code>expect</code> method again. If <code>parse</code>
|
||||
returns an <code>Err</code> <code>Result</code> variant because it could not create a number from the
|
||||
string, the <code>expect</code> call will crash the game and print the message we give
|
||||
it. If <code>parse</code> can successfully turn the string into a number, it will return
|
||||
the <code>Ok</code> variant of <code>Result</code>, and <code>expect</code> will return the number that we
|
||||
want that it will take out of the <code>Ok</code> value for us.</p>
|
||||
<p>Let’s try our program out!</p>
|
||||
<p>We create a variable named <code>guess</code>. But wait, doesn’t the program
|
||||
already have a variable named <code>guess</code>? It does, but Rust allows us to
|
||||
<em>shadow</em> the previous value of <code>guess</code> with a new one. This feature is often
|
||||
used in similar situations in which you want to convert a value from one type
|
||||
to another type. Shadowing lets us reuse the <code>guess</code> variable name rather than
|
||||
forcing us to create two unique variables, like <code>guess_str</code> and <code>guess</code> for
|
||||
example. (Chapter 3 covers shadowing in more detail.)</p>
|
||||
<p>We bind <code>guess</code> to the expression <code>guess.trim().parse()</code>. The <code>guess</code> in the
|
||||
expression refers to the original <code>guess</code> that was a <code>String</code> with the input in
|
||||
it. The <code>trim</code> method on a <code>String</code> instance will eliminate any whitespace at
|
||||
the beginning and end. <code>u32</code> can only contain numerical characters, but the
|
||||
user must press the Return key to satisfy <code>read_line</code>. When the user presses
|
||||
Return, a newline character is added to the string. For example, if the user
|
||||
types 5 and presses return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents
|
||||
“newline,” the return key. The <code>trim</code> method eliminates <code>\n</code>, resulting in just
|
||||
<code>5</code>.</p>
|
||||
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into some
|
||||
kind of number. Because this method can parse a variety of number types, we
|
||||
need to tell Rust the exact number type we want by using <code>let guess: u32</code>. The
|
||||
colon (<code>:</code>) after <code>guess</code> tells Rust we’ll annotate the variable’s type. Rust
|
||||
has a few built-in number types; the <code>u32</code> seen here is an unsigned, 32-bit
|
||||
integer. It’s a good default choice for a small positive number. You’ll learn
|
||||
about other number types in Chapter 3. Additionally, the <code>u32</code> annotation in
|
||||
this example program and the comparison with <code>secret_number</code> means that Rust
|
||||
will infer that <code>secret_number</code> should be a <code>u32</code> as well. So now the
|
||||
comparison will be between two values of the same type!</p>
|
||||
<p>The call to <code>parse</code> could easily cause an error. If, for example, the string
|
||||
contained <code>A👍%</code>, there would be no way to convert that to a number. Because it
|
||||
might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
|
||||
<code>read_line</code> method does as discussed earlier in “Handling Potential Failure
|
||||
with the Result Type” on page XX. We’ll treat this <code>Result</code> the same way by
|
||||
using the <code>expect</code> method again. If <code>parse</code> returns an <code>Err</code> <code>Result</code> variant
|
||||
because it couldn’t create a number from the string, the <code>expect</code> call will
|
||||
crash the game and print the message we give it. If <code>parse</code> can successfully
|
||||
convert the string to a number, it will return the <code>Ok</code> variant of <code>Result</code>,
|
||||
and <code>expect</code> will return the number that we want from the <code>Ok</code> value.</p>
|
||||
<p>Let’s run the program now!</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/guessing_game`
|
||||
@@ -666,14 +673,14 @@ Please input your guess.
|
||||
You guessed: 76
|
||||
Too big!
|
||||
</code></pre>
|
||||
<p>Nice! You can see we even added spaces before our guess, and it still figured
|
||||
out that we guessed 76. Run the program a few times to verify the different
|
||||
behavior with different kinds of input: guess the number correctly, guess a
|
||||
number that is too high, and guess a number that is too low.</p>
|
||||
<p>Now we’ve got most of the game working, but we can only make one guess. Let’s
|
||||
change that by adding a loop!</p>
|
||||
<p>Nice! Even though spaces were added before the guess, the program still figured
|
||||
out that the user guessed 76. Run the program a few times to verify the
|
||||
different behavior with different kinds of input: guess the number correctly,
|
||||
guess a number that is too high, and guess a number that is too low.</p>
|
||||
<p>We have most of the game working now, but the user can make only one guess.
|
||||
Let’s change that by adding a loop!</p>
|
||||
<h2>Allowing Multiple Guesses with Looping</h2>
|
||||
<p>The <code>loop</code> keyword gives us an infinite loop. We'll add that in to give us more
|
||||
<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>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
@@ -710,14 +717,16 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>As you can see, we've moved everything from the guess input onwards into a
|
||||
loop. Make sure to indent those lines another four spaces each, and try it out.
|
||||
You'll notice we have a new problem because the program is doing exactly what we
|
||||
told it to do: ask for another guess forever! It doesn't seem like we can quit!</p>
|
||||
<p>We could always halt the program by using the keyboard shortcut <code>control-c</code>.
|
||||
There's another way to escape the insatiable monster we've created, though,
|
||||
that can be found in our discussion about <code>parse</code>: if we give a non-number
|
||||
answer, the program will crash. We can use that to quit! Observe:</p>
|
||||
<p>As you can see, we've moved everything into a loop from the guess input prompt
|
||||
onward. Be sure to indent those lines another four spaces each, and run the
|
||||
program again. Notice that there is a new problem because the program is doing
|
||||
exactly what we told it to do: ask for another guess forever! It doesn’t seem
|
||||
like the user can quit!</p>
|
||||
<p>The user could always halt the program by using the keyboard shortcut <code>Ctrl-C</code>.
|
||||
But there’s another way to escape this insatiable monster that we mentioned in
|
||||
the <code>parse</code> discussion in “Comparing the Guesses” on page XX: if the user
|
||||
enters a non-number answer, the program will crash. The user can take advantage
|
||||
of that in order to quit, as shown here:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/guessing_game`
|
||||
@@ -741,11 +750,11 @@ thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidD
|
||||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||||
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
|
||||
</code></pre>
|
||||
<p>This method means that typing <code>quit</code> actually quits the game, but so does any
|
||||
other non-number input. This is suboptimal, to say the least. We want the game
|
||||
to automatically stop when the correct number is guessed.</p>
|
||||
<h4>Quitting When you Win</h4>
|
||||
<p>Let’s program the game to quit when you win by adding a <code>break</code> in that case:</p>
|
||||
<p>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>
|
||||
<h4>Quitting After a Correct Guess</h4>
|
||||
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -784,38 +793,40 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>By adding the <code>break</code> line after <code>You win!</code>, we’ll exit the loop when we guess
|
||||
the secret number correctly. Exiting the loop also means exiting the program,
|
||||
since the loop is the last thing in <code>main</code>.</p>
|
||||
<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>
|
||||
<h4>Handling Invalid Input</h4>
|
||||
<p>For our final refinement of the game's behavior, rather than crashing the
|
||||
program when someone inputs a non-number, we want the game to ignore it so we
|
||||
can continue guessing. We can do that by altering the line where we convert
|
||||
<code>guess</code> from a <code>String</code> to a <code>u32</code>:</p>
|
||||
<p>To further refine the game’s behavior, rather than crashing the program when
|
||||
the user inputs a non-number, let’s make the game ignore a non-number so the
|
||||
user can continue guessing. We can do that by altering the line where <code>guess</code> is
|
||||
converted from a <code>String</code> to a <code>u32</code>:</p>
|
||||
<pre><code class="language-rust,ignore">let guess: u32 = match guess.trim().parse() {
|
||||
Ok(num) => num,
|
||||
Err(_) => continue,
|
||||
};
|
||||
</code></pre>
|
||||
<p>This is how you generally move from "crash on error" to "actually handle the
|
||||
error": by switching from an <code>expect</code> statement to a <code>match</code> statement.
|
||||
Remember that <code>parse</code> returns a <code>Result</code> type, and <code>Result</code> is an enum that
|
||||
has the variants <code>Ok</code> or <code>Err</code>. We're going to use a <code>match</code> statement here,
|
||||
like we did with the <code>Ordering</code> result of the <code>cmp</code> method.</p>
|
||||
<p>If <code>parse</code> is able to successfully turn the string into a number, it will
|
||||
return an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will
|
||||
match the first arm's pattern, and the match statement will just return the
|
||||
<code>num</code> value that <code>parse</code> produced and put inside the <code>Ok</code> value. That number
|
||||
will end up right where we want it, in the new <code>guess</code> variable we're creating.</p>
|
||||
<p>If <code>parse</code> is <em>not</em> able to turn the string into a number, it will return an
|
||||
<p>Switching from an <code>expect</code> call to a <code>match</code> expression is how you generally
|
||||
move from crash on error to actually handling the error. Remember that <code>parse</code>
|
||||
returns a <code>Result</code> type, and <code>Result</code> is an enum that has the variants <code>Ok</code> or
|
||||
<code>Err</code>. We're using a <code>match</code> expression here, like we did with the <code>Ordering</code>
|
||||
result of the <code>cmp</code> method.</p>
|
||||
<p>If <code>parse</code> is able to successfully turn the string into a number, it will return
|
||||
an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will match the
|
||||
first arm’s pattern, and the <code>match</code> expression will just return the <code>num</code> value
|
||||
that <code>parse</code> produced and put inside the <code>Ok</code> value. That number will end up
|
||||
right where we want it in the new <code>guess</code> variable we’re creating.</p>
|
||||
<p>If <code>parse</code> is not able to turn the string into a number, it will return an
|
||||
<code>Err</code> value that contains more information about the error. The <code>Err</code> value
|
||||
does not match the <code>Ok(num)</code> pattern in the first match arm, but it does match
|
||||
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catch-all value; we're
|
||||
saying we want to match all <code>Err</code> values, no matter what information they have
|
||||
inside them. So we execute the second arm's code, <code>continue</code>: this means to go
|
||||
to the next iteration of the <code>loop</code> and ask for another guess. So we have
|
||||
effectively ignored all errors that <code>parse</code> might hit!</p>
|
||||
<p>Now everything in our program should work as we expect it to! Let’s try it:</p>
|
||||
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catchall value; in this
|
||||
example, we’re saying we want to match all <code>Err</code> values, no matter what
|
||||
information they have inside them. So the program will execute the second arm’s
|
||||
code, <code>continue</code>, which means to go to the next iteration of the loop and ask
|
||||
for another guess. So effectively, the program ignores all errors that <code>parse</code>
|
||||
might encounter!</p>
|
||||
<p>Now everything in the program should work as expected. Let’s try it by running
|
||||
<code>cargo run</code>:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/guessing_game`
|
||||
@@ -836,10 +847,10 @@ Please input your guess.
|
||||
You guessed: 61
|
||||
You win!
|
||||
</code></pre>
|
||||
<p>Awesome! With one tiny last tweak, we can finish the guessing game: we're still
|
||||
printing out the secret number. That was good for testing, but it kind of ruins
|
||||
the game. Let's delete the <code>println!</code> that outputs the secret number. Here’s our
|
||||
full, final code:</p>
|
||||
<p>Awesome! With one tiny final tweak, we will finish the guessing game: recall
|
||||
that the program is still printing out the secret number. That worked well for
|
||||
testing, but it ruins the game. Let’s delete the <code>println!</code> that outputs the
|
||||
secret number. Listing 2-5 shows the final code:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -865,6 +876,8 @@ fn main() {
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
println!("You guessed: {}", guess);
|
||||
|
||||
match guess.cmp(&secret_number) {
|
||||
Ordering::Less => println!("Too small!"),
|
||||
Ordering::Greater => println!("Too big!"),
|
||||
@@ -876,16 +889,17 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<h2>Complete!</h2>
|
||||
<p>At this point, you have successfully built the Guessing Game! Congratulations!</p>
|
||||
<p>This project was a hands-on way to introduce you to a lot of new Rust concepts:
|
||||
<p>Listing 2-5: Complete code of the guessing game</p>
|
||||
<h2>Summary</h2>
|
||||
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
|
||||
<p>This project was a hands-on way to introduce you to many new Rust concepts:
|
||||
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
|
||||
In the next few chapters, we will go through these concepts in more detail.
|
||||
Chapter 3 covers concepts that most programming languages have, like variables,
|
||||
data types, and functions, and shows how to use them in Rust. Chapter 4 gets
|
||||
into ownership, which is the feature of Rust that is most different from other
|
||||
languages. Chapter 5 discusses structs and method syntax, and Chapter 6
|
||||
endeavors to explain enums.</p>
|
||||
In the next few chapters, you’ll learn about these concepts in more detail.
|
||||
Chapter 3 covers concepts that most programming languages have, such as
|
||||
variables, data types, and functions, and shows how to use them in Rust.
|
||||
Chapter 4 explores ownership, which is a Rust feature that is most different
|
||||
from other languages. Chapter 5 discusses structs and method syntax, and
|
||||
Chapter 6 endeavors to explain enums.</p>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
+394
-380
@@ -442,25 +442,29 @@ $ cargo build
|
||||
<a href="http://doc.crates.io/guide.html">Cargo guide</a>, which covers all of its features.</p>
|
||||
</blockquote>
|
||||
<h1>Guessing Game</h1>
|
||||
<p>Let's jump into Rust with a hands-on project! This chapter will introduce you to
|
||||
a few common Rust concepts by showing how you would use them in a real program.
|
||||
You'll learn about <code>let</code>, <code>match</code>, methods, associated functions, using
|
||||
external crates, and more! Following chapters will explore these ideas in more
|
||||
detail; this chapter will get you practicing the fundamentals.</p>
|
||||
<p>We’re going to implement a classic beginner programming problem: the guessing
|
||||
game. Here’s how it works: Our program will generate a random integer between
|
||||
one and a hundred. It will then prompt us to enter a guess. Upon entering our
|
||||
guess, it will tell us if we’re too low or too high. Once we guess correctly,
|
||||
it will congratulate us.</p>
|
||||
<p>Let’s jump into Rust by working through a hands-on project together! This
|
||||
chapter introduces you to a few common Rust concepts by showing you how to use
|
||||
them in a real program. You’ll learn about <code>let</code>, <code>match</code>, methods, associated
|
||||
functions, using external crates, and more! The following chapters will explore
|
||||
these ideas in more detail. In this chapter, you’ll practice the fundamentals.</p>
|
||||
<p>We’ll implement a classic beginner programming problem: a guessing game.
|
||||
Here’s how it works: the program will generate a random integer between 1 and</p>
|
||||
<ol start="100">
|
||||
<li>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.</li>
|
||||
</ol>
|
||||
<h2>Setting Up a New Project</h2>
|
||||
<p>Let’s set up a new project. Go to your projects directory from the previous
|
||||
chapter, and create a new project using Cargo, like so:</p>
|
||||
<p>To set up a new project, go to the projects directory that you created in
|
||||
Chapter 1, and make a new project using Cargo, like so:</p>
|
||||
<pre><code class="language-bash">$ cargo new guessing_game --bin
|
||||
$ cd guessing_game
|
||||
</code></pre>
|
||||
<p>We pass the name of our project to <code>cargo new</code> and pass the <code>--bin</code> flag, since
|
||||
we’re going to be making another binary like in Chapter 1.</p>
|
||||
<p>Take a look at the generated <code>Cargo.toml</code>:</p>
|
||||
<p>The first command, <code>cargo new</code>, takes the name of the project (<code>guessing_game</code>)
|
||||
as the first argument. The <code>--bin</code> flag tells Cargo to make a binary project,
|
||||
similar to the one in Chapter 1. The second command changes to the new
|
||||
project's directory.</p>
|
||||
<p>Look at the generated <code>Cargo.toml</code> file:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<pre><code class="language-toml">[package]
|
||||
name = "guessing_game"
|
||||
@@ -469,32 +473,30 @@ authors = ["Your Name <you@example.com>"]
|
||||
|
||||
[dependencies]
|
||||
</code></pre>
|
||||
<p>If the author information that Cargo got from your environment is not correct,
|
||||
go ahead and fix that in the file and save it again.</p>
|
||||
<p>As we saw in the last chapter, cargo new generates a “Hello, world!” program
|
||||
for us. Check out src/main.rs:</p>
|
||||
<p>If the author information that Cargo obtained from your environment is not
|
||||
correct, fix that in the file and save it again.</p>
|
||||
<p>As you saw in Chapter 1, <code>cargo new</code> generates a “Hello, world!” program for
|
||||
you. Check out the <code>src/main.rs</code> file:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
</code></pre>
|
||||
<p>Let’s try compiling what Cargo gave us and running it in the same step, using
|
||||
the <code>cargo run</code> command:</p>
|
||||
<p>Now let’s compile this "Hello, world!" program and run it in the same step
|
||||
using the <code>cargo run</code> command:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/debug/guessing_game`
|
||||
Hello, world!
|
||||
</code></pre>
|
||||
<p>Great! The <code>run</code> command comes in handy when you need to rapidly iterate on a
|
||||
project. Our game is such a project: we want to quickly test each
|
||||
iteration before moving on to the next one.</p>
|
||||
<p>Now open up your <code>src/main.rs</code> again. We’ll be writing all of our code in this
|
||||
file.</p>
|
||||
<p>The <code>run</code> command comes in handy when you need to rapidly iterate on a project,
|
||||
and this game is such a project: we want to quickly test each iteration
|
||||
before moving on to the next one.</p>
|
||||
<p>Reopen the <code>src/main.rs</code> file. You’ll be writing all the code in this file.</p>
|
||||
<h2>Processing a Guess</h2>
|
||||
<p>Let’s get to it! We'll split the development of this game up into parts. This
|
||||
first part will ask for input from a user and process the input, checking that
|
||||
the input is in the form we expect. First we need to allow our player to input
|
||||
a guess. Enter this in your <code>src/main.rs</code>:</p>
|
||||
<p>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 <code>src/main.rs</code>.</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">use std::io;
|
||||
|
||||
@@ -511,129 +513,130 @@ fn main() {
|
||||
println!("You guessed: {}", guess);
|
||||
}
|
||||
</code></pre>
|
||||
<p>There’s a lot here! Let’s go over it, bit by bit.</p>
|
||||
<caption>
|
||||
Listing 2-1: Code to get a guess from the user and print it out
|
||||
</caption>
|
||||
<p>This code contains a lot of information, so let’s go over it bit by bit. To
|
||||
obtain user input and then print the result as output, we need to import the
|
||||
<code>io</code> (input/output) library from the standard library (which is known as <code>std</code>):</p>
|
||||
<pre><code class="language-rust,ignore">use std::io;
|
||||
</code></pre>
|
||||
<p>We’ll need to take user input and then print the result as output, and for that
|
||||
functionality we need to import the <code>io</code> (input/output) library from the
|
||||
standard library (which is known as <code>std</code>).</p>
|
||||
<p>By default, Rust only imports a few things into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
|
||||
<em>prelude</em></a><!-- ignore -->. If it’s not in the prelude, you’ll have to
|
||||
import it into your program explicitly with a <code>use</code> statement. Using the
|
||||
<code>std::io</code> library gets you a number of useful <code>io</code>-related things, including
|
||||
the functionality to accept user input.</p>
|
||||
<p>By default, Rust imports only a few types into every program in <a href="https://doc.rust-lang.org/std/prelude/">the
|
||||
<em>prelude</em></a><!-- ignore -->. If a type you want to use isn’t in the
|
||||
prelude, you have to import that type into your program explicitly with a <code>use</code>
|
||||
statement. Using the <code>std::io</code> library provides you with a number of useful
|
||||
<code>io</code>-related features, including the functionality to accept user input.</p>
|
||||
<p>As you saw in Chapter 1, the <code>main</code> function is the entry point into the
|
||||
program:</p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
</code></pre>
|
||||
<p>As you’ve seen in Chapter 1, the <code>main</code> function is the entry point into the
|
||||
program. The <code>fn</code> syntax declares a new function, the <code>()</code>s indicate that
|
||||
there are no arguments, and <code>{</code> starts the body of the function.</p>
|
||||
<p>The <code>fn</code> syntax declares a new function, the <code>()</code> indicate there are no
|
||||
arguments, and <code>{</code> starts the body of the function.</p>
|
||||
<p>As you also learned in Chapter 1, <code>println!</code> is a macro that prints a string to
|
||||
the screen:</p>
|
||||
<pre><code class="language-rust,ignore">println!("Guess the number!");
|
||||
|
||||
println!("Please input your guess.");
|
||||
</code></pre>
|
||||
<p>As we learned in Chapter 1, <code>println!</code> is a macro that prints a string to the
|
||||
screen. This is just a prompt stating what the game is and requesting input from
|
||||
the user.</p>
|
||||
<p>This code is just printing a prompt stating what the game is and requesting
|
||||
input from the user.</p>
|
||||
<h3>Storing Values with Variables</h3>
|
||||
<p>Next we need to store the user input.</p>
|
||||
<p>Next, we'll create a place to store the user input, like this:</p>
|
||||
<pre><code class="language-rust,ignore">let mut guess = String::new();
|
||||
</code></pre>
|
||||
<p>Now we’re getting interesting! There’s a lot going on in this little line.
|
||||
The first thing to notice is that this is a <code>let</code> statement, which is
|
||||
used to create <em>variables</em>. Here's another example:</p>
|
||||
<p>Now the program is getting interesting! There’s a lot going on in this little
|
||||
line. Notice that this is a <code>let</code> statement, which is used to create
|
||||
<em>variables</em>. Here’s another example:</p>
|
||||
<pre><code class="language-rust,ignore">let foo = bar;
|
||||
</code></pre>
|
||||
<p>This will create a new variable named <code>foo</code>, and bind this name to the value
|
||||
<code>bar</code>. In Rust, variables are immutable by default. To make a variable mutable,
|
||||
use <code>mut</code> before the variable name:</p>
|
||||
<pre><code class="language-rust">let foo = 5; // immutable.
|
||||
<p>This line will create a new variable named <code>foo</code> and bind it to the value
|
||||
<code>bar</code>. In Rust, variables are immutable by default. The following example shows
|
||||
how to use <code>mut</code> before the variable name to make a variable mutable:</p>
|
||||
<pre><code class="language-rust">let foo = 5; // immutable
|
||||
let mut bar = 5; // mutable
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>Note: The <code>//</code> syntax will start a comment that continues until the end of the
|
||||
<p>Note: The <code>//</code> syntax starts a comment that continues until the end of the
|
||||
line. Rust ignores everything in comments.</p>
|
||||
</blockquote>
|
||||
<p>So now we know that <code>let mut guess</code> will introduce a mutable variable named
|
||||
<code>guess</code>, but we have to look at the other side of the <code>=</code> for the value it’s
|
||||
bound to: <code>String::new</code>. <code>String</code> is a string type, provided by the standard
|
||||
library. A <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a growable, UTF-8 encoded bit
|
||||
of text.</p>
|
||||
<p>Now you know that <code>let mut guess</code> will introduce a mutable variable named
|
||||
<code>guess</code>. On the other side of the equal sign (<code>=</code>) is the value that <code>guess</code> is
|
||||
bound to, which is the result of calling <code>String::new</code>, a function that returns
|
||||
a new instance of a <code>String</code>. <a href="../std/string/struct.String.html"><code>String</code></a><!-- ignore --> is a string
|
||||
type provided by the standard library that is a growable, UTF-8 encoded bit of
|
||||
text.</p>
|
||||
<p>The <code>::</code> syntax in the <code>::new</code> line indicates that <code>new</code> is an <em>associated
|
||||
function</em> of a particular type. An associated function is a function that is
|
||||
associated with a type, in this case <code>String</code>, rather than a particular
|
||||
instance of a <code>String</code>. Some languages call this a <em>static method</em>.</p>
|
||||
<p>This <code>new</code> function creates a new, empty <code>String</code>.
|
||||
You’ll find a <code>new</code> function on many types, as it’s a common name for making
|
||||
a new value of some kind.</p>
|
||||
<p>So to summarize, the <code>let mut guess = String::new();</code> line has created a
|
||||
mutable variable that is currently bound to a new, empty instance of a <code>String</code>.
|
||||
Whew!</p>
|
||||
<p>Let’s move forward:</p>
|
||||
function</em> of the <code>String</code> type. An associated function is implemented on a type,
|
||||
in this case <code>String</code>, rather than on a particular instance of a <code>String</code>. Some
|
||||
languages call this a <em>static method</em>.</p>
|
||||
<p>This <code>new</code> function creates a new, empty <code>String</code>. You’ll find a <code>new</code> function
|
||||
on many types, because it’s a common name for a function that makes a new value
|
||||
of some kind.</p>
|
||||
<p>To summarize, the <code>let mut guess = String::new();</code> line has created a mutable
|
||||
variable that is currently bound to a new, empty instance of a <code>String</code>. Whew!</p>
|
||||
<p>Recall that we included the input/output functionality from the standard
|
||||
library with <code>use std::io;</code> on the first line of the program. Now we'll call an
|
||||
associated function, <code>stdin</code>, on <code>io</code>:</p>
|
||||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess)
|
||||
.expect("Failed to read line");
|
||||
</code></pre>
|
||||
<p>We included the input/output functionality from the standard library with use
|
||||
std::io; on the first line of the program. We are now calling an associated
|
||||
function, stdin(), on io. If we didn’t have the use std::io line at the
|
||||
beginning of the program, we could have written this function call as
|
||||
std::io::stdin(). The stdin() function returns an instance of std::io::Stdin,
|
||||
which is a type that represents a handle to the standard input for your
|
||||
terminal.</p>
|
||||
<p>The next part, <code>.read_line(&mut guess)</code>, calls the
|
||||
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle
|
||||
to get input from the user. We’re also passing one argument to <code>read_line</code>:
|
||||
<code>&mut guess</code>.</p>
|
||||
<p>If we didn’t have the <code>use std::io</code> line at the beginning of the program, we
|
||||
could have written this function call as <code>std::io::stdin</code>. The <code>stdin</code> function
|
||||
returns an instance of <a href="../std/io/struct.Stdin.html"><code>std::io::Stdin</code></a><!-- ignore -->, which is a
|
||||
type that represents a handle to the standard input for your terminal.</p>
|
||||
<p>The next part of the code, <code>.read_line(&mut guess)</code>, calls the
|
||||
<a href="../std/io/struct.Stdin.html#method.read_line"><code>read_line</code></a><!-- ignore --> method on the standard input handle to
|
||||
get input from the user. We’re also passing one argument to <code>read_line</code>: <code>&mut guess</code>.</p>
|
||||
<p>The job of <code>read_line</code> is to take whatever the user types into standard input
|
||||
and place that into a string, so it takes that string as an argument. The
|
||||
string argument needs to be mutable so that the method can change the string's
|
||||
string argument needs to be mutable so the method can change the string’s
|
||||
content by adding the user input.</p>
|
||||
<p>The <code>&</code> indicates that this argument is a <em>reference</em>, which gives you a way to
|
||||
let multiple parts of your code access one piece of data without needing to
|
||||
copy that data into memory multiple times. References are a complex feature,
|
||||
and one of Rust’s major advantages is how safe and easy it is to use
|
||||
references. We don’t need to know a lot of those details to finish our program
|
||||
right now, though; Chapter XX will cover references in more detail. For now,
|
||||
all we need to know is that like variables, references are immutable by
|
||||
default. Hence, we need to write <code>&mut guess</code>, rather than <code>&guess</code>, to make it
|
||||
mutable.</p>
|
||||
<p>We’re not quite done with this line of code. While it’s a single line of text,
|
||||
it’s only the first part of the single logical line of code. The second part is
|
||||
this method:</p>
|
||||
references. You don’t need to know a lot of those details to finish this
|
||||
program: Chapter 4 will explain references more thoroughly. For now, all you
|
||||
need to know is that like variables, references are immutable by default.
|
||||
Hence, we need to write <code>&mut guess</code> rather than <code>&guess</code> to make it mutable.</p>
|
||||
<p>We’re not quite done with this line of code. Although it’s a single line of
|
||||
text, it’s only the first part of the single logical line of code. The second
|
||||
part is this method:</p>
|
||||
<pre><code class="language-rust,ignore">.expect("Failed to read line");
|
||||
</code></pre>
|
||||
<p>When you call a method with the <code>.foo()</code> syntax, it's often wise to introduce a
|
||||
newline and other whitespace. This helps you split up long lines. We could have
|
||||
<p>When you call a method with the <code>.foo()</code> syntax, it’s often wise to introduce a
|
||||
newline and other whitespace to help break up long lines. We could have
|
||||
written this code as:</p>
|
||||
<pre><code class="language-rust,ignore">io::stdin().read_line(&mut guess).expect("failed to read line");
|
||||
</code></pre>
|
||||
<p>But that gets hard to read. So we’ve split it up, two lines for two method
|
||||
calls. Now let's see what this line does.</p>
|
||||
<p>However, one long line is difficult to read, so it’s best to divide it, two
|
||||
lines for two method calls. Now let’s discuss what this line does.</p>
|
||||
<h3>Handling Potential Failure with the <code>Result</code> Type</h3>
|
||||
<p>We mentioned that <code>read_line</code> puts what the user types into the string we
|
||||
pass it, but it also returns a value: in this case, an
|
||||
<p>As mentioned earlier, <code>read_line</code> puts what the user types into the string we're
|
||||
passing it, but it also returns a value—in this case, an
|
||||
<a href="../std/io/type.Result.html"><code>io::Result</code></a><!-- ignore -->. Rust has a number of types named
|
||||
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore -->,
|
||||
and then specific versions for sub-libraries, like <code>io::Result</code>.</p>
|
||||
<p>The <code>Result</code> types are <a href="ch06-00-enums.html">enums</a><!-- ignore -->, which is short for
|
||||
<em>enumerations</em>. An enumeration is a type that can have a fixed set of values,
|
||||
which are called the enum's <em>variants</em>. We will be covering enums in more
|
||||
detail in Chapter XX.</p>
|
||||
<code>Result</code> in its standard library: a generic <a href="../std/result/enum.Result.html"><code>Result</code></a><!-- ignore --> as
|
||||
well as specific versions for submodules, such as <code>io::Result</code>.</p>
|
||||
<p>The <code>Result</code> types are <a href="ch06-00-enums.html"><em>enumerations</em></a><!-- ignore -->, often referred
|
||||
to as <em>enums</em>. An enumeration is a type that can have a fixed set of values,
|
||||
and those values are called the enum’s <em>variants</em>. Chapter 6 will cover enums
|
||||
in more detail.</p>
|
||||
<p>For <code>Result</code>, the variants are <code>Ok</code> or <code>Err</code>. <code>Ok</code> indicates the operation was
|
||||
successful, and inside the <code>Ok</code> variant is the successfully generated value.
|
||||
<code>Err</code> means the operation failed, and the <code>Err</code> contains information about how
|
||||
or why the operation failed.</p>
|
||||
<code>Err</code> means the operation failed, and <code>Err</code> contains information about how or
|
||||
why the operation failed.</p>
|
||||
<p>The purpose of these <code>Result</code> types is to encode error handling information.
|
||||
Values of the <code>Result</code> type, like any type, have methods defined on them.
|
||||
<code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that we can call.
|
||||
If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will cause our
|
||||
program to crash and display the message that we passed as an argument to
|
||||
<code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would likely be the
|
||||
result of an error coming from the underlying operating system. If this
|
||||
instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the return value
|
||||
that <code>Ok</code> is holding and return just that value to us so that we could use it.
|
||||
In this case, that value is the number of characters the user entered into
|
||||
standard input.</p>
|
||||
<p>If we don't call <code>expect</code>, our program will compile, but we’ll get a warning:</p>
|
||||
Values of the <code>Result</code> type, like any type, have methods defined on them. An
|
||||
instance of <code>io::Result</code> has an <a href="../std/result/enum.Result.html#method.expect"><code>expect</code> method</a><!-- ignore --> that
|
||||
you can call. If this instance of <code>io::Result</code> is an <code>Err</code> value, <code>expect</code> will
|
||||
cause the program to crash and display the message that you passed as an
|
||||
argument to <code>expect</code>. If the <code>read_line</code> method returns an <code>Err</code>, it would
|
||||
likely be the result of an error coming from the underlying operating system.
|
||||
If this instance of <code>io::Result</code> is an <code>Ok</code> value, <code>expect</code> will take the
|
||||
return value that <code>Ok</code> is holding and return just that value to you so you
|
||||
could use it. In this case, that value is the number of characters the user
|
||||
entered into standard input.</p>
|
||||
<p>If we don’t call <code>expect</code>, the program will compile, but we’ll get a warning:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||||
@@ -641,30 +644,29 @@ src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||||
src/main.rs:10 io::stdin().read_line(&mut guess);
|
||||
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
</code></pre>
|
||||
<p>Rust warns that we haven’t used the <code>Result</code> value, telling us that we
|
||||
haven’t handled a possible error. The right way to suppress the warning is to
|
||||
actually write error handling, but if we just want to crash the program when a
|
||||
problem occurs, we can use <code>expect</code>. We’ll save recovering from errors for a
|
||||
future project.</p>
|
||||
<p>Rust warns that we haven’t used the <code>Result</code> value returned from <code>read_line</code>,
|
||||
indicating that the program hasn’t handled a possible error. The right way to
|
||||
suppress the warning is to actually write error handling, but since we just
|
||||
want to crash this program when a problem occurs, we can use <code>expect</code>. You’ll
|
||||
learn about recovering from errors in Chapter 9.</p>
|
||||
<h3>Printing Values with <code>println!</code> Placeholders</h3>
|
||||
<p>There’s only one line of this first example left, aside from the closing curly
|
||||
brace:</p>
|
||||
<pre><code class="language-rust,ignore"> println!("You guessed: {}", guess);
|
||||
<p>Aside from the closing curly brace, there’s only one more line to discuss in
|
||||
the code added so far, which is the following:</p>
|
||||
<pre><code class="language-rust,ignore">println!("You guessed: {}", guess);
|
||||
</code></pre>
|
||||
<p>This prints out the string we saved our input in. The <code>{}</code>s are a placeholder:
|
||||
think of <code>{}</code> as little crab pincers, holding a value in place. You can print
|
||||
more than one value this way: the first <code>{}</code> holds the first value listed after
|
||||
the format string, the second set holds the second value, and so on. Printing
|
||||
out multiple values in one call to <code>println!</code> would then look like this:</p>
|
||||
<p>This line prints out the string we saved the user’s input in. The set of <code>{}</code>
|
||||
is a placeholder that holds a value in place. You can print more than one value
|
||||
using <code>{}</code>: the first set of <code>{}</code> holds the first value listed after the format
|
||||
string, the second set holds the second value, and so on. Printing out multiple
|
||||
values in one call to <code>println!</code> would look like this:</p>
|
||||
<pre><code class="language-rust">let x = 5;
|
||||
let y = 10;
|
||||
|
||||
println!("x = {} and y = {}", x, y);
|
||||
</code></pre>
|
||||
<p>Which would print out "x = 5 and y = 10".</p>
|
||||
<p>This code would print out <code>x = 5 and y = 10</code>.</p>
|
||||
<h3>Testing the First Part</h3>
|
||||
<p>Back to our guessing game, let's test what we have so far. We can run it with
|
||||
<code>cargo run</code>:</p>
|
||||
<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-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/debug/guessing_game`
|
||||
@@ -673,38 +675,39 @@ Please input your guess.
|
||||
6
|
||||
You guessed: 6
|
||||
</code></pre>
|
||||
<p>All right! Our first part is done: we can get input from the keyboard and then
|
||||
print it back out.</p>
|
||||
<p>At this point, the first part of the game is done: we're getting input from the
|
||||
keyboard and then printing it.</p>
|
||||
<h2>Generating a Secret Number</h2>
|
||||
<p>Next, we need to generate a secret number that the user will try to guess. The
|
||||
secret number should be different every time so that the game is fun to play
|
||||
more than once, and we'd like to have a random number between 1 and 100 so the
|
||||
game isn’t too difficult. Rust does not yet include random number functionality
|
||||
in its standard library. The Rust team does, however, provide a <a href="https://crates.io/crates/rand"><code>rand</code>
|
||||
crate</a>.</p>
|
||||
secret number should be different every time so the game is fun to play more
|
||||
than once. Let’s use a random number between 1 and 100 so the game isn’t too
|
||||
difficult. Rust doesn’t yet include random number functionality in its standard
|
||||
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
|
||||
<h3>Using a Crate to Get More Functionality</h3>
|
||||
<p>Remember that <em>crate</em> is what we call a package of Rust code. The project we’ve
|
||||
been building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is
|
||||
a <em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||||
<p>Cargo's use of external crates is where it really shines. Before we can write
|
||||
the code using <code>rand</code>, we need to modify our <code>Cargo.toml</code> to include the <code>rand</code>
|
||||
crate as a dependency. Open it up, and add this line at the bottom beneath the
|
||||
<code>[dependencies]</code> section header that Cargo created for you:</p>
|
||||
<p>Remember that a <em>crate</em> is a package of Rust code. The project we’ve been
|
||||
building is a <em>binary crate</em>, which is an executable. The <code>rand</code> crate is a
|
||||
<em>library crate</em>, which contains code intended to be used in other programs.</p>
|
||||
<p>Cargo’s use of external crates is where it really shines. Before we can write
|
||||
code that uses <code>rand</code>, we need to modify the <code>Cargo.toml</code> file to include the
|
||||
<code>rand</code> crate as a dependency. Open that file now and add the following line to
|
||||
the bottom beneath the <code>[dependencies]</code> section header that Cargo created for
|
||||
you:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<pre><code class="language-toml">[dependencies]
|
||||
|
||||
rand = "0.3.14"
|
||||
</code></pre>
|
||||
<p>In the <code>Cargo.toml</code> file, everything that follows a header is part of a section
|
||||
that goes until another section starts. Cargo uses the <code>[dependencies]</code> section
|
||||
to know what external crates your project depends on and what versions of those
|
||||
crates you require. In this case, we’ve specified the <code>rand</code> crate with the
|
||||
semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
|
||||
Versioning</a><!-- ignore --> (sometimes called <em>semver</em>), which is a
|
||||
standard for writing version numbers. A bare number like above is actually
|
||||
shorthand for <code>^0.3.14</code>, which means "any version that has a public API
|
||||
compatible with version 0.3.14".</p>
|
||||
<p>Now, without changing any of our code, let’s build our project:</p>
|
||||
that continues until another section starts. The <code>[dependencies]</code> section is
|
||||
where you tell Cargo which external crates your project depends on and which
|
||||
versions of those crates you require. In this case, we’ll specify the <code>rand</code>
|
||||
crate with the semantic version specifier <code>0.3.14</code>. Cargo understands <a href="http://semver.org">Semantic
|
||||
Versioning</a><!-- ignore --> (sometimes called <em>SemVer</em>), which is a
|
||||
standard for writing version numbers. The number <code>0.3.14</code> is actually shorthand
|
||||
for <code>^0.3.14</code>, which means “any version that has a public API compatible with
|
||||
version <code>0.3.14</code>.”</p>
|
||||
<p>Now, without changing any of the code, let’s build the project, as shown in
|
||||
Listing 2-2:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||||
Downloading rand v0.3.14
|
||||
@@ -713,80 +716,86 @@ compatible with version 0.3.14".</p>
|
||||
Compiling rand v0.3.14
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-2: The output from running cargo build after adding the rand crate as
|
||||
a dependency
|
||||
</caption>
|
||||
<p>You may see different version numbers (but they will all be compatible with
|
||||
your code, thanks to semver!) and the lines may be in a different order.</p>
|
||||
<p>Lots of new output! Now that we have an external dependency, Cargo fetches the
|
||||
latest versions of everything from the <em>registry</em>, which is a copy of data from
|
||||
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem
|
||||
post their open source Rust projects for others to use.</p>
|
||||
<p>After updating the registry, Cargo checks our <code>[dependencies]</code> and downloads
|
||||
any we don’t have yet. In this case, while we only listed <code>rand</code> as a
|
||||
dependency, we’ve also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
|
||||
the code, thanks to SemVer!), and the lines may be in a different order.</p>
|
||||
<p>Now that we have an external dependency, Cargo fetches the latest versions of
|
||||
everything from the <em>registry</em>, which is a copy of data from
|
||||
<a href="https://crates.io">Crates.io</a>. Crates.io is where people in the Rust ecosystem post
|
||||
their open source Rust projects for others to use.</p>
|
||||
<p>After updating the registry, Cargo checks the <code>[dependencies]</code> section and
|
||||
downloads any you don’t have yet. In this case, although we only listed <code>rand</code>
|
||||
as a dependency, Cargo also grabbed a copy of <code>libc</code>, because <code>rand</code> depends on
|
||||
<code>libc</code> to work. After downloading them, Rust compiles them and then compiles
|
||||
our project with our dependencies available.</p>
|
||||
<p>If we immediately run <code>cargo build</code> again without making any changes, we won't
|
||||
get any output. Cargo knows it has already downloaded and compiled our
|
||||
dependencies, and we haven't changed anything about them in our <code>Cargo.toml</code>
|
||||
file. Cargo also knows that we haven't changed anything about our code, so it
|
||||
doesn't recompile that either. With nothing to do, it simply exits. If we open
|
||||
up <code>src/main.rs</code>, make a trivial change, then save it again, we’ll only see one
|
||||
line:</p>
|
||||
the project with the dependencies available.</p>
|
||||
<p>If you immediately run <code>cargo build</code> again without making any changes, you won’t
|
||||
get any output. Cargo knows it has already downloaded and compiled the
|
||||
dependencies, and you haven't changed anything about them in your <code>Cargo.toml</code>
|
||||
file. Cargo also knows that you haven't changed anything about your code, so it
|
||||
doesn't recompile that either. With nothing to do, it simply exits. If you open
|
||||
up the <code>src/main.rs</code> file, make a trivial change, then save it and build again,
|
||||
you’ll only see one line of output:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
</code></pre>
|
||||
<p>This just updates the build with your tiny change to the <code>main.rs</code> file. Our
|
||||
dependencies haven't changed, so Cargo knows it can reuse what it has already
|
||||
downloaded and compiled for those. It just rebuilds our part of the code.</p>
|
||||
<h4>The Cargo.lock File that Ensures Reproducible Builds</h4>
|
||||
<p>Cargo has a mechanism to make sure we can rebuild the exact same artifact every
|
||||
time we or anyone else builds our code: Cargo will only use the versions of the
|
||||
dependencies you specified until you say otherwise. For example, what happens
|
||||
if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out, containing an
|
||||
important bugfix, but that also contains a regression that will break our code?</p>
|
||||
<p>The answer to this problem is the <code>Cargo.lock</code> file created the first time we
|
||||
ran <code>cargo build</code> that is now in your project directory. When you build your
|
||||
project for the first time, Cargo figures out all of the versions of your
|
||||
dependencies that fit your criteria then writes them to the <code>Cargo.lock</code> file.
|
||||
When you build your project in the future, Cargo will see that the <code>Cargo.lock</code>
|
||||
file exists and use the versions specified there rather than doing all the work
|
||||
of figuring out versions again. This lets you have a reproducible build
|
||||
automatically. In other words, our project will stay at <code>0.3.14</code> until we
|
||||
explicitly upgrade, thanks to the lock file.</p>
|
||||
<p>This line shows Cargo only updates the build with your tiny change to the
|
||||
<code>src/main.rs</code> 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 Cargo.lock File Ensures Reproducible Builds</h4>
|
||||
<p>Cargo has a mechanism that ensures you can rebuild the same artifact every time
|
||||
you or anyone else builds your code: Cargo will use only the versions of the
|
||||
dependencies you specified until you indicate otherwise. For example, what
|
||||
happens if next week version <code>v0.3.15</code> of the <code>rand</code> crate comes out and
|
||||
contains an important bug fix but also contains a regression that will break
|
||||
your code?</p>
|
||||
<p>The answer to this problem is the <code>Cargo.lock</code> file, which was created the
|
||||
first time you ran <code>cargo build</code> and is now in your <code>guessing_game</code> directory.
|
||||
When you build a project for the first time, Cargo figures out all the
|
||||
versions of the dependencies that fit the criteria and then writes them to
|
||||
the <code>Cargo.lock</code> file. When you build your project in the future, Cargo will
|
||||
see that the <code>Cargo.lock</code> file exists and use the versions specified there
|
||||
rather than doing all the work of figuring out versions again. This lets you
|
||||
have a reproducible build automatically. In other words, your project will
|
||||
remain at <code>0.3.14</code> until you explicitly upgrade, thanks to the <code>Cargo.lock</code>
|
||||
file.</p>
|
||||
<h4>Updating a Crate to Get a New Version</h4>
|
||||
<p>When we <em>do</em> want to update a crate, Cargo has another command,
|
||||
<code>update</code>, which will:</p>
|
||||
<ul>
|
||||
<p>When you <em>do</em> want to update a crate, Cargo provides another command, <code>update</code>,
|
||||
which will:</p>
|
||||
<ol>
|
||||
<li>Ignore the <code>Cargo.lock</code> file and figure out all the latest versions that fit
|
||||
our specifications in <code>Cargo.toml</code>.</li>
|
||||
<li>If that works, write those versions out to the lock file.</li>
|
||||
</ul>
|
||||
your specifications in <code>Cargo.toml</code>.</li>
|
||||
<li>If that works, Cargo will write those versions to the <code>Cargo.lock</code> file.</li>
|
||||
</ol>
|
||||
<p>But by default, Cargo will only look for versions larger than <code>0.3.0</code> and
|
||||
smaller than <code>0.4.0</code>. If the <code>rand</code> crate has released two new versions,
|
||||
<code>0.3.15</code> and <code>0.4.0</code>, this is what we would see if we ran <code>cargo update</code>:</p>
|
||||
<code>0.3.15</code> and <code>0.4.0</code>, you would see the following if you ran <code>cargo update</code>:</p>
|
||||
<pre><code class="language-bash">$ cargo update
|
||||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||||
Updating rand v0.3.14 -> v0.3.15
|
||||
</code></pre>
|
||||
<p>At this point, you would also notice a change in your <code>Cargo.lock</code> file noting
|
||||
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</p>
|
||||
<p>If we wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
|
||||
series, we’d have to update what is in the <code>Cargo.toml</code> file to look like this
|
||||
instead:</p>
|
||||
<p>If you wanted to use <code>rand</code> version <code>0.4.0</code> or any version in the <code>0.4.x</code>
|
||||
series, you’d have to update the <code>Cargo.toml</code> file to look like this instead:</p>
|
||||
<pre><code class="language-toml">[dependencies]
|
||||
|
||||
rand = "0.4.0"
|
||||
</code></pre>
|
||||
<p>The next time we <code>cargo build</code>, assuming that the <code>rand</code> crate version <code>0.4.0</code>
|
||||
has been released, Cargo will update the crates index and re-evaluate our
|
||||
<code>rand</code> requirements according to the new version we have specified.</p>
|
||||
<p>The next time you run <code>cargo build</code>, Cargo will update the registry of crates
|
||||
available and reevaluate your <code>rand</code> requirements according to the new version
|
||||
you specified.</p>
|
||||
<p>There’s a lot more to say about <a href="http://doc.crates.io">Cargo</a><!-- ignore --> and <a href="http://doc.crates.io/crates-io.html">its
|
||||
ecosystem</a><!-- ignore --> that we will get into in Chapter XX, but
|
||||
for now, that’s all we need to know. Cargo makes it really easy to re-use
|
||||
libraries, so Rustaceans are able to write smaller projects which are assembled
|
||||
out of a number of sub-packages.</p>
|
||||
ecosystem</a><!-- ignore --> that Chapter XX will discuss, but for
|
||||
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
|
||||
so Rustaceans are able to write smaller projects that are assembled from a
|
||||
number of packages.</p>
|
||||
<h3>Generating a Random Number</h3>
|
||||
<p>Let’s get on to actually <em>using</em> <code>rand</code>. Our next step is to update our
|
||||
<code>main.rs</code> code as follows:</p>
|
||||
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <code>src/main.rs</code>, as shown
|
||||
in Listing 2-3:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -810,39 +819,33 @@ fn main() {
|
||||
println!("You guessed: {}", guess);
|
||||
}
|
||||
</code></pre>
|
||||
<p>First we've added a line to the top, <code>extern crate rand</code>, that lets Rust know
|
||||
we’ll be making use of that external dependency. This also does the equivalent
|
||||
of calling <code>use rand</code>, so we can now call anything in the <code>rand</code> crate by
|
||||
prefixing it with <code>rand::</code>.</p>
|
||||
<p>Next, we added another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
|
||||
<p>Listing 2-3: Code changes needed in order to generate a random number</p>
|
||||
<p>We're adding a <code>extern crate rand;</code> line to the top that lets Rust know we’ll be
|
||||
using that external dependency. This also does the equivalent of calling <code>use rand</code>, so now we can call anything in the <code>rand</code> crate by prefixing it with
|
||||
<code>rand::</code>.</p>
|
||||
<p>Next, we're adding another <code>use</code> line: <code>use rand::Rng</code>. <code>Rng</code> is a trait that
|
||||
defines methods that random number generators implement, and this trait must be
|
||||
in scope for us to use those methods. We'll cover traits in detail in the
|
||||
Traits section in Chapter XX.</p>
|
||||
<p>We also added two more lines in the middle:</p>
|
||||
<pre><code class="language-rust,ignore">let secret_number = rand::thread_rng().gen_range(1, 101);
|
||||
|
||||
println!("The secret number is: {}", secret_number);
|
||||
</code></pre>
|
||||
<p>The <code>rand::thread_rng</code> function will give us the particular random number
|
||||
generator that we're going to use: one that is local to our current thread of
|
||||
execution and seeded by the operating system. Next, we call the <code>gen_range</code>
|
||||
method on our random number generator. This method is defined by the <code>Rng</code>
|
||||
trait that we brought into scope with the <code>use rand::Rng</code> statement above. The
|
||||
<code>gen_range</code> method takes two numbers as arguments and generates a random
|
||||
number between them. It's inclusive on the lower bound but exclusive on the
|
||||
upper bound, so we need <code>1</code> and <code>101</code> to ask for a number ranging from one to a
|
||||
hundred.</p>
|
||||
<p>Knowing what traits to import and what functions and methods to use from a
|
||||
crate isn't something that you'll just <em>know</em>. Instructions for using a crate
|
||||
are in each crate's documentation. Another neat feature of Cargo is that you
|
||||
can run the <code>cargo doc --open</code> command to build documentation provided by all
|
||||
of your dependencies locally and then open it in your browser. If you're
|
||||
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> then click on "rand" in the sidebar on the left.</p>
|
||||
<p>The second line that we added to our code prints out the secret number. This is
|
||||
useful while we’re developing our program to let us easily test it out, but
|
||||
we’ll be deleting it for the final version. It’s not much of a game if it
|
||||
prints out the answer when you start it up!</p>
|
||||
<p>Try running our new program a few times:</p>
|
||||
in scope for us to use those methods. Chapter 10 will cover traits in detail.</p>
|
||||
<p>Also, we're adding two more lines in the middle. The <code>rand::thread_rng</code> function
|
||||
will give us the particular random number generator that we’re going to use:
|
||||
one that is local to the current thread of execution and seeded by the
|
||||
operating system. Next, we call the <code>gen_range</code> method on the random number
|
||||
generator. This method is defined by the <code>Rng</code> trait that we brought into
|
||||
scope with the <code>use rand::Rng</code> statement. The <code>gen_range</code> method takes two
|
||||
numbers as arguments and generates a random number between them. It’s inclusive
|
||||
on the lower bound but exclusive on the upper bound, so we need to specify <code>1</code>
|
||||
and <code>101</code> to request a number between 1 and 100.</p>
|
||||
<p>Knowing which traits to import and which functions and methods to use from a
|
||||
crate isn’t something that you’ll just <em>know</em>. Instructions for using a crate
|
||||
are in each crate’s documentation. Another neat feature of Cargo is that you
|
||||
can run the <code>cargo doc --open</code> command that will build documentation provided
|
||||
by all of your dependencies locally and open it in your browser. If you’re
|
||||
interested in other functionality in the <code>rand</code> crate, for example, run <code>cargo doc --open</code> and click <code>rand</code> in the sidebar on the left.</p>
|
||||
<p>The second line that we added to the code prints the secret number. This is
|
||||
useful while we’re developing the program to be able to test it, but we’ll
|
||||
delete it from the final version. It’s not much of a game if the program prints
|
||||
the answer as soon as it starts!</p>
|
||||
<p>Try running the program a few times:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/debug/guessing_game`
|
||||
@@ -861,9 +864,9 @@ You guessed: 5
|
||||
</code></pre>
|
||||
<p>You should get different random numbers, and they should all be numbers between
|
||||
1 and 100. Great job!</p>
|
||||
<h2>Comparing Our Guesses</h2>
|
||||
<p>Now that we’ve got user input, let’s compare our guess to the secret number.
|
||||
Here’s that part of our next step:</p>
|
||||
<h2>Comparing the Guess to the Secret Number</h2>
|
||||
<p>Now that we have user input and a random number, we can compare them. That
|
||||
step is shown in Listing 2-4:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -894,8 +897,9 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>There are a few new bits here. The first is another <code>use</code>, bringing a type
|
||||
called <code>std::cmp::Ordering</code> into scope from the standard crate. <code>Ordering</code> is
|
||||
<p>Listing 2-4: Handling the possible return values of comparing two numbers</p>
|
||||
<p>The first new bit here is another <code>use</code>, bringing a type called
|
||||
<code>std::cmp::Ordering</code> into scope from the standard library. <code>Ordering</code> is
|
||||
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
|
||||
<code>Greater</code>, and <code>Equal</code>. These are the three outcomes that are possible when you
|
||||
compare two values.</p>
|
||||
@@ -906,56 +910,59 @@ compare two values.</p>
|
||||
Ordering::Equal => println!("You win!"),
|
||||
}
|
||||
</code></pre>
|
||||
<p>The <code>cmp</code> method compares two values, and can be called on anything that can
|
||||
be compared. It takes a reference to whatever you want to compare with, so here
|
||||
it's comparing our <code>guess</code> to our <code>secret_number</code>. <code>cmp</code> returns a variant of
|
||||
the <code>Ordering</code> enum we imported with the <code>use</code> statement earlier. We use a
|
||||
<a href="match.html"><code>match</code></a><!-- ignore --> statement to decide what to do next based on
|
||||
which variant of <code>Ordering</code> we got back from our call to <code>cmp</code> with the values
|
||||
<p>The <code>cmp</code> method compares two values and can be called on anything that can be
|
||||
compared. It takes a reference to whatever you want to compare with: here it’s
|
||||
comparing the <code>guess</code> to the <code>secret_number</code>. <code>cmp</code> returns a variant of the
|
||||
<code>Ordering</code> enum we imported with the <code>use</code> statement. We use a
|
||||
<a href="ch06-02-match.html"><code>match</code></a><!-- ignore --> expression to decide what to do next based on
|
||||
which variant of <code>Ordering</code> was returned from the call to <code>cmp</code> with the values
|
||||
in <code>guess</code> and <code>secret_number</code>.</p>
|
||||
<p><code>match</code> statements are made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
|
||||
the code that we should run if the value given to the beginning of the <code>match</code>
|
||||
statement fits that arm's pattern. Rust takes the value given to <code>match</code> and
|
||||
looks through each arm's pattern in turn. The <code>match</code> construct and patterns
|
||||
are powerful features in Rust that will be covered in detail in Chapter XX and
|
||||
Chapter XX, respectively.</p>
|
||||
<p>Let's walk through an example of what would happen with our <code>match</code>. Say that
|
||||
the user has guessed 50, and the randomly-generated secret number this time
|
||||
is 38. So when we compare 50 to 38, the <code>cmp</code> method will return
|
||||
<code>Ordering::Greater</code>, since 50 is greater than 38. <code>Ordering::Greater</code> is the
|
||||
value that the <code>match</code> statement gets. It looks at the first arm's pattern,
|
||||
<code>Ordering::Less</code>, and says nope, the value we have (<code>Ordering::Greater</code>) does
|
||||
not match <code>Ordering::Less</code>. So it ignores the code in that arm and moves on to
|
||||
the next arm. The next arm's pattern, <code>Ordering::Greater</code>, <strong>does</strong> match
|
||||
<code>Ordering::Greater</code>! The associated code in that arm will get executed, which
|
||||
prints "Too big!" to the screen. Then we're done with the <code>match</code> statement; we
|
||||
don't look at the last arm at all in this particular scenario.</p>
|
||||
<p>However, this code won’t quite compile yet. Let’s try it:</p>
|
||||
<p>A <code>match</code> expression is made up of <em>arms</em>. An arm consists of a <em>pattern</em> and
|
||||
the code that should be run if the value given to the beginning of the <code>match</code>
|
||||
expression fits that arm’s pattern. Rust takes the value given to <code>match</code> and
|
||||
looks through each arm’s pattern in turn. The <code>match</code> construct and patterns
|
||||
are powerful features in Rust that let you express a variety of situations your
|
||||
code might encounter and helps ensure that you handle them all. These features
|
||||
will be covered in detail in Chapter 6 and Chapter XX, respectively.</p>
|
||||
<p>Let’s walk through an example of what would happen with the <code>match</code> expression
|
||||
used here. Say that the user has guessed 50, and the randomly generated secret
|
||||
number this time is 38. When the code compares 50 to 38, the <code>cmp</code> method will
|
||||
return <code>Ordering::Greater</code>, because 50 is greater than 38. <code>Ordering::Greater</code>
|
||||
is the value that the <code>match</code> expression gets. It looks at the first arm’s
|
||||
pattern, <code>Ordering::Less</code>, but the value <code>Ordering::Greater</code> does not match
|
||||
<code>Ordering::Les</code>s. So it ignores the code in that arm and moves to the next arm.
|
||||
The next arm’s pattern, <code>Ordering::Greater</code>, <strong>does</strong> match
|
||||
<code>Ordering::Greater</code>! The associated code in that arm will execute and print
|
||||
<code>Too big!</code> to the screen. The <code>match</code> expression ends because it has no need to
|
||||
look at the last arm in this particular scenario.</p>
|
||||
<p>However, the code in Listing 2-4 won’t compile yet. Let’s try it:</p>
|
||||
<pre><code class="language-bash">$ cargo build
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
src/main.rs:23:21: 23:35 error: mismatched types [E0308]
|
||||
src/main.rs:23 match guess.cmp(&secret_number) {
|
||||
^~~~~~~~~~~~~~
|
||||
src/main.rs:23:21: 23:35 help: run `rustc --explain E0308` to see a detailed explanation
|
||||
src/main.rs:23:21: 23:35 note: expected type `&std::string::String`
|
||||
src/main.rs:23:21: 23:35 note: found type `&_`
|
||||
error[E0308]: mismatched types
|
||||
--> src/main.rs:23:21
|
||||
|
|
||||
23 | match guess.cmp(&secret_number) {
|
||||
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found integral variable
|
||||
|
|
||||
= note: expected type `&std::string::String`
|
||||
= note: found type `&{integer}`
|
||||
|
||||
error: aborting due to previous error
|
||||
Could not compile `guessing_game`.
|
||||
</code></pre>
|
||||
<p>Whew! This is a big error. The core of the error says that we have <em>mismatched
|
||||
types</em>. Rust has a strong, static type system. However, it also has type
|
||||
inference. When we wrote <code>let guess = String::new()</code>, Rust was able to infer
|
||||
that <code>guess</code> should be a <code>String</code> and didn’t make us write the type out. Our
|
||||
<code>secret_number</code> on the other hand is a number type. There are a few number
|
||||
types which can have a value between one and a hundred: <code>i32</code>, a thirty-two-bit
|
||||
number; <code>u32</code>, an unsigned thirty-two-bit number; <code>i64</code>, a sixty-four-bit
|
||||
number; or others. Rust defaults to an <code>i32</code>, so that's the type of
|
||||
<p>The core of the error states that there are <em>mismatched types</em>. Rust has a
|
||||
strong, static type system. However, it also has type inference. When we wrote
|
||||
<code>let guess = String::new()</code>, Rust was able to infer that <code>guess</code> should be a
|
||||
<code>String</code> and didn’t make us write the type. The <code>secret_number</code>, on the other
|
||||
hand, is a number type. A few number types can have a value between 1 and 100:
|
||||
<code>i32</code>, a 32-bit number; <code>u32</code>, an unsigned 32-bit number; <code>i64</code>, a 64-bit
|
||||
number; as well as others. Rust defaults to an <code>i32</code>, which is the type of
|
||||
<code>secret_number</code> unless we add type information elsewhere that would cause Rust
|
||||
to infer a different numerical type. The error is because Rust will not compare
|
||||
a string and a number type.</p>
|
||||
<p>Ultimately, we want to convert the <code>String</code> we read as input into a real number
|
||||
type so that we can compare it to the guess numerically. We can do that with
|
||||
two more lines; to your <code>main</code> function body, add the following two lines:</p>
|
||||
to infer a different numerical type. The reason for the error is that Rust will
|
||||
not compare a string and a number type.</p>
|
||||
<p>Ultimately, we want to convert the <code>String</code> the program reads as input into a
|
||||
real number type so we can compare it to the guess numerically. We can do
|
||||
that by adding the following two lines to the <code>main</code> function body:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -993,43 +1000,43 @@ fn main() {
|
||||
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
|
||||
.expect("Please type a number!");
|
||||
</code></pre>
|
||||
<p>We create a variable <code>guess</code>. But wait a minute, don't we already have
|
||||
a variable named <code>guess</code>? We do, but Rust allows us to <em>shadow</em> the
|
||||
previous value of <code>guess</code> with a new one. This is often used in this exact
|
||||
situation, where we want to convert a value from one type into another type.
|
||||
Shadowing lets us re-use the <code>guess</code> variable name rather than forcing us to
|
||||
come up with two unique variables, like <code>guess_str</code> and <code>guess</code> or something
|
||||
(we'll cover shadowing in more detail in Chapter 3).</p>
|
||||
<p>We bind the second <code>guess</code> variable (a number of type <code>u32</code>) to the result
|
||||
of calling <code>.trim().parse()</code> on the first <code>guess</code> variable (a <code>String</code>).
|
||||
The <code>trim</code> method on <code>String</code>s will eliminate any whitespace at the
|
||||
beginning and end. Our <code>u32</code> can only contain numerical characters, but we have
|
||||
to press the return key to satisfy <code>read_line</code>. When we press the return
|
||||
key, it introduces a newline character. For example, if we type <code>5</code> and hit
|
||||
return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents "newline", the
|
||||
return key. The <code>trim</code> method gets rid of this, leaving our string with only
|
||||
the <code>5</code>.</p>
|
||||
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into
|
||||
some kind of number. Since this method can parse a variety of number types, we
|
||||
need to tell Rust the exact type of number we want with <code>let guess: u32</code>. The
|
||||
colon (<code>:</code>) after <code>guess</code> tells Rust we’re going to annotate its type. Rust has
|
||||
a few built-in number types, but we’ve chosen <code>u32</code>, an unsigned, thirty-two
|
||||
bit integer. It’s a good default choice for a small positive number. You'll see
|
||||
the other number types in Chapter XX. Additionally, our <code>u32</code> annotation here
|
||||
and the comparison with <code>secret_number</code> means that Rust will infer that
|
||||
<code>secret_number</code> should be a <code>u32</code> as well. So now the comparison will be
|
||||
between two values of the same type!</p>
|
||||
<p>Our call to <code>parse</code> could quite easily cause an error. If, for example, our
|
||||
string contained <code>A👍%</code>, there’d be no way to convert that to a number. Because
|
||||
it might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
|
||||
<code>read_line</code> method does that we discussed earlier. We're going to treat this
|
||||
<code>Result</code> the same way by using the <code>expect</code> method again. If <code>parse</code>
|
||||
returns an <code>Err</code> <code>Result</code> variant because it could not create a number from the
|
||||
string, the <code>expect</code> call will crash the game and print the message we give
|
||||
it. If <code>parse</code> can successfully turn the string into a number, it will return
|
||||
the <code>Ok</code> variant of <code>Result</code>, and <code>expect</code> will return the number that we
|
||||
want that it will take out of the <code>Ok</code> value for us.</p>
|
||||
<p>Let’s try our program out!</p>
|
||||
<p>We create a variable named <code>guess</code>. But wait, doesn’t the program
|
||||
already have a variable named <code>guess</code>? It does, but Rust allows us to
|
||||
<em>shadow</em> the previous value of <code>guess</code> with a new one. This feature is often
|
||||
used in similar situations in which you want to convert a value from one type
|
||||
to another type. Shadowing lets us reuse the <code>guess</code> variable name rather than
|
||||
forcing us to create two unique variables, like <code>guess_str</code> and <code>guess</code> for
|
||||
example. (Chapter 3 covers shadowing in more detail.)</p>
|
||||
<p>We bind <code>guess</code> to the expression <code>guess.trim().parse()</code>. The <code>guess</code> in the
|
||||
expression refers to the original <code>guess</code> that was a <code>String</code> with the input in
|
||||
it. The <code>trim</code> method on a <code>String</code> instance will eliminate any whitespace at
|
||||
the beginning and end. <code>u32</code> can only contain numerical characters, but the
|
||||
user must press the Return key to satisfy <code>read_line</code>. When the user presses
|
||||
Return, a newline character is added to the string. For example, if the user
|
||||
types 5 and presses return, <code>guess</code> looks like this: <code>5\n</code>. The <code>\n</code> represents
|
||||
“newline,” the return key. The <code>trim</code> method eliminates <code>\n</code>, resulting in just
|
||||
<code>5</code>.</p>
|
||||
<p>The <a href="../std/primitive.str.html#method.parse"><code>parse</code> method on strings</a><!-- ignore --> parses a string into some
|
||||
kind of number. Because this method can parse a variety of number types, we
|
||||
need to tell Rust the exact number type we want by using <code>let guess: u32</code>. The
|
||||
colon (<code>:</code>) after <code>guess</code> tells Rust we’ll annotate the variable’s type. Rust
|
||||
has a few built-in number types; the <code>u32</code> seen here is an unsigned, 32-bit
|
||||
integer. It’s a good default choice for a small positive number. You’ll learn
|
||||
about other number types in Chapter 3. Additionally, the <code>u32</code> annotation in
|
||||
this example program and the comparison with <code>secret_number</code> means that Rust
|
||||
will infer that <code>secret_number</code> should be a <code>u32</code> as well. So now the
|
||||
comparison will be between two values of the same type!</p>
|
||||
<p>The call to <code>parse</code> could easily cause an error. If, for example, the string
|
||||
contained <code>A👍%</code>, there would be no way to convert that to a number. Because it
|
||||
might fail, the <code>parse</code> method returns a <code>Result</code> type, much like the
|
||||
<code>read_line</code> method does as discussed earlier in “Handling Potential Failure
|
||||
with the Result Type” on page XX. We’ll treat this <code>Result</code> the same way by
|
||||
using the <code>expect</code> method again. If <code>parse</code> returns an <code>Err</code> <code>Result</code> variant
|
||||
because it couldn’t create a number from the string, the <code>expect</code> call will
|
||||
crash the game and print the message we give it. If <code>parse</code> can successfully
|
||||
convert the string to a number, it will return the <code>Ok</code> variant of <code>Result</code>,
|
||||
and <code>expect</code> will return the number that we want from the <code>Ok</code> value.</p>
|
||||
<p>Let’s run the program now!</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/guessing_game`
|
||||
@@ -1040,14 +1047,14 @@ Please input your guess.
|
||||
You guessed: 76
|
||||
Too big!
|
||||
</code></pre>
|
||||
<p>Nice! You can see we even added spaces before our guess, and it still figured
|
||||
out that we guessed 76. Run the program a few times to verify the different
|
||||
behavior with different kinds of input: guess the number correctly, guess a
|
||||
number that is too high, and guess a number that is too low.</p>
|
||||
<p>Now we’ve got most of the game working, but we can only make one guess. Let’s
|
||||
change that by adding a loop!</p>
|
||||
<p>Nice! Even though spaces were added before the guess, the program still figured
|
||||
out that the user guessed 76. Run the program a few times to verify the
|
||||
different behavior with different kinds of input: guess the number correctly,
|
||||
guess a number that is too high, and guess a number that is too low.</p>
|
||||
<p>We have most of the game working now, but the user can make only one guess.
|
||||
Let’s change that by adding a loop!</p>
|
||||
<h2>Allowing Multiple Guesses with Looping</h2>
|
||||
<p>The <code>loop</code> keyword gives us an infinite loop. We'll add that in to give us more
|
||||
<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>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
@@ -1084,14 +1091,16 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>As you can see, we've moved everything from the guess input onwards into a
|
||||
loop. Make sure to indent those lines another four spaces each, and try it out.
|
||||
You'll notice we have a new problem because the program is doing exactly what we
|
||||
told it to do: ask for another guess forever! It doesn't seem like we can quit!</p>
|
||||
<p>We could always halt the program by using the keyboard shortcut <code>control-c</code>.
|
||||
There's another way to escape the insatiable monster we've created, though,
|
||||
that can be found in our discussion about <code>parse</code>: if we give a non-number
|
||||
answer, the program will crash. We can use that to quit! Observe:</p>
|
||||
<p>As you can see, we've moved everything into a loop from the guess input prompt
|
||||
onward. Be sure to indent those lines another four spaces each, and run the
|
||||
program again. Notice that there is a new problem because the program is doing
|
||||
exactly what we told it to do: ask for another guess forever! It doesn’t seem
|
||||
like the user can quit!</p>
|
||||
<p>The user could always halt the program by using the keyboard shortcut <code>Ctrl-C</code>.
|
||||
But there’s another way to escape this insatiable monster that we mentioned in
|
||||
the <code>parse</code> discussion in “Comparing the Guesses” on page XX: if the user
|
||||
enters a non-number answer, the program will crash. The user can take advantage
|
||||
of that in order to quit, as shown here:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/guessing_game`
|
||||
@@ -1115,11 +1124,11 @@ thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidD
|
||||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||||
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
|
||||
</code></pre>
|
||||
<p>This method means that typing <code>quit</code> actually quits the game, but so does any
|
||||
other non-number input. This is suboptimal, to say the least. We want the game
|
||||
to automatically stop when the correct number is guessed.</p>
|
||||
<h4>Quitting When you Win</h4>
|
||||
<p>Let’s program the game to quit when you win by adding a <code>break</code> in that case:</p>
|
||||
<p>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>
|
||||
<h4>Quitting After a Correct Guess</h4>
|
||||
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -1158,38 +1167,40 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>By adding the <code>break</code> line after <code>You win!</code>, we’ll exit the loop when we guess
|
||||
the secret number correctly. Exiting the loop also means exiting the program,
|
||||
since the loop is the last thing in <code>main</code>.</p>
|
||||
<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>
|
||||
<h4>Handling Invalid Input</h4>
|
||||
<p>For our final refinement of the game's behavior, rather than crashing the
|
||||
program when someone inputs a non-number, we want the game to ignore it so we
|
||||
can continue guessing. We can do that by altering the line where we convert
|
||||
<code>guess</code> from a <code>String</code> to a <code>u32</code>:</p>
|
||||
<p>To further refine the game’s behavior, rather than crashing the program when
|
||||
the user inputs a non-number, let’s make the game ignore a non-number so the
|
||||
user can continue guessing. We can do that by altering the line where <code>guess</code> is
|
||||
converted from a <code>String</code> to a <code>u32</code>:</p>
|
||||
<pre><code class="language-rust,ignore">let guess: u32 = match guess.trim().parse() {
|
||||
Ok(num) => num,
|
||||
Err(_) => continue,
|
||||
};
|
||||
</code></pre>
|
||||
<p>This is how you generally move from "crash on error" to "actually handle the
|
||||
error": by switching from an <code>expect</code> statement to a <code>match</code> statement.
|
||||
Remember that <code>parse</code> returns a <code>Result</code> type, and <code>Result</code> is an enum that
|
||||
has the variants <code>Ok</code> or <code>Err</code>. We're going to use a <code>match</code> statement here,
|
||||
like we did with the <code>Ordering</code> result of the <code>cmp</code> method.</p>
|
||||
<p>If <code>parse</code> is able to successfully turn the string into a number, it will
|
||||
return an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will
|
||||
match the first arm's pattern, and the match statement will just return the
|
||||
<code>num</code> value that <code>parse</code> produced and put inside the <code>Ok</code> value. That number
|
||||
will end up right where we want it, in the new <code>guess</code> variable we're creating.</p>
|
||||
<p>If <code>parse</code> is <em>not</em> able to turn the string into a number, it will return an
|
||||
<p>Switching from an <code>expect</code> call to a <code>match</code> expression is how you generally
|
||||
move from crash on error to actually handling the error. Remember that <code>parse</code>
|
||||
returns a <code>Result</code> type, and <code>Result</code> is an enum that has the variants <code>Ok</code> or
|
||||
<code>Err</code>. We're using a <code>match</code> expression here, like we did with the <code>Ordering</code>
|
||||
result of the <code>cmp</code> method.</p>
|
||||
<p>If <code>parse</code> is able to successfully turn the string into a number, it will return
|
||||
an <code>Ok</code> value that contains the resulting number. That <code>Ok</code> value will match the
|
||||
first arm’s pattern, and the <code>match</code> expression will just return the <code>num</code> value
|
||||
that <code>parse</code> produced and put inside the <code>Ok</code> value. That number will end up
|
||||
right where we want it in the new <code>guess</code> variable we’re creating.</p>
|
||||
<p>If <code>parse</code> is not able to turn the string into a number, it will return an
|
||||
<code>Err</code> value that contains more information about the error. The <code>Err</code> value
|
||||
does not match the <code>Ok(num)</code> pattern in the first match arm, but it does match
|
||||
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catch-all value; we're
|
||||
saying we want to match all <code>Err</code> values, no matter what information they have
|
||||
inside them. So we execute the second arm's code, <code>continue</code>: this means to go
|
||||
to the next iteration of the <code>loop</code> and ask for another guess. So we have
|
||||
effectively ignored all errors that <code>parse</code> might hit!</p>
|
||||
<p>Now everything in our program should work as we expect it to! Let’s try it:</p>
|
||||
the <code>Err(_)</code> pattern in the second arm. The <code>_</code> is a catchall value; in this
|
||||
example, we’re saying we want to match all <code>Err</code> values, no matter what
|
||||
information they have inside them. So the program will execute the second arm’s
|
||||
code, <code>continue</code>, which means to go to the next iteration of the loop and ask
|
||||
for another guess. So effectively, the program ignores all errors that <code>parse</code>
|
||||
might encounter!</p>
|
||||
<p>Now everything in the program should work as expected. Let’s try it by running
|
||||
<code>cargo run</code>:</p>
|
||||
<pre><code class="language-bash">$ cargo run
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
Running `target/guessing_game`
|
||||
@@ -1210,10 +1221,10 @@ Please input your guess.
|
||||
You guessed: 61
|
||||
You win!
|
||||
</code></pre>
|
||||
<p>Awesome! With one tiny last tweak, we can finish the guessing game: we're still
|
||||
printing out the secret number. That was good for testing, but it kind of ruins
|
||||
the game. Let's delete the <code>println!</code> that outputs the secret number. Here’s our
|
||||
full, final code:</p>
|
||||
<p>Awesome! With one tiny final tweak, we will finish the guessing game: recall
|
||||
that the program is still printing out the secret number. That worked well for
|
||||
testing, but it ruins the game. Let’s delete the <code>println!</code> that outputs the
|
||||
secret number. Listing 2-5 shows the final code:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
@@ -1239,6 +1250,8 @@ fn main() {
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
println!("You guessed: {}", guess);
|
||||
|
||||
match guess.cmp(&secret_number) {
|
||||
Ordering::Less => println!("Too small!"),
|
||||
Ordering::Greater => println!("Too big!"),
|
||||
@@ -1250,16 +1263,17 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<h2>Complete!</h2>
|
||||
<p>At this point, you have successfully built the Guessing Game! Congratulations!</p>
|
||||
<p>This project was a hands-on way to introduce you to a lot of new Rust concepts:
|
||||
<p>Listing 2-5: Complete code of the guessing game</p>
|
||||
<h2>Summary</h2>
|
||||
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
|
||||
<p>This project was a hands-on way to introduce you to many new Rust concepts:
|
||||
<code>let</code>, <code>match</code>, methods, associated functions, using external crates, and more.
|
||||
In the next few chapters, we will go through these concepts in more detail.
|
||||
Chapter 3 covers concepts that most programming languages have, like variables,
|
||||
data types, and functions, and shows how to use them in Rust. Chapter 4 gets
|
||||
into ownership, which is the feature of Rust that is most different from other
|
||||
languages. Chapter 5 discusses structs and method syntax, and Chapter 6
|
||||
endeavors to explain enums.</p>
|
||||
In the next few chapters, you’ll learn about these concepts in more detail.
|
||||
Chapter 3 covers concepts that most programming languages have, such as
|
||||
variables, data types, and functions, and shows how to use them in Rust.
|
||||
Chapter 4 explores ownership, which is a Rust feature that is most different
|
||||
from other languages. Chapter 5 discusses structs and method syntax, and
|
||||
Chapter 6 endeavors to explain enums.</p>
|
||||
<h1>Common Programming Concepts in Rust</h1>
|
||||
<p>Let's first look at concepts that appear in almost every programming language
|
||||
and see how they work in Rust. Many programming languages have much in common
|
||||
|
||||
Reference in New Issue
Block a user