From ffa6ca754dc5f36e8d26c1b321c7134bc8dd6de8 Mon Sep 17 00:00:00 2001 From: David Wickes Date: Sun, 5 Mar 2017 00:16:52 +0000 Subject: [PATCH 1/3] fixes generic method definition example --- second-edition/src/ch10-01-syntax.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/second-edition/src/ch10-01-syntax.md b/second-edition/src/ch10-01-syntax.md index b4f323af6..171d62cf7 100644 --- a/second-edition/src/ch10-01-syntax.md +++ b/second-edition/src/ch10-01-syntax.md @@ -392,7 +392,7 @@ struct Point { } impl Point { - fn mixup(&self, other: &Point) -> Point { + fn mixup(self, other: Point) -> Point { Point { x: self.x, y: other.y, From 3f2a1bd8dbb19cc48b210fc4fb35c305c8d81b56 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 7 Mar 2017 21:28:17 -0500 Subject: [PATCH 2/3] Remove all figure tags since it prevents testing :( This is terrible --- .../src/ch02-00-guessing-game-tutorial.md | 45 ++------ second-edition/src/ch03-02-data-types.md | 18 +-- .../src/ch03-03-how-functions-work.md | 8 +- second-edition/src/ch03-05-control-flow.md | 27 +---- .../src/ch04-01-what-is-ownership.md | 68 +++-------- .../src/ch04-02-references-and-borrowing.md | 16 +-- second-edition/src/ch04-03-slices.md | 29 +---- second-edition/src/ch05-00-structs.md | 56 ++------- second-edition/src/ch05-01-method-syntax.md | 18 +-- .../src/ch06-01-defining-an-enum.md | 22 +--- second-edition/src/ch06-02-match.md | 32 +----- second-edition/src/ch06-03-if-let.md | 11 +- .../src/ch07-01-mod-and-the-filesystem.md | 40 ++----- ...ch07-02-controlling-visibility-with-pub.md | 10 +- .../src/ch07-03-importing-names-with-use.md | 10 +- ...ch09-01-unrecoverable-errors-with-panic.md | 11 +- .../ch09-02-recoverable-errors-with-result.md | 47 ++------ .../src/ch09-03-to-panic-or-not-to-panic.md | 11 +- second-edition/src/ch10-00-generics.md | 27 +---- second-edition/src/ch10-01-syntax.md | 70 +++--------- second-edition/src/ch10-02-traits.md | 51 ++------- second-edition/src/ch10-03-lifetime-syntax.md | 106 ++++-------------- ...h12-01-accepting-command-line-arguments.md | 18 +-- second-edition/src/ch12-02-reading-a-file.md | 9 +- ...improving-error-handling-and-modularity.md | 90 ++++----------- ...2-04-testing-the-librarys-functionality.md | 20 +--- ...2-05-working-with-environment-variables.md | 11 +- ...-06-writing-to-stderr-instead-of-stdout.md | 9 +- second-edition/src/ch13-01-closures.md | 39 ++----- second-edition/src/ch13-02-iterators.md | 21 +--- .../src/ch14-02-publishing-to-crates-io.md | 48 ++------ second-edition/src/ch15-01-box.md | 61 +++------- second-edition/src/ch15-02-deref.md | 10 +- second-edition/src/ch15-03-drop.md | 21 +--- second-edition/src/ch15-04-rc.md | 37 ++---- .../src/ch15-05-interior-mutability.md | 18 +-- .../src/ch15-06-reference-cycles.md | 61 +++------- second-edition/src/ch16-00-concurrency.md | 41 ++----- 38 files changed, 252 insertions(+), 995 deletions(-) diff --git a/second-edition/src/ch02-00-guessing-game-tutorial.md b/second-edition/src/ch02-00-guessing-game-tutorial.md index de72e4b5d..d261b0fb6 100644 --- a/second-edition/src/ch02-00-guessing-game-tutorial.md +++ b/second-edition/src/ch02-00-guessing-game-tutorial.md @@ -76,7 +76,6 @@ 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*. -
Filename: src/main.rs ```rust,ignore @@ -96,12 +95,7 @@ fn main() { } ``` -
- -Listing 2-1: Code to get a guess from the user and print it out - -
-
+Listing 2-1: Code to get a guess from the user and print it out This code contains a lot of information, so let’s go over it bit by bit. To obtain user input and then print the result as output, we need to bring the @@ -387,8 +381,6 @@ version 0.3.14.” Now, without changing any of the code, let’s build the project, as shown in Listing 2-2: -
- ```text $ cargo build Updating registry `https://github.com/rust-lang/crates.io-index` @@ -399,13 +391,8 @@ $ cargo build Compiling guessing_game v0.1.0 (file:///projects/guessing_game) ``` -
- -Listing 2-2: The output from running `cargo build` after adding the rand crate -as a dependency - -
-
+Listing 2-2: The output from running `cargo build` after +adding the rand crate as a dependency You may see different version numbers (but they will all be compatible with the code, thanks to SemVer!), and the lines may be in a different order. @@ -510,7 +497,6 @@ number of packages. Let’s start *using* `rand`. The next step is to update *src/main.rs*, as shown in Listing 2-3: -
Filename: src/main.rs ```rust,ignore @@ -537,12 +523,8 @@ fn main() { } ``` -
- -Listing 2-3: Code changes needed in order to generate a random number - -
-
+Listing 2-3: Code changes needed in order to generate a +random number We’re adding a `extern crate rand;` line to the top that lets Rust know we’ll be using that external dependency. This also does the equivalent of calling `use @@ -604,7 +586,6 @@ You should get different random numbers, and they should all be numbers between Now that we have user input and a random number, we can compare them. That step is shown in Listing 2-4: -
Filename: src/main.rs ```rust,ignore @@ -638,12 +619,8 @@ fn main() { } ``` -
- -Listing 2-4: Handling the possible return values of comparing two numbers - -
-
+Listing 2-4: Handling the possible return values of +comparing two numbers The first new bit here is another `use`, bringing a type called `std::cmp::Ordering` into scope from the standard library. `Ordering` is @@ -1030,7 +1007,6 @@ that the program is still printing out the secret number. That worked well for testing, but it ruins the game. Let’s delete the `println!` that outputs the secret number. Listing 2-5 shows the final code: -
Filename: src/main.rs ```rust,ignore @@ -1072,12 +1048,7 @@ fn main() { } ``` -
- -Listing 2-5: Complete code of the guessing game - -
-
+Listing 2-5: Complete code of the guessing game ## Summary diff --git a/second-edition/src/ch03-02-data-types.md b/second-edition/src/ch03-02-data-types.md index f5d9d5ef5..d85318dbf 100644 --- a/second-edition/src/ch03-02-data-types.md +++ b/second-edition/src/ch03-02-data-types.md @@ -48,12 +48,7 @@ as opposed to a `u` for unsigned) for a 32-bit system. Table 3-1 shows the built-in integer types in Rust. Each variant in the Signed and Unsigned columns (for example, *i32*) can be used to declare the type of an integer value. -
-
- -Table 3-1: Integer Types in Rust - -
+Table 3-1: Integer Types in Rust | Length | Signed | Unsigned | |--------|--------|----------| @@ -63,8 +58,6 @@ Table 3-1: Integer Types in Rust | 64-bit | i64 | u64 | | arch | isize | usize | -
- Each variant can be either signed or unsigned and has an explicit size. Signed and unsigned refers to whether it’s possible for the number to be negative or positive; in other words, whether the number needs to have a sign @@ -90,12 +83,7 @@ You can write integer literals in any of the forms shown in Table 3-2. Note that all number literals except the byte literal allow a type suffix, such as `57u8`, and `_` as a visual separator, such as `1_000`. -
-
- -Table 3-2: Integer Literals in Rust - -
+Table 3-2: Integer Literals in Rust | Number literals | Example | |------------------|---------------| @@ -105,8 +93,6 @@ Table 3-2: Integer Literals in Rust | Binary | `0b1111_0000` | | Byte (`u8` only) | `b'A'` | -
- So how do you know which type of integer to use? If you’re unsure, Rust’s 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 diff --git a/second-edition/src/ch03-03-how-functions-work.md b/second-edition/src/ch03-03-how-functions-work.md index 2f559b53d..444509dac 100644 --- a/second-edition/src/ch03-03-how-functions-work.md +++ b/second-edition/src/ch03-03-how-functions-work.md @@ -149,7 +149,6 @@ evaluate to a resulting value. Let’s look at some examples. Creating a variable and assigning a value to it with the `let` keyword is a statement. In Listing 3-3, `let y = 6;` is a statement: -
Filename: src/main.rs ```rust @@ -158,12 +157,7 @@ fn main() { } ``` -
- -Listing 3-3: A `main` function declaration containing one statement. - -
-
+Listing 3-3: A `main` function declaration containing one statement. Function definitions are also statements; the entire preceding example is a statement in itself. diff --git a/second-edition/src/ch03-05-control-flow.md b/second-edition/src/ch03-05-control-flow.md index c9ec026c0..3a7b06360 100644 --- a/second-edition/src/ch03-05-control-flow.md +++ b/second-edition/src/ch03-05-control-flow.md @@ -171,7 +171,6 @@ Rust branching construct called `match` for these cases. Because `if` is an expression, we can use it on the right side of a `let` statement, for instance in Listing 3-4: -
Filename: src/main.rs ```rust @@ -187,12 +186,8 @@ fn main() { } ``` -
- -Listing 3-4: Assigning the result of an `if` expression to a variable - -
-
+Listing 3-4: Assigning the result of an `if` expression +to a variable The `number` variable will be bound to a value based on the outcome of the `if` expression. Run this code to see what happens: @@ -343,7 +338,6 @@ true, the code runs; otherwise, it exits the loop. You could use the `while` construct to loop over the elements of a collection, such as an array. For example: -
Filename: src/main.rs ```rust @@ -359,12 +353,8 @@ fn main() { } ``` -
- -Listing 3-5: Looping through each element of a collection using a `while` loop - -
-
+Listing 3-5: Looping through each element of a collection +using a `while` loop Here, the code counts up through the elements in the array. It starts at index `0`, and then loops until it reaches the final index in the array (that is, @@ -394,7 +384,6 @@ iteration through the loop. As a more efficient alternative, you can use a `for` loop and execute some code for each item in a collection. A `for` loop looks like this: -
Filename: src/main.rs ```rust @@ -407,12 +396,8 @@ fn main() { } ``` -
- -Listing 3-6: Looping through each element of a collection using a `for` loop - -
-
+Listing 3-6: Looping through each element of a collection +using a `for` loop When we run this code, we’ll see the same output as in Listing 3-5. More importantly, we’ve now increased the safety of the code and eliminated the diff --git a/second-edition/src/ch04-01-what-is-ownership.md b/second-edition/src/ch04-01-what-is-ownership.md index 85c61058d..0d53487e4 100644 --- a/second-edition/src/ch04-01-what-is-ownership.md +++ b/second-edition/src/ch04-01-what-is-ownership.md @@ -116,8 +116,6 @@ hardcoded into the text of our program. The variable is valid from the point at which it’s declared until the end of the current *scope*. Listing 4-1 has comments annotating where the variable `s` is valid: -
- ```rust { // s is not valid here, it’s not yet declared let s = "hello"; // s is valid from this point forward @@ -126,12 +124,8 @@ comments annotating where the variable `s` is valid: } // this scope is now over, and s is no longer valid ``` -
- -Listing 4-1: A variable and the scope in which it is valid - -
-
+Listing 4-1: A variable and the scope in which it is +valid In other words, there are two important points in time here: @@ -253,19 +247,13 @@ we’ve allocated on the heap. Let’s explore some of those situations now. 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: -
- ```rust let x = 5; let y = x; ``` -
- -Listing 4-2: Assigning the integer value of variable `x` to `y` - -
-
+Listing 4-2: Assigning the integer value of variable `x` +to `y` We can probably guess what this is doing based on our experience with other languages: “Bind the value `5` to `x`; then make a copy of the value in `x` and @@ -290,16 +278,10 @@ left: a pointer to the memory that holds the contents of the string, a length, and a capacity. This group of data is stored on the stack. On the right is the memory on the heap that holds the contents. -
String in memory -
- -Figure 4-3: Representation in memory of a `String` holding the value `"hello"` -bound to `s1` - -
-
+Figure 4-3: Representation in memory of a `String` +holding the value `"hello"` bound to `s1` The length is how much memory, in bytes, the contents of the `String` is currently using. The capacity is the total amount of memory, in bytes, that the @@ -312,32 +294,20 @@ pointer, the length, and the capacity that are on the stack. We do not copy the data on the heap that the pointer refers to. In other words, the data representation in memory looks like Figure 4-4. -
s1 and s2 pointing to the same value -
- -Figure 4-4: Representation in memory of the variable `s2` that has a copy of -the pointer, length, and capacity of `s1` - -
-
+Figure 4-4: Representation in memory of the variable `s2` +that has a copy of the pointer, length, and capacity of `s1` The representation does *not* look like Figure 4-5, which is what memory would look like if Rust instead copied the heap data as well. If Rust did this, the operation `s2 = s1` could potentially be very expensive in terms of runtime performance if the data on the heap was large. -
s1 and s2 to two places -
- -Figure 4-5: Another possibility of what `s2 = s1` might do if Rust copied the -heap data as well - -
-
+Figure 4-5: Another possibility of what `s2 = s1` might +do if Rust copied the heap data as well Earlier, we said that when a variable goes out of scope, Rust automatically calls the `drop` function and cleans up the heap memory for that variable. But @@ -383,15 +353,10 @@ also invalidates the first variable, instead of calling this a shallow copy, it’s known as a *move*. Here we would read this by saying that `s1` was *moved* into `s2`. So what actually happens is shown in Figure 4-6. -
s1 moved to s2 -
- -Figure 4-6: Representation in memory after `s1` has been invalidated - -
-
+Figure 4-6: Representation in memory after `s1` has been +invalidated That solves our problem! With only `s2` valid, when it goes out of scope, it alone will free the memory, and we’re done. @@ -471,7 +436,6 @@ 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 variables go into and out of scope: -
Filename: src/main.rs ```rust @@ -499,12 +463,8 @@ fn makes_copy(some_integer: i32) { // some_integer comes into scope. } // Here, some_integer goes out of scope. Nothing special happens. ``` -
- -Listing 4-7: Functions with ownership and scope annotated - -
-
+Listing 4-7: Functions with ownership and scope +annotated If we tried to use `s` after the call to `takes_ownership`, Rust would throw a compile time error. These static checks protect us from mistakes. Try adding diff --git a/second-edition/src/ch04-02-references-and-borrowing.md b/second-edition/src/ch04-02-references-and-borrowing.md index c6bf43fcf..6cac7c081 100644 --- a/second-edition/src/ch04-02-references-and-borrowing.md +++ b/second-edition/src/ch04-02-references-and-borrowing.md @@ -33,15 +33,9 @@ function return value is gone. Second, note that we pass `&s1` into These ampersands are *references*, and they allow you to refer to some value without taking ownership of it. Figure 4-8 shows a diagram. -
&String s pointing at String s1 -
- -Figure 4-8: `&String s` pointing at `String s1` - -
-
+Figure 4-8: `&String s` pointing at `String s1` Let’s take a closer look at the function call here: @@ -81,7 +75,6 @@ have to give it back. So what happens if we try to modify something we’re borrowing? Try the code in Listing 4-9. Spoiler alert: it doesn’t work! -
Filename: src/main.rs ```rust,ignore @@ -96,12 +89,7 @@ fn change(some_string: &String) { } ``` -
- -Listing 4-9: Attempting to modify a borrowed value - -
-
+Listing 4-9: Attempting to modify a borrowed value Here’s the error: diff --git a/second-edition/src/ch04-03-slices.md b/second-edition/src/ch04-03-slices.md index af2c85b41..e3484915a 100644 --- a/second-edition/src/ch04-03-slices.md +++ b/second-edition/src/ch04-03-slices.md @@ -20,7 +20,6 @@ ownership, so this is fine. But what should we return? We don’t really have a way to talk about *part* of a string. However, we could return the index of the end of the word. Let’s try that as shown in Listing 4-10: -
Filename: src/main.rs ```rust @@ -37,13 +36,8 @@ fn first_word(s: &String) -> usize { } ``` -
- -Listing 4-10: The `first_word` function that returns a byte index value into -the `String` parameter - -
-
+Listing 4-10: The `first_word` function that returns a +byte index value into the `String` parameter Let’s break down this code a bit. Because we need to go through the `String` element by element and check whether a value is a space, we’ll convert our @@ -91,7 +85,6 @@ because it’s a separate value from the `String`, there’s no guarantee that i will still be valid in the future. Consider the program in Listing 4-11 that uses the `first_word` function from Listing 4-10: -
Filename: src/main.rs ```rust @@ -119,13 +112,8 @@ fn main() { } ``` -
- -Listing 4-11: Storing the result from calling the `first_word` function then -changing the `String` contents - -
-
+Listing 4-11: Storing the result from calling the +`first_word` function then changing the `String` contents This program compiles without any errors and also would if we used `word` after calling `s.clear()`. `word` isn’t connected to the state of `s` at all, so @@ -171,15 +159,10 @@ that contains a pointer to the 6th byte of `s` and a length value of 5. Figure 4-12 shows this in a diagram. -
world containing a pointer to the 6th byte of String s and a length 5 -
- -Figure 4-12: String slice referring to part of a `String` - -
-
+Figure 4-12: String slice referring to part of a +`String` With Rust’s `..` range syntax, if you want to start at the first index (zero), you can drop the value before the two periods. In other words, these are equal: diff --git a/second-edition/src/ch05-00-structs.md b/second-edition/src/ch05-00-structs.md index 997ea1e15..69d55dfbf 100644 --- a/second-edition/src/ch05-00-structs.md +++ b/second-edition/src/ch05-00-structs.md @@ -24,8 +24,6 @@ of the pieces of data, which we call *fields*, and specify each field’s type. For example, Listing 5-1 shows a struct to store information about a user account: -
- ```rust struct User { username: String, @@ -35,12 +33,7 @@ struct User { } ``` -
- -Listing 5-1: A `User` struct definition - -
-
+Listing 5-1: A `User` struct definition To use a struct once we've defined it, we create an *instance* of that struct by specifying concrete values for each of the fields. Creating an instance is @@ -135,7 +128,6 @@ the length and width of a rectangle specified in pixels and will calculate the area of the rectangle. Listing 5-2 has a short program with one way of doing just that in our project’s *src/main.rs*: -
Filename: src/main.rs ```rust @@ -154,13 +146,8 @@ fn area(length: u32, width: u32) -> u32 { } ``` -
- -Listing 5-2: Calculating the area of a rectangle specified by its length and -width in separate variables - -
-
+Listing 5-2: Calculating the area of a rectangle +specified by its length and width in separate variables Let’s try running this program with `cargo run`: @@ -189,7 +176,6 @@ manageable to group length and width together. We’ve already discussed one way we might do that in Chapter 3: tuples. Listing 5-3 has a version of our program which uses tuples: -
Filename: src/main.rs ```rust @@ -207,12 +193,8 @@ fn area(dimensions: (u32, u32)) -> u32 { } ``` -
- -Listing 5-3: Specifying the length and width of the rectangle with a tuple - -
-
+Listing 5-3: Specifying the length and width of the +rectangle with a tuple @@ -243,7 +225,6 @@ 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: -
Filename: src/main.rs ```rust @@ -266,12 +247,7 @@ fn area(rectangle: &Rectangle) -> u32 { } ``` -
- -Listing 5-4: Defining a `Rectangle` struct - -
-
+Listing 5-4: Defining a `Rectangle` struct @@ -300,7 +276,6 @@ It’d be nice to be able to print out an instance of our `Rectangle` while we debugging our program and see the values for all its fields. Listing 5-5 tries using the `println!` macro as we have been: -
Filename: src/main.rs ```rust,ignore @@ -316,12 +291,8 @@ fn main() { } ``` -
- -Listing 5-5: Attempting to print a `Rectangle` instance - -
-
+Listing 5-5: Attempting to print a `Rectangle` +instance If we run this, we get an error with this core message: @@ -371,8 +342,6 @@ have to explicitly opt-in to having that functionality be available for our struct. To do that, we add the annotation `#[derive(Debug)]` just before our struct definition, as shown in Listing 5-6: -
- ```rust #[derive(Debug)] struct Rectangle { @@ -387,13 +356,8 @@ fn main() { } ``` -
- -Listing 5-6: Adding the annotation to derive the `Debug` trait and printing the -`Rectangle` instance using debug formatting - -
-
+Listing 5-6: Adding the annotation to derive the `Debug` +trait and printing the `Rectangle` instance using debug formatting At this point, if we run this program, we won’t get any errors and we’ll see the following output: diff --git a/second-edition/src/ch05-01-method-syntax.md b/second-edition/src/ch05-01-method-syntax.md index 4c2870a03..47430ea11 100644 --- a/second-edition/src/ch05-01-method-syntax.md +++ b/second-edition/src/ch05-01-method-syntax.md @@ -14,7 +14,6 @@ Let’s change our `area` function that has a `Rectangle` instance as a paramete and instead make an `area` method defined on the `Rectangle` struct, as shown in Listing 5-7: -
Filename: src/main.rs ```rust @@ -40,12 +39,8 @@ fn main() { } ``` -
- -Listing 5-7: Defining an `area` method on the `Rectangle` struct - -
-
+Listing 5-7: Defining an `area` method on the `Rectangle` +struct @@ -137,7 +132,6 @@ another instance of `Rectangle` and return `true` if the second rectangle could fit completely within `self` and `false` if it would not. That is, if we run the code in Listing 5-8, once we've defined the `can_hold` method: -
Filename: src/main.rs ```rust,ignore @@ -151,12 +145,8 @@ fn main() { } ``` -
- -Listing 5-8: Demonstration of using the as-yet-unwritten `can_hold` method - -
-
+Listing 5-8: Demonstration of using the as-yet-unwritten +`can_hold` method We want to see this output, since both of `rect2`’s dimensions are smaller than `rect1`’s, but `rect3` is wider than `rect1`: diff --git a/second-edition/src/ch06-01-defining-an-enum.md b/second-edition/src/ch06-01-defining-an-enum.md index 6409fd6c8..8168a3956 100644 --- a/second-edition/src/ch06-01-defining-an-enum.md +++ b/second-edition/src/ch06-01-defining-an-enum.md @@ -75,8 +75,6 @@ at the moment we don’t have a way to store the actual IP address *data*; we only know what *kind* it is. Given that you just learned about structs in Chapter 5, you might tackle this problem as shown in Listing 6-1: -
- ```rust enum IpAddrKind { V4, @@ -99,13 +97,8 @@ let loopback = IpAddr { }; ``` -
- -Listing 6-1: Storing the data and `IpAddrKind` variant of an IP address using a -`struct` - -
-
+Listing 6-1: Storing the data and `IpAddrKind` variant of +an IP address using a `struct` Here, we’ve defined a struct `IpAddr` that has two fields: a `kind` field that is of type `IpAddrKind` (the enum we defined previously) and an `address` field @@ -192,8 +185,6 @@ more about importing types in Chapter 7. Let’s look at another example of an enum in Listing 6-2: this one has a wide variety of types embedded in its variants: -
- ```rust enum Message { Quit, @@ -203,13 +194,8 @@ enum Message { } ``` -
- -Listing 6-2: A `Message` enum whose variants each store different amounts and -types of values - -
-
+Listing 6-2: A `Message` enum whose variants each store +different amounts and types of values This enum has four variants with different types: diff --git a/second-edition/src/ch06-02-match.md b/second-edition/src/ch06-02-match.md index 4adf4c1b0..061693d6b 100644 --- a/second-edition/src/ch06-02-match.md +++ b/second-edition/src/ch06-02-match.md @@ -19,8 +19,6 @@ can write a function that can take an unknown United States coin and, in a similar way as the counting machine, determine which coin it is and return its value in cents, as shown here in Listing 6-3: -
- ```rust enum Coin { Penny, @@ -39,13 +37,8 @@ fn value_in_cents(coin: Coin) -> i32 { } ``` -
- -Listing 6-3: An enum and a `match` expression that has the variants of the enum -as its patterns. - -
-
+Listing 6-3: An enum and a `match` expression that has +the variants of the enum as its patterns. Let’s break down the `match` in the `value_in_cents` function. First, we list the `match` keyword followed by an expression, which in this case is the value @@ -109,8 +102,6 @@ designs, so only quarters have this extra value. We can add this information to our `enum` by changing the `Quarter` variant to include a `State` value stored inside it, which we've done here in Listing 6-4: -
- ```rust #[derive(Debug)] // So we can inspect the state in a minute enum UsState { @@ -127,13 +118,8 @@ enum Coin { } ``` -
- -Listing 6-4: A `Coin` enum where the `Quarter` variant also holds a `UsState` -value - -
-
+Listing 6-4: A `Coin` enum where the `Quarter` variant +also holds a `UsState` value Let’s imagine that a friend of ours is trying to collect all 50 state quarters. While we sort our loose change by coin type, we’ll also call out the name of @@ -195,8 +181,6 @@ operations. This function is very easy to write, thanks to `match`, and will look like Listing 6-5: -
- ```rust fn plus_one(x: Option) -> Option { match x { @@ -210,12 +194,8 @@ let six = plus_one(five); let none = plus_one(None); ``` -
- -Listing 6-5: A function that uses a `match` expression on an `Option` - -
-
+Listing 6-5: A function that uses a `match` expression on +an `Option` #### Matching `Some(T)` diff --git a/second-edition/src/ch06-03-if-let.md b/second-edition/src/ch06-03-if-let.md index 7c62616db..b2c9afd05 100644 --- a/second-edition/src/ch06-03-if-let.md +++ b/second-edition/src/ch06-03-if-let.md @@ -5,8 +5,6 @@ handle values that match one pattern and ignore the rest. Consider the program in Listing 6-6 that matches on an `Option` value but only wants to execute code if the value is three: -
- ```rust let some_u8_value = Some(0u8); match some_u8_value { @@ -15,13 +13,8 @@ match some_u8_value { } ``` -
- -Listing 6-6: A `match` that only cares about executing code when the value is -`Some(3)` - -
-
+Listing 6-6: A `match` that only cares about executing +code when the value is `Some(3)` We want to do something with the `Some(3)` match but do nothing with any other `Some` value or the `None` value. To satisfy the `match` expression, we diff --git a/second-edition/src/ch07-01-mod-and-the-filesystem.md b/second-edition/src/ch07-01-mod-and-the-filesystem.md index c42b7a288..9abcc5c7f 100644 --- a/second-edition/src/ch07-01-mod-and-the-filesystem.md +++ b/second-edition/src/ch07-01-mod-and-the-filesystem.md @@ -71,7 +71,6 @@ We can also have multiple modules, side-by-side, in the same *src/lib.rs* file. For example, to have a `client` module too, that also has a function named `connect`, we can add it as shown in Listing 7-1: -
Filename: src/lib.rs ```rust @@ -86,13 +85,8 @@ mod client { } ``` -
- -Listing 7-1: The `network` module and the `client` module defined side-by-side -in *src/lib.rs* - -
-
+Listing 7-1: The `network` module and the `client` module +defined side-by-side in *src/lib.rs* Now we have a `network::connect` function and a `client::connect` function. These can have completely different functionality, and the function names do @@ -108,7 +102,6 @@ the `client` code and its `connect` function might make more sense to users of our library if it was inside the `network` namespace instead, like in Listing 7-2: -
Filename: src/lib.rs ```rust @@ -123,12 +116,8 @@ mod network { } ``` -
- -Listing 7-2: Moving the `client` module inside of the `network` module - -
-
+Listing 7-2: Moving the `client` module inside of the +`network` module In your *src/lib.rs* file, replace the existing `mod network` and `mod client` definitions with this one that has the `client` module as an inner module of @@ -170,7 +159,6 @@ that you’re used to: file systems! We can use Rust’s module system along wit multiple files to split Rust projects up so that not everything lives in *src/lib.rs*. For this example, we will start with the code in Listing 7-3: -
Filename: src/lib.rs ```rust @@ -190,13 +178,8 @@ mod network { } ``` -
- -Listing 7-3: Three modules, `client`, `network`, and `network::server`, all -defined in *src/lib.rs* - -
-
+Listing 7-3: Three modules, `client`, `network`, and +`network::server`, all defined in *src/lib.rs* which has this module hierarchy: @@ -348,8 +331,6 @@ fn connect() { When we try to `cargo build`, we’ll get the error shown in Listing 7-4: -
- ```text $ cargo build Compiling communicator v0.1.0 (file:///projects/communicator) @@ -371,13 +352,8 @@ note: ... or maybe `use` the module `server` instead of possibly redeclaring it | ^^^^^^ ``` -
- -Listing 7-4: Error when trying to extract the `server` submodule into -*src/server.rs* - -
-
+Listing 7-4: Error when trying to extract the `server` +submodule into *src/server.rs* The error says we `cannot declare a new module at this location` and is pointing to the `mod server;` line in *src/network.rs*. So *src/network.rs* is diff --git a/second-edition/src/ch07-02-controlling-visibility-with-pub.md b/second-edition/src/ch07-02-controlling-visibility-with-pub.md index 627559d0d..913722fb3 100644 --- a/second-edition/src/ch07-02-controlling-visibility-with-pub.md +++ b/second-edition/src/ch07-02-controlling-visibility-with-pub.md @@ -226,7 +226,6 @@ Overall, these are the rules for item visibility: 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*: -
Filename: src/lib.rs ```rust,ignore @@ -250,13 +249,8 @@ fn try_me() { } ``` -
- -Listing 7-5: Examples of private and public functions, some of which are -incorrect - -
-
+Listing 7-5: Examples of private and public functions, +some of which are 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 diff --git a/second-edition/src/ch07-03-importing-names-with-use.md b/second-edition/src/ch07-03-importing-names-with-use.md index d42fa3689..ab6ecf8de 100644 --- a/second-edition/src/ch07-03-importing-names-with-use.md +++ b/second-edition/src/ch07-03-importing-names-with-use.md @@ -4,7 +4,6 @@ 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 `nested_modules` function shown here in Listing 7-6. -
Filename: src/main.rs ```rust @@ -21,13 +20,8 @@ fn main() { } ``` -
- -Listing 7-6: Calling a function by fully specifying its enclosing module’s -namespaces - -
-
+Listing 7-6: Calling a function by fully specifying its +enclosing module’s 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. diff --git a/second-edition/src/ch09-01-unrecoverable-errors-with-panic.md b/second-edition/src/ch09-01-unrecoverable-errors-with-panic.md index 6385b8a3b..43ff16038 100644 --- a/second-edition/src/ch09-01-unrecoverable-errors-with-panic.md +++ b/second-edition/src/ch09-01-unrecoverable-errors-with-panic.md @@ -111,8 +111,6 @@ The next note line tells us that we can set the `RUST_BACKTRACE` environment variable to get a backtrace of exactly what happened to cause the error. Let’s try that. Listing 9-1 shows the output: -
- ```text $ RUST_BACKTRACE=1 cargo run Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs @@ -141,13 +139,8 @@ core::ops::Index>::index::h1204ab053b688140 14: 0x1092206e9 - main ``` -
- -Listing 9-1: The backtrace generated by a call to `panic!` displayed when the -environment variable `RUST_BACKTRACE` is set - -
-
+Listing 9-1: The backtrace generated by a call to +`panic!` displayed when the environment variable `RUST_BACKTRACE` is set That’s a lot of output! Line 11 of the backtrace points to the line in our project causing the problem: *src/main.rs*, line four. A backtrace is a list of diff --git a/second-edition/src/ch09-02-recoverable-errors-with-result.md b/second-edition/src/ch09-02-recoverable-errors-with-result.md index 14579075d..316758366 100644 --- a/second-edition/src/ch09-02-recoverable-errors-with-result.md +++ b/second-edition/src/ch09-02-recoverable-errors-with-result.md @@ -31,7 +31,6 @@ value and error value we want to return may differ. Let’s call a function that returns a `Result` value because the function could fail: opening a file, shown in Listing 9-2. -
Filename: src/main.rs ```rust @@ -42,12 +41,7 @@ fn main() { } ``` -
- -Listing 9-2: Opening a file - -
-
+Listing 9-2: Opening a file How do we know `File::open` returns a `Result`? We could look at the standard library API documentation, or we could ask the compiler! If we give `f` a type @@ -98,7 +92,6 @@ on the value `File::open` returned. Listing 9-3 shows one way to handle the `Result` with a basic tool: the `match` expression that we learned about in Chapter 6. -
Filename: src/main.rs ```rust,should_panic @@ -116,13 +109,8 @@ fn main() { } ``` -
- -Listing 9-3: Using a `match` expression to handle the `Result` variants we -might have - -
-
+Listing 9-3: Using a `match` expression to handle the +`Result` variants we might have Note that, like the `Option` enum, the `Result` enum and its variants have been imported in the prelude, so we don’t need to specify `Result::` before the `Ok` @@ -154,7 +142,6 @@ permission to open the file, we still want to `panic!` in the same way as we did in Listing 9-3. Let’s look at Listing 9-4, which adds another arm to the `match`: -
Filename: src/main.rs ```rust,ignore @@ -187,12 +174,8 @@ fn main() { } ``` -
- -Listing 9-4: Handling different kinds of errors in different ways - -
-
+Listing 9-4: Handling different kinds of errors in +different ways The type of the value that `File::open` returns inside the `Err` variant is `io::Error`, which is a struct provided by the standard library. This struct @@ -284,8 +267,6 @@ For example, Listing 9-5 shows a function that reads a username from a file. If the file doesn’t exist or can’t be read, this function will return those errors to the code that called this function: -
- ```rust use std::io; use std::io::Read; @@ -308,12 +289,8 @@ fn read_username_from_file() -> Result { } ``` -
- -Listing 9-5: A function that returns errors to the calling code using `match` - -
-
+Listing 9-5: A function that returns errors to the +calling code using `match` Let’s look at the return type of the function first: `Result`. This means that the function is returning a value of the type @@ -365,8 +342,6 @@ Listing 9-6 shows an implementation of `read_username_from_file` that has the same functionality as it had in Listing 9-5, but this implementation uses the question mark operator: -
- ```rust use std::io; use std::fs::File; @@ -379,12 +354,8 @@ fn read_username_from_file() -> Result { } ``` -
- -Listing 9-6: A function that returns errors to the calling code using `?` - -
-
+Listing 9-6: A function that returns errors to the +calling code using `?` The `?` placed after a `Result` value is defined to work the exact same way as the `match` expressions we defined to handle the `Result` values in Listing diff --git a/second-edition/src/ch09-03-to-panic-or-not-to-panic.md b/second-edition/src/ch09-03-to-panic-or-not-to-panic.md index d9fcc4bca..f203a1200 100644 --- a/second-edition/src/ch09-03-to-panic-or-not-to-panic.md +++ b/second-edition/src/ch09-03-to-panic-or-not-to-panic.md @@ -174,8 +174,6 @@ confidently use the values they receive. Listing 9-8 shows one way to define a `Guess` type that will only create an instance of `Guess` if the `new` function receives a value between 1 and 100: -
- ```rust struct Guess { value: u32, @@ -198,13 +196,8 @@ impl Guess { } ``` -
- -Listing 9-8: A `Guess` type that will only continue with values between 1 and -100 - -
-
+Listing 9-8: A `Guess` type that will only continue with +values between 1 and 100 First, we define a struct named `Guess` that has a field named `value` that holds a `u32`. This is where the number will be stored. diff --git a/second-edition/src/ch10-00-generics.md b/second-edition/src/ch10-00-generics.md index e5dcf55a8..0c91bb449 100644 --- a/second-edition/src/ch10-00-generics.md +++ b/second-edition/src/ch10-00-generics.md @@ -43,7 +43,6 @@ use generics. Consider a small program that finds the largest number in a list, shown in Listing 10-1: -
Filename: src/main.rs ```rust @@ -63,12 +62,8 @@ fn main() { } ``` -
- -Listing 10-1: Code to find the largest number in a list of numbers - -
-
+Listing 10-1: Code to find the largest number in a list +of numbers This code takes a list of integers, stored here in the variable `numbers`. It puts the first item in the list in a variable named `largest`. Then it iterates @@ -82,7 +77,6 @@ If we needed to find the largest number in two different lists of numbers, we could duplicate the code in Listing 10-1 and have the same logic exist in two places in the program, as in Listing 10-2: -
Filename: src/main.rs ```rust @@ -113,12 +107,8 @@ fn main() { } ``` -
- -Listing 10-2: Code to find the largest number in *two* lists of numbers - -
-
+Listing 10-2: Code to find the largest number in *two* +lists of numbers While this code works, duplicating code is tedious and error-prone, and means we have multiple places to update the logic if we need to change it. @@ -138,7 +128,6 @@ number into a function named `largest`. This program can find the largest number in two different lists of numbers, but the code from Listing 10-1 only exists in one spot: -
Filename: src/main.rs ```rust @@ -169,12 +158,8 @@ fn main() { } ``` -
- -Listing 10-3: Abstracted code to find the largest number in two lists - -
-
+Listing 10-3: Abstracted code to find the largest number +in two lists The function has a parameter, `list`, which represents any concrete slice of `i32` values that we might pass into the function. The code in the function diff --git a/second-edition/src/ch10-01-syntax.md b/second-edition/src/ch10-01-syntax.md index b4f323af6..2c5259535 100644 --- a/second-edition/src/ch10-01-syntax.md +++ b/second-edition/src/ch10-01-syntax.md @@ -18,7 +18,6 @@ providing the same functionality to find the largest value in a slice. The first function is the one we extracted in Listing 10-3 that finds the largest `i32` in a slice. The second function finds the largest `char` in a slice: -
Filename: src/main.rs ```rust @@ -61,13 +60,8 @@ fn main() { } ``` -
- -Listing 10-4: Two functions that differ only in their names and the types in -their signatures - -
-
+Listing 10-4: Two functions that differ only in their +names and the types in their signatures Here, the functions `largest_i32` and `largest_char` have the exact same body, so it would be nice if we could turn these two functions into one and get rid @@ -105,7 +99,6 @@ data type in its signature, and shows how we'll be able to call `largest` with either a slice of `i32` values or `char` values. Note that this code won't compile yet! -
Filename: src/main.rs ```rust,ignore @@ -134,13 +127,8 @@ fn main() { } ``` -
- -Listing 10-5: A definition of the `largest` function that uses generic type -parameters but doesn't compile yet - -
-
+Listing 10-5: A definition of the `largest` function that +uses generic type parameters but doesn't compile yet If we try to compile this code right now, we'll get this error: @@ -177,7 +165,6 @@ We can define structs to use a generic type parameter in one or more of the struct's fields with the `<>` syntax too. Listing 10-6 shows the definition and use of a `Point` struct that can hold `x` and `y` coordinate values of any type: -
Filename: src/main.rs ```rust @@ -192,12 +179,8 @@ fn main() { } ``` -
- -Listing 10-6: A `Point` struct that holds `x` and `y` values of type `T` - -
-
+Listing 10-6: A `Point` struct that holds `x` and `y` +values of type `T` The syntax is similar to using generics in function definitions. First, we have to declare the name of the type parameter within angle brackets just after the @@ -210,7 +193,6 @@ Note that because we've only used one generic type in the definition of being. If we try to create an instance of a `Point` that has values of different types, as in Listing 10-7, our code won't compile: -
Filename: src/main.rs ```rust,ignore @@ -224,13 +206,8 @@ fn main() { } ``` -
- -Listing 10-7: The fields `x` and `y` must be the same type because both have -the same generic data type `T` - -
-
+Listing 10-7: The fields `x` and `y` must be the same +type because both have the same generic data type `T` If we try to compile this, we'll get the following error: @@ -257,7 +234,6 @@ parameters. In listing 10-8, we've changed the definition of `Point` to be generic over types `T` and `U`. The field `x` is of type `T`, and the field `y` is of type `U`: -
Filename: src/main.rs ```rust @@ -273,13 +249,8 @@ fn main() { } ``` -
- -Listing 10-8: A `Point` generic over two types so that `x` and `y` may be -values of different types - -
-
+Listing 10-8: A `Point` generic over two types so that +`x` and `y` may be values of different types Now all of these instances of `Point` are allowed! You can use as many generic type parameters in a definition as you want, but using more than a few gets @@ -340,7 +311,6 @@ have generic types in their definitions. Listing 10-9 shows the `Point` struct we defined in Listing 10-6. We've then defined a method named `x` on `Point` that returns a reference to the data in the field `x`: -
Filename: src/main.rs ```rust @@ -362,13 +332,9 @@ fn main() { } ``` -
- -Listing 10-9: Implementing a method named `x` on the `Point` struct that -will return a reference to the `x` field, which is of type `T`. - -
-
+Listing 10-9: Implementing a method named `x` on the +`Point` struct that will return a reference to the `x` field, which is of +type `T`. Note that we have to declare `T` just after `impl`, so that we can use it when we specify that we're implementing methods on the type `Point`. @@ -382,7 +348,6 @@ a new `Point` instance that has the `x` value from the `self` `Point` (which is of type `T`) and the `y` value from the passed-in `Point` (which is of type `W`): -
Filename: src/main.rs ```rust @@ -410,13 +375,8 @@ fn main() { } ``` -
- -Listing 10-10: Methods that use different generic types than their struct's -definition - -
-
+Listing 10-10: Methods that use different generic types +than their struct's definition In `main`, we've defined a `Point` that has an `i32` for `x` (with value `5`) and an `f64` for `y` (with value `10.4`). `p2` is a `Point` that has a string diff --git a/second-edition/src/ch10-02-traits.md b/second-edition/src/ch10-02-traits.md index f2e2670df..20a466ad4 100644 --- a/second-edition/src/ch10-02-traits.md +++ b/second-edition/src/ch10-02-traits.md @@ -30,7 +30,6 @@ ask for that summary by calling a `summary` method on an instance. Listing 10-11 shows the definition of a `Summarizable` trait that expresses this concept: -
Filename: lib.rs ```rust @@ -39,13 +38,8 @@ pub trait Summarizable { } ``` -
- -Listing 10-11: Definition of a `Summarizable` trait that consists of the -behavior provided by a `summary` method - -
-
+Listing 10-11: Definition of a `Summarizable` trait that +consists of the behavior provided by a `summary` method We declare a trait with the `trait` keyword, then the trait's name, in this case `Summarizable`. Inside curly braces we declare the method signatures that @@ -70,7 +64,6 @@ of `summary`. For the `Tweet` struct, we've chosen to define `summary` as the username followed by the whole text of the tweet, assuming that tweet content is already limited to 140 characters. -
Filename: lib.rs ```rust @@ -105,13 +98,8 @@ impl Summarizable for Tweet { } ``` -
- -Listing 10-12: Implementing the `Summarizable` trait on the `NewsArticle` and -`Tweet` types - -
-
+Listing 10-12: Implementing the `Summarizable` trait on +the `NewsArticle` and `Tweet` types Implementing a trait on a type is similar to implementing methods that aren't related to a trait. The difference is after `impl`, we put the trait name that @@ -148,7 +136,6 @@ someone else wants to use our crate's functionality plus implement the to import the `Summarizable` trait into their scope first before they could implement it, like in Listing 10-13: -
Filename: lib.rs ```rust,ignore @@ -171,13 +158,8 @@ impl Summarizable for WeatherForecast { } ``` -
- -Listing 10-13: Bringing the `Summarizable` trait from our `aggregator` crate -into scope in another crate - -
-
+Listing 10-13: Bringing the `Summarizable` trait from our +`aggregator` crate into scope in another crate This code also assumes `Summarizable` is a public trait, which it is because we put the `pub` keyword before `trait` in Listing 10-11. @@ -208,7 +190,6 @@ Listing 10-14 shows how we could have chosen to specify a default string for the `summary` method of the `Summarize` trait instead of only choosing to only define the method signature like we did in Listing 10-11: -
Filename: lib.rs ```rust @@ -219,13 +200,8 @@ pub trait Summarizable { } ``` -
- -Listing 10-14: Definition of a `Summarizable` trait with a default -implementation of the `summary` method - -
-
+Listing 10-14: Definition of a `Summarizable` trait with +a default implementation of the `summary` method If we wanted to use this default implementation to summarize instances of `NewsArticle` instead of defining a custom implementation like we did in @@ -434,7 +410,6 @@ a generic `largest` function that will compile as long as the types of the values in the slice that we pass into `largest` implement both the `PartialOrd` and `Copy` traits, like `i32` and `char`: -
Filename: src/main.rs ```rust @@ -465,13 +440,9 @@ fn main() { } ``` -
- -Listing 10-15: A working definition of the `largest` function that works on any -generic type that implements the `PartialOrd` and `Copy` traits - -
-
+Listing 10-15: A working definition of the `largest` +function that works on any generic type that implements the `PartialOrd` and +`Copy` traits If we don't want to restrict our `largest` function to only types that implement the `Copy` trait, we could specify that `T` has the trait bound diff --git a/second-edition/src/ch10-03-lifetime-syntax.md b/second-edition/src/ch10-03-lifetime-syntax.md index 9c8858614..a7d33f5fe 100644 --- a/second-edition/src/ch10-03-lifetime-syntax.md +++ b/second-edition/src/ch10-03-lifetime-syntax.md @@ -28,8 +28,6 @@ inner scope declares a variable named `x` with the initial value of 5. Inside the inner scope, we attempt to set the value of `r` as a reference to `x`. Then the inner scope ends, and we attempt to print out the value in `r`: -
- ```rust,ignore { let r; @@ -43,12 +41,8 @@ the inner scope ends, and we attempt to print out the value in `r`: } ``` -
- -Listing 10-16: An attempt to use a reference whose value has gone out of scope - -
-
+Listing 10-16: An attempt to use a reference whose value +has gone out of scope > #### Uninitialized Variables Cannot Be Used > @@ -85,8 +79,6 @@ The part of the compiler called the *borrow checker* compares scopes to determine that all borrows are valid. Listing 10-17 shows the same example from Listing 10-16 with annotations showing the lifetimes of the variables: -
- ```rust,ignore { let r; // -------+-- 'a @@ -102,13 +94,8 @@ Listing 10-16 with annotations showing the lifetimes of the variables: } ``` -
- -Listing 10-17: Annotations of the lifetimes of `r` and `x`, named `'a` and `'b` -respectively - -
-
+Listing 10-17: Annotations of the lifetimes of `r` and +`x`, named `'a` and `'b` respectively @@ -71,7 +66,6 @@ something we'll have to remember to account for. Now that we have a way to access all of the arguments, let's find the ones we care about and save them in variables as shown in Listing 12-2: -
Filename: src/main.rs ```rust @@ -88,12 +82,8 @@ fn main() { } ``` -
- -Listing 12-2: Create variables to hold the search argument and filename argument - -
-
+Listing 12-2: Create variables to hold the search +argument and filename argument diff --git a/second-edition/src/ch12-02-reading-a-file.md b/second-edition/src/ch12-02-reading-a-file.md index 2e181237b..a9cfc85ef 100644 --- a/second-edition/src/ch12-02-reading-a-file.md +++ b/second-edition/src/ch12-02-reading-a-file.md @@ -27,7 +27,6 @@ welcome. /Carol --> With that in place, let's edit *src/main.rs* and add code to open the file as shown in Listing 12-3: -
Filename: src/main.rs ```rust @@ -53,12 +52,8 @@ fn main() { } ``` -
- -Listing 12-3: Read the contents of the file specified by the second argument - -
-
+Listing 12-3: Read the contents of the file specified by +the second argument diff --git a/second-edition/src/ch12-03-improving-error-handling-and-modularity.md b/second-edition/src/ch12-03-improving-error-handling-and-modularity.md index abc3b6518..b3d4e6d89 100644 --- a/second-edition/src/ch12-03-improving-error-handling-and-modularity.md +++ b/second-edition/src/ch12-03-improving-error-handling-and-modularity.md @@ -56,7 +56,6 @@ only to parse arguments. Listing 12-4 shows the new start of `main` that calls a new function `parse_config`, which we're still going to define in *src/main.rs*: -
Filename: src/main.rs ```rust @@ -90,12 +89,8 @@ fn parse_config(args: &[String]) -> (&str, &str) { } ``` -
- -Listing 12-4: Extract a `parse_config` function from `main` - -
-
+Listing 12-4: Extract a `parse_config` function from +`main` @@ -121,7 +116,6 @@ Let's introduce a struct to hold all of our configuration. Listing 12-5 shows the addition of the `Config` struct definition, the refactoring of `parse_config`, and updates to `main`: -
Filename: src/main.rs ```rust @@ -162,13 +156,8 @@ fn parse_config(args: &[String]) -> Config { } ``` -
- -Listing 12-5: Refactoring `parse_config` to return an instance of a `Config` -struct - -
-
+Listing 12-5: Refactoring `parse_config` to return an +instance of a `Config` struct @@ -217,7 +206,6 @@ create instances: a `new` function, like `String::new`. Listing 12-6 shows the result of transforming `parse_config` into a `new` function associated with our `Config` struct: -
Filename: src/main.rs ```rust @@ -264,12 +252,8 @@ impl Config { } ``` -
- -Listing 12-6: Changing `parse_config` into `Config::new` - -
-
+Listing 12-6: Changing `parse_config` into +`Config::new` @@ -285,7 +269,6 @@ error message? Let's fix that! Listing 12-7 shows how we can check that our slice is long enough before accessing those locations, and panic with a better error message: -
Filename: src/main.rs ```rust @@ -333,12 +316,8 @@ fn new(args: &[String]) -> Config { # } ``` -
- -Listing 12-7: Adding a check for the number of arguments - -
-
+Listing 12-7: Adding a check for the number of +arguments @@ -360,7 +339,6 @@ now, it returns only a `Config`, so there's no way to indicate that an error happened while creating our `Config`. Instead, we can return a `Result`, as shown in Listing 12-8: -
Filename: src/main.rs ```rust @@ -409,12 +387,7 @@ impl Config { } ``` -
- -Listing 12-8: Return a `Result` from `Config::new` - -
-
+Listing 12-8: Return a `Result` from `Config::new` @@ -432,7 +405,6 @@ conform to its new type signature. Now we need to make some changes to `main` as shown in Listing 12-9: -
Filename: src/main.rs ```rust @@ -485,12 +457,8 @@ fn main() { # } ``` -
- -Listing 12-9: Exiting with an error code if creating a new `Config` fails - -
-
+Listing 12-9: Exiting with an error code if creating a +new `Config` fails @@ -534,7 +502,6 @@ 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 was in `main`: -
Filename: src/main.rs ```rust @@ -591,12 +558,8 @@ fn run(config: Config) { # } ``` -
- -Listing 12-10: Extracting a `run` functionality for the rest of the program logic - -
-
+Listing 12-10: Extracting a `run` functionality for the +rest of the program logic @@ -608,7 +571,6 @@ Listing 12-8: let's return a `Result` instead of calling `panic!` via `std::error::Error` struct into scope and the changes to the `run` function to return a `Result`: -
Filename: src/main.rs ```rust @@ -667,12 +629,8 @@ fn run(config: Config) -> Result<(), Box> { # } ``` -
- -Listing 12-11: Changing the `run` function to return `Result` - -
-
+Listing 12-11: Changing the `run` function to return +`Result` @@ -768,7 +726,6 @@ also need to move the relevant `use` statements and the definition of `Config` and its `new` method as well. Your *src/lib.rs* should now look like Listing 12-12: -
Filename: src/lib.rs ```rust @@ -809,12 +766,8 @@ pub fn run(config: Config) -> Result<(), Box>{ } ``` -
- -Listing 12-12: Moving `Config` and `run` into *src/lib.rs* - -
-
+Listing 12-12: Moving `Config` and `run` into +*src/lib.rs* @@ -826,7 +779,6 @@ through `extern crate greprs`. Then we need to add a `use greprs::Config` line to bring `Config` into scope, and prefix the `run` function with our crate name as shown in Listing 12-13: -
Filename: src/main.rs ```rust,ignore @@ -856,12 +808,8 @@ fn main() { } ``` -
- -Listing 12-13: Bringing the `greprs` crate into the scope of *src/main.rs* - -
-
+Listing 12-13: Bringing the `greprs` crate into the scope +of *src/main.rs* diff --git a/second-edition/src/ch12-04-testing-the-librarys-functionality.md b/second-edition/src/ch12-04-testing-the-librarys-functionality.md index 6cca79171..0381a0c2d 100644 --- a/second-edition/src/ch12-04-testing-the-librarys-functionality.md +++ b/second-edition/src/ch12-04-testing-the-librarys-functionality.md @@ -16,7 +16,6 @@ test will fail with our placeholder implementation, of course, but we can make sure the code compiles and that we get the failure message we expect. Listing 12-14 shows these modifications: -
Filename: src/lib.rs ```rust @@ -66,13 +65,8 @@ Pick three."; } ``` -
- -Listing 12-14: Creating a function where our logic will go and a failing test -for that function - -
-
+Listing 12-14: Creating a function where our logic will +go and a failing test for that function @@ -132,7 +126,6 @@ failures: (left: `["safe, fast, productive."]`, right: `[]`)', src/lib.rs:16 note: Run with `RUST_BACKTRACE=1` for a backtrace. - failures: test::one_result @@ -190,7 +183,6 @@ that, we can make a mutable vector before the `for` loop and call the `push` method to store a `line` in the vector. After the `for` loop, we return the vector. Listing 12-15 has the full implementation: -
Filename: src/lib.rs ```rust @@ -207,12 +199,8 @@ fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { } ``` -
- -Listing 12-15: Fully functioning implementation of the `grep` function - -
-
+Listing 12-15: Fully functioning implementation of the +`grep` function diff --git a/second-edition/src/ch12-05-working-with-environment-variables.md b/second-edition/src/ch12-05-working-with-environment-variables.md index 7dc5ff9be..467f6a035 100644 --- a/second-edition/src/ch12-05-working-with-environment-variables.md +++ b/second-edition/src/ch12-05-working-with-environment-variables.md @@ -54,7 +54,6 @@ We're going to define a new function named `grep_case_insensitive`. Its implementation will be almost the same as the `grep` function, but with some minor changes as shown in Listing 12-16: -
Filename: src/lib.rs ```rust @@ -72,13 +71,9 @@ fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> { } ``` -
- -Listing 12-16: Implementing a `grep_case_insensitive` function by changing the -search string and the lines of the contents to lowercase before comparing them - -
-
+Listing 12-16: Implementing a `grep_case_insensitive` +function by changing the search string and the lines of the contents to +lowercase before comparing them diff --git a/second-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md b/second-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md index b68964faf..1ead7a80a 100644 --- a/second-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md +++ b/second-edition/src/ch12-06-writing-to-stderr-instead-of-stdout.md @@ -26,7 +26,6 @@ We'd like this to be printed to the screen instead, and only have the output from a successful run end up in the file if we run our program this way. Let's change how error messages are printed as shown in Listing 12-17: -
Filename: src/main.rs ```rust,ignore @@ -65,12 +64,8 @@ fn main() { } ``` -
- -Listing 12-17: Writing error messages to `stderr` instead of `stdout` - -
-
+Listing 12-17: Writing error messages to `stderr` instead +of `stdout` diff --git a/second-edition/src/ch13-01-closures.md b/second-edition/src/ch13-01-closures.md index 082fdac4a..4889b786d 100644 --- a/second-edition/src/ch13-01-closures.md +++ b/second-edition/src/ch13-01-closures.md @@ -6,7 +6,6 @@ closures look like, syntactically, and then we'll return to defining what they are. Listing 13-1 shows a small closure whose definition is assigned to the variable `add_one`, which we can then use to call the closure: -
Filename: src/main.rs ```rust @@ -19,13 +18,8 @@ fn main() { } ``` -
- -Listing 13-1: A closure that takes one parameter and adds one to it, assigned to -the variable `add_one` - -
-
+Listing 13-1: A closure that takes one parameter and adds +one to it, assigned to the variable `add_one` The closure definition, on the first line, shows that the closure takes one parameter named `x`. Parameters to closures go in between vertical pipes (`|`). @@ -33,7 +27,6 @@ parameter named `x`. Parameters to closures go in between vertical pipes (`|`). This is a minimal closure with only one expression as its body. Listing 13-2 has a closure with a bit more complexity: -
Filename: src/main.rs ```rust @@ -51,12 +44,8 @@ fn main() { } ``` -
- -Listing 13-2: A closure with two parameters and multiple expressions in its body - -
-
+Listing 13-2: A closure with two parameters and multiple +expressions in its body We can use curly brackets to define a closure body with more than one expression. @@ -68,7 +57,6 @@ We can choose to add type annotations if we want; Listing 13-3 shows the closure from Listing 13-1 with annotations for the parameter's and return value's types: -
Filename: src/main.rs ```rust @@ -79,13 +67,8 @@ fn main() { } ``` -
- -Listing 13-3: A closure definition with optional parameter and return value -type annotations - -
-
+Listing 13-3: A closure definition with optional +parameter and return value type annotations The syntax of closures and functions looks more similar with type annotations. Let's compare the different ways we can specify closures with the syntax for @@ -147,7 +130,6 @@ allowed to access variables from their enclosing scope. Listing 13-4 has an example of a closure in the variable `equal_to_x` that uses the variable `x` from the closure's surrounding environment: -
Filename: src/main.rs ```rust @@ -162,13 +144,8 @@ fn main() { } ``` -
- -Listing 13-4: Example of a closure that refers to a variable in its enclosing -scope - -
-
+Listing 13-4: Example of a closure that refers to a +variable in its enclosing scope Here, even though `x` is not one of the parameters of `equal_to_x`, the `equal_to_x` closure is allowed to use `x`, since `x` is a variable defined in diff --git a/second-edition/src/ch13-02-iterators.md b/second-edition/src/ch13-02-iterators.md index e6ff86e5c..1aa816ddc 100644 --- a/second-edition/src/ch13-02-iterators.md +++ b/second-edition/src/ch13-02-iterators.md @@ -4,8 +4,6 @@ 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: -
- ```rust let v1 = vec![1, 2, 3]; @@ -14,13 +12,8 @@ let v2: Vec = v1.iter().map(|x| x + 1).collect(); assert_eq!(v2, [2, 3, 4]); ``` -
- -Listing 13-5: Using an iterator, `map`, and `collect` to add one to each number -in a vector - -
-
+Listing 13-5: Using an iterator, `map`, and `collect` to +add one to each number in a vector @@ -127,8 +120,6 @@ want our iterator to return one first). If `count` is still less than six, we'll return the current value, but if `count` is six or higher, our iterator will return `None`, as shown in Listing 13-6: -
- ```rust # struct Counter { # count: u32, @@ -152,12 +143,8 @@ impl Iterator for Counter { } ``` -
- -Listing 13-6: Implementing the `Iterator` trait on our `Counter` struct - -
-
+Listing 13-6: Implementing the `Iterator` trait on our +`Counter` struct diff --git a/second-edition/src/ch14-02-publishing-to-crates-io.md b/second-edition/src/ch14-02-publishing-to-crates-io.md index ff6b8f8cd..a8bed4e1d 100644 --- a/second-edition/src/ch14-02-publishing-to-crates-io.md +++ b/second-edition/src/ch14-02-publishing-to-crates-io.md @@ -24,8 +24,6 @@ Documentation comments use `///` instead of `//` and support Markdown notation inside. They go just before the item they are documenting. Here's documentation comments for an `add_one` function: -
- Filename: src/lib.rs ````rust @@ -46,12 +44,8 @@ pub fn add_one(x: i32) -> i32 { } ```` -
- -Listing 14-1: A documentation comment for a function - -
-
+Listing 14-1: A documentation comment for a +function `cargo doc` runs a tool distributed with Rust, `rustdoc`, to generate HTML documentation from these comments. To try this out locally, you can run `cargo @@ -111,7 +105,6 @@ For example, say that we made a library named `art` consisting of a `kinds` module containing an enum named `Color` and a `utils` module containing a function named `mix` as shown in Listing 14-2: -
Filename: src/lib.rs ```rust @@ -147,18 +140,12 @@ pub mod utils { } ``` -
- -Listing 14-2: An `art` library with items organized into `kinds` and `utils` -modules - -
-
+Listing 14-2: An `art` library with items organized into +`kinds` and `utils` modules In order to use this library, another crate would have `use` statements as in Listing 14-3: -
Filename: src/main.rs ```rust,ignore @@ -174,13 +161,8 @@ fn main() { } ``` -
- -Listing 14-3: A program using the `art` crate's items with its internal -structure exported - -
-
+Listing 14-3: A program using the `art` crate's items +with its internal structure exported Users of this crate shouldn't need to know that `PrimaryColor` and `SecondaryColor` are in the `kinds` module, and `mix` is in the `utils` module; @@ -190,7 +172,6 @@ meaning from the outside looking in. To change this, we can add the following `pub use` statements to the code from Listing 14-2 to re-export the types at the top level, as shown in Listing 14-4: -
Filename: src/lib.rs ```rust @@ -213,12 +194,8 @@ pub mod kinds { # } ``` -
- -Listing 14-4: Adding `pub use` statements to re-export items - -
-
+Listing 14-4: Adding `pub use` statements to re-export +items @@ -227,7 +204,6 @@ documentation. Users of the `art` crate can still see and choose to use the internal structure as in Listing 14-3, or they can use the more convenient structure from Listing 14-4, as shown in Listing 14-5: -
Filename: src/main.rs ```rust,ignore @@ -241,12 +217,8 @@ fn main() { } ``` -
- -Listing 14-5: Using the re-exported items from the `art` crate - -
-
+Listing 14-5: Using the re-exported items from the `art` +crate diff --git a/second-edition/src/ch15-01-box.md b/second-edition/src/ch15-01-box.md index 29d87933d..e3cad50e0 100644 --- a/second-edition/src/ch15-01-box.md +++ b/second-edition/src/ch15-01-box.md @@ -5,7 +5,6 @@ The most straightforward smart pointer is a *box*, whose type is written the stack vs. the heap in Chapter 4). Listing 15-1 shows how to use a box to store an `i32` on the heap: -
Filename: src/main.rs ```rust @@ -15,12 +14,8 @@ fn main() { } ``` -
- -Listing 15-1: Storing an `i32` value on the heap using a box - -
-
+Listing 15-1: Storing an `i32` value on the heap using a +box This will print `b = 5`. In this case, we can access the data in the box in a similar way as we would if this data was on the stack. Just like any value that @@ -45,7 +40,6 @@ implementing this data structure is useful as an example. Here's our first try at defining a cons list as an enum; note that this won't compile quite yet: -
Filename: src/main.rs ```rust,ignore @@ -55,16 +49,11 @@ enum List { } ``` -
- -Listing 15-2: The first attempt of defining an enum to represent a cons list -data structure of `i32` values - -
-
+Listing 15-2: The first attempt of defining an enum to +represent a cons list data structure of `i32` values We're implementing a cons list that holds only `i32` values. We -could have also chosen to implement a cons list independent of the +could have also chosen to implement a cons list independent of the type of value by using generics as discussed in Chapter 10. Using a cons list to store the list `1, 2, 3` would look like this: @@ -84,8 +73,6 @@ is one more `Cons` value that holds `3` and a `List` value, which is finally If we try to compile the above code, we get the error shown in Listing 15-3: -
- ```text error[E0072]: recursive type `List` has infinite size --> @@ -101,12 +88,8 @@ error[E0072]: recursive type `List` has infinite size make `List` representable ``` -
- -Listing 15-3: The error we get when attempting to define a recursive enum - -
-
+Listing 15-3: The error we get when attempting to define +a recursive enum The error says this type 'has infinite size'. Why is that? It's because we've defined `List` to have a variant that is recursive: it holds another value of @@ -141,16 +124,10 @@ its variants, starting with the `Cons` variant. The `Cons` variant holds a value of type `i32` and a value of type `List`, and this continues infinitely, as shown in Figure 15-4. -
- An infinite Cons list -
- -Figure 15-4: An infinite `List` consisting of infinite `Cons` variants - -
-
+Figure 15-4: An infinite `List` consisting of infinite +`Cons` variants Rust can't figure out how much space to allocate for recursively defined types, so the compiler gives the error in Listing 15-3. The error did include this @@ -169,7 +146,6 @@ definition from Listing 15-2 to look like the definition here in Listing 15-5, and change `main` to use `Box::new` for the values inside the `Cons` variants like so: -
Filename: src/main.rs ```rust @@ -188,13 +164,8 @@ fn main() { } ``` -
- -Listing 15-5: Definition of `List` that uses `Box` in order to have a -known size - -
-
+Listing 15-5: Definition of `List` that uses `Box` in +order to have a known size The compiler will be able to figure out the size it needs to store a `List` value. Rust will look at `List`, and again start by looking at the `Cons` @@ -205,16 +176,10 @@ value, so `Nil` doesn't need any space. We've broken the infinite, recursive chain by adding in a box. Figure 15-6 shows what the `Cons` variant looks like now: -
- A finite Cons list -
- -Figure 15-6: A `List` that is not infinitely sized since `Cons` holds a `Box` - -
-
+Figure 15-6: A `List` that is not infinitely sized since +`Cons` holds a `Box` This is the main area where boxes are useful: breaking up an infinite data structure so that the compiler can know what size it is. We'll look at another diff --git a/second-edition/src/ch15-02-deref.md b/second-edition/src/ch15-02-deref.md index 47b35ed48..bc6192f3f 100644 --- a/second-edition/src/ch15-02-deref.md +++ b/second-edition/src/ch15-02-deref.md @@ -45,7 +45,6 @@ metadata, so we implement the `Deref` trait to return the audio data. Implementing the `Deref` trait requires implementing one method named `deref` that borrows `self` and returns the inner data: -
Filename: src/main.rs ```rust @@ -77,13 +76,8 @@ fn main() { } ``` -
- -Listing 15-7: An implementation of the `Deref` trait on a struct that holds mp3 -file data and metadata - -
-
+Listing 15-7: An implementation of the `Deref` trait on a +struct that holds mp3 file data and metadata Most of this should look familiar: a struct, a trait implementation, and a main function that creates an instance of the struct. There is one part we diff --git a/second-edition/src/ch15-03-drop.md b/second-edition/src/ch15-03-drop.md index 2d20c55cc..535e3ff95 100644 --- a/second-edition/src/ch15-03-drop.md +++ b/second-edition/src/ch15-03-drop.md @@ -28,7 +28,6 @@ instance goes out of scope so that we can see when each piece of code gets run. Instead of a `println!` statement, you'd fill in `drop` with whatever cleanup code your smart pointer needs to run: -
Filename: src/main.rs ```rust @@ -49,13 +48,9 @@ fn main() { } ``` -
- -Listing 15-8: A `CustomSmartPointer` struct that implements the `Drop` trait, -where we could put code that would clean up after the `CustomSmartPointer`. - -
-
+Listing 15-8: A `CustomSmartPointer` struct that +implements the `Drop` trait, where we could put code that would clean up after +the `CustomSmartPointer`. The `Drop` trait is in the prelude, so we don't need to import it. The `drop` method implementation calls the `println!`; this is where you'd put the actual @@ -84,7 +79,6 @@ in Chapter 16 when we're talking about concurrency. For now, let's just see that it's possible, and `std::mem::drop` is in the prelude so we can just call `drop` as shown in Listing 15-9: -
Filename: src/main.rs ```rust,ignore @@ -96,13 +90,8 @@ fn main() { } ``` -
- -Listing 15-9: Calling `std::mem::drop` to explicitly drop a value before it -goes out of scope - -
-
+Listing 15-9: Calling `std::mem::drop` to explicitly drop +a value before it goes out of scope Running this code will print the following, showing that the destructor code is called since `Dropping CustomSmartPointer!` is printed between diff --git a/second-edition/src/ch15-04-rc.md b/second-edition/src/ch15-04-rc.md index 8e3fcf4e8..28f21c98f 100644 --- a/second-edition/src/ch15-04-rc.md +++ b/second-edition/src/ch15-04-rc.md @@ -38,21 +38,14 @@ first list containing 5 and 10. In other words, we want two lists that both share ownership of the third list, which conceptually will be something like Figure 15-10: -
- Two lists that share ownership of a third list -
- -Figure 15-10: Two lists, `b` and `c`, sharing ownership of a third list, `a` - -
-
+Figure 15-10: Two lists, `b` and `c`, sharing ownership +of a third list, `a` Trying to implement this using our definition of `List` with `Box` won't work, as shown in Listing 15-11: -
Filename: src/main.rs ```rust,ignore @@ -72,13 +65,8 @@ fn main() { } ``` -
- -Listing 15-11: Having two lists using `Box` that try to share ownership of a -third list won't work - -
-
+Listing 15-11: Having two lists using `Box` that try +to share ownership of a third list won't work If we compile this, we get this error: @@ -107,7 +95,6 @@ Otherwise, the borrow checker won't even let us compile the code. Instead, we can change our definition of `List` to use `Rc` instead of `Box` as shown here in Listing 15-12: -
Filename: src/main.rs ```rust @@ -126,12 +113,8 @@ fn main() { } ``` -
- -Listing 15-12: A definition of `List` that uses `Rc` - -
-
+Listing 15-12: A definition of `List` that uses +`Rc` Note that we need to add a `use` statement for `Rc` because it's not in the prelude. In `main`, we create the list holding 5 and 10 and store it in a new @@ -149,7 +132,6 @@ count of the `Rc` value we pass to it, and we'll talk about why this function is named `strong_count` in the section later in this chapter about preventing reference cycles. -
Filename: src/main.rs ```rust @@ -174,12 +156,7 @@ fn main() { } ``` -
- -Listing 15-13: Printing out the reference count - -
-
+Listing 15-13: Printing out the reference count This will print out: diff --git a/second-edition/src/ch15-05-interior-mutability.md b/second-edition/src/ch15-05-interior-mutability.md index d8159b809..75e3e375d 100644 --- a/second-edition/src/ch15-05-interior-mutability.md +++ b/second-edition/src/ch15-05-interior-mutability.md @@ -64,7 +64,6 @@ declared as immutable with `let data` rather than `let mut data`, yet `a_fn_that_mutably_borrows` is allowed to borrow the data mutably and make changes to the data! -
Filename: src/main.rs ```rust @@ -90,12 +89,8 @@ fn main() { } ``` -
- -Listing 15-14: Using `RefCell`, `borrow`, and `borrow_mut` - -
-
+Listing 15-14: Using `RefCell`, `borrow`, and +`borrow_mut` This example prints: @@ -192,7 +187,6 @@ owner of the value that's not part of the list (the multiple owners functionality that `Rc` provides), and so we can mutate the inner `i32` value (the interior mutability functionality that `RefCell` provides): -
Filename: src/main.rs ```rust @@ -223,12 +217,8 @@ fn main() { } ``` -
- -Listing 15-15: Using `Rc>` to create a `List` that we can mutate - -
-
+Listing 15-15: Using `Rc>` to create a +`List` that we can mutate We're creating a value, which is an instance of `Rc>`. We're storing it in a variable named `value` because we want to be able to access it diff --git a/second-edition/src/ch15-06-reference-cycles.md b/second-edition/src/ch15-06-reference-cycles.md index 3a4db5616..a25a7a26a 100644 --- a/second-edition/src/ch15-06-reference-cycles.md +++ b/second-edition/src/ch15-06-reference-cycles.md @@ -21,7 +21,6 @@ we want to be able to modify which `List` a `Cons` variant is pointing to. We've also added a `tail` method to make it convenient for us to access the second item, if we have a `Cons` variant: -
Filename: src/main.rs ```rust @@ -44,13 +43,8 @@ impl List { # use List::{Cons, Nil}; ``` -
- -Listing 15-16: A cons list definition that holds a `RefCell` so that we can -modify what a `Cons` variant is referring to - -
-
+Listing 15-16: A cons list definition that holds a +`RefCell` so that we can modify what a `Cons` variant is referring to Next, in Listing 15-17, we're going to create a `List` value in the variable `a` that initially is a list of `5, Nil`. Then we'll create a `List` value in @@ -58,7 +52,6 @@ the variable `b` that is a list of the value 10 and then points to the list in `a`. Finally, we'll modify `a` so that it points to `b` instead of `Nil`, which will then create a cycle: -
Filename: src/main.rs ```rust @@ -107,29 +100,18 @@ fn main() { } ``` -
- -Listing 15-17: Creating a reference cycle of two `List` values pointing to -each other - -
-
+Listing 15-17: Creating a reference cycle of two `List` +values pointing to each other We use the `tail` method to get a reference to the `RefCell` in `a`, which we put in the variable `link`. Then we use the `borrow_mut` method on the `RefCell` to change the value inside from an `Rc` that holds a `Nil` value to the `Rc` in `b`. We've created a reference cycle that looks like Figure 15-18: -
- Reference cycle of lists -
- -Figure 15-18: A reference cycle of lists `a` and `b` pointing to each other - -
-
+Figure 15-18: A reference cycle of lists `a` and `b` +pointing to each other If you uncomment the last `println!`, Rust will try and print this cycle out with `a` pointing to `b` pointing to `a` and so forth until it overflows the @@ -207,7 +189,6 @@ nodes are another node's children, so that's why we have a `RefCell` in `Node` named `leaf` with the value 3 and no children, and another instance named `branch` with the value 5 and `leaf` as one of its children: -
Filename: src/main.rs ```rust @@ -224,13 +205,9 @@ fn main() { } ``` -
- -Listing 15-19: Creating a `leaf` node and a `branch` node where `branch` has -`leaf` as one of its children but `leaf` has no reference to `branch` - -
-
+Listing 15-19: Creating a `leaf` node and a `branch` node +where `branch` has `leaf` as one of its children but `leaf` has no reference to +`branch` The `Node` in `leaf` now has two owners: `leaf` and `branch`, since we clone the `Rc` in `leaf` and store that in `branch`. The `Node` in `branch` knows @@ -267,7 +244,6 @@ but it does not own its parent. A parent node will be dropped even if it has child nodes referring to it, as long as it doesn't have a parent node as well. Now let's update `main` to look like Listing 15-20: -
Filename: src/main.rs ```rust @@ -292,13 +268,8 @@ fn main() { } ``` -
- -Listing 15-20: A `leaf` node and a `branch` node where `leaf` has a `Weak` -reference to its parent, `branch` - -
-
+Listing 15-20: A `leaf` node and a `branch` node where +`leaf` has a `Weak` reference to its parent, `branch` Creating the `leaf` node looks similar; since it starts out without a parent, we create a new `Weak` reference instance. When we try to get a reference to @@ -335,7 +306,6 @@ case. Another way we can tell is by looking at the values we get from calling inner scope and move the creation of `branch` in there, so that we can see what happens when `branch` is created and then dropped when it goes out of scope: -
Filename: src/main.rs ``` @@ -382,13 +352,8 @@ fn main() { } ``` -
- -Listing 15-21: Creating `branch` in an inner scope and examining strong and -weak reference counts of `leaf` and `branch` - -
-
+Listing 15-21: Creating `branch` in an inner scope and +examining strong and weak reference counts of `leaf` and `branch` Right after creating `leaf`, its strong count is 1 (for `leaf` itself) and its weak count is 0. In the inner scope, after we create `branch` and associate diff --git a/second-edition/src/ch16-00-concurrency.md b/second-edition/src/ch16-00-concurrency.md index 9db08e0dd..f128ec77c 100644 --- a/second-edition/src/ch16-00-concurrency.md +++ b/second-edition/src/ch16-00-concurrency.md @@ -15,8 +15,6 @@ compiler is making sure you don't shoot yourself in your foot. ## What are threads - - ## Rust's concurrency tradeoffs Lots of different languages tackle this problem in different ways. We are not @@ -34,14 +32,12 @@ to not have a heavy runtime. These are the reasons Rust's concurrency model is this way as opposed to other language's ways, which are optimizing for different things. - ## Let's get a thread: `thread::spawn` Code examples - just print stuff, no data sharing ## Communicating between threads - ### Closures, Ownership, and Borrowing The property of being allowed to use variables from the surrounding scope is @@ -53,7 +49,6 @@ borrow immutably, borrow mutably, and move their parameters, then closures that reference values from their environment and call each of the functions. We'll see how this affects inference of when a value is borrowed: -
Filename: src/main.rs ```rust @@ -87,14 +82,9 @@ fn main() { } ``` -
- -Listing 16-something: Closures that borrow, borrow mutably, and take ownership -of their parameters, which is inferred from how the closure body uses the -parameters - -
-
+Listing 16-something: Closures that borrow, borrow +mutably, and take ownership of their parameters, which is inferred from how the +closure body uses the parameters Here, Rust is able to look at how we use the parameters of each closure inside their bodies. If the closure passes its parameter it to a function that takes @@ -174,8 +164,6 @@ Because closures may borrow variables from their enclosing scope, we can construct a similar example with a closure that borrows `x` and tries to return that borrowed value. The code in Listing 13-6 also won't compile: -
- ```rust,ignore { let closure; @@ -188,13 +176,8 @@ that borrowed value. The code in Listing 13-6 also won't compile: } ``` -
- -Listing 16-something: A closure that tries to return a borrowed value that does -not live long enough - -
-
+Listing 16-something: A closure that tries to return a +borrowed value that does not live long enough We get an error because `x` does not live long enough: @@ -217,8 +200,6 @@ from the last section to make the closure take ownership of `x`. Because `x` is a number, it is a `Copy` type and therefore will be copied into the closure. The code in Listing 13-7 will compile: -
- ```rust { let closure; @@ -235,12 +216,8 @@ The code in Listing 13-7 will compile: } ``` -
- -Listing 16-something: Moving a value into the closure to fix the lifetime error - -
-
+Listing 16-something: Moving a value into the closure to +fix the lifetime error Even though we modified `x` between the closure definition and `assert_eq!`, since `closure` now has its own version, the changes to `x` won't change the @@ -313,13 +290,10 @@ code will hang. Deadlocks are safe, you have to manage that yourself. Deadlock bugs usually happen bc you forget to unlock, but drop unlocks automatically. - ## Maybe make the I/O project concurrent? Might be a lot of boilerplate without scoped threads, maybe just allude. - - This is a really rough sketch of some ideas that this chapter might cover. From a comment of steveklabnik's on [the definitely not orange website]. "that paper" refers to [Boehm 2004]. @@ -327,7 +301,6 @@ From a comment of steveklabnik's on [the definitely not orange website]. "that p [the definitely not orange website]: https://news.ycombinator.com/item?id=13078384 [Boehm 2004]: http://www.hpl.hp.com/techreports/2004/HPL-2004-209.pdf - So for example, in that paper, 4.1 is about the problem of concurrent modifiability. And indeed, it says From c49e5ee8859f8eb8f8867cbeafbdf5b802aa5894 Mon Sep 17 00:00:00 2001 From: "Carol (Nichols || Goulding)" Date: Tue, 7 Mar 2017 22:38:53 -0500 Subject: [PATCH 3/3] Fix or ignore the failing tests that haven't been running :( --- .../ch09-02-recoverable-errors-with-result.md | 1 + second-edition/src/ch10-03-lifetime-syntax.md | 12 +- ...h12-01-accepting-command-line-arguments.md | 2 +- second-edition/src/ch12-02-reading-a-file.md | 2 +- ...improving-error-handling-and-modularity.md | 218 +----------------- .../src/ch14-02-publishing-to-crates-io.md | 11 +- .../src/ch15-06-reference-cycles.md | 11 +- 7 files changed, 20 insertions(+), 237 deletions(-) diff --git a/second-edition/src/ch09-02-recoverable-errors-with-result.md b/second-edition/src/ch09-02-recoverable-errors-with-result.md index 316758366..b51d6ac56 100644 --- a/second-edition/src/ch09-02-recoverable-errors-with-result.md +++ b/second-edition/src/ch09-02-recoverable-errors-with-result.md @@ -344,6 +344,7 @@ question mark operator: ```rust use std::io; +use std::io::Read; use std::fs::File; fn read_username_from_file() -> Result { diff --git a/second-edition/src/ch10-03-lifetime-syntax.md b/second-edition/src/ch10-03-lifetime-syntax.md index a7d33f5fe..fb3b4d66d 100644 --- a/second-edition/src/ch10-03-lifetime-syntax.md +++ b/second-edition/src/ch10-03-lifetime-syntax.md @@ -148,7 +148,7 @@ longest string is abcd` once we've implemented the `longest` function: Filename: src/main.rs -```rust +```rust,ignore fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; @@ -369,15 +369,7 @@ inner scope, after it has ended. The code in Listing 10-23 will not compile: Filename: src/main.rs -```rust -# fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { -# if x.len() > y.len() { -# x -# } else { -# y -# } -# } -# +```rust,ignore fn main() { let string1 = String::from("long string is long"); let result; diff --git a/second-edition/src/ch12-01-accepting-command-line-arguments.md b/second-edition/src/ch12-01-accepting-command-line-arguments.md index 48b53680e..df58047c6 100644 --- a/second-edition/src/ch12-01-accepting-command-line-arguments.md +++ b/second-edition/src/ch12-01-accepting-command-line-arguments.md @@ -68,7 +68,7 @@ care about and save them in variables as shown in Listing 12-2: Filename: src/main.rs -```rust +```rust,ignore use std::env; fn main() { diff --git a/second-edition/src/ch12-02-reading-a-file.md b/second-edition/src/ch12-02-reading-a-file.md index a9cfc85ef..6dee9193c 100644 --- a/second-edition/src/ch12-02-reading-a-file.md +++ b/second-edition/src/ch12-02-reading-a-file.md @@ -29,7 +29,7 @@ shown in Listing 12-3: Filename: src/main.rs -```rust +```rust,ignore use std::env; use std::fs::File; use std::io::prelude::*; diff --git a/second-edition/src/ch12-03-improving-error-handling-and-modularity.md b/second-edition/src/ch12-03-improving-error-handling-and-modularity.md index b3d4e6d89..ffcdb7779 100644 --- a/second-edition/src/ch12-03-improving-error-handling-and-modularity.md +++ b/second-edition/src/ch12-03-improving-error-handling-and-modularity.md @@ -58,11 +58,7 @@ a new function `parse_config`, which we're still going to define in Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# +```rust,ignore fn main() { let args: Vec = env::args().collect(); @@ -72,13 +68,6 @@ fn main() { println!("In file {}", filename); // ...snip... -# -# let mut f = File::open(filename).expect("file not found"); -# -# let mut contents = String::new(); -# f.read_to_string(&mut contents).expect("something went wrong reading the file"); -# -# println!("With text:\n{}", contents); } fn parse_config(args: &[String]) -> (&str, &str) { @@ -118,11 +107,7 @@ the addition of the `Config` struct definition, the refactoring of Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# +```rust,ignore fn main() { let args: Vec = env::args().collect(); @@ -134,10 +119,6 @@ fn main() { let mut f = File::open(config.filename).expect("file not found"); // ...snip... -# let mut contents = String::new(); -# f.read_to_string(&mut contents).expect("something went wrong reading the file"); -# -# println!("With text:\n{}", contents); } struct Config { @@ -208,11 +189,7 @@ result of transforming `parse_config` into a `new` function associated with our Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# +```rust,ignore fn main() { let args: Vec = env::args().collect(); @@ -222,21 +199,8 @@ fn main() { println!("In file {}", config.filename); // ...snip... - -# let mut f = File::open(config.filename).expect("file not found"); -# -# let mut contents = String::new(); -# f.read_to_string(&mut contents).expect("something went wrong reading the file"); -# -# println!("With text:\n{}", contents); - } -# struct Config { -# search: String, -# filename: String, -# } -# // ...snip... impl Config { @@ -271,33 +235,7 @@ error message: Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# -# fn main() { -# let args: Vec = env::args().collect(); -# -# let config = Config::new(&args); -# -# println!("Searching for {}", config.search); -# println!("In file {}", config.filename); -# -# let mut f = File::open(config.filename).expect("file not found"); -# -# let mut contents = String::new(); -# f.read_to_string(&mut contents).expect("something went wrong reading the file"); -# -# println!("With text:\n{}", contents); -# } -# -# struct Config { -# search: String, -# filename: String, -# } -# -# impl Config { +```rust,ignore // ...snip... fn new(args: &[String]) -> Config { if args.len() < 3 { @@ -306,14 +244,7 @@ fn new(args: &[String]) -> Config { let search = args[1].clone(); // ...snip... -# let filename = args[2].clone(); -# -# Config { -# search: search, -# filename: filename, -# } } -# } ``` Listing 12-7: Adding a check for the number of @@ -341,35 +272,7 @@ shown in Listing 12-8: Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# use std::process; -# -# fn main() { -# let args: Vec = env::args().collect(); -# -# let config = Config::new(&args).unwrap_or_else(|err| { -# println!("Problem parsing arguments: {}", err); -# process::exit(1); -# }); -# -# println!("Searching for {}", config.search); -# println!("In file {}", config.filename); -# -# let mut f = File::open(config.filename).expect("file not found"); -# -# let mut contents = String::new(); -# f.read_to_string(&mut contents).expect("something went wrong reading the file"); -# -# println!("With text:\n{}", contents); -# } -# struct Config { -# search: String, -# filename: String, -# } -# +```rust,ignore impl Config { fn new(args: &[String]) -> Result { if args.len() < 3 { @@ -407,10 +310,7 @@ Now we need to make some changes to `main` as shown in Listing 12-9: Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; +```rust,ignore // ...snip... use std::process; @@ -426,35 +326,6 @@ fn main() { println!("In file {}", config.filename); // ...snip... -# -# let mut f = File::open(config.filename).expect("file not found"); -# -# let mut contents = String::new(); -# f.read_to_string(&mut contents).expect("something went wrong reading the file"); -# -# println!("With text:\n{}", contents); -# } -# -# struct Config { -# search: String, -# filename: String, -# } -# -# impl Config { -# fn new(args: &[String]) -> Result { -# if args.len() < 3 { -# return Err("not enough arguments"); -# } -# -# let search = args[1].clone(); -# let filename = args[2].clone(); -# -# Ok(Config { -# search: search, -# filename: filename, -# }) -# } -# } ``` Listing 12-9: Exiting with an error code if creating a @@ -504,19 +375,8 @@ was in `main`: Filename: src/main.rs -```rust -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# use std::process; -# +```rust,ignore fn main() { -# let args: Vec = env::args().collect(); -# -# let config = Config::new(&args).unwrap_or_else(|err| { -# println!("Problem parsing arguments: {}", err); -# process::exit(1); -# }); // ...snip... println!("Searching for {}", config.search); @@ -535,27 +395,6 @@ fn run(config: Config) { } // ...snip... -# -# struct Config { -# search: String, -# filename: String, -# } -# -# impl Config { -# fn new(args: &[String]) -> Result { -# if args.len() < 3 { -# return Err("not enough arguments"); -# } -# -# let search = args[1].clone(); -# let filename = args[2].clone(); -# -# Ok(Config { -# search: search, -# filename: filename, -# }) -# } -# } ``` Listing 12-10: Extracting a `run` functionality for the @@ -573,28 +412,10 @@ to return a `Result`: Filename: src/main.rs -```rust +```rust,ignore use std::error::Error; -# use std::env; -# use std::fs::File; -# use std::io::prelude::*; -# use std::process; // ...snip... -# fn main() { -# let args: Vec = env::args().collect(); -# -# let config = Config::new(&args).unwrap_or_else(|err| { -# println!("Problem parsing arguments: {}", err); -# process::exit(1); -# }); -# -# println!("Searching for {}", config.search); -# println!("In file {}", config.filename); -# -# run(config); -# -# } fn run(config: Config) -> Result<(), Box> { let mut f = File::open(config.filename)?; @@ -606,27 +427,6 @@ fn run(config: Config) -> Result<(), Box> { Ok(()) } -# -# struct Config { -# search: String, -# filename: String, -# } -# -# impl Config { -# fn new(args: &[String]) -> Result { -# if args.len() < 3 { -# return Err("not enough arguments"); -# } -# -# let search = args[1].clone(); -# let filename = args[2].clone(); -# -# Ok(Config { -# search: search, -# filename: filename, -# }) -# } -# } ``` Listing 12-11: Changing the `run` function to return @@ -728,7 +528,7 @@ and its `new` method as well. Your *src/lib.rs* should now look like Listing Filename: src/lib.rs -```rust +```rust,ignore use std::error::Error; use std::fs::File; use std::io::prelude::*; diff --git a/second-edition/src/ch14-02-publishing-to-crates-io.md b/second-edition/src/ch14-02-publishing-to-crates-io.md index a8bed4e1d..f12913f39 100644 --- a/second-edition/src/ch14-02-publishing-to-crates-io.md +++ b/second-edition/src/ch14-02-publishing-to-crates-io.md @@ -107,7 +107,7 @@ function named `mix` as shown in Listing 14-2: Filename: src/lib.rs -```rust +```rust,ignore //! # Art //! //! A library for modeling artistic concepts. @@ -174,7 +174,7 @@ Listing 14-2 to re-export the types at the top level, as shown in Listing 14-4: Filename: src/lib.rs -```rust +```rust,ignore //! # Art //! //! A library for modeling artistic concepts. @@ -185,13 +185,6 @@ pub use utils::mix; pub mod kinds { // ...snip... -# pub enum PrimaryColor; -# pub enum SecondaryColor; -# } -# -# pub mod utils { -# pub fn mix() {} -# } ``` Listing 14-4: Adding `pub use` statements to re-export diff --git a/second-edition/src/ch15-06-reference-cycles.md b/second-edition/src/ch15-06-reference-cycles.md index a25a7a26a..a14260698 100644 --- a/second-edition/src/ch15-06-reference-cycles.md +++ b/second-edition/src/ch15-06-reference-cycles.md @@ -23,7 +23,7 @@ second item, if we have a `Cons` variant: Filename: src/main.rs -```rust +```rust,ignore #[derive(Debug)] enum List { Cons(i32, RefCell>), @@ -38,9 +38,6 @@ impl List { } } } -# use std::rc::Rc; -# use std::cell::RefCell; -# use List::{Cons, Nil}; ``` Listing 15-16: A cons list definition that holds a @@ -191,7 +188,7 @@ named `branch` with the value 5 and `leaf` as one of its children: Filename: src/main.rs -```rust +```rust,ignore fn main() { let leaf = Rc::new(Node { value: 3, @@ -246,7 +243,7 @@ node as well. Now let's update `main` to look like Listing 15-20: Filename: src/main.rs -```rust +```rust,ignore fn main() { let leaf = Rc::new(Node { value: 3, @@ -308,7 +305,7 @@ happens when `branch` is created and then dropped when it goes out of scope: Filename: src/main.rs -``` +```rust,ignore fn main() { let leaf = Rc::new(Node { value: 3,