diff --git a/appendix-00.html b/appendix-00.html index 6d9b02b1c..9be4c2721 100644 --- a/appendix-00.html +++ b/appendix-00.html @@ -67,7 +67,7 @@
-

Appendix

+

Appendix

The following sections contain reference material you may find useful in your Rust journey.

diff --git a/appendix-01-keywords.html b/appendix-01-keywords.html index 7df8b08b6..3e2995ba6 100644 --- a/appendix-01-keywords.html +++ b/appendix-01-keywords.html @@ -67,7 +67,7 @@
-

Keywords

+

Keywords

The following keywords are reserved by the Rust language and may not be used as names of functions, variables, macros, modules, crates, constants, static values, attributes, struct fields, or parameters.

diff --git a/appendix-02-operators.html b/appendix-02-operators.html index c02f46116..3e698369a 100644 --- a/appendix-02-operators.html +++ b/appendix-02-operators.html @@ -67,8 +67,8 @@
-

Operators

-

Unary operator expressions

+

Operators

+

Unary operator expressions

Rust defines the following unary operators. They are all written as prefix operators, before the expression they apply to.

-

Binary operator expressions

+

Binary operator expressions

Binary operators expressions are given in order of operator precedence.

-

Arithmetic operators

+

Arithmetic operators

Binary arithmetic expressions are syntactic sugar for calls to built-in traits, defined in the std::ops module of the std library. This means arithmetic operators can be overridden for user-defined types. The default meaning of the @@ -122,7 +122,7 @@ Calls the rem method on the std::ops::Rem trait.

Note that Rust does not have a built-in operator for exponential (power) calculation; see the pow method on the numeric types.

-

Bitwise operators

+

Bitwise operators

Like the arithmetic operators, bitwise operators are syntactic sugar for calls to methods of built-in traits. This means bitwise operators can be overridden for user-defined types. The default meaning of the operators on standard types @@ -145,7 +145,7 @@ Calls the shl method of the std::ops::Shl trait. : Right shift (arithmetic). Calls the shr method of the std::ops::Shr trait. -

Lazy boolean operators

+

Lazy boolean operators

The operators || and && may be applied to operands of boolean type. The || operator denotes logical 'or', and the && operator denotes logical 'and'. They differ from | and & in that the right-hand operand is only @@ -153,7 +153,7 @@ evaluated when the left-hand operand does not already determine the result of the expression. That is, || only evaluates its right-hand operand when the left-hand operand evaluates to false, and && only when it evaluates to true.

-

Comparison operators

+

Comparison operators

Comparison operators are, like the arithmetic operators and bitwise operators, syntactic sugar for calls to built-in traits. This means that comparison operators can be overridden for user-defined types. The default meaning of the @@ -178,7 +178,7 @@ Calls the le method on the std::cmp::PartialOrd trait. : Greater than or equal. Calls the ge method on the std::cmp::PartialOrd trait. -

Type cast expressions

+

Type cast expressions

A type cast expression is denoted with the binary operator as.

Executing an as expression casts the value on the left-hand side to the type on the right-hand side.

@@ -198,7 +198,7 @@ argument passing and assignment to a let binding with an explicit type. Implicit conversions are limited to "harmless" conversions that do not lose information and which have minimal or no risk of surprising side-effects on the dynamic execution semantics.

-

Assignment expressions

+

Assignment expressions

An assignment expression consists of a pattern followed by an equals sign (=) and an expression.

Evaluating an assignment expression either copies or @@ -208,12 +208,12 @@ operand.

# let y = 0; x = y; -

Compound assignment expressions

+

Compound assignment expressions

The +, -, *, /, %, &, |, ^, <<, and >> operators may be composed with the = operator. The expression lval OP= val is equivalent to lval = lval OP val. For example, x = x + 1 may be written as x += 1.

Any such expression always has the unit type.

-

Operator precedence

+

Operator precedence

The precedence of Rust binary operators is ordered as follows, going from strong to weak:

as :
diff --git a/appendix-03-derivable-traits.html b/appendix-03-derivable-traits.html
index 133d77294..01085a492 100644
--- a/appendix-03-derivable-traits.html
+++ b/appendix-03-derivable-traits.html
@@ -67,7 +67,7 @@
                 
-

Derivable Traits

+

Derivable Traits

diff --git a/appendix-04-nightly-rust.html b/appendix-04-nightly-rust.html index fff73d375..f1a0859ad 100644 --- a/appendix-04-nightly-rust.html +++ b/appendix-04-nightly-rust.html @@ -67,7 +67,7 @@
-

Nightly Rust

+

Nightly Rust

diff --git a/appendix-05-macros.html b/appendix-05-macros.html index 5afd79ab0..a482315d2 100644 --- a/appendix-05-macros.html +++ b/appendix-05-macros.html @@ -67,9 +67,9 @@
-

Macros

-

Basics of writing your own macros

-

Macros are changing, go see X for more info

+

Macros

+

Basics of writing your own macros

+

Macros are changing, go see X for more info

