mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 22:21:17 -06:00
964 lines
56 KiB
HTML
964 lines
56 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Guessing Game Tutorial - The Rust Programming Language</title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body class="light">
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li><a href="ch01-00-introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="ch01-01-installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="ch01-02-hello-world.html"><strong>1.2.</strong> Hello, World!</a></li></ul></li><li><a href="ch02-00-guessing-game-tutorial.html" class="active"><strong>2.</strong> Guessing Game Tutorial</a></li><li><a href="ch03-00-common-programming-concepts.html"><strong>3.</strong> Common Programming Concepts</a></li><li><ul class="section"><li><a href="ch03-01-variables-and-mutability.html"><strong>3.1.</strong> Variables and Mutability</a></li><li><a href="ch03-02-data-types.html"><strong>3.2.</strong> Data Types</a></li><li><a href="ch03-03-how-functions-work.html"><strong>3.3.</strong> How Functions Work</a></li><li><a href="ch03-04-comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="ch03-05-control-flow.html"><strong>3.5.</strong> Control Flow</a></li></ul></li><li><a href="ch04-00-understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ch04-01-what-is-ownership.html"><strong>4.1.</strong> What is Ownership?</a></li><li><a href="ch04-02-references-and-borrowing.html"><strong>4.2.</strong> References & Borrowing</a></li><li><a href="ch04-03-slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="ch05-00-structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><a href="ch05-01-method-syntax.html"><strong>5.1.</strong> Method Syntax</a></li></ul></li><li><a href="ch06-00-enums.html"><strong>6.</strong> Enums and Pattern Matching</a></li><li><ul class="section"><li><a href="ch06-01-defining-an-enum.html"><strong>6.1.</strong> Defining an Enum</a></li><li><a href="ch06-02-match.html"><strong>6.2.</strong> The <code>match</code> Control Flow Operator</a></li><li><a href="ch06-03-if-let.html"><strong>6.3.</strong> Concise Control Flow with <code>if let</code></a></li></ul></li><li><a href="ch07-00-modules.html"><strong>7.</strong> Modules</a></li><li><ul class="section"><li><a href="ch07-01-mod-and-the-filesystem.html"><strong>7.1.</strong> <code>mod</code> and the Filesystem</a></li><li><a href="ch07-02-controlling-visibility-with-pub.html"><strong>7.2.</strong> Controlling Visibility with <code>pub</code></a></li><li><a href="ch07-03-importing-names-with-use.html"><strong>7.3.</strong> Importing Names with <code>use</code></a></li></ul></li><li><a href="ch08-00-fundamental-collections.html"><strong>8.</strong> Fundamental Collections</a></li><li><ul class="section"><li><a href="ch08-01-vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="ch08-02-strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="ch08-03-hash-maps.html"><strong>8.3.</strong> Hash Maps</a></li></ul></li><li><a href="ch09-00-error-handling.html"><strong>9.</strong> Error Handling</a></li><li><ul class="section"><li><a href="ch09-01-unrecoverable-errors-with-panic.html"><strong>9.1.</strong> Unrecoverable Errors with <code>panic!</code></a></li><li><a href="ch09-02-recoverable-errors-with-result.html"><strong>9.2.</strong> Recoverable Errors with <code>Result</code></a></li><li><a href="ch09-03-to-panic-or-not-to-panic.html"><strong>9.3.</strong> To <code>panic!</code> or Not To <code>panic!</code></a></li></ul></li><li><a href="ch10-00-generics.html"><strong>10.</strong> Generics</a></li><li><ul class="section"><li><a href="ch10-01-syntax.html"><strong>10.1.</strong> Syntax</a></li><li><a href="ch10-02-traits.html"><strong>10.2.</strong> Traits</a></li><li><a href="ch10-03-lifetime-syntax.html"><strong>10.3.</strong> Lifetime syntax</a></li></ul></li><li><a href="ch11-00-testing.html"><strong>11.</strong> Testing</a></li><li><ul class="section"><li><a href="ch11-01-writing-tests.html"><strong>11.1.</strong> Writing tests</a></li><li><a href="ch11-02-running-tests.html"><strong>11.2.</strong> Running tests</a></li><li><a href="ch11-03-test-organization.html"><strong>11.3.</strong> Test Organization</a></li></ul></li><li><a href="ch12-00-an-io-project.html"><strong>12.</strong> An I/O Project</a></li><li><ul class="section"><li><a href="ch12-01-accepting-command-line-arguments.html"><strong>12.1.</strong> Accepting Command Line Arguments</a></li><li><a href="ch12-02-reading-a-file.html"><strong>12.2.</strong> Reading a File</a></li><li><a href="ch12-03-improving-error-handling-and-modularity.html"><strong>12.3.</strong> Improving Error Handling and Modularity</a></li><li><a href="ch12-04-testing-the-librarys-functionality.html"><strong>12.4.</strong> Testing the Library's Functionality</a></li><li><a href="ch12-05-working-with-environment-variables.html"><strong>12.5.</strong> Working with Environment Variables</a></li><li><a href="ch12-06-writing-to-stderr-instead-of-stdout.html"><strong>12.6.</strong> Writing to <code>stderr</code> instead of <code>stdout</code></a></li></ul></li><li><a href="ch13-00-functional-features.html"><strong>13.</strong> Functional Language Features in Rust</a></li><li><ul class="section"><li><a href="ch13-01-closures.html"><strong>13.1.</strong> Closures</a></li><li><a href="ch13-02-iterators.html"><strong>13.2.</strong> Iterators</a></li><li><a href="ch13-03-improving-our-io-project.html"><strong>13.3.</strong> Improving our I/O Project</a></li><li><a href="ch13-04-performance.html"><strong>13.4.</strong> Performance</a></li></ul></li><li><a href="ch14-00-more-about-cargo.html"><strong>14.</strong> More about Cargo and Crates.io</a></li><li><ul class="section"><li><a href="ch14-01-release-profiles.html"><strong>14.1.</strong> Release Profiles</a></li><li><a href="ch14-02-publishing-to-crates-io.html"><strong>14.2.</strong> Publishing a Crate to Crates.io</a></li><li><a href="ch14-03-cargo-workspaces.html"><strong>14.3.</strong> Cargo Workspaces</a></li><li><a href="ch14-04-installing-binaries.html"><strong>14.4.</strong> Installing Binaries from Crates.io with <code>cargo install</code></a></li><li><a href="ch14-05-extending-cargo.html"><strong>14.5.</strong> Extending Cargo with Custom Commands</a></li></ul></li><li><a href="ch15-00-smart-pointers.html"><strong>15.</strong> Smart Pointers</a></li><li><a href="ch16-00-concurrency.html"><strong>16.</strong> Concurrency</a></li><li><a href="ch17-00-oop.html"><strong>17.</strong> Is Rust OOP?</a></li><li><a href="ch18-00-patterns.html"><strong>18.</strong> Patterns</a></li><li><a href="ch19-00-more-lifetimes.html"><strong>19.</strong> More Lifetimes</a></li><li><a href="ch20-00-advanced-types.html"><strong>20.</strong> Advanced Type System Features</a></li><li><a href="appendix-00.html"><strong>21.</strong> Appendix</a></li><li><ul class="section"><li><a href="appendix-01-keywords.html"><strong>21.1.</strong> Keywords</a></li><li><a href="appendix-02-operators.html"><strong>21.2.</strong> Operators</a></li><li><a href="appendix-03-derivable-traits.html"><strong>21.3.</strong> Derivable Traits</a></li><li><a href="appendix-04-nightly-rust.html"><strong>21.4.</strong> Nightly Rust</a></li><li><a href="appendix-05-macros.html"><strong>21.5.</strong> Macros</a></li></ul></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar" class="menu-bar">
|
||
<div class="left-buttons">
|
||
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
||
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Rust Programming Language</h1>
|
||
|
||
<div class="right-buttons">
|
||
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="content" class="content">
|
||
<h1>Guessing Game</h1>
|
||
<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 100. It
|
||
will then prompt the player to enter a guess. After entering a guess, it will
|
||
indicate whether the guess is too low or too high. If the guess is correct, the
|
||
game will print congratulations and exit.</p>
|
||
<h2>Setting Up a New Project</h2>
|
||
<p>To set up a new project, go to the <em>projects</em> directory that you created in
|
||
Chapter 1, and make a new project using Cargo, like so:</p>
|
||
<pre><code class="language-text">$ cargo new guessing_game --bin
|
||
$ cd guessing_game
|
||
</code></pre>
|
||
<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 <em>Cargo.toml</em> file:</p>
|
||
<p><span class="filename">Filename: Cargo.toml</span></p>
|
||
<pre><code class="language-toml">[package]
|
||
name = "guessing_game"
|
||
version = "0.1.0"
|
||
authors = ["Your Name <you@example.com>"]
|
||
|
||
[dependencies]
|
||
</code></pre>
|
||
<p>If the author information that Cargo 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 <em>src/main.rs</em> file:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust">fn main() {
|
||
println!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<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-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Hello, world!
|
||
</code></pre>
|
||
<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 <em>src/main.rs</em> file. You’ll be writing all the code in this file.</p>
|
||
<h2>Processing a Guess</h2>
|
||
<p>The first part of the program will ask for user input, process that input, and
|
||
check that the input is in the expected form. To start, we’ll allow the player
|
||
to input a guess. Enter the code in Listing 2-1 into <em>src/main.rs</em>.</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">use std::io;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-1: Code to get a guess from the user and print it out</p>
|
||
</figcaption>
|
||
</figure>
|
||
<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>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>The <code>fn</code> syntax declares a new function, the <code>()</code> indicate there are no
|
||
parameters, 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>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’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 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 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 starts a comment that continues until the end of the
|
||
line. Rust ignores everything in comments.</p>
|
||
</blockquote>
|
||
<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 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>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 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. 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 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>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>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 --> 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 <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. 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-text">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
src/main.rs:10:5: 10:39 warning: unused result which must be used,
|
||
#[warn(unused_must_use)] on by default
|
||
src/main.rs:10 io::stdin().read_line(&mut guess);
|
||
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||
</code></pre>
|
||
<p>Rust warns that we haven’t used the <code>Result</code> value 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>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 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>This code would print out <code>x = 5 and y = 10</code>.</p>
|
||
<h3>Testing the First Part</h3>
|
||
<p>Let’s test the first part of the guessing game. You can run it using <code>cargo run</code>:</p>
|
||
<pre><code class="language-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
Please input your guess.
|
||
6
|
||
You guessed: 6
|
||
</code></pre>
|
||
<p>At this point, the first part of the game is done: we’re getting input from the
|
||
keyboard and then printing it.</p>
|
||
<h2>Generating a Secret Number</h2>
|
||
<p>Next, we need to generate a secret number that the user will try to guess. The
|
||
secret number should be different every time so the game is fun to play more
|
||
than once. Let’s use a random number between 1 and 100 so the game isn’t too
|
||
difficult. Rust doesn’t yet include random number functionality in its standard
|
||
library. However, the Rust team does provide a <a href="https://crates.io/crates/rand"><code>rand</code> crate</a>.</p>
|
||
<h3>Using a Crate to Get More Functionality</h3>
|
||
<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 <em>Cargo.toml</em> 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><span class="filename">Filename: Cargo.toml</span></p>
|
||
<pre><code class="language-toml">[dependencies]
|
||
|
||
rand = "0.3.14"
|
||
</code></pre>
|
||
<p>In the <em>Cargo.toml</em> file, everything that follows a header is part of a section
|
||
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 0.3.14.”</p>
|
||
<p>Now, without changing any of the code, let’s build the project, as shown in
|
||
Listing 2-2:</p>
|
||
<figure>
|
||
<pre><code class="language-text">$ cargo build
|
||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||
Downloading rand v0.3.14
|
||
Downloading libc v0.2.14
|
||
Compiling libc v0.2.14
|
||
Compiling rand v0.3.14
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-2: The output from running <code>cargo build</code> after adding the rand crate
|
||
as a dependency</p>
|
||
</figcaption>
|
||
</figure>
|
||
<p>You may see different version numbers (but they will all be compatible with
|
||
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
|
||
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 <em>Cargo.toml</em>
|
||
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 <em>src/main.rs</em> file, make a trivial change, then save it and build again,
|
||
you’ll only see one line of output:</p>
|
||
<pre><code class="language-text">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
</code></pre>
|
||
<p>This line shows Cargo only updates the build with your tiny change to the
|
||
<em>src/main.rs</em> file. Your dependencies haven't changed, so Cargo knows it can
|
||
reuse what it has already downloaded and compiled for those. It just rebuilds
|
||
your part of the code.</p>
|
||
<h4>The <em>Cargo.lock</em> File Ensures Reproducible Builds</h4>
|
||
<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 <em>Cargo.lock</em> file, which was created the
|
||
first time you ran <code>cargo build</code> and is now in your <em>guessing_game</em> 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 <em>Cargo.lock</em> file. When you build your project in the future, Cargo will
|
||
see that the <em>Cargo.lock</em> 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 <em>Cargo.lock</em>
|
||
file.</p>
|
||
<h4>Updating a Crate to Get a New Version</h4>
|
||
<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 <em>Cargo.lock</em> file and figure out all the latest versions that fit
|
||
your specifications in <em>Cargo.toml</em>.</li>
|
||
<li>If that works, Cargo will write those versions to the <em>Cargo.lock</em> 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>, you would see the following if you ran <code>cargo update</code>:</p>
|
||
<pre><code class="language-text">$ 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 <em>Cargo.lock</em> file noting
|
||
that the version of the <code>rand</code> crate you are now using is <code>0.3.15</code>.</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 <em>Cargo.toml</em> file to look like this instead:</p>
|
||
<pre><code class="language-toml">[dependencies]
|
||
|
||
rand = "0.4.0"
|
||
</code></pre>
|
||
<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 Chapter 14 will discuss, but for
|
||
now, that’s all you need to know. Cargo makes it very easy to reuse libraries,
|
||
so Rustaceans are able to write smaller projects that are assembled from a
|
||
number of packages.</p>
|
||
<h3>Generating a Random Number</h3>
|
||
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <em>src/main.rs</em>, as shown
|
||
in Listing 2-3:</p>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-3: Code changes needed in order to generate a random number</p>
|
||
</figcaption>
|
||
</figure>
|
||
<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. 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-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 7
|
||
Please input your guess.
|
||
4
|
||
You guessed: 4
|
||
$ cargo run
|
||
Running `target/debug/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 83
|
||
Please input your guess.
|
||
5
|
||
You guessed: 5
|
||
</code></pre>
|
||
<p>You should get different random numbers, and they should all be numbers between
|
||
1 and 100. Great job!</p>
|
||
<h2>Comparing 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>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-4: Handling the possible return values of comparing two numbers</p>
|
||
</figcaption>
|
||
</figure>
|
||
<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>
|
||
<p>Then we add five new lines at the bottom that use the <code>Ordering</code> type:</p>
|
||
<pre><code class="language-rust,ignore">match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
</code></pre>
|
||
<p>The <code>cmp</code> method compares two values and can be called on anything that can be
|
||
compared. It takes a reference to whatever you want to compare with: 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>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 19, 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::Less</code>. So it ignores the code in that arm and moves to the next arm.
|
||
The next arm’s pattern, <code>Ordering::Greater</code>, <em>does</em> 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-text">$ cargo build
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
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>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 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><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>The two new lines are:</p>
|
||
<pre><code class="language-rust,ignore">let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
</code></pre>
|
||
<p>We create a variable 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-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 58
|
||
Please input your guess.
|
||
76
|
||
You guessed: 76
|
||
Too big!
|
||
</code></pre>
|
||
<p>Nice! 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. Add that now to give users more
|
||
chances at guessing the number:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => println!("You win!"),
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>As you can see, we’ve moved everything 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-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 59
|
||
Please input your guess.
|
||
45
|
||
You guessed: 45
|
||
Too small!
|
||
Please input your guess.
|
||
60
|
||
You guessed: 60
|
||
Too big!
|
||
Please input your guess.
|
||
59
|
||
You guessed: 59
|
||
You win!
|
||
Please input your guess.
|
||
quit
|
||
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:785
|
||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||
error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)
|
||
</code></pre>
|
||
<p>Typing <code>quit</code> actually quits the game, but so will any other non-number input.
|
||
However, this is suboptimal to say the least. We want the game to automatically
|
||
stop when the correct number is guessed.</p>
|
||
<h3>Quitting After a Correct Guess</h3>
|
||
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
|
||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
println!("The secret number is: {}", secret_number);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = guess.trim().parse()
|
||
.expect("Please type a number!");
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => {
|
||
println!("You win!");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>By adding the <code>break</code> line after <code>You win!</code>, the program will exit the loop
|
||
when the user guesses the secret number correctly. Exiting the loop also means
|
||
exiting the program, because the loop is the last part of <code>main</code>.</p>
|
||
<h3>Handling Invalid Input</h3>
|
||
<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>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 <em>not</em> able to turn the string into a number, it will return an
|
||
<code>Err</code> value that contains more information about the error. The <code>Err</code> value
|
||
does not match the <code>Ok(num)</code> pattern in the first <code>match</code> arm, but it does match
|
||
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 <code>loop</code> 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-text">$ cargo run
|
||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||
Running `target/guessing_game`
|
||
Guess the number!
|
||
The secret number is: 61
|
||
Please input your guess.
|
||
10
|
||
You guessed: 10
|
||
Too small!
|
||
Please input your guess.
|
||
99
|
||
You guessed: 99
|
||
Too big!
|
||
Please input your guess.
|
||
foo
|
||
Please input your guess.
|
||
61
|
||
You guessed: 61
|
||
You win!
|
||
</code></pre>
|
||
<p>Awesome! With one tiny 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>
|
||
<figure>
|
||
<span class="filename">Filename: src/main.rs</span>
|
||
<pre><code class="language-rust,ignore">extern crate rand;
|
||
|
||
use std::io;
|
||
use std::cmp::Ordering;
|
||
use rand::Rng;
|
||
|
||
fn main() {
|
||
println!("Guess the number!");
|
||
|
||
let secret_number = rand::thread_rng().gen_range(1, 101);
|
||
|
||
loop {
|
||
println!("Please input your guess.");
|
||
|
||
let mut guess = String::new();
|
||
|
||
io::stdin().read_line(&mut guess)
|
||
.expect("Failed to read line");
|
||
|
||
let guess: u32 = match guess.trim().parse() {
|
||
Ok(num) => num,
|
||
Err(_) => continue,
|
||
};
|
||
|
||
println!("You guessed: {}", guess);
|
||
|
||
match guess.cmp(&secret_number) {
|
||
Ordering::Less => println!("Too small!"),
|
||
Ordering::Greater => println!("Too big!"),
|
||
Ordering::Equal => {
|
||
println!("You win!");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
</code></pre>
|
||
<figcaption>
|
||
<p>Listing 2-5: Complete code of the guessing game</p>
|
||
</figcaption>
|
||
</figure>
|
||
<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, 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>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="ch01-02-hello-world.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="ch03-00-common-programming-concepts.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="ch01-02-hello-world.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="ch03-00-common-programming-concepts.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<!-- Local fallback for Font Awesome -->
|
||
<script>
|
||
if ($(".fa").css("font-family") !== "FontAwesome") {
|
||
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
||
}
|
||
</script>
|
||
|
||
<!-- Livereload script (if served using the cli tool) -->
|
||
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|