From 7bfbc68a4fc94c2dfd4a5807d3694657faa7a8ef Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Fri, 19 Aug 2016 17:13:41 -0400 Subject: [PATCH] Changes shipped to nostarch 2016-08-19 --- nostarch/chapter01.md | 188 +++++----- nostarch/chapter02.md | 780 ++++++++++++++++++++++-------------------- nostarch/chapter03.md | 108 +++++- nostarch/chapter04.md | 103 +++--- nostarch/chapter05.md | 47 ++- nostarch/chapter06.md | 52 +-- 6 files changed, 709 insertions(+), 569 deletions(-) diff --git a/nostarch/chapter01.md b/nostarch/chapter01.md index 2cbf8700d..f4dc4150e 100644 --- a/nostarch/chapter01.md +++ b/nostarch/chapter01.md @@ -26,9 +26,7 @@ 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]. - -[on GitHub]: https://github.com/rust-lang/book +issue or send a pull request on GitHub at *https://github.com/rust-lang/book*. ## Installation @@ -61,22 +59,24 @@ Rust is installed now. Great! ### Installing on Windows -If you're on Windows, please download the appropriate [installer][install-page]. +If you're on Windows, please go to *https://rustup.rs/* and follow +the instructions to download rustup-init.exe. Run that and follow the rest of +the instructions. -[install-page]: https://www.rust-lang.org/install.html +The rest of the Windows-specific commands in the book will assume that you are +using `cmd` as your shell. If you use a different shell, you may be able to run +the same commands that Linux and Mac users do. If neither work, consult the +documentation for the shell you are using. ### Uninstalling -Uninstalling Rust is as easy as installing it. On Linux or Mac, just run +Uninstalling Rust is as easy as installing it. From your shell, run the uninstall script: ```bash $ rustup self uninstall ``` -If you used the Windows installer, you can re-run the `.msi` and it will give -you an uninstall option. - ### Troubleshooting If you've got Rust installed, you can open up a shell, and type this: @@ -96,26 +96,22 @@ If you see this, Rust has been installed successfully! Congrats! 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. +variable. -If not, 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 -include [the user’s forum][users] and [Stack Overflow][stackoverflow]. - -[irc]: irc://irc.mozilla.org/#rust -[mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust -[users]: https://users.rust-lang.org/ -[stackoverflow]: http://stackoverflow.com/questions/tagged/rust +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, which you can access +through Mibbit at +*http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust*. Go to that +address, and you'll be chatting with other Rustaceans (a silly nickname we call +ourselves) who can help you out. Other great resources include the user’s forum +at *https://users.rust-lang.org/* and Stack Overflow at +*http://stackoverflow.com/questions/tagged/rust*. ### Local documentation The installer also includes a copy of the documentation locally, so you can -read it offline. On Linux or Mac, run `rustup doc` to open the local -documentation in your browser. On Windows, the documentation is in a -`share/doc` directory inside the directory where Rust was installed. +read it offline. Run `rustup doc` to open the local documentation in your +browser. ## Hello, World! @@ -126,7 +122,8 @@ 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 +> favorite IDE. ### Creating a Project File @@ -135,6 +132,8 @@ lives, but for this book, we'd suggest making a *projects* directory in your home directory and keeping all your projects there. Open a terminal and enter the following commands to make a directory for this particular project: +Linux and Mac: + ```bash $ mkdir ~/projects $ cd ~/projects @@ -142,18 +141,25 @@ $ mkdir hello_world $ cd hello_world ``` -> Note: If you’re on Windows and not using PowerShell, the `~` that represents -> your home directory may not work. -> Consult the documentation for your shell for more details. +Windows: + +```bash +$ mkdir %USERPROFILE%\projects +$ cd %USERPROFILE%\projects +$ mkdir hello_world +$ cd hello_world +``` ### Writing and Running a Rust Program -Next, make a new source file and call it *main.rs*. Rust files always end with -the *.rs* extension. If you’re using more than one word in your filename, use -an underscore to separate them. For example, you'd use *hello_world.rs* rather -than *helloworld.rs*. +Next, make a new source file and call it `main.rs`. Rust files always end with +the `.rs` extension. If you’re using more than one word in your filename, use +an underscore to separate them. For example, you'd use `hello_world.rs` rather +than `helloworld.rs`. -Now open the *main.rs* file you just created, and type the following code: +Now open the `main.rs` file you just created, and type the following code: + +Filename: main.rs ```rust fn main() { @@ -170,10 +176,10 @@ $ ./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 -did, then congratulations! You've officially written a Rust program. That makes -you a Rust programmer! Welcome. +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 did, then congratulations! You've officially written a Rust +program. That makes you a Rust programmer! Welcome. ### Anatomy of a Rust Program @@ -189,12 +195,10 @@ 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 -omitted the return type entirely. If there was a return type, there would be a -`->` and the return type after the parentheses. +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 +211,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 @@ -249,8 +253,9 @@ main main.rs On Windows, you'd enter: ```bash -$ dir -main.exe main.rs +$ dir /B # the /B option says to only show the file names +main.exe +main.rs ``` This shows we have two files: the source code, with the `.rs` extension, and the @@ -258,10 +263,10 @@ executable (`main.exe` on Windows, `main` everywhere else). All that's left to do from here is run the `main` or `main.exe` file, like this: ```bash -$ ./main # or main.exe on Windows +$ ./main # or .\main.exe on Windows ``` -If *main.rs* were your "Hello, world!" program, this would print `Hello, +If `main.rs` were your "Hello, world!" program, this would print `Hello, world!` to your terminal. If you come from a dynamic language like Ruby, Python, or JavaScript, you may @@ -285,7 +290,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 +309,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 @@ -313,11 +318,19 @@ Let's create a new project using Cargo and look at how it differs from our project in `hello_world`. Go back to your projects directory (or wherever you decided to put your code): +Linux and Mac: + ```bash $ cd ~/projects ``` -And then run: +Windows: + +```bash +$ cd %USERPROFILE%\projects +``` + +And then on any operating system run: ```bash $ cargo new hello_cargo --bin @@ -326,20 +339,22 @@ $ 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 -of the same name that we can then go into. +*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 -generated two files and one directory for us: a `Cargo.toml` and a *src* -directory with a *main.rs* file inside. It has also initialized a new `git` -repository in the `hello_cargo` directory for us; you can change this to use a -different version control system, or no version control system, by using the -`--vcs` flag. +generated two files and one directory for us: a `Cargo.toml` and a `src` +directory with a `main.rs` file inside. It has also initialized a new `git` +repository in the `hello_cargo` directory for us, along with a `.gitignore` +file; you can change this to use a different version control system, or no +version control system, by using the `--vcs` flag. Open up `Cargo.toml` in your text editor of choice. It should look something like this: +Filename: Cargo.toml + ```toml [package] name = "hello_cargo" @@ -349,12 +364,10 @@ authors = ["Your Name "] [dependencies] ``` -This file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is +This file is in the *TOML* (Tom's Obvious, Minimal Language) format. TOML is similar to INI but has some extra goodies and is used as Cargo’s configuration format. -[TOML]: https://github.com/toml-lang/toml - The first line, `[package]`, is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections. @@ -366,12 +379,15 @@ from your environment. If it’s not correct, go ahead and fix that and save the file. The last line, `[dependencies]`, is the start of a section for you to list any -crates that your project will depend on so that Cargo knows to download and -compile those too. We won't need any other crates for this project, but we will -in the guessing game tutorial in the next chapter. +*crates* (which is what we call packages of Rust code) that your project will +depend on so that Cargo knows to download and compile those too. We won't need +any other crates for this project, but we will in the guessing game tutorial in +the next chapter. Now let's look at `src/main.rs`: +Filename: src/main.rs + ```rust fn main() { println!("Hello, world!"); @@ -385,7 +401,7 @@ and the project generated by Cargo that we've seen so far are: 1. Our code goes in the `src` directory 2. The top level contains a `Cargo.toml` configuration file -Cargo expects your source files to live inside the *src* directory so that the +Cargo expects your source files to live inside the `src` directory so that the top-level project directory is just for READMEs, license information, configuration files, and anything else not related to your code. In this way, using Cargo helps you keep your projects nice and tidy. There's a place for @@ -403,20 +419,23 @@ program through Cargo! To do so, enter the following commands: ```bash $ cargo build - Compiling hello_cargo v0.1.0 (file:///home/yourname/projects/hello_cargo) + Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) ``` -This should have created an executable file in `target/debug/hello_cargo` (or `target/debug/hello_cargo.exe` on Windows), which you can run with this command: +This should have created an executable file in `target/debug/hello_cargo` (or +`target\debug\hello_cargo.exe` on Windows), which you can run with this command: ```bash -$ ./target/debug/hello_cargo # or ./target/debug/hello_cargo.exe on Windows +$ ./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. Running `cargo build` for the first time also causes Cargo to create a new file -at the top level called *Cargo.lock*, which looks like this: +at the top level called `Cargo.lock`, which looks like this: + +Filename: Cargo.lock ```toml [root] @@ -424,7 +443,7 @@ name = "hello_cargo" version = "0.1.0" ``` -Cargo uses the *Cargo.lock* file to keep track of dependencies in your +Cargo uses the `Cargo.lock` file to keep track of dependencies in your application. This project doesn't have dependencies, so the file is a bit sparse. Realistically, you won't ever need to touch this file yourself; just let Cargo handle it. @@ -439,22 +458,29 @@ $ cargo run Hello, world! ``` -Notice that this time, we didn't see the output 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: +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: ```bash $ cargo run - Compiling hello_cargo v0.1.0 (file:///home/yourname/projects/hello_cargo) + Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Running `target/debug/hello_cargo` Hello, world! ``` So a few more differences we've now seen: -3. Instead of using `rustc`, build a project using `cargo build` (or build and run it in one step with `cargo run`) -4. Instead of the result of the build being put in the same directory as our code, Cargo will put it in the `target/debug` directory. +3. Instead of using `rustc`, build a project using `cargo build` (or build and + run it in one step with `cargo run`) +4. Instead of the result of the build being put in the same directory as our + code, Cargo will put it in the `target/debug` directory. + +The other advantage of using Cargo is that the commands are the same no matter +what operating system you're on, so at this point we will no longer be +providing specific instructions for Linux and Mac versus Windows. ### Building for Release @@ -477,7 +503,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 @@ -487,6 +513,4 @@ $ cargo build ``` > Note: If you want to look at Cargo in more detail, check out the official -[Cargo guide], which covers all of its features. - -[Cargo guide]: http://doc.crates.io/guide.html +Cargo guide at *http://doc.crates.io/guide.html*, which covers all of its features. diff --git a/nostarch/chapter02.md b/nostarch/chapter02.md index 0deffef99..ab7c0445b 100644 --- a/nostarch/chapter02.md +++ b/nostarch/chapter02.md @@ -1,26 +1,37 @@ + +[TOC] + # Guessing Game -Let's jump into Rust with a hands-on project! We’ll implement a classic -beginner programming problem: the guessing game. Here’s how it works: Our -program will generate a random integer between one and a hundred. It will then -prompt us to enter a guess. Upon entering our guess, it will tell us if we’re -too low or too high. Once we guess correctly, it will congratulate us. +Let's jump into Rust with a hands-on project! This chapter will introduce you to +a few common Rust concepts by showing how you would use them in a real program. +You'll learn about `let`, `match`, methods, associated functions, using +external crates, and more! Following chapters will explore these ideas in more +detail. -## Set up +We’re going to implement a classic beginner programming problem: the guessing +game. Here’s how it works: Our program will generate a random integer between +one and a hundred. It will then prompt us to enter a guess. Upon entering our +guess, it will tell us if we’re too low or too high. Once we guess correctly, +it will congratulate us. -Let’s set up a new project. Go to your projects directory, and create a new project using Cargo. +## Setting Up a New Project + +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 $ 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`: +Filename: Cargo.toml + ```toml [package] name = "guessing_game" @@ -30,11 +41,13 @@ 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 -us. Check out `src/main.rs`: +And as we saw in the last chapter, `cargo new` generates a "Hello, world!" +program for us. Check out `src/main.rs`: + +Filename: src/main.rs ```rust fn main() { @@ -42,11 +55,12 @@ fn main() { } ``` -Let’s try compiling what Cargo gave us and running it in the same step, using the `cargo run` command: +Let’s try compiling what Cargo gave us and running it in the same step, using +the `cargo run` command: ```bash $ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Running `target/debug/guessing_game` Hello, world! ``` @@ -60,8 +74,12 @@ 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`: + +Filename: src/main.rs ```rust,ignore use std::io; @@ -86,13 +104,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` (input/output) library from the +standard library (which is known as `std`). -[prelude]: ../std/prelude/index.html +By default, Rust only imports a few things into every program in the +*prelude*. If it’s not in the prelude, you’ll have to import it into +your program explicitly with a `use` statement. Using the `std::io` library +gets you a number of useful `io`-related things, including the functionality to +accept user input. ```rust,ignore fn main() { @@ -108,56 +128,61 @@ 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 a prompt stating what the game is 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; ``` 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. +many languages, this is called a *variable*, but Rust’s variable bindings have +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` is a growable, UTF-8 encoded bit of text. -[string]: ../std/string/struct.String.html +The `::` syntax in the `::new()` line indicates that `new()` is an *associated +function* of a particular type. An associated function is a function that is +associated with a type, in this case `String`, rather than a particular +instance of a `String`. Some languages call this a *static method*. -The `::new()` syntax uses `::` because this 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’. - -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. +So to summarize, the `let mut guess = String::new();` line has created a +mutable binding that is currently bound to a new, empty instance of a `String`. +Whew! + Let’s move forward: ```rust,ignore @@ -165,135 +190,128 @@ 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() -``` - -Remember how we `use`d `std::io` on the first line of the program? We’re now +Remember how we said `use 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()`. -This particular function returns a handle to the standard input for your -terminal. More specifically, a [std::io::Stdin][iostdin]. +This particular function returns an instance of `std::io::Stdin`, +which is a type that represents a handle to the standard input for your +terminal. -[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) -``` - -Here, we call the [`read_line()`][read_line] method on our handle. We’re also +The next part, `.read_line(&mut guess)`, calls the `readline()` method on the standard input handle to get input from the user. We’re also passing one argument to `read_line()`: `&mut guess`. -[read_line]: ../std/io/struct.Stdin.html#method.read_line +The job of `read_line()` is to take whatever the user types into standard input +and place that into a string, so it takes that string as an argument. The +string argument needs to be mutable so that the method can change the string's +content by adding the user input. -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 -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 -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`. +The `&` indicates that this argument is a *reference*, which gives you a way to +allow multiple parts of your code to access to one piece of data without +needing to copy that data into memory multiple times. References are a complex +feature, and one of Rust’s major advantages is how safe and easy it is to use +references. We don’t need to know a lot of those details to finish our program +right now, though; Chapter XX will cover references in more detail. For now, +all we need to know is that like `let` bindings, references are immutable by +default. Hence, we need to write `&mut guess`, rather than `&guess` to make it +mutable. -Why does `read_line()` take a mutable reference to a string? Its job is -to take what the user types into 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. - -But we’re not quite done with this line of code, though. 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: +We’re not quite done with this line of code. While it’s a single line of text, +it’s only the first part of the single logical line of code. The second part is +this method: ```rust,ignore .expect("Failed to read line"); ``` -When you call a method with the `.foo()` syntax, you may introduce a newline -and other whitespace. This helps you split up long lines. We _could_ have -written this code as: +When you call a method with the `.foo()` syntax, it's often wise to introduce a +newline and other whitespace. This helps you split up long lines. We _could_ +have written this code as: ```rust,ignore 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. -### The `Result` Type +### Handling Potential Failure with 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 -[`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`. +We mentioned that `read_line()` puts what the user types into the string we +pass it, but it also returns a value: in this case, an `io::Result`. Rust has a +number of types named `Result` in its standard library: a generic `Result`, and +then specific versions for sub-libraries, like `io::Result`. -[ioresult]: ../std/io/type.Result.html -[result]: ../std/result/enum.Result.html +The `Result` types are enums, which is short for *enumeration*. An +enumeration is a type that can have a fixed set of values, which are called the +`enum`'s *variants*. We will be covering enums in more detail in Chapter XX. + +For `Result`, the variants are `Ok` or `Err`. `Ok` means the operation was +successful, and inside the `Ok` variant is the successfully generated value. +`Err` means the operation failed, and the `Err` contains information about how +or why the operation failed. 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 -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()`. +this case, `io::Result` has an `expect()` method that we can call. If +this instance of `io::Result` is an `Err` value, `expect()` will cause our +program to crash and display the message that we passed as an argument to +`expect()`. In this case, if the `read_line()` method returns an `Err`, it would +likely be the result of an error coming from the underlying operating system. +If this instance of `io::Result` is an `Ok` value, `expect()` will take the +return value that `Ok` is holding out of the `Ok` and return just that value to +us so that we can use it. In this case, that value will be what the user +entered into standard input. -[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 `expect()`, our program will compile, but we’ll get a warning: ```bash $ cargo build - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + 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); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` -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 -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. +Rust warns that we haven’t used the `Result` value, telling us that we +haven’t handled a possible error. The right way to suppress the warning is to +actually write error handling, but if we just want to crash the program when a +problem occurs, we can use `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: ```rust,ignore println!("You guessed: {}", guess); -} ``` 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 -value, and so on. Printing out multiple values in one call to `println!()` would then look like this: +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". -Anyway, back to our guessing game. We can run what we have with `cargo run`: +### Testing the First Part + +Back to our guessing game, let's test what we have so far. We can run it with +`cargo run`: ```bash $ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Running `target/debug/guessing_game` Guess the number! Please input your guess. @@ -304,21 +322,26 @@ 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 -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 -programs. +Next, we need to generate a secret number that the user is trying to guess. The +secret number should be different every time so that the game is fun to play +more than once. So we'd like to have a random number between 1 and 100. Rust +does not yet include random number functionality in its standard library. The +Rust team does, however, provide a `rand` crate at *https://crates.io/crates/rand*. -[randcrate]: https://crates.io/crates/rand +### Using a Crate to Get More Functionality -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 -add this line at the bottom beneath the `[dependencies]` section header that -Cargo created for you: +Remember that *crate* is what we call 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 in other programs. + +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: + +Filename: Cargo.toml ```toml [dependencies] @@ -326,17 +349,15 @@ Cargo created for you: rand = "0.3.14" ``` -The `[dependencies]` section of `Cargo.toml` is like the `[package]` section: -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 -require. In this case, we’ve specified the `rand` crate with the semantic -version specifier `0.3.14`. Cargo understands [Semantic Versioning][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". - -[semver]: http://semver.org +In the `Cargo.toml` file, everything that follows a header is part of a section +that goes until 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 (sometimes called *semver*), which is 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". Now, without changing any of our code, let’s build our project: @@ -347,23 +368,21 @@ $ cargo build Downloading libc v0.2.14 Compiling libc v0.2.14 Compiling rand v0.3.14 - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) ``` -You may see different versions (but they will be compatible, thanks to semver!) -and the lines may be in a different order. +You may see different version numbers (but they will all be compatible with +your code, thanks to semver!) and the lines may be in a different order. 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: @@ -380,42 +399,75 @@ we’ll only see one line: ```bash $ cargo build - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) ``` +This just updates the build with your tiny change to the `main.rs` 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? +#### The Cargo.lock File that Ensures Reproducible Builds + +Cargo has a mechanism to make sure we can rebuild the exact same artifact every +time we or anyone else builds our code: Cargo will only use the versions of the +dependencies you specified until you say otherwise. For example, what happens +if next week version `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 -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 -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. +project for the first time, Cargo figures out all of the versions of your +dependencies 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 use the versions specified there rather than doing all the work +of figuring out versions again. This lets you have a reproducible build +automatically. In other words, our project will stay at `0.3.14` until we +explicitly upgrade, thanks to the lock file. -What about when we _do_ want to use `v0.3.15`? 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, -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 -do, the next time we `cargo build`, Cargo will update the index and re-evaluate -our `rand` requirements. +#### Updating a Crate to Get a New Version -There’s a lot more to say about [Cargo][doccargo] and [its -ecosystem][doccratesio] that we will get into in Chapter XX, but for now, -that’s all we need to know. Cargo makes it really easy to re-use libraries, so -Rustaceans are able to write smaller projects which are assembled out of a -number of sub-packages. +When we _do_ want to update a crate, Cargo has another command, +`update`, which will: -[doccargo]: http://doc.crates.io -[doccratesio]: http://doc.crates.io/crates-io.html +- Ignore the `Cargo.lock` file and figure out all the latest versions that fit + our specifications in `Cargo.toml`. +- If that works, write those versions out to the lock file. -Let’s get on to actually _using_ `rand`. Here’s our next step: +But by default, Cargo will only look for versions larger than `0.3.0` and +smaller than `0.4.0`. If the `rand` crate has released two new versions, +`0.3.15` and `0.4.0`, this is what we would see if we ran `cargo update`: + +```bash +$ cargo update + Updating registry `https://github.com/rust-lang/crates.io-index` + Updating rand v0.3.14 -> v0.3.15 +``` + +At this point, you would also notice a change in your `Cargo.lock` file noting +that the version of the `rand` crate you are now using is `0.3.15`. + +If we wanted to use `rand` version `0.4.0` or any version in the `0.4.x` +series, we’d have to update what is in the `Cargo.toml` file to look like this +instead: + +```toml +[dependencies] + +rand = "0.4.0" +``` + +The next time we `cargo build`, assuming that the `rand` crate version `0.4.0` +has been released, Cargo will update the crates index and re-evaluate our +`rand` requirements according to the new version we have specified. + +There’s a lot more to say about Cargo and its ecosystem that we will get into +in Chapter XX, but for now, that’s all we need to know. Cargo makes it really +easy to re-use libraries, so Rustaceans are able to write smaller projects +which are assembled out of a number of sub-packages. + +### Generating a Random Number + +Let’s get on to actually _using_ `rand`. Our next step is to update our +`main.rs` code as follows: + +Filename: src/main.rs ```rust,ignore extern crate rand; @@ -441,19 +493,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 -call anything in the `rand` crate by prefixing it with `rand::`. +First we've added a line to the top, `extern crate rand`, that lets Rust know +we’ll be making use of that external dependency. This also does the equivalent +of calling `use rand`, so we can now 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. +Next, we added another `use` line: `use rand::Rng`. `Rng` is a trait that +defines methods that random number generators implement, and this trait must be +in scope for us to use those methods. We'll cover traits in detail in the +Traits section in Chapter XX. -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); @@ -461,24 +511,34 @@ let secret_number = rand::thread_rng().gen_range(1, 101); 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 -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. +`rand::thread_rng()` is a function that will give us the particular random +number generator that we're going to use: one that is local to our current +thread of execution and seeded by the operating system. Next, we call the +`gen_range()` method on our random number generator. This method is one that is +defined by the Rng trait that we brought into scope with the `use rand::Rng` +statement above. `gen_range()` 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. -The second line prints out the secret number. This is useful while -we’re developing our program to let us easily test it out, but we’ll be -deleting it for the final version. It’s not much of a game if it prints out -the answer when you start it up! +Knowing what traits to import and what functions and methods to use from a +crate isn't something that you'll just *know*. Instructions for using a crate +are in each crate's documentation. Another neat feature of Cargo is that you +can run the `cargo doc --open` command to build documentation provided by all +of your dependencies locally and then open it in your browser. If you're +interested in other functionality in the `rand` crate, for example, run `cargo +doc --open` then click on "rand" in the sidebar on the left. + +The second line that we added to our code prints out the secret number. This is +useful while we’re developing our program to let us easily test it out, but +we’ll be deleting it for the final version. It’s not much of a game if it +prints out the answer when you start it up! Try running our new program a few times: ```bash $ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Running `target/debug/guessing_game` Guess the number! The secret number is: 7 @@ -494,13 +554,15 @@ Please input your guess. 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. +You should get different random numbers, and they should all be numbers between +1 and 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: + +Filename: src/main.rs ```rust,ignore extern crate rand; @@ -533,9 +595,13 @@ fn main() { } ``` -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 -use that type: +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. `Ordering` is +another enum, like `Result`, but the variants for `Ordering` are `Less`, +`Greater`, and `Equal`. These are the three outcomes that are possible when you +compare two things. + +Then we add five new lines at the bottom that use the `Ordering` type: ```rust,ignore match guess.cmp(&secret_number) { @@ -545,50 +611,38 @@ 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`. `cmp()` returns a +variant of the `Ordering` type we imported with the `use` statement earlier. We +use a `match` statement to decide what to do next based on which +variant of `Ordering` we got back from our call to `cmp()` with the values in +`guess` and `secret_number`. -```rust -enum Foo { - Bar, - Baz, -} -``` +`match` statements are made up of *arms*. An arm consists of a *pattern* and +the code that we should run if the value given to the beginning of the `match` +statement fits that arm's pattern. Rust takes the value given to `match` and +looks through each arm's pattern in turn. The `match` construct and patterns +are powerful features in Rust that will be covered in detail in Chapter XX and +Chapter XX, respectively. -[match]: match.html -[enum]: enums.html +Let's walk through an example of what would happen with our `match`. Say that +the user has guessed 50, and the randomly-generated secret number this time +is 38. So when we compare 50 to 38, the `cmp()` method will return +`Ordering::Greater`, since 50 is greater than 38. `Ordering::Greater` is the +value that the `match` statement gets. It looks at the first arm's pattern, +`Ordering::Less`, and says nope, the value we have (`Ordering::Greater`) does +not match `Ordering::Less`. So it ignores the code in that arm and moves on to +the next arm. The next arm's pattern, `Ordering::Greater`, **does** match +`Ordering::Greater`! The associated code in that arm will get executed, which +prints "Too big!" to the screen. Then we're done with the `match` statement; we +don't look at the last arm at all in this particular scenario. -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 -we have three types of `Ordering`, we have three arms: - -```rust,ignore -match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), -} -``` - -[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. - -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 - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) src/main.rs:23:21: 23:35 error: mismatched types [E0308] src/main.rs:23 match guess.cmp(&secret_number) { ^~~~~~~~~~~~~~ @@ -599,20 +653,21 @@ 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 number +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; `i64`, a sixty-four-bit +number; or others. Rust defaults to an `i32`, so that's the type of +`secret_number`. The error is because Rust will not compare two different types. 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: + +Filename: src/main.rs ```rust,ignore extern crate rand; @@ -648,53 +703,55 @@ fn main() { } ``` -The new two lines: +The two new lines are: ```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 create a variable binding `guess`. But wait a minute, don't we already have +a variable binding named `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 value from one type into another 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. -We bind `guess` to an expression that looks like something we wrote earlier: +We bind `guess` to the expression `guess.trim().parse()`. -```rust,ignore -guess.trim().parse() -``` +The `guess` in the expression 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. Our u32 can only contain numerical +characters, but we have to press the "return" key to satisfy `read_line()`. +When we press the return key, 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 return key. The `trim()` method gets rid of this, +leaving our string with only the `5`. -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`. +The `parse()` method on strings parses a string into some kind of +number. Since this method can parse a variety of number types, we need to tell +Rust the exact type of number we want with `let guess: u32`. The colon (`:`) +after `guess` tells Rust we’re going to annotate its type. Rust has a few +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. -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. - -[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 -such, we’ll do the same thing we did with `read_line()`: use the `expect()` -method to crash if there’s an error. +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. Because +it might fail, the `parse()` method returns a `Result` type, much like the +`read_line()` method does that we discussed earlier. We're going to treat this +`Result` the same way by using the `expect()` method again. If `parse()` +returns an `Err` `Result` variant because it could not create a number from the +string, the `expect()` call will crash the game and print the message we give +it. If `parse()` can successfully turn the string into a number, it will return +the `Ok` variant of `Result`, and `expect()` will return the number that we +want that it will take out of the `Ok` value for us. Let’s try our program out! ```bash $ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Running `target/guessing_game` Guess the number! The secret number is: 58 @@ -705,15 +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 +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. Now we’ve got most of the game working, but we can only make one guess. Let’s -change that by adding loops! +change that by adding a loop! -## Looping +## Allowing Multiple 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: + +Filename: src/main.rs ```rust,ignore extern crate rand; @@ -751,13 +812,20 @@ fn main() { } ``` -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. +You'll notice we have a new problem because the program is doing exactly what we +told it to do: ask for another guess forever! It doesn't seem like we can quit! + +We could always halt the program by using the keyboard shortcut `control-c`. +There's another way to escape the monster we've created that will infinitely +demand more guesses, though, that can be found in our discussion about +`parse()`: if we give a non-number answer, the program will crash. We can use +that to quit! Observe: ```bash $ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Running `target/guessing_game` Guess the number! The secret number is: 59 @@ -780,8 +848,15 @@ 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. + +#### Quitting When you Win + +Let’s program the game to quit when you win by adding a `break` in that case: + +Filename: src/main.rs ```rust,ignore extern crate rand; @@ -822,54 +897,16 @@ fn main() { } ``` -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: +By adding the `break` line after `You win!`, we’ll exit the loop when we guses +the secret number correctly. Exiting the loop also means exiting the program, +since the loop is the last thing in `main()`. -```rust,ignore -extern crate rand; +#### Handling Invalid Input -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 = 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; - } - } - } -} -``` - -These are the lines that changed: +For our final refinement of the game's behavior, rather than crashing the +program when someone inputs a non-number, we want the game to ignore it so we +can continue guessing. We can do that by altering the line where we convert +`guess` from a `String` to a `u32`: ```rust,ignore let guess: u32 = match guess.trim().parse() { @@ -878,23 +915,32 @@ let guess: u32 = match guess.trim().parse() { }; ``` -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 -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. +This is how you generally move from "crash on error" to "actually handle the +error": by switching from an `expect()` statement to a `match` statement. +Remember that `parse()` returns a `Result` type, and `Result` is an enum that +has the variants `Ok` or `Err`. We're going to use a `match` statement here, +like we did with the `Ordering` result of the `cmp()` method. -Now we should be good! Let’s try it: +If `parse()` is able to successfully turn the string into a number, it will +return an `Ok` value that contains the resulting number. That `Ok` value will +match the first arm's pattern, and the match statement will just return the +`num` value that `parse()` produced and put inside the `Ok` value. That number +will end up right where we want it, in the new `guess` binding we're creating. + +If `parse()` is *not* able to turn the string into a number, it will return an +`Err` value that contains more information about the error. The `Err` value +does not match the `Ok(num)` pattern in the first match arm, but it does match +the `Err(_)` pattern in the second arm. The `_` is a catch-all value; we're +saying we want to match all `Err` values, no matter what information they have +inside them. So we execute the second arm's code, `continue`: this means to go +to the next iteration of the `loop` and ask for another guess. So we have +effectively ignored all errors that `parse()` might hit! + +Now everything in our program should work as we expect it to! Let’s try it: ```bash $ cargo run - Compiling guessing_game v0.1.0 (file:///home/you/projects/guessing_game) + Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Running `target/guessing_game` Guess the number! The secret number is: 61 @@ -914,10 +960,12 @@ 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. Let's delete the `println!` that outputs the secret number. Here’s our +full, final code: + +Filename: src/main.rs ```rust,ignore extern crate rand; @@ -960,7 +1008,13 @@ fn main() { ## Complete! -This project showed you a lot: `let`, `match`, methods, associated -functions, using external crates, and more. - At this point, you have successfully built the Guessing Game! Congratulations! + +This project was a hands-on way to introduce you to a lot of new Rust concepts: +`let`, `match`, methods, associated functions, using external crates, and more. +In the next few chapters, we will go through these concepts in more detail. +Chapter 3 covers concepts that most programming languages have, like variables, +data types, and functions, and shows how to use them in Rust. Chapter 4 gets +into ownership, which is the feature of Rust that is most different from other +languages. Chapter 5 discusses structs and method syntax, and Chapter 6 +endeavors to explain enums. diff --git a/nostarch/chapter03.md b/nostarch/chapter03.md index f5ab796ce..2c21f1818 100644 --- a/nostarch/chapter03.md +++ b/nostarch/chapter03.md @@ -1,3 +1,6 @@ + +[TOC] + # Common Programming Concepts in Rust Let's look at concepts that appear in almost every programming language and see @@ -42,7 +45,9 @@ $ cargo new --bin bindings $ cd bindings ``` -Then open *src/main.rs* and replace its code with the following: +Then open `src/main.rs` and replace its code with the following: + +Filename: src/main.rs ```rust,ignore fn main() { @@ -146,6 +151,8 @@ code will be changing this value. For example, change the program you just wrote to the following: +Filename: src/main.rs + ```rust fn main() { let mut x = 5; @@ -176,12 +183,14 @@ depends on the tradeoffs you want to make in your situation. As we saw in the guessing game tutorial, we can declare new bindings with the same name as a previous binding, and the new binding *shadows* the previous -binding. We say that the first binding is ‘shadowed’ by the second, which means +binding. We say that the first binding is *shadowed* by the second, which means that the second binding's value is what you will see when you use the variable after the second binding. This can be useful if you’d like to perform a few transformations on a value, but have the binding be immutable after those transformations have been completed. For example: +Filename: src/main.rs + ```rust fn main() { let x = 5; @@ -293,6 +302,8 @@ your code if you suspect floating-point size is a problem in your case. Here's an example showing floating-point numbers in action: +Filename: src/main.rs + ```rust fn main() { let x = 2.0; // f64 @@ -310,6 +321,8 @@ Rust supports the usual basic mathematic operations you’d expect for all of these number types: addition, subtraction, multiplication, division, and modulo. This code shows how you'd use each one in a `let` statement: +Filename: src/main.rs + ```rust fn main() { // addition @@ -338,6 +351,8 @@ As in most other programming languages, a boolean type in Rust has two possible values: `true` and `false`. The boolean type in Rust is specified with `bool`. For example: +Filename: src/main.rs + ```rust fn main() { let t = true; @@ -356,6 +371,8 @@ So far we’ve only worked with numbers, but Rust supports letters too. Rust’s `char` type is the language's most primitive alphabetic type, and this code shows one way to use it: +Filename: src/main.rs + ```rust fn main() { let c = 'z'; @@ -375,6 +392,25 @@ about Unicode Scalar Values at *http://www.unicode.org/glossary/#unicode_scalar_value* and find a chart for all unicode code points at *http://www.unicode.org/charts/*. +#### The Byte Type + +You can work with the bytes of data directly. Byte literals can be created from +the ASCII characters using `b` and single quotes: + +Filename: src/main.rs + +```rust +fn main() { + let byte = b'a'; + println!("byte is {}", byte); +} +``` + +This will print `byte is 97`. Similarly, byte string literals can be created +using `b` and double quotes, like `b"some byte string"`. Note that since you are +limited to ASCII characters, it's a best practice to use characters instead of +bytes when you're working with natural language text. + ### Compound Types *Compound types* can group multiple values of other types into one type. Rust @@ -389,6 +425,8 @@ types into one compound type. We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a distinct type, as in this example: +Filename: src/main.rs + ```rust fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); @@ -400,6 +438,8 @@ name `tup` to the entire tuple, emphasizing the fact that a tuple is considered a single compound element. We could then use pattern matching to destructure this tuple value, like this: +Filename: src/main.rs + ```rust fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); @@ -412,7 +452,7 @@ fn main() { In this program, we first create a tuple and bind it to the name `tup`. We then use a pattern with `let` to take `tup` and turn it into three separate -bindings, `x`, `y`, and `z`. This is called ‘destructuring’, because it breaks +bindings, `x`, `y`, and `z`. This is called *destructuring*, because it breaks the single tuple into three parts. Finally, we print the value of `y`, which is `6.4`. @@ -423,6 +463,8 @@ In addition to destructuring through pattern matching, we can also access a tuple element directly by using a period (`.`) followed by the index of the value we want to access. For example: +Filename: src/main.rs + ```rust fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); @@ -449,6 +491,8 @@ in Rust have a fixed length-- once declared, they cannot grow or shrink in size. In Rust, the values going into an array are written as a comma separated list inside square brackets: +Filename: src/main.rs + ```rust fn main() { let a = [1, 2, 3, 4, 5]; @@ -466,6 +510,8 @@ and we'll discuss them in more detail in chapter XX. An array is a single chunk of memory, allocated on the stack. We can access elements of an array using indexing, like this: +Filename: src/main.rs + ```rust fn main() { let a = [1, 2, 3, 4, 5]; @@ -487,6 +533,8 @@ values. What happens if you try to access an element of an array past the end of the array? Say we changed our program to: +Filename: src/main.rs + ```rust,ignore fn main() { let a = [1, 2, 3, 4, 5]; @@ -533,6 +581,8 @@ words. (Rust also uses snake case for the names of variable bindings; we just haven't used any variable bindings with enough letters to need underscores yet). Here's a program containing an example function definition: +Filename: src/main.rs + ```rust fn main() { println!("Hello, world!"); @@ -565,7 +615,7 @@ $ cargo new --bin functions $ cd functions ``` -Place the `another_function()` example in a file named *src/main.rs* and run +Place the `another_function()` example in a file named `src/main.rs` and run it. You should see the following output: ```bash @@ -585,6 +635,8 @@ message is printed. Functions can also take arguments. The following rewritten version of `another_function()` shows what arguments look like in Rust: +Filename: src/main.rs + ```rust fn main() { another_function(5); @@ -617,6 +669,8 @@ the code in order to figure out what you mean. When you want a function to have multiple arguments, just separate them inside the function signature with commas, like this: +Filename: src/main.rs + ```rust fn main() { another_function(5, 6); @@ -666,6 +720,8 @@ evaluate to a resulting value. Let's look at some examples. `Let` bindings are statements. They instruct the program to create a binding name and assign a value to it. `let y = 6;` in this example is a statement: +Filename: src/main.rs + ```rust fn main() { let y = 6; @@ -678,6 +734,8 @@ statement as well. Statements do not return values themselves. Therefore, you can’t assign a `let` binding to another binding, as this code tries to do: +Filename: src/main.rs + ```rust,ignore fn main() { let x = (let y = 6); @@ -718,6 +776,8 @@ y = 6;`, `6` is an expression that evaluates to the value `6`. Calling a function is an expression. Calling a macro is an expression. The block that we use to create new scopes, `{}`, is an expression, for example: +Filename: src/main.rs + ```rust fn main() { let x = 5; @@ -758,6 +818,8 @@ the "return value of the function” is synonymous with “the value of the fina expression in the block of the body of a function.” Here's an example of a function that returns a value: +Filename: src/main.rs + ```rust fn five() -> i32 { 5 @@ -798,6 +860,8 @@ arguments and defines the type of the return value, but the body of the function is a lonely `5` with no semicolon because it is an expression whose value we want to return. Let's look at another example: +Filename: src/main.rs + ```rust fn main() { let x = plus_one(5); @@ -814,6 +878,8 @@ Running this code will print `The value of x is: 6`. What happens if we put a semicolon at the end of the line containing `x + 1`, changing it from an expression to a statement? +Filename: src/main.rs + ```rust,ignore fn main() { let x = plus_one(5); @@ -876,6 +942,8 @@ include `//` on each line, like this: Comments can also be placed at the end of lines of code: +Filename: src/main.rs + ```rust fn main() { let lucky_number = 7; // I’m feeling lucky today. @@ -884,6 +952,8 @@ fn main() { But you’ll more often see them above, like so: +Filename: src/main.rs + ```rust fn main() { // I’m feeling lucky today. @@ -918,6 +988,8 @@ $ cd branches Write this sample program using `if` and save it in the *branches* directory in `src/main.rs`: +Filename: src/main.rs + ```rust fn main() { let number = 3; @@ -934,7 +1006,7 @@ All `if` expressions start with `if`, which is followed by a condition. In this case, our condition is checking if our variable binding `number` has a value that is less than 5. The block of code we want to execute if the condition is true goes immediately after the condition, inside curly braces. These blocks -are sometimes called ‘arms’. We can optionally also include an `else` +are sometimes called *arms*. We can optionally also include an `else` statement, which we have chosen to do here. `else` gives the program a block of code to execute should `condition` evaluate to false. @@ -966,6 +1038,8 @@ condition was false It’s also worth noting that `condition` here _must_ be a `bool`. To see what happens if the condition isn't a `bool`, try running this code: +Filename: src/main.rs + ```rust,ignore fn main() { let number = 3; @@ -997,6 +1071,8 @@ not automatically try to convert non-boolean types to a boolean here, unlike languages like Ruby or JavaScript. We must be explicit and always give `if` a `boolean` as its condition. If your intention is for the `if` code block to be run if a number is not equal to `0`, for example, we would change the `if` expression to read: +Filename: src/main.rs + ```rust fn main() { let number = 3; @@ -1014,6 +1090,8 @@ Running this will print "number was something other than zero". We can have multiple coniditions by combining `if` and `else` in an `else if` expression. For example: +Filename: src/main.rs + ```rust fn main() { let number = 5; @@ -1054,6 +1132,8 @@ The last detail you need to learn about `if` is that it’s an expression. That means that we can use it on the right hand side of a `let` binding, for instance: +Filename: src/main.rs + ```rust fn main() { let condition = true; @@ -1084,6 +1164,8 @@ that results from both arms of the `if` must be the same type; in the previous example, they were both `i32` integers. But what happens if the types are mismatched, as in the following example? +Filename: src/main.rs + ```rust,ignore fn main() { let condition = true; @@ -1106,7 +1188,7 @@ single type. If we try to run this, we’ll get an error: Compiling branches v0.1.0 (file:///projects/branches) src/main.rs:4:18: 8:6 error: if and else have incompatible types: expected `_`, - found `&‘static str` + found `&'static str` (expected integral variable, found &-ptr) [E0308] src/main.rs:4 let number = if condition { @@ -1143,9 +1225,11 @@ in. The `loop` keyword tells Rust to execute a block of code over and over again forever or until we explicitly tell it to stop. -For an example, change the *src/main.rs* file in your *loops* directory to look +For an example, change the `src/main.rs` file in your *loops* directory to look like this: +Filename: src/main.rs + ```rust,ignore fn main() { loop { @@ -1191,6 +1275,8 @@ for it, called a `while` loop. Here's an example using `while`: this program loops three times, counting down each time. Finally, after the loop, it prints another message, then exits: +Filename: src/main.rs + ```rust fn main() { let mut number = 3; @@ -1214,6 +1300,8 @@ this code; otherwise, exit the loop. We could use this `while` construct to loop over the elements of a collection, like an array. For example: +Filename: src/main.rs + ```rust fn main() { let a = [10, 20, 30, 40, 50]; @@ -1254,6 +1342,8 @@ loop. As a more efficient alternative, we can use a `for` loop and execute some code for each item in a collection. A `for` loop looks like this: +Filename: src/main.rs + ```rust fn main() { let a = [10, 20, 30, 40, 50]; @@ -1272,7 +1362,7 @@ and missing some items. For example, in the previous code that uses the `while` loop, if we removed an item from the `a` array but forgot to update the condition to be `while index < 4`, our code would panic. Using the `for` loop means we would not need to -remember to change any other code if we changed the the number of values in the +remember to change any other code if we changed the number of values in the array. If you're wondering about the `.iter()` code in this example, keep reading! We @@ -1288,6 +1378,8 @@ one number and ending before another number. Here's what the countdown would look like with a for loop, and using another method we haven't yet talked about, `.rev()`, to reverse the range: +Filename: src/main.rs + ```rust fn main() { for number in (1..4).rev() { diff --git a/nostarch/chapter04.md b/nostarch/chapter04.md index 74e142b93..bed0f376e 100644 --- a/nostarch/chapter04.md +++ b/nostarch/chapter04.md @@ -1,3 +1,6 @@ + +[TOC] + # Understanding Ownership Ownership is important to understand: it's Rust's most unique feature, and @@ -7,7 +10,7 @@ and how Rust lays things out in memory. ## Ownership -Rust’s central feature is called ‘ownership’. It is a feature that is +Rust’s central feature is called *ownership*. It is a feature that is straightforward to explain, but has deep implications for the rest of the language. @@ -55,8 +58,8 @@ at which it’s declared until the end of the current _scope_. That is: In other words, there are two important points in time here: -- When `s` comes ‘into scope’, it is valid. -- It remains so until it ‘goes out of scope’. +- When `s` comes "into scope", it is valid. +- It remains so until it "goes out of scope". At this point, things are similar to other programming languages. Now let’s build on top of this understanding by introducing the `String` type. @@ -113,8 +116,8 @@ That first part is done by us: when we call `String::from()`, its implementation requests the memory it needs. This is pretty much universal in programming languages. -The second case, however, is different. In languages with a garbage collector -(‘GC’), the GC will keep track and clean up memory that isn't being used +The second case, however, is different. In languages with a *garbage collector* +(*GC*), the GC will keep track and clean up memory that isn't being used anymore, and we, as the programmer, don’t need to think about it. Without GC, it’s our responsibility to identify when memory is no longer being used and call code to explicitly return it, just as we did to request it. Doing this @@ -123,7 +126,6 @@ waste memory. If we do it too early, we will have an invalid variable. If we do it twice, that’s a bug too. We need to pair exactly one `allocate()` with exactly one `free()`. - Rust takes a different path. Remember our example? Here’s a version with `String`: @@ -256,20 +258,21 @@ alone will free the memory, and we’re done. This leads us to the Ownership Rules: -> 1. Each value in Rust has a variable binding that’s called its ‘owner’. +> 1. Each value in Rust has a variable binding that’s called its *owner*. > 2. There can only be one owner at a time. > 3. When the owner goes out of scope, the value will be `drop()`ped. Furthermore, there’s a design choice that’s implied by this: Rust will never -automatically create ‘deep’ copies of your data. Therefore, any _automatic_ +automatically create "deep" copies of your data. Therefore, any _automatic_ copying can be assumed to be inexpensive. ### Clone But what if we _do_ want to deeply copy the `String`’s data and not just the `String` itself? There’s a common method for that: `clone()`. We will discuss -methods in the section on [`structs`], but they’re a common enough feature -in many programming languages that you have probably seen them before. +methods in the section on `structs` in Chapter XX, but they’re a +common enough feature in many programming languages that you have probably seen +them before. Here’s an example of the `clone()` method in action: @@ -280,8 +283,6 @@ let s2 = s1.clone(); println!("{}", s1); ``` -[`structs`]: ch05-01-structs.html - This will work just fine. Remember our diagram from before? In this case, it _is_ doing this: @@ -333,6 +334,8 @@ but nothing that requires allocation or is some form of resource is `Copy`. Here Passing a value to a function has similar semantics as assigning it: +Filename: src/main.rs + ```rust fn main() { let s = String::from("hello"); @@ -357,6 +360,8 @@ Passing a binding to a function will move or copy, just like assignment. Here’ the same example, but with some annotations showing where things go into and out of scope: +Filename: src/main.rs + ```rust fn main() { let s = String::from("hello"); // s goes into scope. @@ -389,6 +394,8 @@ and where the ownership rules prevent you from doing so. Returning values can also transfer ownership: +Filename: src/main.rs + ```rust fn main() { let s1 = gives_ownership(); @@ -412,6 +419,8 @@ fn takes_and_gives_back(a_string: String) -> String { With similiar annotations: +Filename: src/main.rs + ```rust fn main() { let s1 = gives_ownership(); // gives_ownership moves its return @@ -452,6 +461,8 @@ also needs to be passed back if we want to use it again, in addition to any data resulting from the body of the function that we might want to return as well. It's _possible_ to return multiple values, using a tuple, like this: +Filename: src/main.rs + ```rust fn main() { let s1 = String::from("hello"); @@ -477,6 +488,8 @@ next section is about. At the end of the last section, we had some example Rust that wasn’t very good. Here it is again: +Filename: src/main.rs + ```rust fn main() { let s1 = String::from("hello"); @@ -499,6 +512,8 @@ function so that we can still use it there, since it was moved when we called There is a better way. It looks like this: +Filename: src/main.rs + ```rust fn main() { let s1 = String::from("hello"); @@ -520,7 +535,7 @@ function return value is gone. Next, note that we pass `&s1` into `calculate_length()`, and in its definition, we take `&String` rather than `String`. -These `&`s are called ‘references’, and they allow you to refer to some value +These `&`s are called *references*, and they allow you to refer to some value without taking ownership of it. Here’s a diagram: DIAGRAM GOES HERE of a &String pointing at a String, with (ptr, len, capacity) @@ -528,11 +543,6 @@ DIAGRAM GOES HERE of a &String pointing at a String, with (ptr, len, capacity) Let’s take a closer look at the function call here: ```rust -# fn calculate_length(s: &String) -> usize { -# let length = s.len(); -# -# length -# } let s1 = String::from("hello"); let len = calculate_length(&s1); @@ -559,13 +569,15 @@ we don’t drop what a reference points to when the reference goes out of scope. This lets us write functions which take references as arguments instead of the values themselves, so that we won’t need to return them to give back ownership. -There’s another word for what references do, and that’s ‘borrowing’. Just like +There’s another word for what references do, and that’s *borrowing*. Just like with real life, if a person owns something, you can borrow it from them. When you’re done, you have to give it back. Speaking of which, what if you try to modify something you borrow from me? Try this code out. Spoiler alert: it doesn’t work! +Filename: src/main.rs + ```rust,ignore fn main() { let s = String::from("hello"); @@ -595,6 +607,8 @@ allowed to modify something we have a reference to. We can fix this bug! Just a small tweak: +Filename: src/main.rs + ```rust fn main() { let mut s = String::from("hello"); @@ -613,6 +627,8 @@ String`. Mutable references have one big restriction, though. This code fails: +Filename: src/main.rs + ```rust,ignore let mut s = String::from("hello"); @@ -693,6 +709,8 @@ out of scope before the reference does. Let’s try to create a dangling reference: +Filename: src/main.rs + ```rust,ignore fn main() { let reference_to_nothing = dangle(); @@ -722,7 +740,7 @@ error: aborting due to previous error ``` This error message refers to a feature we haven’t learned about yet, -‘lifetimes’. The message does contain the key to why this code is a problem, +*lifetimes*. The message does contain the key to why this code is a problem, though: ```bash @@ -792,12 +810,14 @@ ownership, so this is fine. But what should we return? We don’t really have a way to talk about _part_ of a string. We could return the index of the end of the word, though. Let’s try that: +Filename: src/main.rs + ```rust fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { - if item == 32 { + if item == b' ' { return i; } } @@ -832,35 +852,25 @@ match against the tuple with i for the index and &item for a single byte. Since we get a reference from `.iter().enumerate()`, we use `&` in the pattern. ```rust,ignore - if item == 32 { + if item == b' ' { return i; } } s.len() ``` -We search for the value 32, which represents a space in UTF-8. If we find one, -we return the position. Otherwise, we return the length of the string, using -`s.len()`. +We search for the byte that represents the space, using the byte literal +syntax. If we find one, we return the position. Otherwise, we return the length +of the string, using `s.len()`. This works, but there’s a problem. We’re returning a `usize` on its own, but it’s only a meaningful number in the context of the `&String`. In other words, because it’s a separate value from the `String`, there’s no guarantee that it will still be valid in the future. Consider this: -```rust -# fn first_word(s: &String) -> usize { -# let bytes = s.as_bytes(); -# -# for (i, &item) in bytes.iter().enumerate() { -# if item == 32 { -# return i; -# } -# } -# -# s.len() -# } +Filename: src/main.rs +```rust fn main() { let mut s = String::from("hello world"); @@ -948,12 +958,14 @@ let slice = &s[..]; With this in mind, let’s re-write `first_word()` to return a slice: +Filename: src/main.rs + ```rust fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { - if item == 32 { + if item == b' ' { return &s[0..i]; } } @@ -977,6 +989,8 @@ We now have a straightforward API that’s much harder to mess up. But what about our error condition from before? Slices also fix that. Using the slice version of `first_word()` will throw an error: +Filename: src/main.rs + ```rust,ignore fn main() { let mut s = String::from("hello world"); @@ -1046,18 +1060,9 @@ the ability to talk about full `String`s. And additionally, we can take string slices of string literals too, so this function is more useful, but with no loss of functionality: +Filename: src/main.rs + ```rust -# fn first_word(s: &str) -> &str { -# let bytes = s.as_bytes(); -# -# for (i, &item) in bytes.iter().enumerate() { -# if item == 32 { -# return &s[0..i]; -# } -# } -# -# &s[..] -# } fn main() { let my_string = String::from("hello world"); diff --git a/nostarch/chapter05.md b/nostarch/chapter05.md index d97cb5517..4d797e86f 100644 --- a/nostarch/chapter05.md +++ b/nostarch/chapter05.md @@ -1,3 +1,6 @@ + +[TOC] + # Structs A `struct`, short for "structure", gives us the ability to name and package @@ -22,6 +25,8 @@ $ cd points Here’s a short program which calculates the distance between two points. Put it into your `src/main.rs`: +Filename: src/main.rs + ```rust fn main() { let x1 = 0.0; @@ -78,7 +83,7 @@ modules and namespaces in depth yet, but you can think of the `powi()` function as being scoped inside of another name. In this case, the name is `f64`, the same as the type. The `powi()` function takes two arguments: the first is a number, and the second is the power that it raises that number to. In this -case, the second number is an integer, hence the ‘i’ in its name. Similarly, +case, the second number is an integer, hence the `i` in its name. Similarly, `sqrt()` is a function under the `f64` module, which takes the square root of its argument. @@ -100,6 +105,8 @@ and `(x2, y2)` together. We’ve already discussed one way to do that: tuples. Here’s a version of our program which uses tuples: +Filename: src/main.rs + ```rust fn main() { let p1 = (0.0, 5.0); @@ -173,6 +180,8 @@ let x = p1.x; Let’s convert our program to use our `Point` `struct`. Here’s what it looks like now: +Filename: src/main.rs + ```rust #[derive(Debug,Copy,Clone)] struct Point { @@ -224,6 +233,8 @@ So far, we’ve been printing values using `{}` in a `println!` macro. If we try that with a struct, however, by default, we'll get an error. Say we have the following program: +Filename: src/main.rs + ```rust,ignore struct Point { x: f64, @@ -270,6 +281,8 @@ defined. To ask `println!` to use `Debug` formatting with our `Point`, we add the annotation to derive the trait and include `:?` in the print string, like this: +Filename: src/main.rs + ```rust #[derive(Debug)] struct Point { @@ -298,8 +311,8 @@ Chapter XX. ## Method Syntax -In the last section on ownership, we made several references to ‘methods’. -Methods look like this: +In Chapter 4 when we discussed ownership, we made several references to +*methods*. Methods look like this: ```rust let s1 = "hello"; @@ -310,8 +323,8 @@ let s2 = s1.clone(); println!("{}", s1); ``` -The call to `clone()` is attached to `s1` with a dot. This is called ‘method -syntax’, and it’s a way to call certain functions with a different style. +The call to `clone()` is attached to `s1` with a dot. This is called *method +syntax*, and it’s a way to call certain functions with a different style. Why have two ways to call functions? We’ll talk about some deeper reasons related to ownership in a moment, but one big reason is that methods look nicer @@ -335,7 +348,7 @@ methods. ### Defining methods We can define methods with the `impl` keyword. `impl` is short for -‘implementation’. Doing so looks like this: +*implementation*. Doing so looks like this: ```rust #[derive(Debug,Copy,Clone)] @@ -432,28 +445,12 @@ assert_eq!(8.200609733428363, p1.distance(&p2)); When we defined `distance()`, we took both `self` and the other argument by reference. Yet, we needed a `&` for `p2` but not `p1`. What gives? -This feature is called ‘automatic referencing’, and calling methods is one +This feature is called *automatic referencing*, and calling methods is one of the few places in Rust that has behavior like this. Here’s how it works: when you call a method with `self.(`, Rust will automatically add in `&`s or `&mut`s to match the signature. In other words, these are the same: ```rust -# #[derive(Debug,Copy,Clone)] -# struct Point { -# x: f64, -# y: f64, -# } -# -# impl Point { -# fn distance(&self, other: &Point) -> f64 { -# let x_squared = f64::powi(other.x - self.x, 2); -# let y_squared = f64::powi(other.y - self.y, 2); -# -# f64::sqrt(x_squared + y_squared) -# } -# } -# let p1 = Point { x: 0.0, y: 0.0 }; -# let p2 = Point { x: 5.0, y: 6.5 }; p1.distance(&p2); (&p1).distance(&p2); ``` @@ -471,14 +468,12 @@ s.push_str(" world!"); assert_eq!("Hello, world!", s); ``` -Because [`push_str()`] has the following signature: +Because `push_str()` has the following signature: ```rust,ignore fn push_str(&mut self, string: &str) { ``` -[`push_str()`]: http://doc.rust-lang.org/collections/string/struct.String.html#method.push_str - This automatic referencing behavior works because methods have a clear receiver — the type of `self` — and in most cases it’s clear given the receiver and name of a method whether the method is just reading (so needs `&self`), mutating (so diff --git a/nostarch/chapter06.md b/nostarch/chapter06.md index 57d5ba53d..7dead4e5b 100644 --- a/nostarch/chapter06.md +++ b/nostarch/chapter06.md @@ -1,3 +1,6 @@ + +[TOC] + # Enums Next, let’s look at *enumerations*, which allow you to define a type by @@ -25,11 +28,6 @@ enumerate all of the possible kinds that our value can have. We can create values of `IpAddrKind` like this: ```rust -# enum IpAddrKind { -# V4, -# V6, -# } -# let four = IpAddrKind::V4; let six = IpAddrKind::V6; ``` @@ -98,7 +96,7 @@ let loopback = IpAddr::V6(String::from("::1")); ``` You can put any kind of data inside of an enum variant, including another enum! -The `IpAddr` enum is [in the standard library][IpAddr], but it embeds two +The `IpAddr` enum is in the standard library, but it embeds two different structs inside of its variants: ```rust @@ -116,8 +114,6 @@ enum IpAddr { } ``` -[IpAddr]: http://doc.rust-lang.org/std/net/enum.IpAddr.html - Here’s an enum with a variety of types embedded in its variants: ```rust @@ -140,7 +136,7 @@ that you already know, except without the `struct` keyword and they are grouped together under the `Message` type. These structs could hold the same data that these enum variants hold: -``` +```rust struct QuitMessage; // unit struct struct MoveMessage { x: i32, @@ -160,7 +156,7 @@ feature that we talked a little bit about in the previous chapter: generics. Programming language design is often thought of as which features you include, but it's also about which features you leave out. Rust does not have a feature -that is in many other languages: 'null'. In languages with this feature, +that is in many other languages: *null*. In languages with this feature, variables can have two states: null or not-null. The inventor of this concept has this to say: @@ -195,13 +191,11 @@ enum Option { } ``` -This enum is [provided by the standard library][option], and is so useful that +This enum is provided by the standard library, and is so useful that it's even in the prelude; you don't need to import it explicitly. Furthermore, so are its variants: you can say `Some` and `None` directly, without prefixing them with `Option::`. -[option]: ../std/option/enum.Option.html - Here's an example of using `Option`: ```rust @@ -215,7 +209,7 @@ let absent_number: Option = None; Let's dig in. First, you'll notice that we used the `` syntax when defining `Option`: it's a generic enum. `Option` has two variants: `Some`, which contains a `T`, and `None`, which has no data associated with it. In some -sense, `None` means 'null', and `Some` means 'not null'. So why is this any +sense, `None` means "null", and `Some` means "not null". So why is this any better than null? In short, because `Option` and `T` are different types. That's a bit too @@ -230,7 +224,7 @@ let sum = x + y; This will not compile. We get an error message like this: -```text +```bash error: the trait bound `i8: std::ops::Add>` is not satisfied [E0277] @@ -255,11 +249,9 @@ deliberate design decision for Rust to limit null's pervasiveness and increase the safety of Rust code. So, how _do_ you get a `T` from an `Option`? The `Option` enum has a -large number of methods that you can check out in [its documentation], and +large number of methods that you can check out in its documentation, and becoming familiar with them will be extremely useful in your journey with Rust. -[its documentation]: ../std/option/enum.Option.html - But we want a deeper understanding than that. If we didn't have those methods defined for us already, what would we do? And more generally, how do we get the inner values out of any enum variant? We need a new feature: `match`. @@ -332,13 +324,6 @@ print out "Lucky penny!" every time the method was called with a `Coin::Penny`, but would still return the last value of the block, `1`: ```rust -# enum Coin { -# Penny, -# Nickel, -# Dime, -# Quarter, -# } -# fn value_in_cents(coin: Coin) -> i32 { match coin { Coin::Penny => { @@ -385,19 +370,6 @@ created if the coin matches the `Quarter` pattern. Then we can use the binding in the code for that arm: ```rust -# #[derive(Debug)] -# enum UsState { -# Alabama, -# Alaska, -# } -# -# enum Coin { -# Penny, -# Nickel, -# Dime, -# Quarter(UsState), -# } -# fn value_in_cents(coin: Coin) -> i32 { match coin { Coin::Penny => 1, @@ -494,7 +466,7 @@ fn plus_one(x: Option) -> Option { A bug! We didn't handle the `None` case. Luckily, it's a bug Rust knows how to catch. If we try to compile this code, we'll get an error: -```text +```bash error: non-exhaustive patterns: `None` not covered [E0004] match x { Some(i) => Some(i + 1), @@ -539,7 +511,6 @@ There's one more advanced control flow structure we haven't discussed: `if let`. Imagine we're in a situation like this: ```rust -# let some_option = Some(5); match some_option { Some(x) => { // do something with x @@ -559,7 +530,6 @@ others." Enter `if let`: ```rust -# let some_option = Some(5); if let Some(x) = some_option { // do something with x }