diff --git a/book.js b/book.js index 8731880ce..21295140d 100644 --- a/book.js +++ b/book.js @@ -55,20 +55,6 @@ $( document ).ready(function() { var page_wrapper = $("#page-wrapper"); var content = $("#content"); - - // Add anchors for all content headers - content.find("h1, h2, h3, h4, h5").wrap(function(){ - var wrapper = $(""); - var header_name = $(this).text().trim().replace(/\W/g, '-') - wrapper.attr("name", header_name); - // Add so that when you click the link actually shows up in the url bar... - // Remove any existing anchor then append the new one - // ensuring eg. no spaces are present within it ie. they become %20 - wrapper.attr("href", $(location).attr('href').split("#")[0] + "#" + header_name ); - return wrapper; - }); - - // Toggle sidebar $("#sidebar-toggle").click(function(event){ if ( html.hasClass("sidebar-hidden") ) { diff --git a/ch01-00-introduction.html b/ch01-00-introduction.html index 92682e889..008d41afb 100644 --- a/ch01-00-introduction.html +++ b/ch01-00-introduction.html @@ -67,7 +67,7 @@
-

Introduction

+

Introduction

Welcome to “The Rust Programming Language,” an introductory book about Rust. Rust is a programming language that’s focused on safety, speed, and concurrency. Its design lets you create programs that have the performance and @@ -88,7 +88,7 @@ one programming language. After reading this book, you should be comfortable writing Rust programs. We’ll be learning Rust through small, focused examples that build on each other to demonstrate how to use various features of Rust as well as how they work behind the scenes.

-

Contributing to the book

+

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.

diff --git a/ch01-01-installation.html b/ch01-01-installation.html index 08d345ce0..b5242a368 100644 --- a/ch01-01-installation.html +++ b/ch01-01-installation.html @@ -67,7 +67,7 @@
-

Installation

+

Installation

The first step to using Rust is to install it. You’ll need an internet connection to run the commands in this chapter, as we’ll be downloading Rust from the internet.

@@ -77,7 +77,7 @@ the start of each command. You’ll see many tutorials and examples around the w that follow this convention: $ for commands run as a regular user, and # for commands you should be running as an administrator. Lines that don't start with $ are typically showing the output of the previous command.

-

Installing on Linux or Mac

+

Installing on Linux or Mac

If you're on Linux or a Mac, all you need to do is open a terminal and type this:

$ curl https://sh.rustup.rs -sSf | sh
@@ -88,7 +88,7 @@ your password. If it all goes well, you’ll see this appear:

Of course, if you disapprove of the curl | sh pattern, you can download, inspect and run the script however you like.

-

Installing on Windows

+

Installing on Windows

On Windows, go to https://rustup.rs and follow the instructions to download rustup-init.exe. Run that and follow the rest of the instructions it gives you.

@@ -96,15 +96,15 @@ rest of the instructions it gives you.

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.

-

Custom installations

+

Custom installations

If you have reasons for preferring not to use rustup.rs, please see the Rust installation page for other options.

-

Uninstalling

+

Uninstalling

Uninstalling Rust is as easy as installing it. From your shell, run the uninstall script:

$ rustup self uninstall
 
-

Troubleshooting

+

Troubleshooting

If you've got Rust installed, you can open up a shell, and type this:

$ rustc --version
 
@@ -122,7 +122,7 @@ which you can access through the user’s forum and Stack Overflow.

-

Local documentation

+

Local documentation

The installer also includes a copy of the documentation locally, so you can read it offline. Run rustup doc to open the local documentation in your browser.

diff --git a/ch01-02-hello-world.html b/ch01-02-hello-world.html index 10ce50fe2..6b7f0b514 100644 --- a/ch01-02-hello-world.html +++ b/ch01-02-hello-world.html @@ -67,7 +67,7 @@
-

Hello, World!

+

Hello, World!

Now that you have Rust installed, let’s write your first Rust program. It's traditional when learning a new language to write a little program to print the text “Hello, world!” to the screen, and in this section, we'll follow that @@ -78,7 +78,7 @@ makes no specific demands about your editing, tooling, or where your code lives, so if you prefer an IDE to the command line, feel free to use your favorite IDE.

-

Creating a Project Directory

+

Creating a Project Directory

First, make a directory to put your Rust code in. Rust doesn't care where your code lives, but for this book, we'd suggest making a projects directory in your home directory and keeping all your projects there. Open a terminal and enter @@ -95,7 +95,7 @@ $ cd hello_world > mkdir hello_world > cd hello_world -

Writing and Running a Rust Program

+

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 @@ -116,7 +116,7 @@ Hello, world! 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

+

Anatomy of a Rust Program

Now, let’s go over what just happened in your "Hello, world!" program in detail. Here's the first piece of the puzzle:

fn main() {
@@ -149,7 +149,7 @@ argument to println!, which prints the string to the screen. Easy e
 

The line ends with a semicolon (;). The ; indicates that this expression is over, and the next one is ready to begin. Most lines of Rust code end with a ;.

-

Compiling and Running Are Separate Steps

+

Compiling and Running Are Separate Steps

In "Writing and Running a Rust Program", we showed you how to run a newly created program. We'll break that process down and examine each step now.

Before running a Rust program, you have to compile it. You can use the Rust @@ -188,7 +188,7 @@ grows, you'll want to be able to manage all of the options your project has and make it easy to share your code with other people and projects. Next, we'll introduce you to a tool called Cargo, which will help you write real-world Rust programs.

-

Hello, Cargo!

+

Hello, Cargo!

Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to manage their Rust projects because it makes a lot of tasks easier. For example, Cargo takes care of building your code, downloading the libraries your code @@ -208,7 +208,7 @@ have Cargo installed by typing the following into your terminal:

If you see a version number, great! If you see an error like command not 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

+

Creating a Project with Cargo

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):

@@ -281,7 +281,7 @@ everything, and everything is in its place.

the hello_world directory, you can convert it to a project that does use Cargo by moving your code into the src directory and creating an appropriate Cargo.toml.

-

Building and Running a Cargo Project

+

Building and Running a Cargo Project

Now let's look at what's different about building and running your Hello World program through Cargo! To do so, enter the following commands:

$ cargo build
@@ -331,7 +331,7 @@ 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

+

Building for Release

When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. This will create an executable in target/release instead of target/debug. These optimizations make your Rust code run faster, but turning them on makes your program take @@ -341,7 +341,7 @@ building the final program you’ll give to a user that won't be rebuilt and that we want to run as fast as possible. If you're benchmarking the running time of your code, be sure to run cargo build --release and benchmark with the executable in target/release.

-

Cargo as Convention

+

Cargo as Convention

With simple projects, Cargo doesn't provide a whole lot of value over just using rustc, but it will prove its worth as you continue. With complex projects composed of multiple crates, it’s much easier to let Cargo coordinate diff --git a/ch02-00-guessing-game-tutorial.html b/ch02-00-guessing-game-tutorial.html index 557223999..691b0f393 100644 --- a/ch02-00-guessing-game-tutorial.html +++ b/ch02-00-guessing-game-tutorial.html @@ -67,7 +67,7 @@

-

Guessing Game

+

Guessing Game

Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about let, match, methods, associated @@ -78,7 +78,7 @@ how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After entering a guess, it will indicate whether the guess is too low or too high. If the guess is correct, the game will print congratulations and exit.

-

Setting Up a New Project

+

Setting Up a New Project

To set up a new project, go to the projects directory that you created in Chapter 1, and make a new project using Cargo, like so:

$ cargo new guessing_game --bin
@@ -117,7 +117,7 @@ Hello, world!
 and this game is such a project: we want to quickly test each iteration
 before moving on to the next one.

Reopen the src/main.rs file. You’ll be writing all the code in this file.

-

Processing a Guess

+

Processing a Guess

The first part of the program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess. Enter the code in Listing 2-1 into src/main.rs.

@@ -166,7 +166,7 @@ println!("Please input your guess.");

This code is just printing a prompt stating what the game is and requesting input from the user.

-

Storing Values with Variables

+

Storing Values with Variables

Next, we’ll create a place to store the user input, like this:

let mut guess = String::new();
 
@@ -237,7 +237,7 @@ written this code as:

However, one long line is difficult to read, so it’s best to divide it, two lines for two method calls. Now let’s discuss what this line does.

-

Handling Potential Failure with the Result Type

+

Handling Potential Failure with the Result Type

As mentioned earlier, read_line puts what the user types into the string we’re passing it, but it also returns a value—in this case, an io::Result. Rust has a number of types named @@ -275,7 +275,7 @@ indicating that the program hasn’t handled a possible error. The right way to suppress the warning is to actually write error handling, but since we just want to crash this program when a problem occurs, we can use expect. You’ll learn about recovering from errors in Chapter 9.

-

Printing Values with println! Placeholders

+

Printing Values with println! Placeholders

Aside from the closing curly brace, there’s only one more line to discuss in the code added so far, which is the following:

println!("You guessed: {}", guess);
@@ -291,7 +291,7 @@ let y = 10;
 println!("x = {} and y = {}", x, y);
 

This code would print out x = 5 and y = 10.

-

Testing the First Part

+

Testing the First Part

Let’s test the first part of the guessing game. You can run it using cargo run:

$ cargo run
    Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
@@ -303,13 +303,13 @@ You guessed: 6
 

At this point, the first part of the game is done: we’re getting input from the keyboard and then printing it.

-

Generating a Secret Number

+

Generating a Secret Number

Next, we need to generate a secret number that the user will try to guess. The secret number should be different every time so the game is fun to play more than once. Let’s use a random number between 1 and 100 so the game isn’t too difficult. Rust doesn’t yet include random number functionality in its standard library. However, the Rust team does provide a rand crate.

-

Using a Crate to Get More Functionality

+

Using a Crate to Get More Functionality

Remember that a crate is 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.

@@ -373,7 +373,7 @@ you’ll only see one line of output:

src/main.rs file. Your dependencies haven't changed, so Cargo knows it can reuse what it has already downloaded and compiled for those. It just rebuilds your part of the code.

-

The Cargo.lock File Ensures Reproducible Builds

+

The Cargo.lock File Ensures Reproducible Builds

Cargo has a mechanism that ensures you can rebuild the same artifact every time you or anyone else builds your code: Cargo will use only the versions of the dependencies you specified until you indicate otherwise. For example, what @@ -390,7 +390,7 @@ rather than doing all the work of figuring out versions again. This lets you have a reproducible build automatically. In other words, your project will remain at 0.3.14 until you explicitly upgrade, thanks to the Cargo.lock file.

-

Updating a Crate to Get a New Version

+

Updating a Crate to Get a New Version

When you do want to update a crate, Cargo provides another command, update, which will:

    @@ -421,7 +421,7 @@ ecosystem that Chapter 14 will discuss, but for now, that’s all you need to know. Cargo makes it very easy to reuse libraries, so Rustaceans are able to write smaller projects that are assembled from a number of packages.

    -

    Generating a Random Number

    +

    Generating a Random Number

    Let’s start using rand. The next step is to update src/main.rs, as shown in Listing 2-3:

    @@ -496,7 +496,7 @@ You guessed: 5

    You should get different random numbers, and they should all be numbers between 1 and 100. Great job!

    -

    Comparing the Guess to the Secret Number

    +

    Comparing the Guess to the Secret Number

    Now that we have user input and a random number, we can compare them. That step is shown in Listing 2-4:

    @@ -689,7 +689,7 @@ different behavior with different kinds of input: guess the number correctly, guess a number that is too high, and guess a number that is too low.

    We have most of the game working now, but the user can make only one guess. Let’s change that by adding a loop!

    -

    Allowing Multiple Guesses with Looping

    +

    Allowing Multiple Guesses with Looping

    The loop keyword gives us an infinite loop. Add that now to give users more chances at guessing the number:

    Filename: src/main.rs

    @@ -763,7 +763,7 @@ error: Process didn't exit successfully: `target/debug/guess` (exit code: 101)

    Typing quit actually quits the game, but so will any other non-number input. However, this is suboptimal to say the least. We want the game to automatically stop when the correct number is guessed.

    -

    Quitting After a Correct Guess

    +

    Quitting After a Correct Guess

    Let’s program the game to quit when the user wins by adding a break:

    Filename: src/main.rs

    extern crate rand;
    @@ -806,7 +806,7 @@ fn main() {
     

    By adding the break line after You win!, the program will exit the loop when the user guesses the secret number correctly. Exiting the loop also means exiting the program, because the loop is the last part of main.

    -

    Handling Invalid Input

    +

    Handling Invalid Input

    To further refine the game’s behavior, rather than crashing the program when the user inputs a non-number, let’s make the game ignore a non-number so the user can continue guessing. We can do that by altering the line where guess is @@ -904,7 +904,7 @@ fn main() {

    Listing 2-5: Complete code of the guessing game

    -

    Summary

    +

    Summary

    At this point, you’ve successfully built the guessing game! Congratulations!

    This project was a hands-on way to introduce you to many new Rust concepts: let, match, methods, associated functions, using external crates, and more. diff --git a/ch03-00-common-programming-concepts.html b/ch03-00-common-programming-concepts.html index 518d3f570..2d172417e 100644 --- a/ch03-00-common-programming-concepts.html +++ b/ch03-00-common-programming-concepts.html @@ -67,7 +67,7 @@

-

Common Programming Concepts

+

Common Programming Concepts

This chapter covers concepts that appear in almost every programming language and how they work in Rust. Many programming languages have much in common at their core. None of the concepts presented in this chapter are unique to Rust, @@ -77,7 +77,7 @@ and control flow. These foundations will be in every Rust program, and learning them early will give you a strong core to start from.

-

Keywords

+

Keywords

The Rust language has a set of keywords that have been reserved for use by the language only, much like other languages do. Keep in mind that you cannot use these words as names of variables or functions. Most of the keywords have diff --git a/ch03-01-variables-and-mutability.html b/ch03-01-variables-and-mutability.html index 2dea494e0..19aef9c43 100644 --- a/ch03-01-variables-and-mutability.html +++ b/ch03-01-variables-and-mutability.html @@ -67,7 +67,7 @@

-

Variables and Mutability

+

Variables and Mutability

As mentioned in Chapter 2, by default variables are immutable. This is one of many nudges in Rust that encourages you to write your code in a way that takes advantage of the safety and easy concurrency that Rust offers. However, you @@ -147,7 +147,7 @@ an instance in place may be faster than copying and returning newly allocated instances. With smaller data structures, always creating new instances and writing in a more functional programming style may be easier to reason about, so the lower performance penalty might be worth it to gain that clarity.

-

Differences Between Variables and Constants

+

Differences Between Variables and Constants

Not being able to change the value of a variable might have reminded you of another programming concept that most languages have: constants. Constants are also values bound to a name that are not allowed to change, but there are a @@ -175,7 +175,7 @@ of seconds in a year.

constants is useful to convey the meaning of that value to future maintainers of the code. It also helps to have only one place in your code that you would need to change if the hardcoded value needed to be updated in the future.

-

Shadowing

+

Shadowing

As we saw in the guessing game tutorial in Chapter 2, we can declare new variables with the same name as a previous variables, and the new variable shadows the previous variable. Rustaceans say that the first variable is diff --git a/ch03-02-data-types.html b/ch03-02-data-types.html index 5443c628a..9970fed50 100644 --- a/ch03-02-data-types.html +++ b/ch03-02-data-types.html @@ -67,7 +67,7 @@

-

Data Types

+

Data Types

Every value in Rust is of a certain type, which tells Rust what kind of data is being specified so it knows how to work with that data. In this section, we’ll look at a number of types that are built into the language. We split the @@ -92,12 +92,12 @@ possible type we want to use:

= note: type annotations or generic parameter binding required

You’ll see different type annotations as we discuss the various data types.

-

Scalar Types

+

Scalar Types

A scalar type represents a single value. Rust has four primary scalar types: integers, floating-point numbers, booleans, and characters. You’ll likely recognize these from other programming languages, but let’s jump into how they work in Rust.

-

Integer Types

+

Integer Types

An integer is a number without a fractional component. We used one integer type earlier in this chapter, the i32 type. This type declaration indicates that the value it’s associated with should be a signed integer (hence the i, @@ -153,7 +153,7 @@ that all number literals except the byte literal allow a type suffix, such as defaults are generally good choices, and integer types default to i32: it’s generally the fastest, even on 64-bit systems. The primary situation in which you’d use isize or usize is when indexing some sort of collection.

-

Floating-Point Types

+

Floating-Point Types

Rust also has two primitive types for floating-point numbers, which are numbers with decimal points. Rust’s floating-point types are f32 and f64, which are 32 bits and 64 bits in size, respectively. The default type is f64 @@ -173,7 +173,7 @@ your situation.

Floating-point numbers are represented according to the IEEE-754 standard. The f32 type is a single-precision float, and f64 has double precision.

-

Numeric Operations

+

Numeric Operations

Rust supports the usual basic mathematic operations you’d expect for all of the number types: addition, subtraction, multiplication, division, and remainder. The following code shows how you’d use each one in a let statement:

@@ -198,7 +198,7 @@ The following code shows how you’d use each one in a let statemen

Each expression in these statements uses a mathematical operator and evaluates to a single value, which is then bound to a variable. Appendix B contains a list of all operators that Rust provides.

-

The Boolean Type

+

The Boolean Type

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 using bool. For example:

@@ -212,7 +212,7 @@ For example:

The main way to consume boolean values is through conditionals, such as an if statement. We’ll cover how if statements work in Rust in the “Control Flow” section.

-

The Character Type

+

The Character Type

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 the following code shows one way to use it:

@@ -231,10 +231,10 @@ Unicode Scalar Values range from U+0000 to U+D7FF and so your human intuition for what a “character” is may not match up with what a char is in Rust. We’ll discuss this topic in detail in the “Strings” section in Chapter 8.

-

Compound Types

+

Compound Types

Compound types can group multiple values of other types into one type. Rust has two primitive compound types: tuples and arrays.

-

Grouping Values into Tuples

+

Grouping Values into Tuples

A tuple is a general way of grouping together some number of other values with a variety of types into one compound type.

We create a tuple by writing a comma-separated list of values inside @@ -280,7 +280,7 @@ value we want to access. For example:

This program creates a tuple, x, and then makes new variables for each element by using their index. As with most programming languages, the first index in a tuple is 0.

-

Arrays

+

Arrays

Another way to have a collection of multiple values is with an array. Unlike a tuple, every element of an array must have the same type. Arrays in Rust are different than arrays in some other languages because arrays in Rust have a @@ -306,7 +306,7 @@ an array because you know it will always contain 12 items:

let months = ["January", "February", "March", "April", "May", "June", "July",
               "August", "September", "October", "November", "December"];
 
-
Accessing Array Elements
+
Accessing Array Elements

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

@@ -320,7 +320,7 @@ elements of an array using indexing, like this:

In this example, the variable named first will get the value 1, because that is the value at index [0] in the array. The variable named second will get the value 2 from index [1] in the array.

-
Invalid Array Element Access
+
Invalid Array Element Access

What happens if we try to access an element of an array that is past the end of the array? Say we change the example to the following:

Filename: src/main.rs

diff --git a/ch03-03-how-functions-work.html b/ch03-03-how-functions-work.html index 3731dbf3a..73d433eec 100644 --- a/ch03-03-how-functions-work.html +++ b/ch03-03-how-functions-work.html @@ -67,7 +67,7 @@
-

How Functions Work

+

How Functions Work

Functions are pervasive in Rust code. You’ve already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the fn keyword, which allows you to @@ -107,7 +107,7 @@ Another function.

The lines execute in the order in which they appear in the main function. First, the “Hello, world!” message prints, and then another_function is called and its message is printed.

-

Function Parameters

+

Function Parameters

Functions can also be defined to have parameters, which are special variables that are part of a function's signature. When a function has parameters, we can provide it with concrete values for those parameters. Technically, the concrete @@ -167,7 +167,7 @@ The value of y is: 6

Because we called the function with 5 as the value for x and 6 as the value for y, the two strings are printed using those values.

-

Function Bodies

+

Function Bodies

Function bodies are made up of a series of statements optionally ending in an expression. So far, we’ve only covered functions without an ending expression, but we have seen expressions as parts of statements. Because Rust is an @@ -175,7 +175,7 @@ expression-based language, this is an important distinction to understand. Other languages don’t have the same distinctions, so let’s look at what statements and expressions are and how their differences affect the bodies of functions.

-

Statements and Expressions

+

Statements and Expressions

We’ve actually already used statements and expressions. Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.

@@ -247,7 +247,7 @@ unlike most of the lines you’ve seen so far. Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value. Keep this in mind as you explore function return values and expressions next.

-

Functions with Return Values

+

Functions with Return Values

Functions can return values to the code that calls them. We don’t name return values, but we do declare their type after an arrow (->). In Rust, the return value of the function is synonymous with the value of the final expression in diff --git a/ch03-04-comments.html b/ch03-04-comments.html index e155e8b1b..dfb799b64 100644 --- a/ch03-04-comments.html +++ b/ch03-04-comments.html @@ -67,7 +67,7 @@

-

Comments

+

Comments

All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted. In these cases, programmers leave notes, or comments, in their source code that the compiler will ignore but people diff --git a/ch03-05-control-flow.html b/ch03-05-control-flow.html index b5cae4f06..a38bfb66f 100644 --- a/ch03-05-control-flow.html +++ b/ch03-05-control-flow.html @@ -67,13 +67,13 @@

-

Control Flow

+

Control Flow

Deciding whether or not to run some code depending on if a condition is true or deciding to run some code repeatedly while a condition is true are basic building blocks in most programming languages. The most common constructs that let you control the flow of execution of Rust code are if expressions and loops.

-

if Expressions

+

if Expressions

An if expression allows us to branch our code depending on conditions. We provide a condition and then state, “If this condition is met, run this block of code. If the condition is not met, do not run this block of code.”

@@ -161,7 +161,7 @@ expression to the following:

}

Running this code will print number was something other than zero.

-

Multiple Conditions with else if

+

Multiple Conditions with else if

We can have multiple conditions by combining if and else in an else if expression. For example:

Filename: src/main.rs

@@ -195,7 +195,7 @@ and once it finds one, it won’t even check the rest.

Using too many else if expressions can clutter your code, so if you have more than one, you might want to refactor your code. Chapter 6 describes a powerful Rust branching construct called match for these cases.

-

Using if in a let statement

+

Using if in a let statement

Because if is an expression, we can use it on the right side of a let statement, for instance in Listing 3-4:

@@ -263,13 +263,13 @@ valid everywhere we use number. Rust wouldn’t be able to do that of number was only determined at runtime; the compiler would be more complex and would make fewer guarantees about the code if it had to keep track of multiple hypothetical types for any variable.

-

Repetition with Loops

+

Repetition with Loops

It’s often useful to execute a block of code more than once. For this task, Rust provides several loops. A loop runs through the code inside the loop body to the end and then starts immediately back at the beginning. To experiment with loops, let’s make a new project called loops.

Rust has three kinds of loops: loop, while, and for. Let’s try each one.

-

Repeating Code with loop

+

Repeating Code with loop

The loop keyword tells Rust to execute a block of code over and over again forever or until you explicitly tell it to stop.

As an example, change the src/main.rs file in your loops directory to look @@ -301,7 +301,7 @@ You can place the break keyword within the loop to tell the program stop executing the loop. Recall that we did this in the guessing game in the “Quitting After a Correct Guess” section of Chapter 2 to exit the program when the user won the game by guessing the correct number.

-

Conditional Loops with while

+

Conditional Loops with while

It’s often useful for a program to evaluate a condition within a loop. While the condition is true, the loop runs. When the condition ceases to be true, you call break, stopping the loop. This loop type could be implemented using a @@ -327,7 +327,7 @@ prints another message and exits:

This construct eliminates a lot of nesting that would be necessary if you used loop, if, else, and break, and it’s clearer. While a condition holds true, the code runs; otherwise, it exits the loop.

-

Looping Through a Collection with for

+

Looping Through a Collection with for

You could use the while construct to loop over the elements of a collection, such as an array. For example:

@@ -409,7 +409,7 @@ we’ve not yet talked about, rev, to reverse the range:

}

This code is a bit nicer, isn’t it?

-

Summary

+

Summary

You made it! That was a sizable chapter: you learned about variables, scalar andif expressions, and loops! If you want to practice with the concepts discussed in this chapter, try building programs to do the following:

diff --git a/ch04-00-understanding-ownership.html b/ch04-00-understanding-ownership.html index 4bf6769d0..228150fda 100644 --- a/ch04-00-understanding-ownership.html +++ b/ch04-00-understanding-ownership.html @@ -67,7 +67,7 @@
-

Understanding Ownership

+

Understanding Ownership

Ownership is Rust’s most unique feature, and it enables Rust to make memory safety guarantees without needing a garbage collector. Therefore, it’s important to understand how ownership works in Rust. In this chapter we’ll talk diff --git a/ch04-01-what-is-ownership.html b/ch04-01-what-is-ownership.html index fe5a2db96..b1f35b2cd 100644 --- a/ch04-01-what-is-ownership.html +++ b/ch04-01-what-is-ownership.html @@ -67,7 +67,7 @@

-

What Is Ownership?

+

What Is Ownership?

Rust’s central feature is ownership. Although the feature is straightforward to explain, it has deep implications for the rest of the language.

All programs have to manage the way they use a computer’s memory while running. @@ -86,7 +86,7 @@ working through some examples that focus on a very common data structure: strings.

-

The Stack and the Heap

+

The Stack and the Heap

In many programming languages, we don’t have to think about the stack and the heap very often. But in a systems programming language like Rust, whether a value is on the stack or the heap has more of an effect on how the language @@ -140,7 +140,7 @@ heap very often, but knowing that managing heap data is why ownership exists can help explain why it works the way it does.

-

Ownership Rules

+

Ownership Rules

First, let’s take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate the rules:

@@ -150,7 +150,7 @@ work through the examples that illustrate the rules:

  • When the owner goes out of scope, the value will be dropped.
  • -

    Variable Scope

    +

    Variable Scope

    We’ve walked through an example of a Rust program already in Chapter 2. Now that we’re past basic syntax, we won’t include all the fn main() { code in examples, so if you’re following along, you’ll have to put the following @@ -185,7 +185,7 @@ comments annotating where the variable s is valid:

    At this point, the relationship between scopes and when variables are valid is similar to other programming languages. Now we’ll build on top of this understanding by introducing the String type.

    -

    The String Type

    +

    The String Type

    To illustrate the rules of ownership, we need a data type that is more complex than the ones we covered in Chapter 3. All the data types we’ve looked at previously are stored on the stack and popped off the stack when their scope is @@ -220,7 +220,7 @@ println!("{}", s); // This will print `hello, world!`

    So, what’s the difference here? Why can String be mutated but literals cannot? The difference is how these two types deal with memory.

    -

    Memory and Allocation

    +

    Memory and Allocation

    In the case of a string literal, we know the contents at compile time so the text is hardcoded directly into the final executable, making string literals fast and efficient. But these properties only come from its immutability. @@ -272,7 +272,7 @@ patterns.

    simple right now, but the behavior of code can be unexpected in more complicated situations when we want to have multiple variables use the data we’ve allocated on the heap. Let’s explore some of those situations now.

    -

    Ways Variables and Data Interact: Move

    +

    Ways Variables and Data Interact: Move

    Multiple variables can interact with the same data in different ways in Rust. Let’s look at an example using an integer in Listing 4-2:

    @@ -381,7 +381,7 @@ alone will free the memory, and we’re done.

    In addition, there’s a design choice that’s implied by this: Rust will never automatically create “deep” copies of your data. Therefore, any automatic copying can be assumed to be inexpensive in terms of runtime performance.

    -

    Ways Variables and Data Interact: Clone

    +

    Ways Variables and Data Interact: Clone

    If we do want to deeply copy the heap data of the String, not just the stack data, we can use a common method called clone. We’ll discuss method syntax in Chapter 5, but because methods are a common feature in many @@ -397,7 +397,7 @@ in Figure 4-5, where the heap data does get copied.

    When you see a call to clone, you know that some arbitrary code is being executed and that code may be expensive. It’s a visual indicator that something different is going on.

    -

    Stack-Only Data: Copy

    +

    Stack-Only Data: Copy

    There’s another wrinkle we haven’t talked about yet. This code using integers, part of which was shown earlier in Listing 4-2, works and is valid:

    let x = 5;
    @@ -431,7 +431,7 @@ be sure, but as a general rule, any group of simple scalar values can be
     
  • Tuples, but only if they contain types that are also Copy. (i32, i32) is Copy, but (i32, String) is not.
  • -

    Ownership and Functions

    +

    Ownership and Functions

    The semantics for passing a value to a function are similar to assigning a value to a variable. Passing a variable to a function will move or copy, just like assignment. Listing 4-7 has an example with some annotations showing where @@ -469,7 +469,7 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope. compile time error. These static checks protect us from mistakes. Try adding code to main that uses s and x to see where you can use them and where the ownership rules prevent you from doing so.

    -

    Return Values and Scope

    +

    Return Values and Scope

    Returning values can also transfer ownership. Here’s an example with similar annotations to those in Listing 4-7:

    Filename: src/main.rs

    diff --git a/ch04-02-references-and-borrowing.html b/ch04-02-references-and-borrowing.html index 28ac2682b..3899497f0 100644 --- a/ch04-02-references-and-borrowing.html +++ b/ch04-02-references-and-borrowing.html @@ -67,7 +67,7 @@
    -

    References and Borrowing

    +

    References and Borrowing

    The issue with the tuple code at the end of the preceding section is that we have to return the String to the calling function so we can still use the String after the call to calculate_length, because the String was moved @@ -153,7 +153,7 @@ fn change(some_string: &String) {

    Just as variables are immutable by default, so are references. We’re not allowed to modify something we have a reference to.

    -

    Mutable References

    +

    Mutable References

    We can fix the error in the code from Listing 4-9 with just a small tweak:

    Filename: src/main.rs

    fn main() {
    @@ -243,7 +243,7 @@ the data.

    Rust compiler pointing out a potential bug early (at compile time rather than at runtime) and showing you exactly where the problem is instead of you having to track down why sometimes your data isn’t what you thought it should be.

    -

    Dangling References

    +

    Dangling References

    In languages with pointers, it’s easy to erroneously create a dangling pointer, a pointer that references a location in memory that may have been given to someone else, by freeing some memory while preserving a pointer to @@ -306,7 +306,7 @@ won’t let us do this.

    This works without any problems. Ownership is moved out, and nothing is deallocated.

    -

    The Rules of References

    +

    The Rules of References

    Let’s recap what we’ve discussed about references:

    1. At any given time, you can have either but not both of:
    2. diff --git a/ch04-03-slices.html b/ch04-03-slices.html index 1d99a3a4c..ea2d9e771 100644 --- a/ch04-03-slices.html +++ b/ch04-03-slices.html @@ -67,7 +67,7 @@
    -

    Slices

    +

    Slices

    Another data type that does not have ownership is the slice. Slices let you reference a contiguous sequence of elements in a collection rather than the whole collection.

    @@ -180,7 +180,7 @@ that were calculated from data in a particular state but aren’t tied to that state at all. We now have three unrelated variables floating around that need to be kept in sync.

    Luckily, Rust has a solution to this problem: string slices.

    -

    String Slices

    +

    String Slices

    A string slice is a reference to part of a String, and looks like this:

    let s = String::from("hello world");
     
    @@ -290,7 +290,7 @@ something, we cannot also take a mutable reference. Because clear n
     truncate the String, it tries to take a mutable reference, which fails. Not
     only has Rust made our API easier to use, but it has also eliminated an entire
     class of errors at compile time!

    -

    String Literals Are Slices

    +

    String Literals Are Slices

    Recall that we talked about string literals being stored inside the binary. Now that we know about slices, we can properly understand string literals:

    let s = "Hello, world!";
    @@ -298,7 +298,7 @@ that we know about slices, we can properly understand string literals:

    The type of s here is &str: it’s a slice pointing to that specific point of the binary. This is also why string literals are immutable; &str is an immutable reference.

    -

    String Slices as Parameters

    +

    String Slices as Parameters

    Knowing that you can take slices of literals and Strings leads us to one more improvement on first_word, and that’s its signature:

    fn first_word(s: &String) -> &str {
    @@ -339,7 +339,7 @@ fn main() {
         let word = first_word(my_string_literal);
     }
     
    -

    Other Slices

    +

    Other Slices

    String slices, as you might imagine, are specific to strings. But there’s a more general slice type, too. Consider this array:

    let a = [1, 2, 3, 4, 5];
    @@ -354,7 +354,7 @@ let slice = &a[1..3];
     storing a reference to the first element and a length. You’ll use this kind of
     slice for all sorts of other collections. We’ll discuss these collections in
     detail when we talk about vectors in Chapter 8.

    -

    Summary

    +

    Summary

    The concepts of ownership, borrowing, and slices are what ensure memory safety in Rust programs at compile time. The Rust language gives you control over your memory usage like other systems programming languages, but having the owner of diff --git a/ch05-00-structs.html b/ch05-00-structs.html index cc8b4bb0d..35eed38bc 100644 --- a/ch05-00-structs.html +++ b/ch05-00-structs.html @@ -67,7 +67,7 @@

    -

    Structs

    +

    Structs

    A struct, short for structure, is a custom data type that lets us name and package together multiple related values that make up a meaningful group. If you come from an object-oriented language, a struct is like an object’s data @@ -126,7 +126,7 @@ let user1 = User {

    To get a particular value out of a struct, we can use dot notation. If we wanted just this user’s email address, we can say user1.email.

    -

    Ownership of Struct Data

    +

    Ownership of Struct Data

    In the User struct definition in Listing 5-1, we used the owned String type rather than the &str string slice type. This is a deliberate choice because we want instances of this struct to own all of its data, and for that data to @@ -169,7 +169,7 @@ error[E0106]: missing lifetime specifier

    We will talk about how to fix these errors in order to store references in structs in Chapter 10, but for now, fix errors like these by switching to owned types like String instead of references like &str.

    -

    An Example Program

    +

    An Example Program

    To understand when we might want to use structs, let’s write a program that calculates the area of a rectangle. We’ll start off with single variables, then refactor our program until we’re using structs instead.

    @@ -201,7 +201,7 @@ width in separate variables

    Let’s try running this program with cargo run:

    The area of the rectangle is 1500 square pixels.
     
    -

    Refactoring with Tuples

    +

    Refactoring with Tuples

    Our little program works okay; it figures out the area of the rectangle by calling the area function with each dimension. But we can do better. The length and the width are related to each other since together they describe one @@ -251,7 +251,7 @@ index 1. If someone else was to work on this code, they would have this out and remember it as well. It would be easy to forget or mix these values up and cause errors, since we haven’t conveyed the meaning of our data in our code.

    -

    Refactoring with Structs: Adding More Meaning

    +

    Refactoring with Structs: Adding More Meaning

    Here is where we bring in structs. We can transform our tuple into a data type with a name for the whole as well as names for the parts, as shown in Listing 5-4:

    @@ -296,7 +296,7 @@ calculate the area of a Rectangle, using its length an This conveys that the length and width are related to each other, and gives descriptive names to the values rather than using the tuple index values of 0 and 1. This is a win for clarity.

    -

    Adding Useful Functionality with Derived Traits

    +

    Adding Useful Functionality with Derived Traits

    It’d be nice to be able to print out an instance of our Rectangle while we’re debugging our program and see the values for all its fields. Listing 5-5 tries using the println! macro as we have been:

    diff --git a/ch05-01-method-syntax.html b/ch05-01-method-syntax.html index e07508cfa..19a76b7ec 100644 --- a/ch05-01-method-syntax.html +++ b/ch05-01-method-syntax.html @@ -67,7 +67,7 @@
    -

    Method Syntax

    +

    Method Syntax

    Methods are similar to functions: they’re declared with the fn keyword and their name, they can have parameters and return values, and they contain some code that gets run when they’re called from somewhere else. Methods are @@ -75,7 +75,7 @@ different from functions, however, because they’re defined within the context of a struct (or an enum or a trait object, which we will cover in Chapters 6 and 13, respectively), and their first parameter is always self, which represents the instance of the struct that the method is being called on.

    -

    Defining Methods

    +

    Defining Methods

    Let’s change our area function that has a Rectangle instance as a parameter and instead make an area method defined on the Rectangle struct, as shown in Listing 5-7:

    @@ -136,7 +136,7 @@ instance of a type together in one impl block, rather than make fut of our code search for capabilities of Rectangle all over the place.

    -

    Where’s the -> operator?

    +

    Where’s the -> operator?

    In languages like C++, there are two different operators for calling methods: . if you’re calling a method on the object directly, and -> if you’re calling the method on a pointer to the object and thus need to dereference the @@ -175,7 +175,7 @@ consuming (so self). The fact that Rust makes borrowing implicit fo receivers is a big part of making ownership ergonomic in practice.

    -

    Methods with More Parameters

    +

    Methods with More Parameters

    Let’s practice some more with methods by implementing a second method on our Rectangle struct. This time, we’d like for an instance of Rectangle to take another instance of Rectangle and return true if the second rectangle could @@ -235,7 +235,7 @@ impl Rectangle { Methods can have multiple parameters that we add to the signature after the self parameter, and those parameters work just like parameters in functions do.

    -

    Associated Functions

    +

    Associated Functions

    One more useful feature of impl blocks: we’re allowed to define functions within impl blocks that don’t take self as a parameter. These are called associated functions, since they’re associated with the struct. They’re still @@ -263,7 +263,7 @@ impl Rectangle { let sq = Rectangle::square(3);, for example. This function is namespaced by the struct: the :: syntax is used for both associated functions and namespaces created by modules, which we’ll learn about in Chapter 7.

    -

    Summary

    +

    Summary

    Structs let us create custom types that are meaningful for our domain. By using structs, we can keep associated pieces of data connected to each other and name each piece to make our code clear. Methods let us specify the behavior that diff --git a/ch06-00-enums.html b/ch06-00-enums.html index e7763a531..5a198a73e 100644 --- a/ch06-00-enums.html +++ b/ch06-00-enums.html @@ -67,7 +67,7 @@

    -

    Enums and Pattern Matching

    +

    Enums and Pattern Matching

    In this chapter we’ll look at enumerations, also referred to as enums. Enums allow you to define a type by enumerating its possible values. First, we’ll define and use an enum to show how an enum can encode meaning along with diff --git a/ch06-01-defining-an-enum.html b/ch06-01-defining-an-enum.html index e1f96a1d3..def5c20ea 100644 --- a/ch06-01-defining-an-enum.html +++ b/ch06-01-defining-an-enum.html @@ -67,7 +67,7 @@

    -

    Defining an Enum

    +

    Defining an Enum

    Let’s look at a situation we might want to express in code and see why enums are useful and more appropriate than structs in this case. Say we need to work with IP addresses. Currently, two major standards are used for IP addresses: @@ -89,7 +89,7 @@ as the variants of the enum:

    }

    IpAddrKind is now a custom data type that we can use elsewhere in our code.

    -

    Enum Values

    +

    Enum Values

    We can create instances of each of the two variants of IpAddrKind like this:

    # enum IpAddrKind {
     #     V4,
    @@ -283,7 +283,7 @@ method on. In this example, we’ve created a variable m that has t
     call method when m.call() runs.

    Let’s look at another enum in the standard library that is very common and useful: Option.

    -

    The Option Enum and Its Advantages Over Null Values

    +

    The Option Enum and Its Advantages Over Null Values

    In the previous section, we looked at how the IpAddr enum let us use Rust’s type system to encode more information than just the data into our program. This section explores a case study of Option, which is another enum defined diff --git a/ch06-02-match.html b/ch06-02-match.html index 9cf6ae9bf..2e77b7e6e 100644 --- a/ch06-02-match.html +++ b/ch06-02-match.html @@ -67,7 +67,7 @@

    -

    The match Control Flow Operator

    +

    The match Control Flow Operator

    Rust has an extremely powerful control-flow operator called match that allows us to compare a value against a series of patterns and then execute code based on which pattern matches. Patterns can be made up of literal values, variable @@ -148,7 +148,7 @@ fn value_in_cents(coin: Coin) -> i32 { } } -

    Patterns that Bind to Values

    +

    Patterns that Bind to Values

    Another useful feature of match arms is that they can bind to parts of the values that match the pattern. This is how we can extract values out of enum variants.

    @@ -217,7 +217,7 @@ of the match arms, none of them match until we reach Coin::Quarter(state)< that point, the binding for state will be the value UsState::Alaska. We can then use that binding in the println! expression, thus getting the inner state value out of the Coin enum variant for Quarter.

    -

    Matching with Option<T>

    +

    Matching with Option<T>

    In the previous section we wanted to get the inner T value out of the Some case when using Option<T>; we can also handle Option<T> using match as we did with the Coin enum! Instead of comparing coins, we’ll compare the @@ -245,7 +245,7 @@ let none = plus_one(None);

    Listing 6-5: A function that uses a match expression on an Option<i32>

    -

    Matching Some(T)

    +

    Matching Some(T)

    Let’s examine the first execution of plus_one in more detail. When we call plus_one(five), the variable x in the body of plus_one will have the value Some(5). We then compare that against each match arm.

    @@ -259,7 +259,7 @@ next arm.

    The i binds to the value contained in Some, so i takes the value 5. The code in the match arm is then executed, so we add one to the value of i and create a new Some value with our total 6 inside.

    -

    Matching None

    +

    Matching None

    Now let’s consider the second call of plus_one in Listing 6-5 where x is None. We enter the match and compare to the first arm.

    None => None,
    @@ -272,7 +272,7 @@ pattern a lot in Rust code: match against an enum, bind a variable
     data inside, and then execute code based on it. It’s a bit tricky at first, but
     once you get used to it, you’ll wish you had it in all languages. It’s
     consistently a user favorite.

    -

    Matches Are Exhaustive

    +

    Matches Are Exhaustive

    There’s one other aspect of match we need to discuss. Consider this version of our plus_one function:

    fn plus_one(x: Option<i32>) -> Option<i32> {
    @@ -296,7 +296,7 @@ possibility in order for the code to be valid. Especially in the case of
     Option<T>, when Rust prevents us from forgetting to explicitly handle the
     None case, it protects us from assuming that we have a value when we might
     have null, thus making the billion dollar mistake discussed earlier.

    -

    The _ Placeholder

    +

    The _ Placeholder

    Rust also has a pattern we can use in situations when we don’t want to list all possible values. For example, a u8 can have valid values of 0 through 255. If we only care about the values 1, 3, 5, and 7, we don’t want to have to list out diff --git a/ch06-03-if-let.html b/ch06-03-if-let.html index 743d1cfab..b7f7314a8 100644 --- a/ch06-03-if-let.html +++ b/ch06-03-if-let.html @@ -67,7 +67,7 @@

    -

    Concise Control Flow with if let

    +

    Concise Control Flow with if let

    The if let syntax lets you combine if and let into a less verbose way to handle values that match one pattern and ignore the rest. Consider the program in Listing 6-6 that matches on an Option<u8> value but only wants to execute @@ -154,7 +154,7 @@ if let Coin::Quarter(state) = coin {

    If you have a situation in which your program has logic that is too verbose to express using a match, remember that if let is in your Rust toolbox as well.

    -

    Summary

    +

    Summary

    We’ve now covered how to use enums to create custom types that can be one of a set of enumerated values. We’ve shown how the standard library’s Option<T> type helps you use the type system to prevent errors. When enum values have diff --git a/ch07-00-modules.html b/ch07-00-modules.html index 8c2298e27..6bffffef0 100644 --- a/ch07-00-modules.html +++ b/ch07-00-modules.html @@ -67,7 +67,7 @@

    -

    Modules

    +

    Modules

    When you start writing programs in Rust, your code might live solely in the main function. As your code grows, you’ll eventually move functionality out into other functions, both for re-use and for better organization. By splitting diff --git a/ch07-01-mod-and-the-filesystem.html b/ch07-01-mod-and-the-filesystem.html index 6c539d50f..f4f665e46 100644 --- a/ch07-01-mod-and-the-filesystem.html +++ b/ch07-01-mod-and-the-filesystem.html @@ -67,7 +67,7 @@

    -

    mod and the Filesystem

    +

    mod and the Filesystem

    We’ll start our module example by making a new project with Cargo, but instead of creating a binary crate, we’re going to make a library crate: a project that other people can pull into their projects as a dependency. We saw this with the @@ -101,7 +101,7 @@ to only compile our library crate’s code.

    We’re going to look at different options for organizing your library’s code which will be suitable in a variety of situations, depending on the intentions you have for your code.

    -

    Module Definitions

    +

    Module Definitions

    For our communicator networking library, we’re first going to define a module named network that contains the definition of a function called connect. Every module definition in Rust starts with the mod keyword. Add this code to @@ -190,7 +190,7 @@ they’ll need to be organized logically in order to keep track of them. What of your library think about your project’s domain. Use the techniques we’ve shown here to create side-by-side modules and nested modules in whatever structure you would like.

    -

    Moving Modules to Other Files

    +

    Moving Modules to Other Files

    Modules form a hierarchical structure, much like another structure in computing that you’re used to: file systems! We can use Rust’s module system along with multiple files to split Rust projects up so that not everything lives in @@ -422,7 +422,7 @@ module then goes into the src/network/mod.rs file, and the submodule network::client can have its own src/network/client.rs file. Now the top-level src/client.rs is unambiguously the code that belongs to the client module.

    -

    Rules of Module File Systems

    +

    Rules of Module File Systems

    In summary, these are the rules of modules with regards to files:

    • diff --git a/ch07-02-controlling-visibility-with-pub.html b/ch07-02-controlling-visibility-with-pub.html index 0281de41a..84a10ba6d 100644 --- a/ch07-02-controlling-visibility-with-pub.html +++ b/ch07-02-controlling-visibility-with-pub.html @@ -67,7 +67,7 @@
    -

    Controlling Visibility with pub

    +

    Controlling Visibility with pub

    We resolved the error messages shown in Listing 7-4 by moving the network and network::server code into the src/network/mod.rs and src/network/server.rs files, respectively. At that point, cargo build was @@ -139,7 +139,7 @@ considers the theoretical external usage that’s now possible as the function “being used.” Thus, when something is marked as public, Rust will not require that it’s used in our own program and will stop warning that the item is unused.

    -

    Making a Function Public

    +

    Making a Function Public

    To tell Rust to make something public, we add the pub keyword to the start of the declaration of the item we want to make public. We’ll focus on fixing the warning that tells us that client::connect has gone unused for now, as well @@ -226,7 +226,7 @@ pub mod network; | ^

    Only one warning left! Try to fix this one on your own!

    -

    Privacy Rules

    +

    Privacy Rules

    Overall, these are the rules for item visibility:

    1. If an item is public, it can be accessed through any of its @@ -234,7 +234,7 @@ parent modules.
    2. If an item is private, it may be accessed only by the current module and its child modules.
    -

    Privacy Examples

    +

    Privacy Examples

    Let’s look at a few more examples to get some practice. Create a new library project and enter the code in Listing 7-5 into your new project’s src/lib.rs:

    @@ -266,7 +266,7 @@ incorrect

    Before you try to compile this code, make a guess about which lines in try_me function will have errors. Then try compiling to see if you were right, and read on for discussion of the errors!

    -

    Looking at the Errors

    +

    Looking at the Errors

    The try_me function is in the root module of our project. The module named outermost is private, but the second privacy rule says the try_me function is allowed to access the outermost module since outermost is in the current @@ -283,7 +283,7 @@ is), nor is it a child module of the current module of middle_secret_funct be accessed by its current module, outermost. That means the try_me function is not allowed to call outermost::inside::inner_function or outermost::inside::secret_function either.

    -

    Fixing the Errors

    +

    Fixing the Errors

    Here are some suggestions for changing the code in an attempt to fix the errors. Before you try each one, make a guess as to whether it will fix the errors, then compile to see if you’re right and use the privacy rules to diff --git a/ch07-03-importing-names-with-use.html b/ch07-03-importing-names-with-use.html index 88f2b9343..3aa913a70 100644 --- a/ch07-03-importing-names-with-use.html +++ b/ch07-03-importing-names-with-use.html @@ -67,7 +67,7 @@

    -

    Importing Names

    +

    Importing Names

    We’ve covered how to call functions defined within a module using the module name as part of the call, as in the call to the namespaces function shown here in Listing 7-6.

    @@ -92,7 +92,7 @@ namespaces

    As you can see, referring to the fully qualified name can get quite lengthy. Luckily, Rust has a keyword to make these calls more concise.

    -

    Concise Imports with use

    +

    Concise Imports with use

    Rust’s use keyword works to shorten lengthy function calls by bringing the modules of the function you want to call into a scope. Here’s an example of bringing the a::series::of namespace into a binary crate’s root scope:

    @@ -153,7 +153,7 @@ fn main() { let green = TrafficLight::Green; // because we didn’t `use` TrafficLight::Green }
    -

    Glob Imports with *

    +

    Glob Imports with *

    To import all the items in a namespace at once, we can use the * syntax. For example:

    enum TrafficLight {
    @@ -173,7 +173,7 @@ fn main() {
     

    The * is called a glob, and it will import everything that’s visible inside of the namespace. Globs should be used sparingly: they are convenient, but you might also pull in more things than you expected and cause naming conflicts.

    -

    Using super to Access a Parent Module

    +

    Using super to Access a Parent Module

    As you now know, when you create a library crate, Cargo makes a tests module for you. Let’s go into more detail about that now. In your communicator project, open src/lib.rs.

    @@ -278,7 +278,7 @@ test tests::it_works ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
    -

    Summary

    +

    Summary

    Now you know techniques for organizing your code! Use these to group related functionality together, keep files from getting too long, and present a tidy public API to users of your library.

    diff --git a/ch08-00-fundamental-collections.html b/ch08-00-fundamental-collections.html index 09364e3f8..469498287 100644 --- a/ch08-00-fundamental-collections.html +++ b/ch08-00-fundamental-collections.html @@ -67,7 +67,7 @@
    -

    Fundamental Collections

    +

    Fundamental Collections

    Rust's standard library includes a number of really useful data structures called collections. Most other data types represent one specific value, but collections can contain multiple values. Unlike the built-in array and tuple diff --git a/ch08-01-vectors.html b/ch08-01-vectors.html index d86e057d6..948e91f49 100644 --- a/ch08-01-vectors.html +++ b/ch08-01-vectors.html @@ -67,13 +67,13 @@

    -

    Vectors

    +

    Vectors

    The first type we'll look at is Vec<T>, also known as a vector. Vectors allow us to store more than one value in a single data structure that puts all the values next to each other in memory. Vectors can only store values of the same type. They are useful in situations where you have a list of items, such as the lines of text in a file or the prices of items in a shopping cart.

    -

    Creating a New Vector

    +

    Creating a New Vector

    To create a new, empty vector, we can call the Vec::new function:

    let v: Vec<i32> = Vec::new();
     
    @@ -96,7 +96,7 @@ it. This will create a new Vec<i32> that holds the values Because we've given initial i32 values, Rust can infer that the type of v is Vec<i32>, and the type annotation isn't necessary. Let's look at how to modify a vector next.

    -

    Updating a Vector

    +

    Updating a Vector

    To create a vector then add elements to it, we can use the push method:

    let mut v = Vec::new();
     
    @@ -109,7 +109,7 @@ v.push(8);
     change its value, we need to make it mutable with the mut keyword. The
     numbers we place inside are all i32s, and Rust infers this from the data, so
     we don't need the Vec<i32> annotation.

    -

    Dropping a Vector Drops its Elements

    +

    Dropping a Vector Drops its Elements

    Like any other struct, a vector will be freed when it goes out of scope:

    {
         let v = vec![1, 2, 3, 4];
    @@ -122,7 +122,7 @@ we don't need the Vec<i32> annotation.

    those integers it holds will be cleaned up. This may seem like a straightforward point, but can get a little more complicated once we start to introduce references to the elements of the vector. Let's tackle that next!

    -

    Reading Elements of Vectors

    +

    Reading Elements of Vectors

    Now that you know how to create, update, and destroy vectors, knowing how to read their contents is a good next step. There are two ways to reference a value stored in a vector. In the examples, we've annotated the types of the @@ -164,7 +164,7 @@ enter a number that's too large and your program gets a None value, tell the user how many items are in the current Vec and give them another chance to enter a valid value. That would be more user-friendly than crashing the program for a typo!

    -

    Invalid References

    +

    Invalid References

    Once the program has a valid reference, the borrow checker will enforce the ownership and borrowing rules covered in Chapter 4 to ensure this reference and any other references to the contents of the vector stay valid. Recall the rule @@ -199,7 +199,7 @@ memory. The borrowing rules prevent programs from ending up in that situation.

    Note: For more on this, see The Nomicon.

    -

    Using an Enum to Store Multiple Types

    +

    Using an Enum to Store Multiple Types

    At the beginning of this chapter, we said that vectors can only store values that are all the same type. This can be inconvenient; there are definitely use cases for needing to store a list of things of different types. Luckily, the diff --git a/ch08-02-strings.html b/ch08-02-strings.html index 41e0795ce..d2a622f7d 100644 --- a/ch08-02-strings.html +++ b/ch08-02-strings.html @@ -67,7 +67,7 @@

    -

    Strings

    +

    Strings

    We've already talked about strings a bunch in Chapter 4, but let's take a more in-depth look at them now. Strings are an area that new Rustaceans commonly get stuck on. This is due to a combination of three things: Rust's propensity for @@ -82,7 +82,7 @@ creating, updating, and reading. We'll also discuss the ways in which Stri is different than the other collections, namely how indexing into a String is complicated by the differences in which people and computers interpret String data.

    -

    What is a String?

    +

    What is a String?

    Before we can dig into those aspects, we need to talk about what exactly we mean by the term 'string'. Rust actually only has one string type in the core language itself: str, the string slice, which is usually seen in its borrowed @@ -104,7 +104,7 @@ These string types may store different encodings or be represented in memory in a different way, for example. We won't be talking about these other string types in this chapter; see their API documentation for more about how to use them and when each is appropriate.

    -

    Creating a New String

    +

    Creating a New String

    Many of the same operations available with Vec are available with String as well, starting with the new function to create a string, like so:

    let s = String::new();
    @@ -144,11 +144,11 @@ let hello = "Olá";
     let hello = "Здравствуйте";
     let hello = "Hola";
     
    -

    Updating a String

    +

    Updating a String

    A String can grow in size and its contents can change just like the contents of a Vec, by pushing more data into it. In addition, String has concatenation operations implemented with the + operator for convenience.

    -

    Appending to a String with Push

    +

    Appending to a String with Push

    We can grow a String by using the push_str method to append a string slice:

    let mut s = String::from("foo");
     s.push_str("bar");
    @@ -167,7 +167,7 @@ it to the String:

    s.push('l');

    After this, s will contain "lol".

    -

    Concatenation with the + Operator or the format! Macro

    +

    Concatenation with the + Operator or the format! Macro

    Often, we'll want to combine two existing strings together. One way is to use the + operator like this:

    let s1 = String::from("Hello, ");
    @@ -234,7 +234,7 @@ have in the next paragraph without repeating the `println!` content too much?
     same way as println!, but instead of printing the output to the screen, it
     returns a String with the contents. This version is much easier to read, and
     also does not take ownership of any of its parameters.

    -

    Indexing into Strings

    +

    Indexing into Strings

    In many other languages, accessing individual characters in a string by referencing them by index is a valid and common operation. In Rust, however, if we try to access parts of a String using indexing syntax, we'll get an error. @@ -253,7 +253,7 @@ note: the type `std::string::String` cannot be indexed by `_`

    The error and the note tell the story: Rust strings don't support indexing. So the follow-up question is, why not? In order to answer that, we have to talk a bit about how Rust stores strings in memory.

    -

    Internal Representation

    +

    Internal Representation

    A String is a wrapper over a Vec<u8>. Let's take a look at some of our properly-encoded UTF-8 example strings from before. First, this one:

    let len = String::from("Hola").len();
    @@ -281,7 +281,7 @@ only Latin letters: &"hello"[0] would return 10
     returning an unexpected value and causing bugs that might not be discovered
     immediately, Rust chooses to not compile this code at all and prevent
     misunderstandings earlier.

    -

    Bytes and Scalar Values and Grapheme Clusters! Oh my!

    +

    Bytes and Scalar Values and Grapheme Clusters! Oh my!

    This leads to another point about UTF-8: there are really three relevant ways to look at strings, from Rust's perspective: as bytes, scalar values, and grapheme clusters (the closest thing to what people would call 'letters').

    @@ -310,7 +310,7 @@ though, since Rust would have to walk through the contents from the beginning to the index to determine how many valid characters there were.

    All of these problems mean that Rust does not implement [] for String, so we cannot directly do this.

    -

    Slicing Strings

    +

    Slicing Strings

    However, indexing the bytes of a string is very useful, and is not expected to be fast. While we can't use [] with a single number, we can use [] with a range to create a string slice containing particular bytes:

    @@ -327,7 +327,7 @@ runtime, in the same way that accessing an invalid index in a vector does:

    character boundary', ../src/libcore/str/mod.rs:1694

    You should use this with caution, since it can cause your program to crash.

    -

    Methods for Iterating Over Strings

    +

    Methods for Iterating Over Strings

    Luckily, there are other ways we can access elements in a String.

    If we need to perform operations on individual characters, the best way to do so is to use the chars method. Calling chars on "नमस्ते" separates out and @@ -369,7 +369,7 @@ method here, ie it's complicated and therefore best to use a crate? --> provided by the community, so we don't want to mention some and not others and seem biased towards certain crates, plus crates can change more quickly (and new crates can be created) than the language and this book will. /Carol --> -

    Strings are Not so Simple

    +

    Strings are Not so Simple

    To summarize, strings are complicated. Different programming languages make different choices about how to present this complexity to the programmer. Rust has chosen to make the correct handling of String data the default behavior diff --git a/ch08-03-hash-maps.html b/ch08-03-hash-maps.html index 000a27852..2745f3592 100644 --- a/ch08-03-hash-maps.html +++ b/ch08-03-hash-maps.html @@ -67,7 +67,7 @@

    -

    Hash Maps

    +

    Hash Maps

    The last of our fundamental collections is the hash map. The type HashMap<K, V> stores a mapping of keys of type K to values of type V. It does this via a hashing function, which determines how it places these keys and values into memory. Many different programming languages support this kind of data @@ -82,7 +82,7 @@ team name, you can retrieve their score.

    more goodies hiding in the functions defined on HashMap by the standard library. As always, check the standard library documentation for more information.

    -

    Creating a New Hash Map

    +

    Creating a New Hash Map

    We can create an empty HashMap with new, and add elements with insert. Here we're keeping track of the scores of two teams whose names are Blue and Yellow. The Blue team will start with 10 points and the Yellow team starts with @@ -122,7 +122,7 @@ let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collec want unless you specify. For the type parameters for the key and value types, however, we use underscores and Rust can infer the types that the hash map contains based on the types of the data in the vector.

    -

    Hash Maps and Ownership

    +

    Hash Maps and Ownership

    For types that implement the Copy trait, like i32, the values are copied into the hash map. For owned values like String, the values will be moved and the hash map will be the owner of those values:

    @@ -141,7 +141,7 @@ they have been moved into the hash map with the call to insert.

    not be moved into the hash map. The values that the references point to must be valid for at least as long as the hash map is valid, though. We will talk more about these issues in the Lifetimes section of Chapter 10.

    -

    Accessing Values in a Hash Map

    +

    Accessing Values in a Hash Map

    We can get a value out of the hash map by providing its key to the get method:

    use std::collections::HashMap;
     
    @@ -175,7 +175,7 @@ for (key, value) in &scores {
     
    Yellow: 50
     Blue: 10
     
    -

    Updating a Hash Map

    +

    Updating a Hash Map

    -

    Unwinding

    +

    Unwinding

    By default, when a panic! occurs, the program starts unwinding, which means Rust walks back up the stack and cleans up the data from each function it encounters, but this walking and cleanup is a lot of @@ -116,7 +116,7 @@ code that our code calls. The filename and line number reported by the error message will be someone else's code where the panic! macro is called, not the line of our code that eventually led to the panic!. We can use the backtrace of the functions the panic! call came from to figure this out.

    -

    Using a panic! Backtrace

    +

    Using a panic! Backtrace

    Let's look at another example to see what it's like when a panic! call comes from a library because of a bug in our code instead of from our code calling the macro directly:

    diff --git a/ch09-02-recoverable-errors-with-result.html b/ch09-02-recoverable-errors-with-result.html index f4b3a8a82..bc31b0535 100644 --- a/ch09-02-recoverable-errors-with-result.html +++ b/ch09-02-recoverable-errors-with-result.html @@ -67,7 +67,7 @@
    -

    Recoverable Errors with Result

    +

    Recoverable Errors with Result

    Most errors aren't serious enough to require the program to stop entirely. Sometimes, when a function fails, it's for a reason that we can easily interpret and respond to. For example, if we try to open a file and that @@ -207,7 +207,7 @@ Os { code: 2, message: "No such file or directory" } }', src/main.rs:8 run the program? --> -

    Matching on Different Errors

    +

    Matching on Different Errors

    The code in Listing 9-3 will panic! no matter the reason that File::open failed. What we'd really like to do instead is take different actions for different failure reasons: if File::open failed because the file doesn't @@ -265,7 +265,7 @@ could also fail, we need to add an inner match statement as well! W file can't be opened, a different error message will be printed. The last arm of the outer match stays the same so that the program panics on any error besides the missing file error.

    -

    Shortcuts for Panic on Error: unwrap and expect

    +

    Shortcuts for Panic on Error: unwrap and expect

    Using match works well enough, but it can be a bit verbose and doesn't always communicate intent well. The Result<T, E> type has many helper methods defined on it to do various things. One of those methods, called unwrap, is @@ -334,7 +334,7 @@ goes over the criteria the reader should use to decide if they're in a situation that's recoverable or not. I've actually moved the text that was here into that section to keep that whole discussion together. /Carol --> -

    Propagating Errors

    +

    Propagating Errors

    When writing a function whose implementation calls something that might fail, instead of handling the error within this function, you can choose to let your caller know about the error so they can decide what to do. This is known as @@ -412,7 +412,7 @@ to do, so we propagate all the success or error information upwards for them to handle as they see fit.

    This pattern of propagating errors is so common in Rust that there is dedicated syntax to make this easier: ?.

    -

    A Shortcut for Propagating Errors: ?

    +

    A Shortcut for Propagating Errors: ?

    Listing 9-6 shows an implementation of read_username_from_file that has the @@ -476,7 +476,7 @@ chained the call to read_to_string directly onto the result of username in s when both File::open and read_to_string succeed rather than returning errors. The functionality is again the same as in Listing 9-5 and Listing 9-6, this is just a different, more ergonomic way to write it.

    -

    ? Can Only Be Used in Functions That Return Result

    +

    ? Can Only Be Used in Functions That Return Result

    -

    Creating Custom Types for Validation

    +

    Creating Custom Types for Validation

    Let's take the idea of using Rust's type system to ensure we have a valid value one step further, and look at creating a custom type for validation. Recall the guessing game in Chapter 2, where our code asked the user to guess a number @@ -289,7 +289,7 @@ hasn't been checked by the conditions in the constructor.

    A function that has a parameter or returns only numbers between 1 and 100 could then declare in its signature that it takes or returns a Guess rather than a u32, and wouldn't need to do any additional checks in its body.

    -

    Summary

    +

    Summary

    Rust's error handling features are designed to help you write more robust code. The panic! macro signals that your program is in a state it can't handle, and lets you tell the process to stop instead of trying to proceed with invalid or diff --git a/ch10-00-generics.html b/ch10-00-generics.html index a270200d3..542d5c933 100644 --- a/ch10-00-generics.html +++ b/ch10-00-generics.html @@ -67,7 +67,7 @@

    -

    Generics

    +

    Generics

    One of the core tools a programming language gives you is the ability to deal effectively with duplication of code. It's important to minimize the amount of code that is duplicated throughout a program to make maintenance easier and @@ -80,7 +80,7 @@ hard to track down. Rust has the concept of generics as one way to elim duplicate code. Generics come in the form of generic types, traits that those generic types have, and generic lifetimes. We'll cover how to use all of these in this chapter.

    -

    Removing Duplication by Extracting a Function

    +

    Removing Duplication by Extracting a Function

    Let's first go through a technique for dealing with duplication that you're probably familiar with: extracting a function. Consider a small program that finds the largest number in a list, shown in Listing 10-1:

    diff --git a/ch10-01-syntax.html b/ch10-01-syntax.html index d29c35356..96a1c59f1 100644 --- a/ch10-01-syntax.html +++ b/ch10-01-syntax.html @@ -67,7 +67,7 @@
    -

    Generics Syntax

    +

    Generics Syntax

    We've already hinted at the idea of generics in previous chapters, but we never dug into what exactly they are or how to use them. In places where we specify a type, like function signatures or structs, instead we can use @@ -82,7 +82,7 @@ with a concrete type, and that determines how the overall type works. In the same way that a function like foo(x: i32) can be called with a specific value such as foo(5), a Vec<T> can be created with a specific type, like Vec<i32>.

    -

    Duplicated Enum Definitions

    +

    Duplicated Enum Definitions

    Let's dive into generic data types in more detail. We learned about how to use the Option<T> enum in Chapter 6, but we never examined its definition. Let's try to imagine how we'd write it! We'll start from duplicated code like we did @@ -122,7 +122,7 @@ what we currently know how to do in Rust, we would have to write a unique type for every single kind of value we wanted to have either Some or None of. In other words, the idea of "an optional value" is a more abstract concept than one specific type. We want it to work for any type at all.

    -

    Removing Duplication by Extracting a Generic Data Type

    +

    Removing Duplication by Extracting a Generic Data Type

    Let's see how to get from duplicated types to the generic type. Here are the definitions of our two enums side-by-side:

    enum OptionalNumber {   enum OptionalFloatingPointNumber {
    @@ -180,7 +180,7 @@ let float = Some(5.0);
     

    When you recognize situations with almost-duplicate types like this in your code, you can follow this process to reduce duplication using generics.

    -

    Monomorphization at Compile Time

    +

    Monomorphization at Compile Time

    Understanding this refactoring process is also useful in understanding how generics work behind the scenes: the compiler does the exact opposite of this process when compiling your code. Monomorphization means taking code that @@ -217,7 +217,7 @@ fn main() { code, but Rust will compile that into code that acts as though we wrote the specific type out in each instance. This means we pay no runtime cost for using generics; it's just like we duplicated each particular definition.

    -

    Generic Structs

    +

    Generic Structs

    In a similar fashion as we did with enums, we can use <>s with structs as well in order to define structs that have a generic type parameter in one or more of their fields. Generic structs also get monomorphized into specialized @@ -242,7 +242,7 @@ fn main() {

    The syntax is the same with structs: add a <T> after the name of the struct, then use T in the definition where you want to use that generic type instead of a specific type.

    -

    Multiple Type Parameters

    +

    Multiple Type Parameters

    Note that in the Point definition in Listing 10-2, we've used the same T parameter for both fields. This means x and y must always be values of the same type. Trying to instantiate a Point that uses an i32 for x and an @@ -296,7 +296,7 @@ definition:

    values in function signatures, if you have a lot of parameters, the code can get quite confusing, so try to keep the number of parameters defined in any one type small if you can.

    -

    Generic Functions and Methods

    +

    Generic Functions and Methods

    In a similar way to data structures, we can use the <> syntax in function or method definitions. The angle brackets for type parameters go after the function or method name and before the parameter list in parentheses:

    diff --git a/ch10-02-traits.html b/ch10-02-traits.html index 4392b1fc6..6e3816c37 100644 --- a/ch10-02-traits.html +++ b/ch10-02-traits.html @@ -67,7 +67,7 @@
    -

    Traits

    +

    Traits

    Traits are similar to a feature often called 'interfaces' in other languages, but are also different. Traits let us do another kind of abstraction: they let us abstract over behavior that types can have in common.

    @@ -162,7 +162,7 @@ wanted to call the print method. This is because it's possible to h traits that both define a method named print, and our Temperature enum might implement both. Rust wouldn't know which print method we wanted unless we brought the trait we wanted into our current scope with use.

    -

    Trait Bounds

    +

    Trait Bounds

    Defining traits with methods and implementing the trait methods on a particular type gives Rust more information than just defining methods on a type directly. The information Rust gets is that the type that implements the trait can be @@ -266,7 +266,7 @@ fn show_anything<T: Display>(value: T) {

    Now that this function specifies that T can be any type as long as that type implements the Display trait, this code will compile.

    -

    Multiple Trait Bounds and where Syntax

    +

    Multiple Trait Bounds and where Syntax

    Each generic type can have its own trait bounds. The signature for a function that takes a type T that implements Display and a type U that implements Printable looks like:

    diff --git a/ch10-03-lifetime-syntax.html b/ch10-03-lifetime-syntax.html index ed621b244..9c2ec1fcd 100644 --- a/ch10-03-lifetime-syntax.html +++ b/ch10-03-lifetime-syntax.html @@ -67,7 +67,7 @@
    -

    Lifetime Syntax

    +

    Lifetime Syntax

    Generic type parameters let us abstract over types, and traits let us abstract over behavior. There's one more way that Rust allows us to do something similar: lifetimes allow us to be generic over scopes of code.

    @@ -78,7 +78,7 @@ to cover everything about them in this chapter. What we are going to do talk about the very basics of lifetimes, so that when you see the syntax in documentation or other places, you'll be familiar with the concepts. Chapter 20 will contain more advanced information about everything lifetimes can do.

    -

    Core Syntax

    +

    Core Syntax

    We talked about references in Chapter 4, but we left out an important detail. As it turns out, every reference in Rust has a lifetime, which is the scope for which that reference is valid. Most of the time, lifetimes are implicit, @@ -104,7 +104,7 @@ declaration and a generic type declaration:

    reference has the lifetime 'a. In the same way that we parameterize functions that take generic types, we parameterize references with lifetimes.

    So, that's the syntax, but why? What does a lifetime do, anyway?

    -

    Lifetimes Prevent Dangling References

    +

    Lifetimes Prevent Dangling References

    Consider the program in listing 10-8. There's an outer scope and an inner scope. The outer scope declares a variable named r with no initial value, and the inner scope declares a variable named x with the initial value of 5. @@ -188,7 +188,7 @@ it out for us. One situation in which Rust can't figure out the lifetimes is for a function or method when one of the parameters or return values is a reference, except for a few scenarios we'll discuss in the lifetime elision section.

    -

    Lifetime Annotations in Struct Definitions

    +

    Lifetime Annotations in Struct Definitions

    Another time that Rust can't figure out the lifetimes is when structs have a field that holds a reference. In that case, naming the lifetimes looks like this:

    @@ -208,7 +208,7 @@ function that has a parameter of a generic type: we don't know what type the values will actually end up being when the function gets called. Lifetimes are the same idea, but they are generic over the scope of a reference, rather than a type.

    -

    Lifetime Annotations in Function Signatures

    +

    Lifetime Annotations in Function Signatures

    Lifetime annotations for functions go on the function signature, but we don't have to annotate any of the code in the function body with lifetimes. That's because Rust can analyze the specific code inside the function without any @@ -353,7 +353,7 @@ cleaning up the value.

    parameters and return values of functions. Once they're connected, Rust has enough information to allow memory-safe operations and disallow operations that would create dangling pointers or otherwise violate memory safety.

    -

    Lifetime Elision

    +

    Lifetime Elision

    If every reference has a lifetime, and we need to provide them for functions that use references as parameters or return values, then why did this function from the "String Slices" section of Chapter 4 compile? We haven't annotated any @@ -411,7 +411,7 @@ code without needing to specify explicit lifetimes. However, Rust is always checking these rules and the lifetimes in your program, and cases in which the lifetime elision rules do not apply are cases where you'll need to add lifetime parameters to help Rust understand the contracts of your code.

    -

    Lifetime Annotations in Method Definitions

    +

    Lifetime Annotations in Method Definitions

    Now that we've gone over the lifetime elision rules, defining methods on structs that hold references will make more sense. The lifetime name needs to be declared after the impl keyword and then used after the struct's name, @@ -437,7 +437,7 @@ impl<'a> App<'a> { } } -

    The Static Lifetime

    +

    The Static Lifetime

    There is one special lifetime that Rust knows about: 'static. The 'static lifetime is the entire duration of the program. All string literals have the 'static lifetime:

    @@ -452,7 +452,7 @@ program or not (or even if you want it to live that long, if it could). Most of the time, the problem in the code is an attempt to create a dangling reference or a mismatch of the available lifetimes, and the solution is fixing those problems, not specifying the 'static lifetime.

    -

    Summary

    +

    Summary

    We've covered the basics of Rust's system of generics. Generics are the core to building good abstractions, and can be used in a number of ways. There's more to learn about them, particularly lifetimes, but we'll cover those in later diff --git a/ch11-00-testing.html b/ch11-00-testing.html index f8f8fffd5..6b849d496 100644 --- a/ch11-00-testing.html +++ b/ch11-00-testing.html @@ -67,7 +67,7 @@

    -

    Testing

    +

    Testing

    Program testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.

    diff --git a/ch11-01-writing-tests.html b/ch11-01-writing-tests.html index 52fa971ae..9b78910eb 100644 --- a/ch11-01-writing-tests.html +++ b/ch11-01-writing-tests.html @@ -67,13 +67,13 @@
    -

    Writing Tests

    +

    Writing Tests

    Tests are Rust functions that use particular features and are written in such a way as to verify that non-test code is functioning in the expected manner. Everything we've discussed about Rust code applies to Rust tests as well! Let's look at the features Rust provides specifically for writing tests: the test attribute, a few macros, and the should_panic attribute.

    -

    The test attribute

    +

    The test attribute

    At its simplest, a test in Rust is a function that's annotated with the test attribute. Let's make a new library project with Cargo called adder:

    $ cargo new adder
    @@ -121,7 +121,7 @@ this line:

    tests that we have:

    test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
     
    -

    The assert! macro

    +

    The assert! macro

    The empty test function passes because any test which doesn't panic! passes, and any test that does panic! fails. Let's make the test fail by using the assert! macro:

    @@ -166,7 +166,7 @@ line 5 got a false value:

    The test failure is also reflected in the summary line:

    test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
     
    -

    Testing equality with the assert_eq! and assert_ne! macros

    +

    Testing equality with the assert_eq! and assert_ne! macros

    A common way to test functionality is to compare the result of the code under test to the value you expect it to be, and check that they're equal. You can do this using the assert! macro by passing it an expression using the == @@ -237,7 +237,7 @@ order to be able to print out the values in the case that the assertion fails. Because both of these traits are derivable traits that we mentioned in Chapter 5, usually this is as straightforward as adding the #[derive(PartialEq, Debug)] annotation to your struct or enum definition. See Appendix C for more details about these and other derivable traits.

    -

    Test for failure with should_panic

    +

    Test for failure with should_panic

    We can invert our test's failure with another attribute: should_panic. This is useful when we want to test that calling a particular function will cause an error. For example, let's test something that we know will panic from Chapter diff --git a/ch11-02-running-tests.html b/ch11-02-running-tests.html index 4bbf470f0..fdf5112a6 100644 --- a/ch11-02-running-tests.html +++ b/ch11-02-running-tests.html @@ -67,7 +67,7 @@

    -

    Running tests

    +

    Running tests

    Just like cargo run compiles your code and then runs the resulting binary, cargo test compiles your code in test mode and runs the resulting test binary. The default behavior of the binary that cargo test produces is to run @@ -79,7 +79,7 @@ be passed instead to the resulting test binary. The way to separate these arguments is with --: after cargo test, list the arguments that go to cargo test, then the separator --, and then the arguments that go to the test binary.

    -

    Tests Run in Parallel

    +

    Tests Run in Parallel

    Tests are run in parallel using threads. For this reason, you should take care that your tests are written in such a way as to not depend on each other or on any shared state. Shared state can also include the environment, such as the @@ -90,7 +90,7 @@ number of threads to the test binary. Setting the number of test threads to 1 means to not use any parallelism:

    $ cargo test -- --test-threads=1
     
    -

    Tests Capture Output

    +

    Tests Capture Output

    By default, Rust's test library captures and discards output to standard out and standard error, unless the test fails. For example, if you call println! in a test and the test passes, you won't see the println! output in your @@ -98,7 +98,7 @@ terminal. This behavior can be disabled by sending the --nocapture the test binary:

    $ cargo test -- --nocapture
     
    -

    Running a Subset of Tests by Name

    +

    Running a Subset of Tests by Name

    Sometimes, running a full test suite can take a long time. If you're only working on code in a particular area, you might want to only run the tests having to do with that code. cargo test takes an argument that allows you to @@ -218,7 +218,7 @@ test adding::add_two_and_two ... ok test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured -

    Ignore Some Tests Unless Specifically Requested

    +

    Ignore Some Tests Unless Specifically Requested

    Sometimes a few specific tests can be very time-consuming to execute, so during most runs of cargo test, we'd like to exclude them. Instead of having to construct an argument to cargo test to run all tests except these and diff --git a/ch11-03-test-organization.html b/ch11-03-test-organization.html index bef5cf55b..d63fbab27 100644 --- a/ch11-03-test-organization.html +++ b/ch11-03-test-organization.html @@ -67,7 +67,7 @@

    -

    Test Organization

    +

    Test Organization

    As mentioned before, testing is a large discipline, and different people sometimes use different terminology and organization. The Rust community tends to think about tests in terms of two main categories: unit tests and @@ -78,13 +78,13 @@ the same way any other code would, using only the public interface and exercising multiple modules per test. Both kinds of tests are important to ensure that the pieces of your library are doing what you expect them to separately and together.

    -

    Unit Tests

    +

    Unit Tests

    The purpose of unit tests is to test each unit of code in isolation from the rest of the code, in order to be able to quickly pinpoint where code is working as expected or not. Unit tests live in the src directory, in the same files as the code they are testing. They are separated into their own tests module in each file.

    -

    The Tests Module and cfg(test)

    +

    The Tests Module and cfg(test)

    By placing tests in their own module and using the cfg annotation on the module, we can tell Rust to only compile and run the test code when we run cargo test. This saves compile time when we only want to build the library @@ -160,7 +160,7 @@ unresolved name error since the tests module wouldn't know anything to list everything in the use statement in the tests. It's common instead to put use super::*; within a module's test submodule in order to bring everything into the test module scope at once.

    -

    Testing Private Functions

    +

    Testing Private Functions

    There's controversy within the testing community about whether you should write unit tests for private functions or not. Regardless of which testing ideology you adhere to, Rust does allow you to test private functions due to the way @@ -194,13 +194,13 @@ mod tests { we can import and call internal_adder in a test just fine. If you don't think private functions should be tested, there's nothing in Rust that will compel you to do so.

    -

    Integration Tests

    +

    Integration Tests

    In Rust, integration tests are tests that are entirely external to your library. They use your library in the same way any other code would. Their purpose is to test that many parts of your library work correctly together. Units of code that work correctly by themselves could have problems when integrated, so test coverage of the integrated code is important as well.

    -

    The tests Directory

    +

    The tests Directory

    Cargo has support for integration tests in the tests directory. If you make one and put Rust files inside, Cargo will compile each of the files as an individual crate. Let's give it a try!

    @@ -272,7 +272,7 @@ test it_adds_two ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
    -

    Submodules in Integration Tests

    +

    Submodules in Integration Tests

    As you add more integration tests, you may want to make more than one file in the tests directory in order to group the test functions by the functionality they're testing, for example. As we mentioned before, that will work fine, @@ -287,7 +287,7 @@ what you want, it's recommended to instead use a mod.rs file in a subdirectory, like tests/common/mod.rs, for helper functions. Files in subdirectories of the tests directory do not get compiled as separate crates or have sections in the test output.

    -

    Integration Tests for Binary Crates

    +

    Integration Tests for Binary Crates

    If your project is a binary crate that only contains a src/main.rs and does not have a src/lib.rs, it is not possible to create integration tests in the tests directory and use extern crate to import the functions in @@ -297,7 +297,7 @@ have a straightforward src/main.rs that calls logic that lives in crate by using extern crate to cover the important functionality, and if that works, the small amount of code in src/main.rs will work as well and does not need to be tested.

    -

    Summary

    +

    Summary

    Rust's testing features provide a way to specify how code should function to ensure the code continues to work in the specified ways even as we make changes. Unit tests exercise different parts of a library separately and can diff --git a/ch12-00-an-io-project.html b/ch12-00-an-io-project.html index ce15b1778..344f523e2 100644 --- a/ch12-00-an-io-project.html +++ b/ch12-00-an-io-project.html @@ -67,7 +67,7 @@

    -

    An I/O Project

    +

    An I/O Project

    We've learned a lot over the last few chapters. Let's take that new knowledge and apply it by building a project together. Along the way, we'll learn a bit more about Rust's standard library.

    diff --git a/ch12-01-accepting-command-line-arguments.html b/ch12-01-accepting-command-line-arguments.html index 19a1de75c..16d9ae2e1 100644 --- a/ch12-01-accepting-command-line-arguments.html +++ b/ch12-01-accepting-command-line-arguments.html @@ -67,7 +67,7 @@
    -

    Accepting Command Line Arguments

    +

    Accepting Command Line Arguments

    Our first task is to have greprs accept its two command line arguments. There are some existing libraries on crates.io that can help us do this, but since we're learning, we'll implement this ourselves.

    diff --git a/ch12-02-reading-a-file.html b/ch12-02-reading-a-file.html index 2da84c1da..2fc9c8cd6 100644 --- a/ch12-02-reading-a-file.html +++ b/ch12-02-reading-a-file.html @@ -67,7 +67,7 @@
    -

    Reading a File

    +

    Reading a File

    Now that we have some variables containing the information that we need, let's try using them. The next step is to open the file that we want to search. To do that, we need a file. Create one called poem.txt at the root level of your diff --git a/ch12-03-improving-error-handling-and-modularity.html b/ch12-03-improving-error-handling-and-modularity.html index b92bbd3af..681c33cf9 100644 --- a/ch12-03-improving-error-handling-and-modularity.html +++ b/ch12-03-improving-error-handling-and-modularity.html @@ -67,7 +67,7 @@

    -

    Improving Error Handling and Modularity

    +

    Improving Error Handling and Modularity

    There are four problems that we'd like to fix to improve our program, and they all have to do with potential errors and the way the program is structured. The first problem is where we open the file: we've used expect to print out an @@ -94,7 +94,7 @@ harder it is to keep track of which ones we need for which purpose. It would be better if we grouped the configuration variables into one structure to make their purpose clear.

    Let's address these problems by restructuring our project.

    -

    Separation of Concerns for Binary Projects

    +

    Separation of Concerns for Binary Projects

    These kinds of organizational problems are common to many similar kinds of projects, so the Rust community has developed a pattern for organizing the separate concerns. This pattern is useful for organizing any binary project @@ -160,7 +160,7 @@ fn parse_config(args: &[String]) -> (&str, &str) { this change, run the program again to verify that the argument parsing still works. It's good to check your progress often, so that you have a better idea of which change caused a problem, should you encounter one.

    -

    Grouping Configuration Values

    +

    Grouping Configuration Values

    Now that we have a function, let's improve it. Our code still has an indication that there's a better design possible: we return a tuple, but then immediately break that tuple up into individual parts again. This code isn't bad on its @@ -235,7 +235,7 @@ than storing a reference to the string data, but cloning the data makes our code very straightforward.

    -

    The Tradeoffs of Using clone

    +

    The Tradeoffs of Using clone

    There's a tendency amongst many Rustaceans to prefer not to use clone to fix ownership problems due to its runtime cost. In Chapter XX on iterators, we'll learn how to make this situation more efficient. For now, it's okay to copy a @@ -251,7 +251,7 @@ call clone.

    returns in a variable named config, and we've updated the code that was using the separate search and filename variables to use the fields on the Config struct instead.

    -

    Creating a Constructor for Config

    +

    Creating a Constructor for Config

    Let's now think about the purpose of parse_config: it's a function that creates a Config instance. We've already seen a convention for functions that create instances: a new function, like String::new. Listing 12-6 shows the @@ -309,7 +309,7 @@ impl Config {

    We've changed the name of parse_config to new and moved it within an impl block. We've also updated the callsite in main. Try compiling this again to make sure it works.

    -

    Returning a Result from the Constructor

    +

    Returning a Result from the Constructor

    Here's our last refactoring of this method: remember how accessing the vector with indices 1 and 2 panics when it contains fewer than 3 items and gives a bad error message? Let's fix that! Listing 12-7 shows how we can check that our @@ -438,7 +438,7 @@ literals, which is what our error message is for now.

    panic! if there aren't enough arguments, we now return an Err value. We wrapped the Config return value in an Ok. These changes make the function conform to its new type signature.

    -

    Calling Config::new and Handling Errors

    +

    Calling Config::new and Handling Errors

    Now we need to make some changes to main as shown in Listing 12-9:

    Filename: src/main.rs @@ -522,7 +522,7 @@ but we no longer get all the extra output. Let's try it:

    Problem parsing arguments: not enough arguments

    Great! This output is much friendlier for our users.

    -

    Handling Errors from the run Function

    +

    Handling Errors from the run Function

    Now that we're done refactoring our configuration parsing, let's improve our program's logic. Listing 12-10 shows the code after extracting a function named run that we'll call from main. The run function contains the code that @@ -724,7 +724,7 @@ we care about is the first case: detecting an error. If we used very useful.

    The bodies of the if let and of the unwrap_or_else are the same in both cases though: we print out an error and exit.

    -

    Split Code into a Library Crate

    +

    Split Code into a Library Crate

    This is looking pretty good! There's one more thing we haven't done yet: split the src/main.rs up and put some code into src/lib.rs Let's do that now: move the run function from src/main.rs to a new file, src/lib.rs. You'll diff --git a/ch12-04-testing-the-librarys-functionality.html b/ch12-04-testing-the-librarys-functionality.html index 98b8e8d9b..ca8d8d8b0 100644 --- a/ch12-04-testing-the-librarys-functionality.html +++ b/ch12-04-testing-the-librarys-functionality.html @@ -67,7 +67,7 @@

    -

    Testing the Library's Functionality

    +

    Testing the Library's Functionality

    Writing tests for the core functionality of our code is now easier since we extracted the logic into src/lib.rs and left all the argument parsing and error handling in src/main.rs. We can now call our code directly with various diff --git a/ch12-05-working-with-environment-variables.html b/ch12-05-working-with-environment-variables.html index 12c1a5a5b..9fd8a9614 100644 --- a/ch12-05-working-with-environment-variables.html +++ b/ch12-05-working-with-environment-variables.html @@ -67,13 +67,13 @@

    -

    Working with Environment Variables

    +

    Working with Environment Variables

    Let's add one more feature: case insensitive searching. In addition, this setting won't be a command line option: it'll be an environment variable instead. We could choose to make case insensitivity a command line option, but our users have requested an environment variable that they could set once and make all their searches case insensitive in that terminal session.

    -

    Implement and Test a Case-Insensitive grep Function

    +

    Implement and Test a Case-Insensitive grep Function

    First, let's add a new function that we will call when the environment variable is on. Let's start by adding a new test and re-naming our existing one:

    #[cfg(test)]
    diff --git a/ch12-06-writing-to-stderr-instead-of-stdout.html b/ch12-06-writing-to-stderr-instead-of-stdout.html
    index e427fc573..60d2f8776 100644
    --- a/ch12-06-writing-to-stderr-instead-of-stdout.html
    +++ b/ch12-06-writing-to-stderr-instead-of-stdout.html
    @@ -67,7 +67,7 @@
                     
    -

    Write to stderr Instead of stdout

    +

    Write to stderr Instead of stdout

    Right now, we're writing all of our output to the terminal with println!. This works, but most terminals provide two kinds of output: "standard out" is used for most information, but "standard error" is used for error messages. This @@ -150,7 +150,7 @@ our results:

    Are you nobody, too?
     How dreary to be somebody!
     
    -

    Summary

    +

    Summary

    In this chapter, we've covered how to do common I/O operations in a Rust context. By using command line arguments, files, environment variables, and the ability to write to stderr, you're now prepared to write command line diff --git a/ch13-00-functional-features.html b/ch13-00-functional-features.html index 00e8da469..3be9d7993 100644 --- a/ch13-00-functional-features.html +++ b/ch13-00-functional-features.html @@ -67,7 +67,7 @@

    -

    Functional Language features in Rust - Iterators and Closures

    +

    Functional Language features in Rust - Iterators and Closures

    Rust's design has taken inspiration from a lot of previous work. One of Rust's influences is functional programming, where functions are values that can be used as arguments or return values to other functions, assigned to variables, diff --git a/ch13-01-closures.html b/ch13-01-closures.html index ce7dba9dc..4733e6870 100644 --- a/ch13-01-closures.html +++ b/ch13-01-closures.html @@ -67,7 +67,7 @@

    -

    Closures

    +

    Closures

    Rust gives you the ability to define closures, which are similar to functions. Instead of starting with a technical definition, let's see what closures look like, syntactically, and then we'll return to defining what they @@ -171,7 +171,7 @@ let three = add_one(2i32); it would be tedious if we were required to annotate their types.

    Another reason to have a different syntax from functions for closures is that they have different behavior than functions: closures possess an environment.

    -

    Closures Can Reference Their Environment

    +

    Closures Can Reference Their Environment

    We've learned that functions can only use variables that are in scope, either by being const or being declared as parameters. Closures can do more: they're allowed to access variables from their enclosing scope. Listing 13-4 has an @@ -222,7 +222,7 @@ closure form instead the context of starting new threads. We'll show some more examples and explain more detail about this feature of closures in Chapter 16 when we talk about concurrency.

    -

    Closures as Function Parameters Using the Fn Traits

    +

    Closures as Function Parameters Using the Fn Traits

    While we can bind closures to variables, that's not the most useful thing we can do with them. We can also define functions that have closures as parameters by using the Fn traits. Here's an example of a function named call_with_one diff --git a/ch13-02-iterators.html b/ch13-02-iterators.html index a9fc0e73f..70d681e8e 100644 --- a/ch13-02-iterators.html +++ b/ch13-02-iterators.html @@ -67,7 +67,7 @@

    -

    Iterators

    +

    Iterators

    Iterators are a pattern in Rust that allows you to do some processing on a sequence of items. For example, the code in Listing 13-5 adds one to each number in a vector:

    @@ -105,7 +105,7 @@ the closure it's passed to create the new sequence of values.

    That's how we end up with [2, 3, 4]. As you can see, closures are a very important part of using iterators: they provide a way of customizing the behavior of an iterator adaptor like map.

    -

    Iterators are Lazy

    +

    Iterators are Lazy

    In the previous section, you may have noticed a subtle difference in wording: we said that map adapts an iterator, but collect consumes one. That was intentional. By themselves, iterators won't do anything; they're lazy. That is, @@ -128,7 +128,7 @@ chain to evaluate. We call those consuming adaptors, and collect< them.

    So how do we tell which iterator methods consume the iterator or not? And what adaptors are available? For that, let's look at the Iterator trait.

    -

    The Iterator trait

    +

    The Iterator trait

    Iterators all implement a trait named Iterator that is defined in the standard library. The definition of the trait looks like this:

    trait Iterator {
    @@ -241,7 +241,7 @@ println!("{:?}", x);
     

    This will print Some(1) through Some(5) and then None, each on their own line.

    -

    All Sorts of Iterator Adaptors

    +

    All Sorts of Iterator Adaptors

    In Listing 13-5, we had iterators and we called methods like map and collect on them. In Listing 13-6, however, we only implemented the next method on our Counter. How do we get methods like map and collect on our diff --git a/ch13-03-improving-our-io-project.html b/ch13-03-improving-our-io-project.html index e7ba895ca..173016ea9 100644 --- a/ch13-03-improving-our-io-project.html +++ b/ch13-03-improving-our-io-project.html @@ -67,12 +67,12 @@

    -

    Improving our I/O Project

    +

    Improving our I/O Project

    In our I/O project implementing grep in the last chapter, there are some places where the code could be made clearer and more concise using iterators. Let's take a look at how iterators can improve our implementation of the Config::new function and the grep function.

    -

    Removing a clone by Using an Iterator

    +

    Removing a clone by Using an Iterator

    Back in listing 12-8, we had this code that took a slice of String values and created an instance of the Config struct by checking for the right number of arguments, indexing into the slice, and cloning the values so that the Config @@ -167,7 +167,7 @@ nice if we could use ? on the Option returned from Result values currently. Even if we could use ? on Option like we can on Result, the value we would get would be borrowed, and we want to move the String from the iterator into Config.

    -

    Making Code Clearer with Iterator Adaptors

    +

    Making Code Clearer with Iterator Adaptors

    The other bit of code where we could take advantage of iterators was in the grep function as implemented in Listing 12-15: