Merge pull request #525 from rust-lang/remove-figure-html

Remove figure html
This commit is contained in:
Carol (Nichols || Goulding)
2017-03-07 22:50:32 -05:00
committed by GitHub
38 changed files with 273 additions and 1233 deletions
@@ -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*.
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -96,12 +95,7 @@ fn main() {
}
```
<figcaption>
Listing 2-1: Code to get a guess from the user and print it out
</figcaption>
</figure>
<span class="caption">Listing 2-1: Code to get a guess from the user and print it out</span>
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:
<figure>
```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)
```
<figcaption>
Listing 2-2: The output from running `cargo build` after adding the rand crate
as a dependency
</figcaption>
</figure>
<span class="caption">Listing 2-2: The output from running `cargo build` after
adding the rand crate as a dependency</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -537,12 +523,8 @@ fn main() {
}
```
<figcaption>
Listing 2-3: Code changes needed in order to generate a random number
</figcaption>
</figure>
<span class="caption">Listing 2-3: Code changes needed in order to generate a
random number</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -638,12 +619,8 @@ fn main() {
}
```
<figcaption>
Listing 2-4: Handling the possible return values of comparing two numbers
</figcaption>
</figure>
<span class="caption">Listing 2-4: Handling the possible return values of
comparing two numbers</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -1072,12 +1048,7 @@ fn main() {
}
```
<figcaption>
Listing 2-5: Complete code of the guessing game
</figcaption>
</figure>
<span class="caption">Listing 2-5: Complete code of the guessing game</span>
## Summary
+2 -16
View File
@@ -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.
<figure>
<figcaption>
Table 3-1: Integer Types in Rust
</figcaption>
<span class="caption">Table 3-1: Integer Types in Rust</span>
| Length | Signed | Unsigned |
|--------|--------|----------|
@@ -63,8 +58,6 @@ Table 3-1: Integer Types in Rust
| 64-bit | i64 | u64 |
| arch | isize | usize |
</figure>
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`.
<figure>
<figcaption>
Table 3-2: Integer Literals in Rust
</figcaption>
<span class="caption">Table 3-2: Integer Literals in Rust</span>
| Number literals | Example |
|------------------|---------------|
@@ -105,8 +93,6 @@ Table 3-2: Integer Literals in Rust
| Binary | `0b1111_0000` |
| Byte (`u8` only) | `b'A'` |
</figure>
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
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -158,12 +157,7 @@ fn main() {
}
```
<figcaption>
Listing 3-3: A `main` function declaration containing one statement.
</figcaption>
</figure>
<span class="caption">Listing 3-3: A `main` function declaration containing one statement.</span>
Function definitions are also statements; the entire preceding example is a
statement in itself.
+6 -21
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -187,12 +186,8 @@ fn main() {
}
```
<figcaption>
Listing 3-4: Assigning the result of an `if` expression to a variable
</figcaption>
</figure>
<span class="caption">Listing 3-4: Assigning the result of an `if` expression
to a variable</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -359,12 +353,8 @@ fn main() {
}
```
<figcaption>
Listing 3-5: Looping through each element of a collection using a `while` loop
</figcaption>
</figure>
<span class="caption">Listing 3-5: Looping through each element of a collection
using a `while` loop</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -407,12 +396,8 @@ fn main() {
}
```
<figcaption>
Listing 3-6: Looping through each element of a collection using a `for` loop
</figcaption>
</figure>
<span class="caption">Listing 3-6: Looping through each element of a collection
using a `for` loop</span>
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
+14 -54
View File
@@ -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:
<figure>
```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
```
<figcaption>
Listing 4-1: A variable and the scope in which it is valid
</figcaption>
</figure>
<span class="caption">Listing 4-1: A variable and the scope in which it is
valid</span>
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:
<figure>
```rust
let x = 5;
let y = x;
```
<figcaption>
Listing 4-2: Assigning the integer value of variable `x` to `y`
</figcaption>
</figure>
<span class="caption">Listing 4-2: Assigning the integer value of variable `x`
to `y`</span>
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.
<figure>
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 4-3: Representation in memory of a `String` holding the value `"hello"`
bound to `s1`
</figcaption>
</figure>
<span class="caption">Figure 4-3: Representation in memory of a `String`
holding the value `"hello"` bound to `s1`</span>
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.
<figure>
<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 4-4: Representation in memory of the variable `s2` that has a copy of
the pointer, length, and capacity of `s1`
</figcaption>
</figure>
<span class="caption">Figure 4-4: Representation in memory of the variable `s2`
that has a copy of the pointer, length, and capacity of `s1`</span>
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.
<figure>
<img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 4-5: Another possibility of what `s2 = s1` might do if Rust copied the
heap data as well
</figcaption>
</figure>
<span class="caption">Figure 4-5: Another possibility of what `s2 = s1` might
do if Rust copied the heap data as well</span>
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.
<figure>
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 4-6: Representation in memory after `s1` has been invalidated
</figcaption>
</figure>
<span class="caption">Figure 4-6: Representation in memory after `s1` has been
invalidated</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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.
```
<figcaption>
Listing 4-7: Functions with ownership and scope annotated
</figcaption>
</figure>
<span class="caption">Listing 4-7: Functions with ownership and scope
annotated</span>
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
@@ -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.
<figure>
<img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" />
<figcaption>
Figure 4-8: `&String s` pointing at `String s1`
</figcaption>
</figure>
<span class="caption">Figure 4-8: `&String s` pointing at `String s1`</span>
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!
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -96,12 +89,7 @@ fn change(some_string: &String) {
}
```
<figcaption>
Listing 4-9: Attempting to modify a borrowed value
</figcaption>
</figure>
<span class="caption">Listing 4-9: Attempting to modify a borrowed value</span>
Here’s the error:
+6 -23
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -37,13 +36,8 @@ fn first_word(s: &String) -> usize {
}
```
<figcaption>
Listing 4-10: The `first_word` function that returns a byte index value into
the `String` parameter
</figcaption>
</figure>
<span class="caption">Listing 4-10: The `first_word` function that returns a
byte index value into the `String` parameter</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -119,13 +112,8 @@ fn main() {
}
```
<figcaption>
Listing 4-11: Storing the result from calling the `first_word` function then
changing the `String` contents
</figcaption>
</figure>
<span class="caption">Listing 4-11: Storing the result from calling the
`first_word` function then changing the `String` contents</span>
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.
<figure>
<img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 4-12: String slice referring to part of a `String`
</figcaption>
</figure>
<span class="caption">Figure 4-12: String slice referring to part of a
`String`</span>
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:
+10 -46
View File
@@ -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:
<figure>
```rust
struct User {
username: String,
@@ -35,12 +33,7 @@ struct User {
}
```
<figcaption>
Listing 5-1: A `User` struct definition
</figcaption>
</figure>
<span class="caption">Listing 5-1: A `User` struct definition</span>
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*:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -154,13 +146,8 @@ fn area(length: u32, width: u32) -> u32 {
}
```
<figcaption>
Listing 5-2: Calculating the area of a rectangle specified by its length and
width in separate variables
</figcaption>
</figure>
<span class="caption">Listing 5-2: Calculating the area of a rectangle
specified by its length and width in separate variables</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -207,12 +193,8 @@ fn area(dimensions: (u32, u32)) -> u32 {
}
```
<figcaption>
Listing 5-3: Specifying the length and width of the rectangle with a tuple
</figcaption>
</figure>
<span class="caption">Listing 5-3: Specifying the length and width of the
rectangle with a tuple</span>
<!-- I will add ghosting & wingdings once we're in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -266,12 +247,7 @@ fn area(rectangle: &Rectangle) -> u32 {
}
```
<figcaption>
Listing 5-4: Defining a `Rectangle` struct
</figcaption>
</figure>
<span class="caption">Listing 5-4: Defining a `Rectangle` struct</span>
<!-- Will add ghosting & wingdings once we're in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -316,12 +291,8 @@ fn main() {
}
```
<figcaption>
Listing 5-5: Attempting to print a `Rectangle` instance
</figcaption>
</figure>
<span class="caption">Listing 5-5: Attempting to print a `Rectangle`
instance</span>
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:
<figure>
```rust
#[derive(Debug)]
struct Rectangle {
@@ -387,13 +356,8 @@ fn main() {
}
```
<figcaption>
Listing 5-6: Adding the annotation to derive the `Debug` trait and printing the
`Rectangle` instance using debug formatting
</figcaption>
</figure>
<span class="caption">Listing 5-6: Adding the annotation to derive the `Debug`
trait and printing the `Rectangle` instance using debug formatting</span>
At this point, if we run this program, we won’t get any errors and we’ll see
the following output:
+4 -14
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -40,12 +39,8 @@ fn main() {
}
```
<figcaption>
Listing 5-7: Defining an `area` method on the `Rectangle` struct
</figcaption>
</figure>
<span class="caption">Listing 5-7: Defining an `area` method on the `Rectangle`
struct</span>
<!-- Will add ghosting and wingdings here in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -151,12 +145,8 @@ fn main() {
}
```
<figcaption>
Listing 5-8: Demonstration of using the as-yet-unwritten `can_hold` method
</figcaption>
</figure>
<span class="caption">Listing 5-8: Demonstration of using the as-yet-unwritten
`can_hold` method</span>
We want to see this output, since both of `rect2`’s dimensions are smaller than
`rect1`’s, but `rect3` is wider than `rect1`:
+4 -18
View File
@@ -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:
<figure>
```rust
enum IpAddrKind {
V4,
@@ -99,13 +97,8 @@ let loopback = IpAddr {
};
```
<figcaption>
Listing 6-1: Storing the data and `IpAddrKind` variant of an IP address using a
`struct`
</figcaption>
</figure>
<span class="caption">Listing 6-1: Storing the data and `IpAddrKind` variant of
an IP address using a `struct`</span>
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:
<figure>
```rust
enum Message {
Quit,
@@ -203,13 +194,8 @@ enum Message {
}
```
<figcaption>
Listing 6-2: A `Message` enum whose variants each store different amounts and
types of values
</figcaption>
</figure>
<span class="caption">Listing 6-2: A `Message` enum whose variants each store
different amounts and types of values</span>
This enum has four variants with different types:
+6 -26
View File
@@ -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:
<figure>
```rust
enum Coin {
Penny,
@@ -39,13 +37,8 @@ fn value_in_cents(coin: Coin) -> i32 {
}
```
<figcaption>
Listing 6-3: An enum and a `match` expression that has the variants of the enum
as its patterns.
</figcaption>
</figure>
<span class="caption">Listing 6-3: An enum and a `match` expression that has
the variants of the enum as its patterns.</span>
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:
<figure>
```rust
#[derive(Debug)] // So we can inspect the state in a minute
enum UsState {
@@ -127,13 +118,8 @@ enum Coin {
}
```
<figcaption>
Listing 6-4: A `Coin` enum where the `Quarter` variant also holds a `UsState`
value
</figcaption>
</figure>
<span class="caption">Listing 6-4: A `Coin` enum where the `Quarter` variant
also holds a `UsState` value</span>
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:
<figure>
```rust
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
@@ -210,12 +194,8 @@ let six = plus_one(five);
let none = plus_one(None);
```
<figcaption>
Listing 6-5: A function that uses a `match` expression on an `Option<i32>`
</figcaption>
</figure>
<span class="caption">Listing 6-5: A function that uses a `match` expression on
an `Option<i32>`</span>
#### Matching `Some(T)`
+2 -9
View File
@@ -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<u8>` value but only wants to execute
code if the value is three:
<figure>
```rust
let some_u8_value = Some(0u8);
match some_u8_value {
@@ -15,13 +13,8 @@ match some_u8_value {
}
```
<figcaption>
Listing 6-6: A `match` that only cares about executing code when the value is
`Some(3)`
</figcaption>
</figure>
<span class="caption">Listing 6-6: A `match` that only cares about executing
code when the value is `Some(3)`</span>
We want to do something with the `Some(3)` match but do nothing with any other
`Some<u8>` value or the `None` value. To satisfy the `match` expression, we
@@ -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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -86,13 +85,8 @@ mod client {
}
```
<figcaption>
Listing 7-1: The `network` module and the `client` module defined side-by-side
in *src/lib.rs*
</figcaption>
</figure>
<span class="caption">Listing 7-1: The `network` module and the `client` module
defined side-by-side in *src/lib.rs*</span>
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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -123,12 +116,8 @@ mod network {
}
```
<figcaption>
Listing 7-2: Moving the `client` module inside of the `network` module
</figcaption>
</figure>
<span class="caption">Listing 7-2: Moving the `client` module inside of the
`network` module</span>
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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -190,13 +178,8 @@ mod network {
}
```
<figcaption>
Listing 7-3: Three modules, `client`, `network`, and `network::server`, all
defined in *src/lib.rs*
</figcaption>
</figure>
<span class="caption">Listing 7-3: Three modules, `client`, `network`, and
`network::server`, all defined in *src/lib.rs*</span>
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:
<figure>
```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
| ^^^^^^
```
<figcaption>
Listing 7-4: Error when trying to extract the `server` submodule into
*src/server.rs*
</figcaption>
</figure>
<span class="caption">Listing 7-4: Error when trying to extract the `server`
submodule into *src/server.rs*</span>
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
@@ -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*:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust,ignore
@@ -250,13 +249,8 @@ fn try_me() {
}
```
<figcaption>
Listing 7-5: Examples of private and public functions, some of which are
incorrect
</figcaption>
</figure>
<span class="caption">Listing 7-5: Examples of private and public functions,
some of which are incorrect</span>
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
@@ -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.
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -21,13 +20,8 @@ fn main() {
}
```
<figcaption>
Listing 7-6: Calling a function by fully specifying its enclosing module’s
namespaces
</figcaption>
</figure>
<span class="caption">Listing 7-6: Calling a function by fully specifying its
enclosing module’s namespaces</span>
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.
@@ -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:
<figure>
```text
$ RUST_BACKTRACE=1 cargo run
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
@@ -141,13 +139,8 @@ core::ops::Index<usize>>::index::h1204ab053b688140
14: 0x1092206e9 - main
```
<figcaption>
Listing 9-1: The backtrace generated by a call to `panic!` displayed when the
environment variable `RUST_BACKTRACE` is set
</figcaption>
</figure>
<span class="caption">Listing 9-1: The backtrace generated by a call to
`panic!` displayed when the environment variable `RUST_BACKTRACE` is set</span>
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
@@ -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.
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -42,12 +41,7 @@ fn main() {
}
```
<figcaption>
Listing 9-2: Opening a file
</figcaption>
</figure>
<span class="caption">Listing 9-2: Opening a file</span>
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.
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,should_panic
@@ -116,13 +109,8 @@ fn main() {
}
```
<figcaption>
Listing 9-3: Using a `match` expression to handle the `Result` variants we
might have
</figcaption>
</figure>
<span class="caption">Listing 9-3: Using a `match` expression to handle the
`Result` variants we might have</span>
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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -187,12 +174,8 @@ fn main() {
}
```
<figcaption>
Listing 9-4: Handling different kinds of errors in different ways
</figcaption>
</figure>
<span class="caption">Listing 9-4: Handling different kinds of errors in
different ways</span>
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:
<figure>
```rust
use std::io;
use std::io::Read;
@@ -308,12 +289,8 @@ fn read_username_from_file() -> Result<String, io::Error> {
}
```
<figcaption>
Listing 9-5: A function that returns errors to the calling code using `match`
</figcaption>
</figure>
<span class="caption">Listing 9-5: A function that returns errors to the
calling code using `match`</span>
Let’s look at the return type of the function first: `Result<String,
io::Error>`. This means that the function is returning a value of the type
@@ -365,10 +342,9 @@ 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:
<figure>
```rust
use std::io;
use std::io::Read;
use std::fs::File;
fn read_username_from_file() -> Result<String, io::Error> {
@@ -379,12 +355,8 @@ fn read_username_from_file() -> Result<String, io::Error> {
}
```
<figcaption>
Listing 9-6: A function that returns errors to the calling code using `?`
</figcaption>
</figure>
<span class="caption">Listing 9-6: A function that returns errors to the
calling code using `?`</span>
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
@@ -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:
<figure>
```rust
struct Guess {
value: u32,
@@ -198,13 +196,8 @@ impl Guess {
}
```
<figcaption>
Listing 9-8: A `Guess` type that will only continue with values between 1 and
100
</figcaption>
</figure>
<span class="caption">Listing 9-8: A `Guess` type that will only continue with
values between 1 and 100</span>
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.
+6 -21
View File
@@ -43,7 +43,6 @@ use generics.
Consider a small program that finds the largest number in a list, shown in
Listing 10-1:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -63,12 +62,8 @@ fn main() {
}
```
<figcaption>
Listing 10-1: Code to find the largest number in a list of numbers
</figcaption>
</figure>
<span class="caption">Listing 10-1: Code to find the largest number in a list
of numbers</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -113,12 +107,8 @@ fn main() {
}
```
<figcaption>
Listing 10-2: Code to find the largest number in *two* lists of numbers
</figcaption>
</figure>
<span class="caption">Listing 10-2: Code to find the largest number in *two*
lists of numbers</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -169,12 +158,8 @@ fn main() {
}
```
<figcaption>
Listing 10-3: Abstracted code to find the largest number in two lists
</figcaption>
</figure>
<span class="caption">Listing 10-3: Abstracted code to find the largest number
in two lists</span>
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
+16 -56
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -61,13 +60,8 @@ fn main() {
}
```
<figcaption>
Listing 10-4: Two functions that differ only in their names and the types in
their signatures
</figcaption>
</figure>
<span class="caption">Listing 10-4: Two functions that differ only in their
names and the types in their signatures</span>
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!
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -134,13 +127,8 @@ fn main() {
}
```
<figcaption>
Listing 10-5: A definition of the `largest` function that uses generic type
parameters but doesn't compile yet
</figcaption>
</figure>
<span class="caption">Listing 10-5: A definition of the `largest` function that
uses generic type parameters but doesn't compile yet</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -192,12 +179,8 @@ fn main() {
}
```
<figcaption>
Listing 10-6: A `Point` struct that holds `x` and `y` values of type `T`
</figcaption>
</figure>
<span class="caption">Listing 10-6: A `Point` struct that holds `x` and `y`
values of type `T`</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -224,13 +206,8 @@ fn main() {
}
```
<figcaption>
Listing 10-7: The fields `x` and `y` must be the same type because both have
the same generic data type `T`
</figcaption>
</figure>
<span class="caption">Listing 10-7: The fields `x` and `y` must be the same
type because both have the same generic data type `T`</span>
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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -273,13 +249,8 @@ fn main() {
}
```
<figcaption>
Listing 10-8: A `Point` generic over two types so that `x` and `y` may be
values of different types
</figcaption>
</figure>
<span class="caption">Listing 10-8: A `Point` generic over two types so that
`x` and `y` may be values of different types</span>
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<T>`
struct we defined in Listing 10-6. We've then defined a method named `x` on
`Point<T>` that returns a reference to the data in the field `x`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -362,13 +332,9 @@ fn main() {
}
```
<figcaption>
Listing 10-9: Implementing a method named `x` on the `Point<T>` struct that
will return a reference to the `x` field, which is of type `T`.
</figcaption>
</figure>
<span class="caption">Listing 10-9: Implementing a method named `x` on the
`Point<T>` struct that will return a reference to the `x` field, which is of
type `T`.</span>
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<T>`.
@@ -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`):
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -392,7 +357,7 @@ struct Point<T, U> {
}
impl<T, U> Point<T, U> {
fn mixup<V, W>(&self, other: &Point<V, W>) -> Point<T, W> {
fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> {
Point {
x: self.x,
y: other.y,
@@ -410,13 +375,8 @@ fn main() {
}
```
<figcaption>
Listing 10-10: Methods that use different generic types than their struct's
definition
</figcaption>
</figure>
<span class="caption">Listing 10-10: Methods that use different generic types
than their struct's definition</span>
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
+11 -40
View File
@@ -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:
<figure>
<span class="filename">Filename: lib.rs</span>
```rust
@@ -39,13 +38,8 @@ pub trait Summarizable {
}
```
<figcaption>
Listing 10-11: Definition of a `Summarizable` trait that consists of the
behavior provided by a `summary` method
</figcaption>
</figure>
<span class="caption">Listing 10-11: Definition of a `Summarizable` trait that
consists of the behavior provided by a `summary` method</span>
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.
<figure>
<span class="filename">Filename: lib.rs</span>
```rust
@@ -105,13 +98,8 @@ impl Summarizable for Tweet {
}
```
<figcaption>
Listing 10-12: Implementing the `Summarizable` trait on the `NewsArticle` and
`Tweet` types
</figcaption>
</figure>
<span class="caption">Listing 10-12: Implementing the `Summarizable` trait on
the `NewsArticle` and `Tweet` types</span>
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:
<figure>
<span class="filename">Filename: lib.rs</span>
```rust,ignore
@@ -171,13 +158,8 @@ impl Summarizable for WeatherForecast {
}
```
<figcaption>
Listing 10-13: Bringing the `Summarizable` trait from our `aggregator` crate
into scope in another crate
</figcaption>
</figure>
<span class="caption">Listing 10-13: Bringing the `Summarizable` trait from our
`aggregator` crate into scope in another crate</span>
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:
<figure>
<span class="filename">Filename: lib.rs</span>
```rust
@@ -219,13 +200,8 @@ pub trait Summarizable {
}
```
<figcaption>
Listing 10-14: Definition of a `Summarizable` trait with a default
implementation of the `summary` method
</figcaption>
</figure>
<span class="caption">Listing 10-14: Definition of a `Summarizable` trait with
a default implementation of the `summary` method</span>
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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -465,13 +440,9 @@ fn main() {
}
```
<figcaption>
Listing 10-15: A working definition of the `largest` function that works on any
generic type that implements the `PartialOrd` and `Copy` traits
</figcaption>
</figure>
<span class="caption">Listing 10-15: A working definition of the `largest`
function that works on any generic type that implements the `PartialOrd` and
`Copy` traits</span>
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
+25 -93
View File
@@ -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`:
<figure>
```rust,ignore
{
let r;
@@ -43,12 +41,8 @@ the inner scope ends, and we attempt to print out the value in `r`:
}
```
<figcaption>
Listing 10-16: An attempt to use a reference whose value has gone out of scope
</figcaption>
</figure>
<span class="caption">Listing 10-16: An attempt to use a reference whose value
has gone out of scope</span>
> #### 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:
<figure>
```rust,ignore
{
let r; // -------+-- 'a
@@ -102,13 +94,8 @@ Listing 10-16 with annotations showing the lifetimes of the variables:
}
```
<figcaption>
Listing 10-17: Annotations of the lifetimes of `r` and `x`, named `'a` and `'b`
respectively
</figcaption>
</figure>
<span class="caption">Listing 10-17: Annotations of the lifetimes of `r` and
`x`, named `'a` and `'b` respectively</span>
<!-- Just checking I'm reading this right: the inside block is the b lifetime,
correct? I want to leave a note for production, make sure we can make that
@@ -129,8 +116,6 @@ as long as the reference.
Let's look at an example in Listing 10-18 that doesn't try to make a dangling
reference and compiles without any errors:
<figure>
```rust
{
let x = 5; // -----+-- 'b
@@ -142,13 +127,8 @@ reference and compiles without any errors:
} // -----+
```
<figcaption>
Listing 10-18: A valid reference because the data has a longer lifetime than
the reference
</figcaption>
</figure>
<span class="caption">Listing 10-18: A valid reference because the data has a
longer lifetime than the reference</span>
Here, `x` has the lifetime `'b`, which in this case is larger than `'a`. This
means `r` can reference `x`: Rust knows that the reference in `r` will always
@@ -166,11 +146,9 @@ want to be able to call this function by passing it two string slices, and we
want to get back a string slice. The code in Listing 10-19 should print `The
longest string is abcd` once we've implemented the `longest` function:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
```rust,ignore
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
@@ -180,13 +158,8 @@ fn main() {
}
```
<figcaption>
Listing 10-19: A `main` function that calls the `longest` function to find the
longest of two string slices
</figcaption>
</figure>
<span class="caption">Listing 10-19: A `main` function that calls the `longest`
function to find the longest of two string slices</span>
Note that we want the function to take string slices (which are references, as
we talked about in Chapter 4) since we don't want the `longest` function to
@@ -217,7 +190,6 @@ discussion about why these are the arguments we want.
If we try to implement the `longest` function as shown in Listing 10-20, it
won't compile:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -230,13 +202,9 @@ fn longest(x: &str, y: &str) -> &str {
}
```
<figcaption>
Listing 10-20: An implementation of the `longest` function that returns the
longest of two string slices, but does not yet compile
</figcaption>
</figure>
<span class="caption">Listing 10-20: An implementation of the `longest`
function that returns the longest of two string slices, but does not yet
compile</span>
Instead we get the following error that talks about lifetimes:
@@ -311,7 +279,6 @@ references in the parameters and the return value is that they all must have
the same lifetime, which we'll name `'a` and add to each reference as shown in
Listing 10-21:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -324,13 +291,9 @@ fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
}
```
<figcaption>
Listing 10-21: The `longest` function definition that specifies all the
references in the signature must have the same lifetime, `'a`
</figcaption>
</figure>
<span class="caption">Listing 10-21: The `longest` function definition that
specifies all the references in the signature must have the same lifetime,
`'a`</span>
This will compile and will produce the result we want when used with the `main`
function in Listing 10-19.
@@ -372,7 +335,6 @@ the end of the inner scope, and `result` references something that is valid
until the end of the outer scope. The borrow checker approves of this code; it
will compile and print `The longest string is long string is long` when run:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -395,13 +357,8 @@ fn main() {
}
```
<figcaption>
Listing 10-22: Using the `longest` function with references to `String` values
that have different concrete lifetimes
</figcaption>
</figure>
<span class="caption">Listing 10-22: Using the `longest` function with
references to `String` values that have different concrete lifetimes</span>
Next, let's try an example that will show that the lifetime of the reference in
`result` must be the smaller lifetime of the two arguments. We'll move the
@@ -410,18 +367,9 @@ assignment of the value to the `result` variable inside the scope with
`string2`. Next, we'll move the `println!` that uses `result` outside of the
inner scope, after it has ended. The code in Listing 10-23 will not compile:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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;
@@ -433,13 +381,8 @@ fn main() {
}
```
<figcaption>
Listing 10-23: Attempting to use `result` after `string2` has gone out of scope
won't compile
</figcaption>
</figure>
<span class="caption">Listing 10-23: Attempting to use `result` after `string2`
has gone out of scope won't compile</span>
If we try to compile this, we'll get this error:
@@ -550,7 +493,6 @@ for structs to hold references, but we need to add a lifetime annotation on
every reference in the struct's definition. Listing 10-24 has a struct named
`ImportantExcerpt` that holds a string slice:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -567,13 +509,8 @@ fn main() {
}
```
<figcaption>
Listing 10-24: A struct that holds a reference, so its definition needs a
lifetime annotation
</figcaption>
</figure>
<span class="caption">Listing 10-24: A struct that holds a reference, so its
definition needs a lifetime annotation</span>
This struct has one field, `part`, that holds a string slice, which is a
reference. Just like with generic data types, we have to declare the name of
@@ -592,7 +529,6 @@ to specify lifetime parameters for functions or structs that use references.
However, in Chapter 4 we had a function in the "String Slices" section, shown
again in Listing 10-25, that compiled without lifetime annotations:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -609,13 +545,9 @@ fn first_word(s: &str) -> &str {
}
```
<figcaption>
Listing 10-25: A function we defined in Chapter 4 that compiled without
lifetime annotations, even though the parameter and return type are references
</figcaption>
</figure>
<span class="caption">Listing 10-25: A function we defined in Chapter 4 that
compiled without lifetime annotations, even though the parameter and return
type are references</span>
The reason this function compiles without lifetime annotations is historical:
in early versions of pre-1.0 Rust, this indeed wouldn't have compiled. Every
@@ -17,7 +17,6 @@ understand two things:
Let's give it a try as shown in Listing 12-1:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -29,12 +28,8 @@ fn main() {
}
```
<figcaption>
Listing 12-1: Collect the command line arguments into a vector and print them out
</figcaption>
</figure>
<span class="caption">Listing 12-1: Collect the command line arguments into a
vector and print them out</span>
<!-- Will add wingdings in libreoffice /Carol -->
@@ -71,10 +66,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
```rust,ignore
use std::env;
fn main() {
@@ -88,12 +82,8 @@ fn main() {
}
```
<figcaption>
Listing 12-2: Create variables to hold the search argument and filename argument
</figcaption>
</figure>
<span class="caption">Listing 12-2: Create variables to hold the search
argument and filename argument</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
+3 -8
View File
@@ -27,10 +27,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
```rust,ignore
use std::env;
use std::fs::File;
use std::io::prelude::*;
@@ -53,12 +52,8 @@ fn main() {
}
```
<figcaption>
Listing 12-3: Read the contents of the file specified by the second argument
</figcaption>
</figure>
<span class="caption">Listing 12-3: Read the contents of the file specified by
the second argument</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -56,14 +56,9 @@ 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*:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
```rust,ignore
fn main() {
let args: Vec<String> = env::args().collect();
@@ -73,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) {
@@ -90,12 +78,8 @@ fn parse_config(args: &[String]) -> (&str, &str) {
}
```
<figcaption>
Listing 12-4: Extract a `parse_config` function from `main`
</figcaption>
</figure>
<span class="caption">Listing 12-4: Extract a `parse_config` function from
`main`</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -121,14 +105,9 @@ 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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
```rust,ignore
fn main() {
let args: Vec<String> = env::args().collect();
@@ -140,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 {
@@ -162,13 +137,8 @@ fn parse_config(args: &[String]) -> Config {
}
```
<figcaption>
Listing 12-5: Refactoring `parse_config` to return an instance of a `Config`
struct
</figcaption>
</figure>
<span class="caption">Listing 12-5: Refactoring `parse_config` to return an
instance of a `Config` struct</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -217,14 +187,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
```rust,ignore
fn main() {
let args: Vec<String> = env::args().collect();
@@ -234,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 {
@@ -264,12 +216,8 @@ impl Config {
}
```
<figcaption>
Listing 12-6: Changing `parse_config` into `Config::new`
</figcaption>
</figure>
<span class="caption">Listing 12-6: Changing `parse_config` into
`Config::new`</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -285,36 +233,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
#
# fn main() {
# let args: Vec<String> = 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 {
@@ -323,22 +244,11 @@ fn new(args: &[String]) -> Config {
let search = args[1].clone();
// ...snip...
# let filename = args[2].clone();
#
# Config {
# search: search,
# filename: filename,
# }
}
# }
```
<figcaption>
Listing 12-7: Adding a check for the number of arguments
</figcaption>
</figure>
<span class="caption">Listing 12-7: Adding a check for the number of
arguments</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -360,38 +270,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
# use std::process;
#
# fn main() {
# let args: Vec<String> = 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<Config, &'static str> {
if args.len() < 3 {
@@ -409,12 +290,7 @@ impl Config {
}
```
<figcaption>
Listing 12-8: Return a `Result` from `Config::new`
</figcaption>
</figure>
<span class="caption">Listing 12-8: Return a `Result` from `Config::new`</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -432,13 +308,9 @@ conform to its new type signature.
Now we need to make some changes to `main` as shown in Listing 12-9:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
```rust,ignore
// ...snip...
use std::process;
@@ -454,43 +326,10 @@ 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<Config, &'static str> {
# 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,
# })
# }
# }
```
<figcaption>
Listing 12-9: Exiting with an error code if creating a new `Config` fails
</figcaption>
</figure>
<span class="caption">Listing 12-9: Exiting with an error code if creating a
new `Config` fails</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -534,22 +373,10 @@ 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`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
# use std::env;
# use std::fs::File;
# use std::io::prelude::*;
# use std::process;
#
```rust,ignore
fn main() {
# let args: Vec<String> = 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);
@@ -568,35 +395,10 @@ fn run(config: Config) {
}
// ...snip...
#
# struct Config {
# search: String,
# filename: String,
# }
#
# impl Config {
# fn new(args: &[String]) -> Result<Config, &'static str> {
# 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,
# })
# }
# }
```
<figcaption>
Listing 12-10: Extracting a `run` functionality for the rest of the program logic
</figcaption>
</figure>
<span class="caption">Listing 12-10: Extracting a `run` functionality for the
rest of the program logic</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -608,31 +410,12 @@ Listing 12-8: let's return a `Result<T, E>` instead of calling `panic!` via
`std::error::Error` struct into scope and the changes to the `run` function
to return a `Result`:
<figure>
<span class="filename">Filename: src/main.rs</span>
```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<String> = 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<Error>> {
let mut f = File::open(config.filename)?;
@@ -644,35 +427,10 @@ fn run(config: Config) -> Result<(), Box<Error>> {
Ok(())
}
#
# struct Config {
# search: String,
# filename: String,
# }
#
# impl Config {
# fn new(args: &[String]) -> Result<Config, &'static str> {
# 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,
# })
# }
# }
```
<figcaption>
Listing 12-11: Changing the `run` function to return `Result`
</figcaption>
</figure>
<span class="caption">Listing 12-11: Changing the `run` function to return
`Result`</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -768,10 +526,9 @@ 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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
```rust,ignore
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
@@ -809,12 +566,8 @@ pub fn run(config: Config) -> Result<(), Box<Error>>{
}
```
<figcaption>
Listing 12-12: Moving `Config` and `run` into *src/lib.rs*
</figcaption>
</figure>
<span class="caption">Listing 12-12: Moving `Config` and `run` into
*src/lib.rs*</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -826,7 +579,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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -856,12 +608,8 @@ fn main() {
}
```
<figcaption>
Listing 12-13: Bringing the `greprs` crate into the scope of *src/main.rs*
</figcaption>
</figure>
<span class="caption">Listing 12-13: Bringing the `greprs` crate into the scope
of *src/main.rs*</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -66,13 +65,8 @@ Pick three.";
}
```
<figcaption>
Listing 12-14: Creating a function where our logic will go and a failing test
for that function
</figcaption>
</figure>
<span class="caption">Listing 12-14: Creating a function where our logic will
go and a failing test for that function</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -207,12 +199,8 @@ fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
}
```
<figcaption>
Listing 12-15: Fully functioning implementation of the `grep` function
</figcaption>
</figure>
<span class="caption">Listing 12-15: Fully functioning implementation of the
`grep` function</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
@@ -72,13 +71,9 @@ fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
}
```
<figcaption>
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
</figcaption>
</figure>
<span class="caption">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</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -65,12 +64,8 @@ fn main() {
}
```
<figcaption>
Listing 12-17: Writing error messages to `stderr` instead of `stdout`
</figcaption>
</figure>
<span class="caption">Listing 12-17: Writing error messages to `stderr` instead
of `stdout`</span>
<!-- Will add ghosting and wingdings in libreoffice /Carol -->
+8 -31
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -19,13 +18,8 @@ fn main() {
}
```
<figcaption>
Listing 13-1: A closure that takes one parameter and adds one to it, assigned to
the variable `add_one`
</figcaption>
</figure>
<span class="caption">Listing 13-1: A closure that takes one parameter and adds
one to it, assigned to the variable `add_one`</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -51,12 +44,8 @@ fn main() {
}
```
<figcaption>
Listing 13-2: A closure with two parameters and multiple expressions in its body
</figcaption>
</figure>
<span class="caption">Listing 13-2: A closure with two parameters and multiple
expressions in its body</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -79,13 +67,8 @@ fn main() {
}
```
<figcaption>
Listing 13-3: A closure definition with optional parameter and return value
type annotations
</figcaption>
</figure>
<span class="caption">Listing 13-3: A closure definition with optional
parameter and return value type annotations</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -162,13 +144,8 @@ fn main() {
}
```
<figcaption>
Listing 13-4: Example of a closure that refers to a variable in its enclosing
scope
</figcaption>
</figure>
<span class="caption">Listing 13-4: Example of a closure that refers to a
variable in its enclosing scope</span>
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
+4 -17
View File
@@ -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:
<figure>
```rust
let v1 = vec![1, 2, 3];
@@ -14,13 +12,8 @@ let v2: Vec<i32> = v1.iter().map(|x| x + 1).collect();
assert_eq!(v2, [2, 3, 4]);
```
<figcaption>
Listing 13-5: Using an iterator, `map`, and `collect` to add one to each number
in a vector
</figcaption>
</figure>
<span class="caption">Listing 13-5: Using an iterator, `map`, and `collect` to
add one to each number in a vector</span>
<!-- Will add wingdings in libreoffice /Carol -->
@@ -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:
<figure>
```rust
# struct Counter {
# count: u32,
@@ -152,12 +143,8 @@ impl Iterator for Counter {
}
```
<figcaption>
Listing 13-6: Implementing the `Iterator` trait on our `Counter` struct
</figcaption>
</figure>
<span class="caption">Listing 13-6: Implementing the `Iterator` trait on our
`Counter` struct</span>
<!-- I will add wingdings in libreoffice /Carol -->
@@ -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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
````rust
@@ -46,12 +44,8 @@ pub fn add_one(x: i32) -> i32 {
}
````
<figcaption>
Listing 14-1: A documentation comment for a function
</figcaption>
</figure>
<span class="caption">Listing 14-1: A documentation comment for a
function</span>
`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,10 +105,9 @@ 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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
```rust,ignore
//! # Art
//!
//! A library for modeling artistic concepts.
@@ -147,18 +140,12 @@ pub mod utils {
}
```
<figcaption>
Listing 14-2: An `art` library with items organized into `kinds` and `utils`
modules
</figcaption>
</figure>
<span class="caption">Listing 14-2: An `art` library with items organized into
`kinds` and `utils` modules</span>
In order to use this library, another crate would have `use` statements as in
Listing 14-3:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -174,13 +161,8 @@ fn main() {
}
```
<figcaption>
Listing 14-3: A program using the `art` crate's items with its internal
structure exported
</figcaption>
</figure>
<span class="caption">Listing 14-3: A program using the `art` crate's items
with its internal structure exported</span>
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,10 +172,9 @@ 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:
<figure>
<span class="filename">Filename: src/lib.rs</span>
```rust
```rust,ignore
//! # Art
//!
//! A library for modeling artistic concepts.
@@ -204,21 +185,10 @@ pub use utils::mix;
pub mod kinds {
// ...snip...
# pub enum PrimaryColor;
# pub enum SecondaryColor;
# }
#
# pub mod utils {
# pub fn mix() {}
# }
```
<figcaption>
Listing 14-4: Adding `pub use` statements to re-export items
</figcaption>
</figure>
<span class="caption">Listing 14-4: Adding `pub use` statements to re-export
items</span>
<!-- Will add ghosting in libreoffice /Carol -->
@@ -227,7 +197,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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -241,12 +210,8 @@ fn main() {
}
```
<figcaption>
Listing 14-5: Using the re-exported items from the `art` crate
</figcaption>
</figure>
<span class="caption">Listing 14-5: Using the re-exported items from the `art`
crate</span>
<!-- Will add ghosting in libreoffice /Carol -->
+13 -48
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -15,12 +14,8 @@ fn main() {
}
```
<figcaption>
Listing 15-1: Storing an `i32` value on the heap using a box
</figcaption>
</figure>
<span class="caption">Listing 15-1: Storing an `i32` value on the heap using a
box</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -55,16 +49,11 @@ enum List {
}
```
<figcaption>
Listing 15-2: The first attempt of defining an enum to represent a cons list
data structure of `i32` values
</figcaption>
</figure>
<span class="caption">Listing 15-2: The first attempt of defining an enum to
represent a cons list data structure of `i32` values</span>
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:
<figure>
```text
error[E0072]: recursive type `List` has infinite size
-->
@@ -101,12 +88,8 @@ error[E0072]: recursive type `List` has infinite size
make `List` representable
```
<figcaption>
Listing 15-3: The error we get when attempting to define a recursive enum
</figcaption>
</figure>
<span class="caption">Listing 15-3: The error we get when attempting to define
a recursive enum</span>
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.
<figure>
<img alt="An infinite Cons list" src="img/trpl15-01.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 15-4: An infinite `List` consisting of infinite `Cons` variants
</figcaption>
</figure>
<span class="caption">Figure 15-4: An infinite `List` consisting of infinite
`Cons` variants</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -188,13 +164,8 @@ fn main() {
}
```
<figcaption>
Listing 15-5: Definition of `List` that uses `Box<T>` in order to have a
known size
</figcaption>
</figure>
<span class="caption">Listing 15-5: Definition of `List` that uses `Box<T>` in
order to have a known size</span>
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:
<figure>
<img alt="A finite Cons list" src="img/trpl15-02.svg" class="center" />
<figcaption>
Figure 15-6: A `List` that is not infinitely sized since `Cons` holds a `Box`
</figcaption>
</figure>
<span class="caption">Figure 15-6: A `List` that is not infinitely sized since
`Cons` holds a `Box`</span>
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
+2 -8
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -77,13 +76,8 @@ fn main() {
}
```
<figcaption>
Listing 15-7: An implementation of the `Deref` trait on a struct that holds mp3
file data and metadata
</figcaption>
</figure>
<span class="caption">Listing 15-7: An implementation of the `Deref` trait on a
struct that holds mp3 file data and metadata</span>
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
+5 -16
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -49,13 +48,9 @@ fn main() {
}
```
<figcaption>
Listing 15-8: A `CustomSmartPointer` struct that implements the `Drop` trait,
where we could put code that would clean up after the `CustomSmartPointer`.
</figcaption>
</figure>
<span class="caption">Listing 15-8: A `CustomSmartPointer` struct that
implements the `Drop` trait, where we could put code that would clean up after
the `CustomSmartPointer`.</span>
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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -96,13 +90,8 @@ fn main() {
}
```
<figcaption>
Listing 15-9: Calling `std::mem::drop` to explicitly drop a value before it
goes out of scope
</figcaption>
</figure>
<span class="caption">Listing 15-9: Calling `std::mem::drop` to explicitly drop
a value before it goes out of scope</span>
Running this code will print the following, showing that the destructor code is
called since `Dropping CustomSmartPointer!` is printed between
+7 -30
View File
@@ -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:
<figure>
<img alt="Two lists that share ownership of a third list" src="img/trpl15-03.svg" class="center" />
<figcaption>
Figure 15-10: Two lists, `b` and `c`, sharing ownership of a third list, `a`
</figcaption>
</figure>
<span class="caption">Figure 15-10: Two lists, `b` and `c`, sharing ownership
of a third list, `a`</span>
Trying to implement this using our definition of `List` with `Box<T>` won't
work, as shown in Listing 15-11:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust,ignore
@@ -72,13 +65,8 @@ fn main() {
}
```
<figcaption>
Listing 15-11: Having two lists using `Box<T>` that try to share ownership of a
third list won't work
</figcaption>
</figure>
<span class="caption">Listing 15-11: Having two lists using `Box<T>` that try
to share ownership of a third list won't work</span>
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<T>` instead of
`Box<T>` as shown here in Listing 15-12:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -126,12 +113,8 @@ fn main() {
}
```
<figcaption>
Listing 15-12: A definition of `List` that uses `Rc<T>`
</figcaption>
</figure>
<span class="caption">Listing 15-12: A definition of `List` that uses
`Rc<T>`</span>
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.
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -174,12 +156,7 @@ fn main() {
}
```
<figcaption>
Listing 15-13: Printing out the reference count
</figcaption>
</figure>
<span class="caption">Listing 15-13: Printing out the reference count</span>
This will print out:
@@ -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!
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -90,12 +89,8 @@ fn main() {
}
```
<figcaption>
Listing 15-14: Using `RefCell<T>`, `borrow`, and `borrow_mut`
</figcaption>
</figure>
<span class="caption">Listing 15-14: Using `RefCell<T>`, `borrow`, and
`borrow_mut`</span>
This example prints:
@@ -192,7 +187,6 @@ owner of the value that's not part of the list (the multiple owners
functionality that `Rc<T>` provides), and so we can mutate the inner `i32`
value (the interior mutability functionality that `RefCell<T>` provides):
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -223,12 +217,8 @@ fn main() {
}
```
<figcaption>
Listing 15-15: Using `Rc<RefCell<i32>>` to create a `List` that we can mutate
</figcaption>
</figure>
<span class="caption">Listing 15-15: Using `Rc<RefCell<i32>>` to create a
`List` that we can mutate</span>
We're creating a value, which is an instance of `Rc<RefCell<i32>>`. We're
storing it in a variable named `value` because we want to be able to access it
+17 -55
View File
@@ -21,10 +21,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
```rust,ignore
#[derive(Debug)]
enum List {
Cons(i32, RefCell<Rc<List>>),
@@ -39,18 +38,10 @@ impl List {
}
}
}
# use std::rc::Rc;
# use std::cell::RefCell;
# use List::{Cons, Nil};
```
<figcaption>
Listing 15-16: A cons list definition that holds a `RefCell` so that we can
modify what a `Cons` variant is referring to
</figcaption>
</figure>
<span class="caption">Listing 15-16: A cons list definition that holds a
`RefCell` so that we can modify what a `Cons` variant is referring to</span>
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 +49,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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -107,29 +97,18 @@ fn main() {
}
```
<figcaption>
Listing 15-17: Creating a reference cycle of two `List` values pointing to
each other
</figcaption>
</figure>
<span class="caption">Listing 15-17: Creating a reference cycle of two `List`
values pointing to each other</span>
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:
<figure>
<img alt="Reference cycle of lists" src="img/trpl15-04.svg" class="center" style="width: 50%;" />
<figcaption>
Figure 15-18: A reference cycle of lists `a` and `b` pointing to each other
</figcaption>
</figure>
<span class="caption">Figure 15-18: A reference cycle of lists `a` and `b`
pointing to each other</span>
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,10 +186,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
```rust,ignore
fn main() {
let leaf = Rc::new(Node {
value: 3,
@@ -224,13 +202,9 @@ fn main() {
}
```
<figcaption>
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`
</figcaption>
</figure>
<span class="caption">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`</span>
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,10 +241,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
```rust,ignore
fn main() {
let leaf = Rc::new(Node {
value: 3,
@@ -292,13 +265,8 @@ fn main() {
}
```
<figcaption>
Listing 15-20: A `leaf` node and a `branch` node where `leaf` has a `Weak`
reference to its parent, `branch`
</figcaption>
</figure>
<span class="caption">Listing 15-20: A `leaf` node and a `branch` node where
`leaf` has a `Weak` reference to its parent, `branch`</span>
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,10 +303,9 @@ 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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```
```rust,ignore
fn main() {
let leaf = Rc::new(Node {
value: 3,
@@ -382,13 +349,8 @@ fn main() {
}
```
<figcaption>
Listing 15-21: Creating `branch` in an inner scope and examining strong and
weak reference counts of `leaf` and `branch`
</figcaption>
</figure>
<span class="caption">Listing 15-21: Creating `branch` in an inner scope and
examining strong and weak reference counts of `leaf` and `branch`</span>
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
+7 -34
View File
@@ -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:
<figure>
<span class="filename">Filename: src/main.rs</span>
```rust
@@ -87,14 +82,9 @@ fn main() {
}
```
<figcaption>
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
</figcaption>
</figure>
<span class="caption">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</span>
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:
<figure>
```rust,ignore
{
let closure;
@@ -188,13 +176,8 @@ that borrowed value. The code in Listing 13-6 also won't compile:
}
```
<figcaption>
Listing 16-something: A closure that tries to return a borrowed value that does
not live long enough
</figcaption>
</figure>
<span class="caption">Listing 16-something: A closure that tries to return a
borrowed value that does not live long enough</span>
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:
<figure>
```rust
{
let closure;
@@ -235,12 +216,8 @@ The code in Listing 13-7 will compile:
}
```
<figcaption>
Listing 16-something: Moving a value into the closure to fix the lifetime error
</figcaption>
</figure>
<span class="caption">Listing 16-something: Moving a value into the closure to
fix the lifetime error</span>
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