diff --git a/nostarch/chapter01.md b/nostarch/chapter01.md index 2cbf8700da..b91f17f94b 100644 --- a/nostarch/chapter01.md +++ b/nostarch/chapter01.md @@ -26,9 +26,12 @@ well as how they work behind the scenes. ## Contributing to the book This book is open source. If you find an error, please don’t hesitate to file an -issue or send a pull request [on GitHub]. +issue or send a pull request on GitHub at *https://github.com/rust-lang/book*. -[on GitHub]: https://github.com/rust-lang/book + ## Installation @@ -65,6 +68,10 @@ If you're on Windows, please download the appropriate [installer][install-page]. [install-page]: https://www.rust-lang.org/install.html + + ### Uninstalling Uninstalling Rust is as easy as installing it. On Linux or Mac, just run @@ -99,7 +106,7 @@ If you don't and you're on Windows, check that Rust is in your `%PATH%` system variable. If it isn't, run the installer again, select "Change" on the "Change, repair, or remove installation" page and ensure "Add to PATH" is checked. -If not, there are a number of places where you can get help. The easiest is +If it still isn't working, there are a number of places where you can get help. The easiest is [the #rust IRC channel on irc.mozilla.org][irc], which you can access through [Mibbit][mibbit]. Click that link, and you'll be chatting with other Rustaceans (a silly nickname we call ourselves) who can help you out. Other great resources @@ -126,7 +133,7 @@ tradition. > Note: This book assumes basic familiarity with the command line. Rust itself > makes no specific demands about your editing, tooling, or where your code -> lives, so if you prefer an IDE to the command line, that's an option. +> lives, so if you prefer an IDE to the command line, feel free to use your favored IDE. ### Creating a Project File @@ -146,6 +153,9 @@ $ cd hello_world > your home directory may not work. > Consult the documentation for your shell for more details. + + ### Writing and Running a Rust Program Next, make a new source file and call it *main.rs*. Rust files always end with @@ -169,6 +179,9 @@ $ rustc main.rs $ ./main Hello, world! ``` + On Windows, just replace `main` with `main.exe`. Regardless of your operating system, you should see the string `Hello, world!` print to the terminal. If you @@ -189,12 +202,12 @@ fn main() { These lines define a *function* in Rust. The `main` function is special: it's the first thing that is run for every executable Rust program. The first line says, “I’m declaring a function named `main` that takes no arguments and -returns nothing.” If there were arguments, they would go inside the parentheses -(`(` and `)`). We aren’t returning anything from this function, so we have +returns nothing.” If there were arguments, they would go inside the parentheses, +`(` and `)`. -Also note that the function body is wrapped in curly braces (`{` and `}`). Rust +Also note that the function body is wrapped in curly braces, `{` and `}`. Rust requires these around all function bodies. It's considered good style to put the opening curly brace on the same line as the function declaration, with one space in between. @@ -207,7 +220,7 @@ Inside the `main()` function: This line does all of the work in this little program: it prints text to the screen. There are a number of details that are important here. The first is -that it’s indented with four spaces, not tabs. +that it’s indented with four spaces, not a tab. The second important part is `println!()`. This is calling a Rust *macro*, which is how metaprogramming is done in Rust. If it were calling a function @@ -252,6 +265,10 @@ On Windows, you'd enter: $ dir main.exe main.rs ``` + This shows we have two files: the source code, with the `.rs` extension, and the executable (`main.exe` on Windows, `main` everywhere else). All that's left to @@ -260,6 +277,7 @@ do from here is run the `main` or `main.exe` file, like this: ```bash $ ./main # or main.exe on Windows ``` + If *main.rs* were your "Hello, world!" program, this would print `Hello, world!` to your terminal. @@ -285,7 +303,7 @@ Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to manage their Rust projects because it makes a lot of tasks easier. For example, Cargo takes care of building your code, downloading the libraries your code depends on, and building those libraries. We call libraries your code needs -‘dependencies’ since your code depends on them. +*dependencies*. The simplest Rust programs, like the one we've written so far, don’t have any dependencies, so right now, you'd only be using the part of Cargo that can take @@ -304,8 +322,8 @@ $ cargo --version ``` If you see a version number, great! If you see an error like `command not -found`, then you should look at the documentation for the way you installed -Rust to determine how to install Cargo separately. +found`, then you should look at the documentation for your method of installation +to determine how to install Cargo separately. ### Creating a Project with Cargo @@ -326,8 +344,8 @@ $ cd hello_cargo We passed the `--bin` argument to `cargo new` because our goal is to make an executable application, as opposed to a library. Executables are often called -*binaries* (as in `/usr/bin`, if you’re on a Unix system). `hello_cargo` is the -name we've chosen for our project, and Cargo creates its files in a directory +*binaries* (as in `/usr/bin`, if you’re on a Unix system). We've given `hello_cargo` as the +name for our project, and Cargo creates its files in a directory of the same name that we can then go into. If we list the files in the `hello_cargo` directory, we can see that Cargo has @@ -412,6 +430,7 @@ This should have created an executable file in `target/debug/hello_cargo` (or `t $ ./target/debug/hello_cargo # or ./target/debug/hello_cargo.exe on Windows Hello, world! ``` + Bam! If all goes well, `Hello, world!` should print to the terminal once more. @@ -439,7 +458,7 @@ $ cargo run Hello, world! ``` -Notice that this time, we didn't see the output that Cargo was compiling +Notice that this time, we didn't see the output telling us that Cargo was compiling `hello_cargo`. Cargo figured out that the files haven’t changed, so it just ran the binary. If you had modified your source code, Cargo would have rebuilt the project before running it, and you would have seen something like this: @@ -477,7 +496,7 @@ projects composed of multiple crates, it’s much easier to let Cargo coordinate the build. With Cargo, you can just run `cargo build`, and it should work the right way. Even though this project is simple, it now uses much of the real tooling you’ll use for the rest of your Rust career. In fact, you can get -started with virtually all Rust projects you might find that you want to work +started with virtually all Rust projects you want to work on with the following commands: ```bash diff --git a/nostarch/chapter02.md b/nostarch/chapter02.md index 0deffef99e..ac1deb02f3 100644 --- a/nostarch/chapter02.md +++ b/nostarch/chapter02.md @@ -1,3 +1,12 @@ + +[TOC] + + + # Guessing Game Let's jump into Rust with a hands-on project! We’ll implement a classic @@ -6,9 +15,10 @@ 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. -## Set up +## Setting Up a New Project -Let’s set up a new project. Go to your projects directory, and create a new project using Cargo. +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: ```bash $ cd ~/projects @@ -16,11 +26,11 @@ $ cargo new guessing_game --bin $ cd guessing_game ``` -We pass the name of our project to `cargo new`, then the `--bin` flag, since +We pass the name of our project to `cargo new` and pass the `--bin` flag, since we’re going to be making another binary like in Chapter 1. -Take a look at the generated `Cargo.toml`: - +Take a look inside the generated `Cargo.toml` file: +Filename: Cargo.toml ```toml [package] name = "guessing_game" @@ -30,10 +40,10 @@ authors = ["Your Name "] [dependencies] ``` -If the authors information that Cargo got from your environment is not correct, -go ahead and fix that. +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. -And as we saw in the last chapter, `cargo new` generates a ‘Hello, world!’ for +And as we saw in the last chapter, `cargo new` generates a ‘Hello, world!’ program for us. Check out `src/main.rs`: ```rust @@ -60,8 +70,10 @@ file. ## Processing a Guess -Let’s get to it! The first thing we need to do for our guessing game is -allow our player to input a guess. Put this in your `src/main.rs`: +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 `src/main.rs`: ```rust,ignore use std::io; @@ -86,13 +98,15 @@ There’s a lot here! Let’s go over it, bit by bit. use std::io; ``` -We’ll need to take user input and then print the result as output. As such, we -need the `io` library from the standard library. Rust only imports a few things -by default into every program, [the ‘prelude’][prelude]. If it’s not in the -prelude, you’ll have to `use` it directly. Using the `std::io` library gets -you a number of useful `io`-related things, so that's what we've done here. +We’ll need to take user input and then print the result as output, and for that +functonality we need to import the `io` library from the standard `std` +library. By default, Rust only imports a few things into every program in the +‘prelude’(../std/prelude/index.html). If it’s not in the prelude, you’ll have +to `use` it directly by importing it into your program. Using the `std::io` +library gets you a number of useful `io`-related things, including the +functionality to accept user input. -[prelude]: ../std/prelude/index.html + ```rust,ignore fn main() { @@ -108,18 +122,24 @@ println!("Guess the number!"); println!("Please input your guess."); ``` -We previously learned in Chapter 1 that `println!()` is a macro that -prints a string to the screen. +As we learned in Chapter 1, `println!()` is a macro that prints a string to the +screen. This is just giving the game name and requesting input from the user. -### Variable Bindings +### Storing Values with Variable Bindings + + + +Next we need to store the user input. ```rust,ignore let mut guess = String::new(); ``` Now we’re getting interesting! There’s a lot going on in this little line. -The first thing to notice is that this is a let statement, which is -used to create what are called ‘variable bindings’. Here's an example: +The first thing to notice is that this is a `let` statement, which is +used to create ‘variable bindings’. Here's another example: ```rust,ignore let foo = bar; @@ -127,37 +147,46 @@ let foo = bar; This will create a new binding named `foo`, and bind it to the value `bar`. In many languages, this is called a ‘variable’, but Rust’s variable bindings have -a few tricks up their sleeves. +a few differences. -For example, they’re immutable by default. That’s why our example -uses `mut`: it makes a binding mutable, rather than immutable. +For example, they’re immutable by default. To make our binding mutable, our example +uses `mut` before the binding name. ```rust let foo = 5; // immutable. let mut bar = 5; // mutable ``` -Oh, and `//` will start a comment, until the end of the line. Rust ignores -everything in comments. +*Note: The `//` syntax will start a comment that continues until the end of the line. Rust ignores +everything in comments.* So now we know that `let mut guess` will introduce a mutable binding named -`guess`, but we have to look at the other side of the `=` for what it’s +`guess`, but we have to look at the other side of the `=` for the value it’s bound to: `String::new()`. `String` is a string type, provided by the standard library. A [`String`][string] is a growable, UTF-8 encoded bit of text. [string]: ../std/string/struct.String.html + -The `::new()` syntax uses `::` because this is an ‘associated function’ of +The `::` syntax in the `::new()` line indicates that `new()` is an *associated function* of a particular type. That is to say, it’s associated with `String` itself, rather than a particular instance of a `String`. Some languages call this a -‘static method’. +*static method*. + -This function is named `new()`, because it creates a new, empty `String`. +This `new()` function creates a new, empty `String`. You’ll find a `new()` function on many types, as it’s a common name for making a new value of some kind. + + Let’s move forward: ```rust,ignore @@ -165,13 +194,7 @@ io::stdin().read_line(&mut guess) .expect("Failed to read line"); ``` -Let’s go through this together bit-by-bit. The first line has two parts. Here’s -the first: - -```rust,ignore -io::stdin() -``` - +This two-line code first line has three parts, starting with `io::stdin()`. Remember how we `use`d `std::io` on the first line of the program? We’re now calling an associated function on it. If we didn’t `use std::io`, we could have written this line as `std::io::stdin()`. @@ -179,44 +202,50 @@ have written this line as `std::io::stdin()`. This particular function returns a handle to the standard input for your terminal. More specifically, a [std::io::Stdin][iostdin]. -[iostdin]: ../std/io/struct.Stdin.html + -The next part will use this handle to get input from the user: - -```rust,ignore -.read_line(&mut guess) -``` +[iostdin]: ../std/io/struct.Stdin.html + -Here, we call the [`read_line()`][read_line] method on our handle. We’re also +The next part, `.read_line(&mut guess)`, will use this handle to get input from the user. +We call the [`read_line()`][read_line] method on our handle. We’re also passing one argument to `read_line()`: `&mut guess`. +The job of `read_line()` is +to take whatever the user types as standard input and place that into a +string, so it takes that string as an argument; and in order to add +the input, that string needs to be mutable. + [read_line]: ../std/io/struct.Stdin.html#method.read_line + -Remember how we bound `guess` above? We said it was mutable. However, -`read_line` doesn’t take a `String` as an argument: it takes a `&mut String`. -The `&` is the feature of Rust called a ‘reference’, which allows you to have -multiple ways to access one piece of data in order to reduce copying. -References are a complex feature, as one of Rust’s major selling points is how +Remember that when we bound `guess` above, we made it mutable; +with `read_line` we make the string mutable with `&mut String`. +The `&` indicates that this is a `reference`, which allows you +multiple ways to access one piece of data to reduce the amount that you copy that data into memory. +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 them in +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 `let` bindings, references are immutable by default. Hence, we need to write `&mut guess`, -rather than `&guess`. +rather than `&guess` to make it mutable. -Why does `read_line()` take a mutable reference to a string? Its job is + -But we’re not quite done with this line of code, though. While it’s +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. This is the second part of the line: +code, with the second part a method: ```rust,ignore .expect("Failed to read line"); ``` -When you call a method with the `.foo()` syntax, you may introduce a newline +When you call a method with the `.foo()` syntax, it's often be wise to introduce a newline and other whitespace. This helps you split up long lines. We _could_ have written this code as: @@ -225,19 +254,20 @@ io::stdin().read_line(&mut guess).expect("failed to read line"); ``` But that gets hard to read. So we’ve split it up, two lines for two method -calls. +calls. Now let's see what this line does. + +### Checking Input with the Result Type -### The `Result` Type -We already talked about `read_line()`, but what about `expect()`? Well, -we already mentioned that `read_line()` puts what the user types into the `&mut -String` we pass it. But it also returns a value: in this case, an +We mentioned that `read_line()` puts what the user types into the `&mut +String` we pass it, but it also returns a value: in this case, an [`io::Result`][ioresult]. Rust has a number of types named `Result` in its standard library: a generic [`Result`][result], and then specific versions for sub-libraries, like `io::Result`. -[ioresult]: ../std/io/type.Result.html -[result]: ../std/result/enum.Result.html + The purpose of these `Result` types is to encode error handling information. Values of the `Result` type, like any type, have methods defined on them. In @@ -245,9 +275,14 @@ this case, `io::Result` has an [`expect()` method][expect] that takes a value it’s called on, and if it isn’t a successful result, will cause our program to crash and display the message that we passed as an argument to `expect()`. -[expect]: ../std/result/enum.Result.html#method.expect + -If we don't call this method, our program will compile, but we’ll get a warning: + + +If we don't call this method, when an incorrect value is input our program will compile, but we’ll get a warning: ```bash $ cargo build @@ -258,14 +293,12 @@ src/main.rs:10 io::stdin().read_line(&mut guess); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` -Rust warns us that we haven’t used the `Result` value. This warning comes from -a special annotation that `io::Result` has. Rust is trying to tell you that you +Rust warns that we haven’t used the `Result` value, telling you that you haven’t handled a possible error. The right way to suppress the error is to -actually write error handling. Luckily, if we want to crash if there’s a -problem, we can use `expect()`. If we can recover from the error somehow, we’d -do something else, but we’ll save that for a future project. +actually write error handling, but if we just want to crash the program when a +problem occurs, we can use `expect()`. We’ll save recovering from errors for a future project. -### `println!()` Placeholders +### Printing Values with println!() Placeholders There’s only one line of this first example left, aside from the closing curly brace: @@ -276,20 +309,23 @@ brace: ``` This prints out the string we saved our input in. The `{}`s are a placeholder: -think of `{}` as little crab pincers, holding a value in place. The first `{}` -holds the first value after the format string, the second set holds the second +think of `{}` as little crab pincers, holding a value in place. +You can print more than one value this way: the first `{}` +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 `println!()` would then look like this: ```rust let x = 5; let y = 10; -println!("x and y: {} and {}", x, y); +println!("x = {} and y = {}", x, y); ``` -Which would print out "x and y: 5 and 10". +Which would print out "x = 5 and y = 10". + +### Testing the First Part -Anyway, back to our guessing game. We can run what we have with `cargo run`: +Back to our guessing game, let's test what we have so far. We can run it with `cargo run`: ```bash $ cargo run @@ -304,19 +340,24 @@ You guessed: 6 All right! Our first part is done: we can get input from the keyboard and then print it back out. -## Generating a secret number +## Generating a Secret Number -Next, we need to generate a secret number. Rust does not yet include random +Next, we need to generate a secret number to compare the input guess against. Rust does not yet include random number functionality in its standard library. The Rust team does, however, -provide a [`rand` crate][randcrate]. A ‘crate’ is a package of Rust code. -We’ve been building a ‘binary crate’, which is an executable. `rand` is a -‘library crate’, which contains code that’s intended to be used with other +provide a [`rand` crate][randcrate]. + +### Using a Crate +A ‘crate’ is just the term for a package of Rust code. +The project we’ve been building is a ‘binary crate’, which is an executable. The `rand` crate is a +*library* crate, which contains code intended to be used with other programs. + + [randcrate]: https://crates.io/crates/rand -Using external crates is where Cargo really shines. Before we can write -the code using `rand`, we need to modify our `Cargo.toml`. Open it up, and +Cargo's use of external crates is where it really shines. Before we can write +the code using `rand`, we need to modify our `Cargo.toml` to include the `rand` crate as a dependency. Open it up, and add this line at the bottom beneath the `[dependencies]` section header that Cargo created for you: @@ -326,12 +367,12 @@ Cargo created for you: rand = "0.3.14" ``` -The `[dependencies]` section of `Cargo.toml` is like the `[package]` section: +In the `Cargo.toml` file everything that follows the section heading is part of that section, until -another section starts. Cargo uses the dependencies section to know what -dependencies on external crates you have and what versions of those crates you +another section starts. Cargo uses the `dependencies` 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 `rand` crate with the semantic -version specifier `0.3.14`. Cargo understands [Semantic Versioning][semver], a +version specifier `0.3.14`. Cargo understands [Semantic Versioning][semver](semver), a standard for writing version numbers. A bare number like above is actually shorthand for `^0.3.14`, which means "any version that has a public API compatible with version 0.3.14". @@ -350,20 +391,19 @@ $ cargo build Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) ``` -You may see different versions (but they will be compatible, thanks to semver!) +You may see different version numbers (but they will all be compatible, thanks to semver!) and the lines may be in a different order. Lots of new output! Now that we have an external dependency, Cargo fetches the latest versions of everything from the *registry*, which is a copy of data from -[Crates.io][cratesio]. Crates.io is where people in the Rust ecosystem +*https://crates.io*. Crates.io is where people in the Rust ecosystem post their open source Rust projects for others to use. -[cratesio]: https://crates.io After updating the registry, Cargo checks our `[dependencies]` and downloads -any we don’t have yet. In this case, while we only said we wanted to depend on -`rand`, we’ve also grabbed a copy of `libc`. This is because `rand` depends on -`libc` to work. After downloading them, it compiles them and then compiles +any we don’t have yet. In this case, while we only listed +`rand` as a dependency, we’ve also grabbed a copy of `libc`, because `rand` depends on +`libc` to work. After downloading them, Rust compiles them and then compiles our project. If we run `cargo build` again, we’ll get different output: @@ -382,27 +422,35 @@ we’ll only see one line: $ cargo build Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) ``` +This just updates the build with your tiny change to the* main.rs *file. + +#### The Cargo.lock File -What happens when next week version `v0.3.15` of the `rand` crate comes out, -with an important bugfix? While getting bugfixes is important, what if `0.3.15` -contains a regression that breaks our code? +Cargo has a few in-build security measures. Cargo will only use the versions of +the dependencies you specified until you say otherwise. For example, what +happens if next week version `v0.3.15` of the `rand` crate comes out, +containing an important bugfix, but that also contains a regression that will +break our code? The answer to this problem is the `Cargo.lock` file created the first time we ran `cargo build` that is now in your project directory. When you build your -project for the first time, Cargo figures out all of the versions that fit your +project for the first time, Cargo figures out all of the versions of the crate that fit your criteria then writes them to the `Cargo.lock` file. When you build your project -in the future, Cargo will see that the `Cargo.lock` file exists and then use -that specific version rather than do all the work of figuring out versions +in the future, Cargo will see that the `Cargo.lock` file exists and use +the versions specified there rather than do all the work of figuring out versions again. This lets you have a repeatable build automatically. In other words, -we’ll stay at `0.3.14` until we explicitly upgrade, and so will anyone who we -share our code with, thanks to the lock file. +our project will stay at `0.3.14` until we explicitly upgrade, thanks to the lock file. + +#### Updating a Crate + + -What about when we _do_ want to use `v0.3.15`? Cargo has another command, +When we _do_ want to update a crate, Cargo has another command, `update`, which says ‘ignore the `Cargo.lock` file and figure out all the -latest versions that fit what we’ve specified in `Cargo.toml`. If that works, +latest versions that fit our specifications in `Cargo.toml`. If that works, write those versions out to the lock file’. But by default, Cargo will only -look for versions larger than `0.3.0` and smaller than `0.4.0`. If we want to -move to `0.4.x`, we’d have to update what is in the `Cargo.toml` file. When we +look for versions larger than `0.3.0` and smaller than `0.4.0`. If we wanted to +move to `rand` version `0.4.x`, we’d have to update what is in the `Cargo.toml` file. When we do, the next time we `cargo build`, Cargo will update the index and re-evaluate our `rand` requirements. @@ -415,20 +463,27 @@ number of sub-packages. [doccargo]: http://doc.crates.io [doccratesio]: http://doc.crates.io/crates-io.html -Let’s get on to actually _using_ `rand`. Here’s our next step: +### Generating a Random Number + +Let’s get on to actually _using_ `rand`. Our next step is to update our *main.rs* code as follows: + + ```rust,ignore -extern crate rand; +**extern crate rand;** use std::io; -use rand::Rng; +**use rand::Rng;** fn main() { println!("Guess the number!"); - let secret_number = rand::thread_rng().gen_range(1, 101); +** let secret_number = rand::thread_rng().gen_range(1, 101);** - println!("The secret number is: {}", secret_number); + **println!("The secret number is: {}", secret_number);** println!("Please input your guess."); @@ -441,19 +496,17 @@ fn main() { } ``` -The first thing we’ve done is change the first line. It now says `extern crate -rand`. Because we declared `rand` in our `[dependencies]`, we can now put -`extern crate` in our code to let Rust know we’ll be making use of that -dependency. This also does the equivalent of a `use rand;` as well, so we can +First we've added a line to the top, `extern crate +rand`,that let's Rust know we’ll be making use of that +external dependency. This also does the equivalent of a `use rand;` command, so we can call anything in the `rand` crate by prefixing it with `rand::`. Next, we added another `use` line: `use rand::Rng`. We’re going to use a -method in a moment, and it requires that `Rng` be in scope to work. The basic -idea is this: methods are defined on something called ‘traits’, and for the -method to work, it needs the trait to be in scope. For more about the -details, read the traits section in Chapter XX. +range method in a moment, and it requires that the `Rng` trait be in scope to work. The basic +idea is this: methods are defined on *traits*, and for the +method to work, it needs the trait to be in scope. We'll cover traits in detail in the Traits section in Chapter XX. -There are two other lines we added, in the middle: +We also added two more lines in the middle: ```rust,ignore let secret_number = rand::thread_rng().gen_range(1, 101); @@ -462,9 +515,14 @@ println!("The secret number is: {}", secret_number); ``` We use the `rand::thread_rng()` function to get a copy of the random number -generator, which is local to the particular thread of execution -we’re in. Because we put `use rand::Rng` above, the random number generator has -a `gen_range()` method available. This method takes two numbers as arguments +generator, which is local to the particular thread of execution we’re in. By +using `use rand::Rng` above, we've made the random number generator +`gen_range()` method available from the `rand` crate. This method takes two +numbers as arguments + + + and generates a random number between them. It’s inclusive on the lower bound but exclusive on the upper bound, so we need `1` and `101` to ask for a number ranging from one to a hundred. @@ -495,18 +553,20 @@ You guessed: 5 ``` You should get different random numbers, and they should all be between 1 and -100. Great job! Next up: comparing our guess to the secret number. +100. Great job! -## Comparing guesses +## Comparing Our Guesses Now that we’ve got user input, let’s compare our guess to the secret number. -Here’s part of our next step. It won't quite compile yet though: +Here’s that part of our next step: + + ```rust,ignore extern crate rand; use std::io; -use std::cmp::Ordering; +**use std::cmp::Ordering;** use rand::Rng; fn main() { @@ -525,16 +585,19 @@ fn main() { println!("You guessed: {}", guess); - match guess.cmp(&secret_number) { + **match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), - } + }** } ``` -A few new bits here. The first is another `use`. We bring a type called -`std::cmp::Ordering` into scope. Then we add five new lines at the bottom that +There are a few new bits here. The first is another `use`, bringing a type called +`std::cmp::Ordering` into scope from the standard crate. + + +Then we add five new lines at the bottom that use that type: ```rust,ignore @@ -545,11 +608,19 @@ match guess.cmp(&secret_number) { } ``` -The `cmp()` method can be called on anything that can be compared, and it -takes a reference to the thing you want to compare it to. It returns the -`Ordering` type we `use`d earlier. We use a [`match`][match] statement to -determine exactly what kind of `Ordering` it is. `Ordering` is an -[`enum`][enum], short for ‘enumeration’, which looks like this: + + +The `cmp()` method compares two values, and can be called on anything that can +be compared. It takes a reference to the thing you want to compare it to, so +here it's comparing our `guess` to our `$secret_number` reference, and returns +the `Ordering` type we `use`d earlier. We use a [`match`][match] statement to +determine exactly what kind of `Ordering` it is. + + + +`Ordering` is an +[`enum`][enum], short for ‘enumeration’. Here's a simple example: ```rust enum Foo { @@ -558,6 +629,8 @@ enum Foo { } ``` + + [match]: match.html [enum]: enums.html @@ -565,12 +638,17 @@ With this definition, anything of type `Foo` can be either a `Foo::Bar` or a `Foo::Baz`. We use the `::` to indicate the namespace for a particular `enum` variant. + + The [`Ordering`][ordering] `enum` has three possible variants: `Less`, `Equal`, -and `Greater`. The `match` statement takes a value of a type and lets you -create an ‘arm’ for each possible value. An arm is made up of a pattern and the -code that we should execute if the pattern matches the value of the type. Since +and `Greater`. The `match` statement lets you +create an ‘arm’ for each possible value. An arm is the +code that we should execute if the pattern specified matches the value of the type. Since we have three types of `Ordering`, we have three arms: + + ```rust,ignore match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), @@ -581,10 +659,11 @@ match guess.cmp(&secret_number) { [ordering]: ../std/cmp/enum.Ordering.html -If it’s `Less`, we print `Too small!`, if it’s `Greater`, `Too big!`, and if -`Equal`, `You win!`. `match` is really useful and is used often in Rust. +If the `guess` is `Less` than the reference we compare it to, `$secret number`, +we print `Too small!`; if it’s `Greater`, `Too big!`; and if `Equal`, `You +win!`. The `match` command is really useful and is used often in Rust. -We did mention that this won’t quite compile yet, though. Let’s try it: +However, this code won’t quite compile yet. Let’s try it: ```bash $ cargo build @@ -599,96 +678,74 @@ error: aborting due to previous error Could not compile `guessing_game`. ``` -Whew! This is a big error. The core of it is that we have ‘mismatched types’. -Rust has a strong, static type system. However, it also has type inference. -When we wrote `let guess = String::new()`, Rust was able to infer that `guess` -should be a `String`, so it doesn’t make us write out the type. With our -`secret_number`, there are a number of types which can have a value between one -and a hundred: `i32`, a thirty-two-bit number, or `u32`, an unsigned -thirty-two-bit number, or `i64`, a sixty-four-bit number or others. So far, -that hasn’t mattered, and so Rust defaults to an `i32`. However, here, Rust -doesn’t know how to compare the `guess` and the `secret_number`. They need to -be the same type. +Whew! This is a big error. The core of the error says that we have ‘mismatched +types’. Rust has a strong, static type system. However, it also has type +inference. When we wrote `let guess = String::new()`, Rust was able to infer +that `guess` should be a `String`, and didn’t make us write the type out. Our +`secret_number` on the other hand is a number type; there are a few types which +can have a value between one and a hundred: `i32`, a thirty-two-bit number, or +`u32`, an unsigned thirty-two-bit number, or `i64`, a sixty-four-bit number or +others. Rust defaults to an `i32`. Here, Rust doesn’t know how to compare the +string `guess` and the i32 `secret_number` because they need to be the same +type in order to compare them. Ultimately, we want to convert the `String` we read as input into a real number type so that we can compare it to the guess numerically. We -can do that with two more lines. Here’s our new program: +can do that with two more lines; add this to your program: -```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(); +```rust,ignore +---snip--- io::stdin().read_line(&mut guess) .expect("failed to read line"); - let guess: u32 = guess.trim().parse() - .expect("Please type a number!"); + ** 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!"), - } -} +---snip--- ``` -The new two lines: +We bind a variable `guess`. But wait a minute, don't we already have a `guess`? +We do, but Rust allows us to ‘shadow’ the previous value of `guess` with a new +one. This is often used in this exact situation, where we want to convert a +string to a numerical type. Shadowing lets us re-use the `guess` variable name +rather than forcing us to come up with two unique bindings, like `guess_str` +and `guess` or something. -```rust,ignore -let guess: u32 = guess.trim().parse() - .expect("Please type a number!"); -``` - -Wait a minute, didn't we already have a `guess`? We do, but Rust allows us -to ‘shadow’ the previous `guess` with a new one. This is often used in this -exact situation, where `guess` starts as a `String`, but we want to convert it -to a `u32`. Shadowing lets us re-use the `guess` name rather than forcing us -to come up with two unique names like `guess_str` and `guess` or something -else. - -We bind `guess` to an expression that looks like something we wrote earlier: - -```rust,ignore +We bind `guess` to the expression +` guess.trim().parse() -``` +`. -Here, `guess` refers to the old `guess`, the one that was a `String` with our -input in it. The `trim()` method on `String`s will eliminate any white space at -the beginning and end of our string. This is important, as we had to press the -‘return’ key to satisfy `read_line()`. If we type `5` and hit return, `guess` -looks like this: `5\n`. The `\n` represents ‘newline’, the enter key. `trim()` -gets rid of this, leaving our string with only the `5`. +Here, `guess` refers to the original `guess` that was a `String` with our input +in it. The `trim()` method on `String`s will eliminate any white space at the +beginning and end of our string. This is important, because our u32 can only +contain numerical characters, but we have to press the ‘return’ key to satisfy +`read_line()` and when we do that it introduces a newline character. For +example, if we type `5` and hit return, `guess` looks like this: `5\n`. The +`\n` represents ‘newline’, the enter key. The `trim()` method gets rid of this, +leaving our string with only the `5`. The [`parse()` method on strings][parse] parses a string into some kind of -number. Since it can parse a variety of numbers, we need to give Rust a hint as -to the exact type of number we want. Hence, `let guess: u32`. The colon (`:`) -after `guess` tells Rust we’re going to annotate its type. `u32` is an -unsigned, thirty-two bit integer. Rust has a number of built-in number -types, but we’ve chosen `u32`. It’s a good default choice for a small -positive number. You'll see the other number types in Chapter XX. +number. Since it can parse a variety of number types, we need to tell Rust the +exact type of number we want with `let guess: u32`. The colon (`:`) after +`guess` tells Rust we’re going to annotate its type. Rust has a number of +built-in number types, but we’ve chosen `u32`, 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. [parse]: ../std/primitive.str.html#method.parse -Just like `read_line()`, our call to `parse()` could cause an error. What if -our string contained `A👍%`? There’d be no way to convert that to a number. As +Our call to `parse()` could quite easily cause an error, if, for example, our +string contained `A👍%`; there’d be no way to convert that to a number. As such, we’ll do the same thing we did with `read_line()`: use the `expect()` -method to crash if there’s an error. +method to crash the game if there’s an error. Let’s try our program out! @@ -705,22 +762,19 @@ Too big! ``` Nice! You can see we even added spaces before our guess, and it still figured -out that we guessed 76. Run the program a few times. Verify that guessing -the secret number works, as well as guessing a number too small. +out that we guessed 76. Run the program a few times to verify the different +options; guessing the number, guessing too high, and guessing too low. Now we’ve got most of the game working, but we can only make one guess. Let’s change that by adding loops! -## Looping +## Adding More Guesses with Looping -The `loop` keyword gives us an infinite loop. Let’s add that in: +The `loop` keyword gives us an infinite loop. We'll add that in to give us more +chances at guessing the number: ```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; +---Snip--- fn main() { println!("Guess the number!"); @@ -729,7 +783,7 @@ fn main() { println!("The secret number is: {}", secret_number); - loop { +** loop {** println!("Please input your guess."); let mut guess = String::new(); @@ -746,14 +800,18 @@ fn main() { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), - } + ** }** } } ``` -And try it out. But wait, didn’t we just add an infinite loop? Yup. Remember -our discussion about `parse()`? If we give a non-number answer, the program -will crash and, therefore, quit. Observe: +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. +However, now we have a new problem: We just added an infinite loop, doesn't +that mean we can't quit? + +One solution would be found from our discussion about `parse()`---if we give a +non-number answer the program will crash, and we can use that to quit. Observe: ```bash $ cargo run @@ -780,22 +838,17 @@ note: Run with `RUST_BACKTRACE=1` for a backtrace. error: Process didn't exit successfully: `target/debug/guess` (exit code: 101) ``` -Ha! `quit` actually quits. As does any other non-number input. Well, this is -suboptimal to say the least. First, let’s actually quit when you win the game: +This method means that typing `quit` 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. -```rust,ignore -extern crate rand; +#### Quitting When you Win -use std::io; -use std::cmp::Ordering; -use rand::Rng; +Let’s program the game to quit when you win by adding a `break` to the end of +the loop: -fn main() { - println!("Guess the number!"); - - let secret_number = rand::thread_rng().gen_range(1, 101); - - println!("The secret number is: {}", secret_number); +```rust,ignore +---snip--- loop { println!("Please input your guess."); @@ -815,33 +868,25 @@ fn main() { Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); - break; + ** break;** } } } } ``` -By adding the `break` line after the `You win!`, we’ll exit the loop when we -win. Exiting the loop also means exiting the program, since the loop is the last -thing in `main()`. We have another tweak to make: when someone inputs a -non-number, we don’t want to quit, we want to ignore it. We can do that -like this: - -```rust,ignore -extern crate rand; - -use std::io; -use std::cmp::Ordering; -use rand::Rng; - -fn main() { - println!("Guess the number!"); +By adding the `break` line after `You win!`, we’ll exit the loop when we enter +a correct guess. Exiting the loop also means exiting the program, since the +loop is the last thing in `main()`. - let secret_number = rand::thread_rng().gen_range(1, 101); +#### Handling Incorrect Input - println!("The secret number is: {}", secret_number); +For our final refinement, rather than quitting the loop when someone inputs a +non-number, we want the game to ignore it so we can continue guessing. We can +do that by altering our `guess` line: +```rust,ignore +---snip--- loop { println!("Please input your guess."); @@ -850,10 +895,10 @@ fn main() { io::stdin().read_line(&mut guess) .expect("failed to read line"); - let guess: u32 = match guess.trim().parse() { + ** let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, - }; + };** println!("You guessed: {}", guess); @@ -869,28 +914,28 @@ fn main() { } ``` -These are the lines that changed: - -```rust,ignore -let guess: u32 = match guess.trim().parse() { - Ok(num) => num, - Err(_) => continue, -}; -``` - This is how you generally move from ‘crash on error’ to ‘actually handle the -error’: by switching from `expect()` to a `match` statement. A `Result` is the +error’: by switching from an `expect()` statement to a `match` statement. A +`Result` is the + return type of `parse()`. `Result` is an `enum` like `Ordering`, but in this -case, each variant has some data associated with it. `Ok` is a success, and -`Err` is a failure. Each contains more information: in this case, the -successfully parsed integer or an error type, respectively. When we `match` an -`Ok(num)`, that pattern sets the name `num` to the value inside the `Ok` (the -integer), and the code we run just returns that integer. In the `Err` case, we -don’t care what kind of error it is, so we just use the catch-all `_` instead -of a name. So for all errors, we run the code `continue`, which lets us move to -the next iteration of the loop, effectively ignoring the errors. - -Now we should be good! Let’s try it: +case, each variant has some data associated with it: `Ok` indicates a success, +and contains the successfully parsed integer, and +`Err` indicated a failure, containing an error type. + +When we `match` an `Ok(num)` to the input, that pattern sets the name `num` to +the value inside the `Ok` (the + +integer), and the code we run just returns that integer. In the `Err` case we +use the catch-all `_` error message instead of a name because we don’t care +what kind of error it is. This means for all errors, the code `continue` code +will run, which lets us move to the next iteration of the loop, effectively +ignoring the errors. + +Now everything in our program should work as we expect it to! Let’s try it: ```bash $ cargo run @@ -914,10 +959,10 @@ You guessed: 61 You win! ``` -Awesome! With one tiny last tweak, we can finish the guessing game. Can you -think of what it is? That’s right, we don’t want to print out the secret -number. It was good for testing, but it kind of ruins the game. Here’s our -final source: +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, so delete the `println!` that outputs the secret number. Here’s our +full final code: ```rust,ignore extern crate rand; @@ -960,7 +1005,11 @@ fn main() { ## Complete! -This project showed you a lot: `let`, `match`, methods, associated -functions, using external crates, and more. + + +This project showed you a lot of new Rust concepts: `let`, `match`, methods, associated +functions, using external crates, and more. In the next few chapters..... At this point, you have successfully built the Guessing Game! Congratulations!