From c146ca11b84cd0473605aefed7b484732ae4ca6b Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 23 Jan 2017 20:33:53 +0000 Subject: [PATCH] rebuild pages at f80cb17 --- appendix-00.html | 2 +- appendix-01-keywords.html | 2 +- appendix-02-operators.html | 2 +- appendix-03-derivable-traits.html | 2 +- appendix-04-nightly-rust.html | 2 +- appendix-05-macros.html | 2 +- ch01-00-introduction.html | 2 +- ch01-01-installation.html | 2 +- ch01-02-hello-world.html | 2 +- ch02-00-guessing-game-tutorial.html | 2 +- ch03-00-common-programming-concepts.html | 2 +- ch03-01-variables-and-mutability.html | 2 +- ch03-02-data-types.html | 2 +- ch03-03-how-functions-work.html | 2 +- ch03-04-comments.html | 2 +- ch03-05-control-flow.html | 2 +- ch04-00-understanding-ownership.html | 2 +- ch04-01-what-is-ownership.html | 2 +- ch04-02-references-and-borrowing.html | 2 +- ch04-03-slices.html | 2 +- ch05-00-structs.html | 2 +- ch05-01-method-syntax.html | 2 +- ch06-00-enums.html | 2 +- ch06-01-option.html | 2 +- ch06-02-match.html | 2 +- ch06-03-if-let.html | 2 +- ch07-00-modules.html | 2 +- ch07-01-mod-and-the-filesystem.html | 2 +- ch07-02-controlling-visibility-with-pub.html | 2 +- ch07-03-importing-names-with-use.html | 2 +- ch08-00-fundamental-collections.html | 2 +- ch08-01-vectors.html | 2 +- ch08-02-strings.html | 2 +- ch08-03-hash-maps.html | 2 +- ch09-00-error-handling.html | 2 +- ch09-01-unrecoverable-errors-with-panic.html | 2 +- ch09-02-recoverable-errors-with-result.html | 2 +- ch09-03-to-panic-or-not-to-panic.html | 2 +- ch10-00-generics.html | 2 +- ch10-01-syntax.html | 2 +- ch10-02-traits.html | 2 +- ch10-03-lifetime-syntax.html | 2 +- ch11-00-testing.html | 2 +- ch11-01-writing-tests.html | 2 +- ch11-02-running-tests.html | 2 +- ch11-03-test-organization.html | 2 +- ch12-00-an-io-project.html | 2 +- ch12-01-accepting-command-line-arguments.html | 2 +- ch12-02-reading-a-file.html | 2 +- ...proving-error-handling-and-modularity.html | 2 +- ...04-testing-the-librarys-functionality.html | 11 +- ...05-working-with-environment-variables.html | 12 +- ...6-writing-to-stderr-instead-of-stdout.html | 6 +- ch13-00-functional-features.html | 45 +- ch13-01-closures.html | 310 +++++++ ch13-02-iterators.html | 317 +++++++ ch13-03-improving-our-io-project.html | 267 ++++++ ch13-04-performance.html | 190 ++++ ch14-00-more-about-cargo.html | 6 +- ch14-01-release-profiles.html | 2 +- ch14-02-publishing-to-crates-io.html | 2 +- ch14-03-cargo-workspaces.html | 2 +- ch14-04-installing-binaries.html | 2 +- ch14-05-extending-cargo.html | 2 +- ch15-00-smart-pointers.html | 2 +- ch16-00-concurrency.html | 188 +++- ch17-00-oop.html | 2 +- ch18-00-patterns.html | 2 +- ch19-00-more-lifetimes.html | 2 +- ch20-00-advanced-types.html | 2 +- index.html | 2 +- print.html | 862 +++++++++++++++++- 72 files changed, 2216 insertions(+), 120 deletions(-) create mode 100644 ch13-01-closures.html create mode 100644 ch13-02-iterators.html create mode 100644 ch13-03-improving-our-io-project.html create mode 100644 ch13-04-performance.html diff --git a/appendix-00.html b/appendix-00.html index ce7ce5dbe..a16d0b40c 100644 --- a/appendix-00.html +++ b/appendix-00.html @@ -47,7 +47,7 @@
diff --git a/appendix-01-keywords.html b/appendix-01-keywords.html index 3b70fd5e1..3d44b3ade 100644 --- a/appendix-01-keywords.html +++ b/appendix-01-keywords.html @@ -47,7 +47,7 @@
diff --git a/appendix-02-operators.html b/appendix-02-operators.html index 1a7ca627e..286d21c37 100644 --- a/appendix-02-operators.html +++ b/appendix-02-operators.html @@ -47,7 +47,7 @@
diff --git a/appendix-03-derivable-traits.html b/appendix-03-derivable-traits.html index 40519bcbd..afe1e1d67 100644 --- a/appendix-03-derivable-traits.html +++ b/appendix-03-derivable-traits.html @@ -47,7 +47,7 @@
diff --git a/appendix-04-nightly-rust.html b/appendix-04-nightly-rust.html index b690bc57d..cf3c1469e 100644 --- a/appendix-04-nightly-rust.html +++ b/appendix-04-nightly-rust.html @@ -47,7 +47,7 @@
diff --git a/appendix-05-macros.html b/appendix-05-macros.html index ab6765731..73e26f949 100644 --- a/appendix-05-macros.html +++ b/appendix-05-macros.html @@ -47,7 +47,7 @@
diff --git a/ch01-00-introduction.html b/ch01-00-introduction.html index ac5445666..c3467bd8a 100644 --- a/ch01-00-introduction.html +++ b/ch01-00-introduction.html @@ -47,7 +47,7 @@
diff --git a/ch01-01-installation.html b/ch01-01-installation.html index b7a310160..d0c51ab4f 100644 --- a/ch01-01-installation.html +++ b/ch01-01-installation.html @@ -47,7 +47,7 @@
diff --git a/ch01-02-hello-world.html b/ch01-02-hello-world.html index 2998e7f41..f80a70597 100644 --- a/ch01-02-hello-world.html +++ b/ch01-02-hello-world.html @@ -47,7 +47,7 @@
diff --git a/ch02-00-guessing-game-tutorial.html b/ch02-00-guessing-game-tutorial.html index 4426181dd..97db69cf9 100644 --- a/ch02-00-guessing-game-tutorial.html +++ b/ch02-00-guessing-game-tutorial.html @@ -47,7 +47,7 @@
diff --git a/ch03-00-common-programming-concepts.html b/ch03-00-common-programming-concepts.html index 8567dd767..710a48cf1 100644 --- a/ch03-00-common-programming-concepts.html +++ b/ch03-00-common-programming-concepts.html @@ -47,7 +47,7 @@
diff --git a/ch03-01-variables-and-mutability.html b/ch03-01-variables-and-mutability.html index 27ad15bdd..dadf6c7b5 100644 --- a/ch03-01-variables-and-mutability.html +++ b/ch03-01-variables-and-mutability.html @@ -47,7 +47,7 @@
diff --git a/ch03-02-data-types.html b/ch03-02-data-types.html index b7780e1ac..d9643d4b3 100644 --- a/ch03-02-data-types.html +++ b/ch03-02-data-types.html @@ -47,7 +47,7 @@
diff --git a/ch03-03-how-functions-work.html b/ch03-03-how-functions-work.html index 3ef7a4e0f..8db063894 100644 --- a/ch03-03-how-functions-work.html +++ b/ch03-03-how-functions-work.html @@ -47,7 +47,7 @@
diff --git a/ch03-04-comments.html b/ch03-04-comments.html index f58a75e74..2a3d33956 100644 --- a/ch03-04-comments.html +++ b/ch03-04-comments.html @@ -47,7 +47,7 @@
diff --git a/ch03-05-control-flow.html b/ch03-05-control-flow.html index 828376311..52c4892ef 100644 --- a/ch03-05-control-flow.html +++ b/ch03-05-control-flow.html @@ -47,7 +47,7 @@
diff --git a/ch04-00-understanding-ownership.html b/ch04-00-understanding-ownership.html index 7c27939fb..edc6c5e22 100644 --- a/ch04-00-understanding-ownership.html +++ b/ch04-00-understanding-ownership.html @@ -47,7 +47,7 @@
diff --git a/ch04-01-what-is-ownership.html b/ch04-01-what-is-ownership.html index 5a7eea534..dfd705dbb 100644 --- a/ch04-01-what-is-ownership.html +++ b/ch04-01-what-is-ownership.html @@ -47,7 +47,7 @@
diff --git a/ch04-02-references-and-borrowing.html b/ch04-02-references-and-borrowing.html index 123b41763..4a0ea1fe8 100644 --- a/ch04-02-references-and-borrowing.html +++ b/ch04-02-references-and-borrowing.html @@ -47,7 +47,7 @@
diff --git a/ch04-03-slices.html b/ch04-03-slices.html index 7211ea9b9..07e529920 100644 --- a/ch04-03-slices.html +++ b/ch04-03-slices.html @@ -47,7 +47,7 @@
diff --git a/ch05-00-structs.html b/ch05-00-structs.html index 3dee97f41..c4c65a9ee 100644 --- a/ch05-00-structs.html +++ b/ch05-00-structs.html @@ -47,7 +47,7 @@
diff --git a/ch05-01-method-syntax.html b/ch05-01-method-syntax.html index 9d11135be..6aaa684ec 100644 --- a/ch05-01-method-syntax.html +++ b/ch05-01-method-syntax.html @@ -47,7 +47,7 @@
diff --git a/ch06-00-enums.html b/ch06-00-enums.html index 94b47d50f..40df9122d 100644 --- a/ch06-00-enums.html +++ b/ch06-00-enums.html @@ -47,7 +47,7 @@
diff --git a/ch06-01-option.html b/ch06-01-option.html index dfd3e8e49..6e59b1004 100644 --- a/ch06-01-option.html +++ b/ch06-01-option.html @@ -47,7 +47,7 @@
diff --git a/ch06-02-match.html b/ch06-02-match.html index 9b873f404..4758916f1 100644 --- a/ch06-02-match.html +++ b/ch06-02-match.html @@ -47,7 +47,7 @@
diff --git a/ch06-03-if-let.html b/ch06-03-if-let.html index 11ad7fb9b..60dd5be2f 100644 --- a/ch06-03-if-let.html +++ b/ch06-03-if-let.html @@ -47,7 +47,7 @@
diff --git a/ch07-00-modules.html b/ch07-00-modules.html index 54943764e..ec9b471e9 100644 --- a/ch07-00-modules.html +++ b/ch07-00-modules.html @@ -47,7 +47,7 @@
diff --git a/ch07-01-mod-and-the-filesystem.html b/ch07-01-mod-and-the-filesystem.html index 9f437dff6..c7fe247f9 100644 --- a/ch07-01-mod-and-the-filesystem.html +++ b/ch07-01-mod-and-the-filesystem.html @@ -47,7 +47,7 @@
diff --git a/ch07-02-controlling-visibility-with-pub.html b/ch07-02-controlling-visibility-with-pub.html index 428d00337..80442ce74 100644 --- a/ch07-02-controlling-visibility-with-pub.html +++ b/ch07-02-controlling-visibility-with-pub.html @@ -47,7 +47,7 @@
diff --git a/ch07-03-importing-names-with-use.html b/ch07-03-importing-names-with-use.html index 96d61c706..5269776b8 100644 --- a/ch07-03-importing-names-with-use.html +++ b/ch07-03-importing-names-with-use.html @@ -47,7 +47,7 @@
diff --git a/ch08-00-fundamental-collections.html b/ch08-00-fundamental-collections.html index ac1097106..51dbd771a 100644 --- a/ch08-00-fundamental-collections.html +++ b/ch08-00-fundamental-collections.html @@ -47,7 +47,7 @@
diff --git a/ch08-01-vectors.html b/ch08-01-vectors.html index cfb993ff1..ee05be3aa 100644 --- a/ch08-01-vectors.html +++ b/ch08-01-vectors.html @@ -47,7 +47,7 @@
diff --git a/ch08-02-strings.html b/ch08-02-strings.html index 24ab35de3..10c5b018a 100644 --- a/ch08-02-strings.html +++ b/ch08-02-strings.html @@ -47,7 +47,7 @@
diff --git a/ch08-03-hash-maps.html b/ch08-03-hash-maps.html index a38ee6233..c7b200e0d 100644 --- a/ch08-03-hash-maps.html +++ b/ch08-03-hash-maps.html @@ -47,7 +47,7 @@
diff --git a/ch09-00-error-handling.html b/ch09-00-error-handling.html index cee648246..155159c96 100644 --- a/ch09-00-error-handling.html +++ b/ch09-00-error-handling.html @@ -47,7 +47,7 @@
diff --git a/ch09-01-unrecoverable-errors-with-panic.html b/ch09-01-unrecoverable-errors-with-panic.html index b8cf50b07..4da26c962 100644 --- a/ch09-01-unrecoverable-errors-with-panic.html +++ b/ch09-01-unrecoverable-errors-with-panic.html @@ -47,7 +47,7 @@
diff --git a/ch09-02-recoverable-errors-with-result.html b/ch09-02-recoverable-errors-with-result.html index 653e1dcc9..68db51bef 100644 --- a/ch09-02-recoverable-errors-with-result.html +++ b/ch09-02-recoverable-errors-with-result.html @@ -47,7 +47,7 @@
diff --git a/ch09-03-to-panic-or-not-to-panic.html b/ch09-03-to-panic-or-not-to-panic.html index def9dde00..48a6a7b1c 100644 --- a/ch09-03-to-panic-or-not-to-panic.html +++ b/ch09-03-to-panic-or-not-to-panic.html @@ -47,7 +47,7 @@
diff --git a/ch10-00-generics.html b/ch10-00-generics.html index 08f7136cc..dae858162 100644 --- a/ch10-00-generics.html +++ b/ch10-00-generics.html @@ -47,7 +47,7 @@
diff --git a/ch10-01-syntax.html b/ch10-01-syntax.html index bbc6e82b7..ca82cf1bb 100644 --- a/ch10-01-syntax.html +++ b/ch10-01-syntax.html @@ -47,7 +47,7 @@
diff --git a/ch10-02-traits.html b/ch10-02-traits.html index 4885bbfd3..15d5bf269 100644 --- a/ch10-02-traits.html +++ b/ch10-02-traits.html @@ -47,7 +47,7 @@
diff --git a/ch10-03-lifetime-syntax.html b/ch10-03-lifetime-syntax.html index f4c4e7e1f..8faa4ce6e 100644 --- a/ch10-03-lifetime-syntax.html +++ b/ch10-03-lifetime-syntax.html @@ -47,7 +47,7 @@
diff --git a/ch11-00-testing.html b/ch11-00-testing.html index ee3d9a319..8344df9ed 100644 --- a/ch11-00-testing.html +++ b/ch11-00-testing.html @@ -47,7 +47,7 @@
diff --git a/ch11-01-writing-tests.html b/ch11-01-writing-tests.html index 12457fb00..3e685ca99 100644 --- a/ch11-01-writing-tests.html +++ b/ch11-01-writing-tests.html @@ -47,7 +47,7 @@
diff --git a/ch11-02-running-tests.html b/ch11-02-running-tests.html index 2c8235011..6a19f4cd9 100644 --- a/ch11-02-running-tests.html +++ b/ch11-02-running-tests.html @@ -47,7 +47,7 @@
diff --git a/ch11-03-test-organization.html b/ch11-03-test-organization.html index 3ad80c629..da610415a 100644 --- a/ch11-03-test-organization.html +++ b/ch11-03-test-organization.html @@ -47,7 +47,7 @@
diff --git a/ch12-00-an-io-project.html b/ch12-00-an-io-project.html index 2f91e617c..69a6d558e 100644 --- a/ch12-00-an-io-project.html +++ b/ch12-00-an-io-project.html @@ -47,7 +47,7 @@
diff --git a/ch12-01-accepting-command-line-arguments.html b/ch12-01-accepting-command-line-arguments.html index 303bcad9c..ecac3bc35 100644 --- a/ch12-01-accepting-command-line-arguments.html +++ b/ch12-01-accepting-command-line-arguments.html @@ -47,7 +47,7 @@
diff --git a/ch12-02-reading-a-file.html b/ch12-02-reading-a-file.html index f2cc6968a..36db59509 100644 --- a/ch12-02-reading-a-file.html +++ b/ch12-02-reading-a-file.html @@ -47,7 +47,7 @@
diff --git a/ch12-03-improving-error-handling-and-modularity.html b/ch12-03-improving-error-handling-and-modularity.html index 7012e598c..de08ce666 100644 --- a/ch12-03-improving-error-handling-and-modularity.html +++ b/ch12-03-improving-error-handling-and-modularity.html @@ -47,7 +47,7 @@
diff --git a/ch12-04-testing-the-librarys-functionality.html b/ch12-04-testing-the-librarys-functionality.html index 1e11fc533..f1f0129e6 100644 --- a/ch12-04-testing-the-librarys-functionality.html +++ b/ch12-04-testing-the-librarys-functionality.html @@ -47,7 +47,7 @@
@@ -232,8 +232,9 @@ method looks like this:

Finally, we need a way to store the lines that contain our search string. For 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:

-

Filename: src/lib.rs

+vector. Listing 12-15 has the full implementation:

+
+Filename: src/lib.rs
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
     let mut results = Vec::new();
 
@@ -246,6 +247,10 @@ vector:

results }
+
+

Listing 12-15: Fully functioning implementation of the grep function

+
+

Let's give it a try:

$ cargo test
diff --git a/ch12-05-working-with-environment-variables.html b/ch12-05-working-with-environment-variables.html
index fff3985e6..aff5d3132 100644
--- a/ch12-05-working-with-environment-variables.html
+++ b/ch12-05-working-with-environment-variables.html
@@ -47,7 +47,7 @@
         
 
         
 
         
@@ -114,8 +114,9 @@ Trust me.";

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:

-

Filename: src/lib.rs

+minor changes as shown in Listing 12-16:

+
+Filename: src/lib.rs
fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
     let search = search.to_lowercase();
     let mut results = Vec::new();
@@ -129,6 +130,11 @@ minor changes:

results }
+
+

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

+
+

First, we lowercase the search string, and store it in a shadowed variable with the same name. Note that search is now a String rather than a string diff --git a/ch12-06-writing-to-stderr-instead-of-stdout.html b/ch12-06-writing-to-stderr-instead-of-stdout.html index 674b8622a..893054551 100644 --- a/ch12-06-writing-to-stderr-instead-of-stdout.html +++ b/ch12-06-writing-to-stderr-instead-of-stdout.html @@ -47,7 +47,7 @@

@@ -85,7 +85,7 @@ running we'll see our error message:

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

+change how error messages are printed as shown in Listing 12-17:

Filename: src/main.rs
extern crate greprs;
@@ -123,7 +123,7 @@ fn main() {
 }
 
-

Listing 12-15: Writing error messages to stderr instead of stdout

+

Listing 12-17: Writing error messages to stderr instead of stdout

diff --git a/ch13-00-functional-features.html b/ch13-00-functional-features.html index 50a9ff878..4b5a5480c 100644 --- a/ch13-00-functional-features.html +++ b/ch13-00-functional-features.html @@ -2,7 +2,7 @@ - Functional Language Features in Rust - Iterators and Closures - The Rust Programming Language + Functional Language Features in Rust - The Rust Programming Language @@ -47,7 +47,7 @@
@@ -68,25 +68,24 @@

Functional Language features in Rust - Iterators and Closures

-

Closures

-

What is a closure

-

How are they diff from fns

-

Fn traits

-

Iterators

-

Iterator & for loop

-

.into_iter()

-

Iterators are Lazy

-

Difference between adapter and consumer - another iterator or consuming?

-

Implementing the Iterator trait

-

Talk about using Associated Types here, foreshadow to advanced type systems -chapter about why this is a different thing than normal

-

??? How does this improve the I/O project from Chapter 12

-

Does this get woven into the above sections?

-

Summary: Performance

-

Iterators compile down to ASM == for loop

-

Most complicated chain of iterator functions that compile down to the same ASM as a for loop

-

Representation: Closures are a Struct

-

Closures don't have any further performance penalty over regular fn calls

+

Rust's design has taken inspiration from a lot of previous work. One of Rust's +influences is functional programming, where functions are values that can be +used as arguments or return values to other functions, assigned to variables, +and so forth. We're going to sidestep the issue of what, exactly, functional +programming is or is not, and instead show off some features of Rust that +are similar to features in many languages referred to as functional.

+

More specifically, we're going to cover:

+
    +
  • Closures, a function-like construct you can store in a variable.
  • +
  • Iterators, a way of processing series of elements.
  • +
  • How to use these features to improve upon the project from the last chapter.
  • +
  • The performance of these features. Spoiler alert: they're faster than you +might think!
  • +
+

This is not a complete list of Rust's influence from the functional style: +pattern matching, enums, and many other features are too. But mastering +closures and iterators are an important part of writing idiomatic, fast Rust +code.

@@ -98,7 +97,7 @@ chapter about why this is a different thing than normal

- @@ -112,7 +111,7 @@ chapter about why this is a different thing than normal

- diff --git a/ch13-01-closures.html b/ch13-01-closures.html new file mode 100644 index 000000000..40ae62ba1 --- /dev/null +++ b/ch13-01-closures.html @@ -0,0 +1,310 @@ + + + + + Closures - The Rust Programming Language + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + +
+

Closures

+

Rust gives you the ability to define closures, which are similar to +functions. Instead of starting with a technical definition, let's see what +closures look like, syntactically, and then we'll return to defining what they +are. Listing 13-1 shows a small closure whose definition is assigned to the +variable add_one, which we can then use to call the closure:

+
+Filename: src/main.rs +
fn main() {
+    let add_one = |x| x + 1;
+
+    let five = add_one(4);
+
+    assert_eq!(5, five);
+}
+
+
+

Listing 13-1: A closure that takes one parameter and adds one to it, assigned to +the variable add_one

+
+
+

The closure definition, on the first line, shows that the closure takes one +parameter named x. Parameters to closures go in between vertical pipes (|).

+

This is a minimal closure with only one expression as its body. Listing 13-2 has +a closure with a bit more complexity:

+
+Filename: src/main.rs +
fn main() {
+    let calculate = |a, b| {
+        let mut result = a * 2;
+
+        result += b;
+
+        result
+    };
+
+    assert_eq!(7, calculate(2, 3)); // 2 * 2 + 3 == 7
+    assert_eq!(13, calculate(4, 5)); // 4 * 2 + 5 == 13
+}
+
+
+

Listing 13-2: A closure with two parameters and multiple expressions in its body

+
+
+

We can use curly brackets to define a closure body with more than one +expression.

+

You'll notice a few things about closures that are different from functions +defined with the fn keyword. The first difference is that we did not need to +annotate the types of the parameters the closure takes or the value it returns. +We can choose to add type annotations if we want; Listing 13-3 shows the +closure from Listing 13-1 with annotations for the parameter's and return +value's types:

+
+Filename: src/main.rs +
fn main() {
+    let add_one = |x: i32| -> i32 { x + 1 };
+
+    assert_eq!(2, add_one(1));
+}
+
+
+

Listing 13-3: A closure definition with optional parameter and return value +type annotations

+
+
+

The syntax of closures and functions looks more similar with type annotations. +Let's compare the different ways we can specify closures with the syntax for +defining a function more directly. We've added some spaces here to line up the +relevant parts:

+
fn  add_one_v1   (x: i32) -> i32 { x + 1 }  // a function
+let add_one_v2 = |x: i32| -> i32 { x + 1 }; // the full syntax for a closure
+let add_one_v3 = |x|             { x + 1 }; // a closure eliding types
+let add_one_v4 = |x|               x + 1  ; // without braces
+
+

The reason type annotations are not required for defining a closure but are +required for defining a function is that functions are part of an explicit +interface exposed to your users, so defining this interface rigidly is +important for ensuring that everyone agrees on what types of values a function +uses and returns. Closures aren't used in an exposed interface like this, +though: they're stored in bindings and called directly. Being forced to +annotate the types would be a significant ergonomic loss for little advantage.

+

Closure definitions do have one type inferred for each of their parameters and +for their return value. For instance, if we call the closure without type +annotations from Listing 13-1 using an i8, we'll get an error if we then try +to call the same closure with an i32:

+

Filename: src/main.rs

+
let add_one = |x| x + 1;
+
+let five = add_one(4i8);
+assert_eq!(5i8, five);
+
+let three = add_one(2i32);
+
+

The compiler gives us this error:

+
error[E0308]: mismatched types
+ -->
+  |
+7 | let three = add_one(2i32);
+  |                     ^^^^ expected i8, found i32
+
+

Since closures' types can be inferred reliably since they're called directly, +it would be tedious if we were required to annotate their types.

+

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

+

Closures Can Reference Their Environment

+

We've learned that functions can only use variables that are in scope, either +by being const or being declared as parameters. Closures can do more: they're +allowed to access variables from their enclosing scope. Listing 13-4 has an +example of a closure in the variable equal_to_x that uses the variable x +from the closure's surrounding environment:

+
+Filename: src/main.rs +
fn main() {
+    let x = 4;
+
+    let equal_to_x = |z| z == x;
+
+    let y = 4;
+
+    assert!(equal_to_x(y));
+}
+
+
+

Listing 13-4: Example of a closure that refers to a variable in its enclosing +scope

+
+
+

Here, even though x is not one of the parameters of equal_to_x, the +equal_to_x closure is allowed to use x, since x is a variable defined in +the scope that equal_to_x is defined. We aren't allowed to do the same thing +that Listing 13-4 does with functions; let's see what happens if we try:

+

Filename: src/main.rs

+
fn main() {
+    let x = 4;
+
+    fn equal_to_x(z: i32) -> bool { z == x }
+
+    let y = 4;
+
+    assert!(equal_to_x(y));
+}
+
+

We get an error:

+
error[E0434]: can't capture dynamic environment in a fn item; use the || { ... }
+closure form instead
+ -->
+  |
+4 |     fn equal_to_x(z: i32) -> bool { z == x }
+  |                                          ^
+
+

The compiler even reminds us that this only works with closures!

+

Creating closures that capture values from their environment is mostly used in +the context of starting new threads. We'll show some more examples and explain +more detail about this feature of closures in Chapter 16 when we talk about +concurrency.

+

Closures as Function Parameters Using the Fn Traits

+

While we can bind closures to variables, that's not the most useful thing we +can do with them. We can also define functions that have closures as parameters +by using the Fn traits. Here's an example of a function named call_with_one +whose signature has a closure as a parameter:

+
fn call_with_one<F>(some_closure: F) -> i32
+    where F: Fn(i32) -> i32 {
+
+    some_closure(1)
+}
+
+let answer = call_with_one(|x| x + 2);
+
+assert_eq!(3, answer);
+
+

We pass the closure |x| x + 2, to call_with_one, and call_with_one calls +that closure with 1 as an argument. The return value of the call to +some_closure is then returned from call_with_one.

+

The signature of call_with_one is using the where syntax discussed in the +Traits section of Chapter 10. The some_closure parameter has the generic type +F, which in the where clause is defined as having the trait bounds +Fn(i32) -> i32. The Fn trait represents a closure, and we can add types to +the Fn trait to represent a specific type of closure. In this case, our +closure has a parameter of type i32 and returns an i32, so the generic bound +we specify is Fn(i32) -> i32.

+

Specifying a function signature that contains a closure requires the use of +generics and trait bounds. Each closure has a unique type, so we can't write +the type of a closure directly, we have to use generics.

+

Fn isn't the only trait bound available for specifying closures, however. +There are three: Fn, FnMut, and FnOnce. This continues the patterns of +threes we've seen elsewhere in Rust: borrowing, borrowing mutably, and +ownership. Using Fn specifies that the closure used may only borrow values in +its environment. To specify a closure that mutates the environment, use +FnMut, and if the closure takes ownership of the environment, FnOnce. Most +of the time, you can start with Fn, and the compiler will tell you if you +need FnMut or FnOnce based on what happens when the function calls the +closure.

+

To illustrate a situation where it's useful for a function to have a parameter +that's a closure, let's move on to our next topic: iterators.

+ +
+ + + + + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + + + diff --git a/ch13-02-iterators.html b/ch13-02-iterators.html new file mode 100644 index 000000000..d914daae9 --- /dev/null +++ b/ch13-02-iterators.html @@ -0,0 +1,317 @@ + + + + + Iterators - The Rust Programming Language + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + +
+

Iterators

+

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

+
+
let v1 = vec![1, 2, 3];
+
+let v2: Vec<i32> = v1.iter().map(|x| x + 1).collect();
+
+assert_eq!(v2, [2, 3, 4]);
+
+
+

Listing 13-5: Using an iterator, map, and collect to add one to each number +in a vector

+
+
+ +

The iter method on vectors allows us to produce an iterator from the +vector. Next, the map method called on the iterator allows us to process each +element: in this case, we've passed a closure to map that specifies for every +element x, add one to it. map is one of the most basic ways of interacting +with an iterator, as processing each element in turn is very useful! Finally, +the collect method consumes the iterator and puts the iterator's elements +into a new data structure. In this case, since we've said that v2 has the +type Vec<i32>, collect will create a new vector out of the i32 values.

+

Methods on iterators like map are sometimes called iterator adaptors +because they take one iterator and produce a new iterator. That is, map +builds on top of our previous iterator and produces another iterator by calling +the closure it's passed to create the new sequence of values.

+

So, to recap, this line of code does the following:

+
    +
  1. Creates an iterator from the vector.
  2. +
  3. Uses the map adaptor with a closure argument to add one to each element.
  4. +
  5. Uses the collect adaptor to consume the iterator and make a new vector.
  6. +
+

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

+

Iterators are Lazy

+

In the previous section, you may have noticed a subtle difference in wording: +we said that map adapts an iterator, but collect consumes one. That was +intentional. By themselves, iterators won't do anything; they're lazy. That is, +if we write code like Listing 13-5 except we don't call collect:

+
let v1: Vec<i32> = vec![1, 2, 3];
+
+v1.iter().map(|x| x + 1); // without collect
+
+

It will compile, but it will give us a warning:

+
warning: unused result which must be used: iterator adaptors are lazy and do
+nothing unless consumed, #[warn(unused_must_use)] on by default
+ --> src/main.rs:4:1
+  |
+4 | v1.iter().map(|x| x + 1); // without collect
+  | ^^^^^^^^^^^^^^^^^^^^^^^^^
+
+

We get this warning because iterator adaptors won't start actually doing the +processing on their own. They need some other method that causes the iterator +chain to evaluate. We call those consuming adaptors, and collect is one of +them.

+

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

+

The Iterator trait

+

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

+
trait Iterator {
+    type Item;
+
+    fn next(&mut self) -> Option<Self::Item>;
+}
+
+

There's some new syntax that we haven't covered here yet: type Item and +Self::Item are defining an associated type with this trait, and we'll talk +about associated types in depth in Chapter XX. For now, all you need to know is +that this code says the Iterator trait requires that you also define an +Item type, and this Item type is used in the return type of the next +method. In other words, the Item type will be the type of element that's +returned from the iterator.

+

Let's make an iterator named Counter that will count from 1 to 5, using +the Iterator trait. First, we need to create a struct that holds the current +state of the iterator, which is one field named count that will hold a u32. +We'll also define a new method, which isn't strictly necessary. We want our +Counter to go from one to five, though, so we're always going to have it +holding a zero to start:

+
struct Counter {
+    count: u32,
+}
+
+impl Counter {
+    fn new() -> Counter {
+        Counter { count: 0 }
+    }
+}
+
+

Next, we're going to implement the Iterator trait for our Counter type by +defining the body of the next method. The way we want our iterator to work +is to add one to the state (which is why we initialized count to 0, since we +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:

+
+
# struct Counter {
+#     count: u32,
+# }
+#
+impl Iterator for Counter {
+    // Our iterator will produce u32s
+    type Item = u32;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        // increment our count. This is why we started at zero.
+        self.count += 1;
+
+        // check to see if we've finished counting or not.
+        if self.count < 6 {
+            Some(self.count)
+        } else {
+            None
+        }
+    }
+}
+
+
+

Listing 13-6: Implementing the Iterator trait on our Counter struct

+
+
+ +

The type Item = u32 line is saying that the associated Item type will be +a u32 for our iterator. Again, don't worry about associated types yet, because +we'll be covering them in Chapter XX.

+

The next method is the main interface into an iterator, and it returns an +Option. If the option is Some(value), we have gotten another value from the +iterator. If it's None, iteration is finished. Inside of the next method, +we do whatever kind of calculation our iterator needs to do. In this case, we +add one, then check to see if we're still below six. If we are, we can return +Some(self.count) to produce the next value. If we're at six or more, +iteration is over, so we return None.

+

The iterator trait specifies that when an iterator returns None, that +indicates iteration is finished. The trait does not mandate anything about the +behavior an iterator must have if the next method is called again after +having returned one None value. In this case, every time we call next after +getting the first None value will still return None, but the internal +count field will continue to be incremented by one each time. If we call +next as many times as the maximum value a u32 value can hold, count will +overflow (which will panic! in debug mode and wrap in release mode). Other +iterator implementations choose to start iterating again. If you need to be +sure to have an iterator that will always return None on subsequent calls to +the next method after the first None value is returned, you can use the +fuse method to create an iterator with that characteristic out of any other +iterator.

+

Once we've implemented the Iterator trait, we have an iterator! We can use +the iterator functionality that our Counter struct now has by calling the +next method on it repeatedly:

+
let mut counter = Counter::new();
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+

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

+

All Sorts of Iterator Adaptors

+

In Listing 13-5, we had iterators and we called methods like map and +collect on them. In Listing 13-6, however, we only implemented the next +method on our Counter. How do we get methods like map and collect on our +Counter?

+

Well, when we told you about the definition of Iterator, we committed a small +lie of omission. The Iterator trait has a number of other useful methods +defined on it that come with default implementations that call the next +method. Since next is the only method of the Iterator trait that does not +have a default implementation, once you've done that, you get all of the other +Iterator adaptors for free. There are a lot of them!

+

For example, if for some reason we wanted to take the first five values that +an instance of Counter produces, pair those values with values produced by +another Counter instance after skipping the first value that instance +produces, multiply each pair together, keep only those results that are +divisible by three, and add all the resulting values together, we could do:

+
let sum: u32 = Counter::new().take(5)
+                             .zip(Counter::new().skip(1))
+                             .map(|(a, b)| a * b)
+                             .filter(|x| x % 3 == 0)
+                             .sum();
+assert_eq!(48, sum);
+
+

All of these method calls are possible because we implemented the Iterator +trait by specifying how the next method works. Use the standard library +documentation to find more useful methods that will come in handy when you're +working with iterators.

+ +
+ + + + + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + + + diff --git a/ch13-03-improving-our-io-project.html b/ch13-03-improving-our-io-project.html new file mode 100644 index 000000000..f52b572c1 --- /dev/null +++ b/ch13-03-improving-our-io-project.html @@ -0,0 +1,267 @@ + + + + + Improving our I/O Project - The Rust Programming Language + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + +
+

Improving our I/O Project

+

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

+

Removing a clone by Using an Iterator

+

Back in listing 12-8, we had this code that took a slice of String values and +created an instance of the Config struct by checking for the right number of +arguments, indexing into the slice, and cloning the values so that the Config +struct could own those values:

+
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,
+        })
+    }
+}
+
+

At the time, we said not to worry about the clone calls here, and that we +could remove them in the future. Well, that time is now! So, why do we need +clone here? The issue is that we have a slice with String elements in the +parameter args, and the new function does not own args. In order to be +able to return ownership of a Config instance, we need to clone the values +that we put in the search and filename fields of Config, so that the +Config instance can own its values.

+

Now that we know more about iterators, we can change the new function to +instead take ownership of an iterator as its argument. We'll use the iterator +functionality instead of having to check the length of the slice and index into +specific locations. Since we've taken ownership of the iterator, and we won't be +using indexing operations that borrow anymore, we can move the String values +from the iterator into Config instead of calling clone and making a new +allocation.

+

First, let's take main as it was in Listing 12-6, and change it to pass the +return value of env::args to Config::new, instead of calling collect and +passing a slice:

+
fn main() {
+    let config = Config::new(env::args());
+    // ...snip...
+
+ +

If we look in the standard library documentation for the env::args function, +we'll see that its return type is std::env::Args. So next we'll update the +signature of the Config::new function so that the parameter args has the +type std::env::Args instead of &[String]:

+
impl Config {
+    fn new(args: std::env::Args) -> Result<Config, &'static str> {
+        // ...snip...
+
+ +

Next, we'll fix the body of Config::new. As we can also see in the standard +library documentation, std::env::Args implements the Iterator trait, so we +know we can call the next method on it! Here's the new code:

+
# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+impl Config {
+    fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
+        args.next();
+
+        let search = match args.next() {
+            Some(arg) => arg,
+            None => return Err("Didn't get a search string"),
+        };
+
+        let filename = match args.next() {
+            Some(arg) => arg,
+            None => return Err("Didn't get a file name"),
+        };
+
+        Ok(Config {
+            search: search,
+            filename: filename,
+        })
+    }
+}
+
+ +

Remember that the first value in the return value of env::args is the name of +the program. We want to ignore that, so first we'll call next and not do +anything with the return value. The second time we call next should be the +value we want to put in the search field of Config. We use a match to +extract the value if next returns a Some, and we return early with an Err +value if there weren't enough arguments (which would cause this call to next +to return None).

+

We do the same thing for the filename value. It's slightly unfortunate that +the match expressions for search and filename are so similar. It would be +nice if we could use ? on the Option returned from next, but ? only +works with Result values currently. Even if we could use ? on Option like +we can on Result, the value we would get would be borrowed, and we want to +move the String from the iterator into Config.

+

Making Code Clearer with Iterator Adaptors

+

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

+ +
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+    let mut results = Vec::new();
+
+    for line in contents.lines() {
+        if line.contains(search) {
+            results.push(line);
+        }
+    }
+
+    results
+}
+
+

We can write this code in a much shorter way, and avoiding having to have a +mutable intermediate results vector, by using iterator adaptor methods like +this instead:

+
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+    contents.lines()
+        .filter(|line| line.contains(search))
+        .collect()
+}
+
+

Here, we use the filter adaptor to only keep the lines that +line.contains(search) returns true for. We then collect them up into another +vector with collect. Much simpler!

+

We can use the same technique in the grep_case_insensitive function that we +defined in Listing 12-16 as follows:

+ +
fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+    contents.lines()
+        .filter(|line| {
+            line.to_lowercase().contains(&search)
+        }).collect()
+}
+
+

Not too bad! So which style should you choose? Most Rust programmers prefer to +use the iterator style. It's a bit tougher to understand at first, but once you +gain an intuition for what the various iterator adaptors do, this is much +easier to understand. Instead of fiddling with the various bits of looping +and building a new vector, the code focuses on the high-level objective of the +loop, abstracting some of the commonplace code so that it's easier to see the +concepts that are unique to this usage of the code, like the condition on which +the code is filtering each element in the iterator.

+

But are they truly equivalent? Surely the more low-level loop will be faster. +Let's talk about performance.

+ +
+ + + + + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + + + diff --git a/ch13-04-performance.html b/ch13-04-performance.html new file mode 100644 index 000000000..a38cc334f --- /dev/null +++ b/ch13-04-performance.html @@ -0,0 +1,190 @@ + + + + + Performance - The Rust Programming Language + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + +
+

Performance

+

Which version of our grep functions is faster: the version with an explicit +for loop or the version with iterators? We ran a benchmark by loading the +entire contents of "The Adventures of Sherlock Holmes" by Sir Arthur Conan +Doyle into a String and looking for the word "the" in the contents. Here were +the results of the benchmark on the version of grep using the for loop and the +version using iterators:

+
test bench_grep_for  ... bench:  19,620,300 ns/iter (+/- 915,700)
+test bench_grep_iter ... bench:  19,234,900 ns/iter (+/- 657,200)
+
+

The iterator version ended up slightly faster! We're not going to go through +the benchmark code here, as the point is not to prove that they're exactly +equivalent, but to get a general sense of how these two implementations +compare. For a real benchmark, you'd want to check various texts of various +sizes, different words, words of different lengths, and all kinds of other +variations. The point is this: iterators, while a high-level abstraction, get +compiled down to roughly the same code as if you'd written the lower-level code +yourself. Iterators are one of Rust's zero-cost abstractions, by which we mean +using the abstraction imposes no additional runtime overhead in the same way +that Bjarne Stroustrup, the original designer and implementer of C++, defines +zero-overhead:

+
+

In general, C++ implementations obey the zero-overhead principle: What you +don’t use, you don’t pay for. And further: What you do use, you couldn’t hand +code any better.

+
    +
  • Bjarne Stroustrup "Foundations of C++"
  • +
+
+

As another example, here is some code taken from an audio decoder. This code +uses an iterator chain to do some math on three variables in scope: a buffer +slice of data, an array of 12 coefficients, and an amount by which to shift +data in qlp_shift. We've declared the variables within this example but not +given them any values; while this code doesn't have much meaning outside of its +context, it's still a concise, real-world example of how Rust translates +high-level ideas to low-level code:

+
let buffer: &mut [i32];
+let coefficients: [i64; 12];
+let qlp_shift: i16;
+
+for i in 12..buffer.len() {
+    let prediction = coefficients.iter()
+                                 .zip(&buffer[i - 12..i])
+                                 .map(|(&c, &s)| c * s as i64)
+                                 .sum::<i64>() >> qlp_shift;
+    let delta = buffer[i];
+    buffer[i] = prediction as i32 + delta;
+}
+
+

In order to calculate the value of prediction, this code iterates through +each of the 12 values in coefficients, uses the zip method to pair the +coefficient values with the previous 12 values in buffer. Then for each pair, +multiply the values together, sum all the results, and shift the bits in the +sum qlp_shift bits to the right

+

Calculations in applications like audio decoders often prioritize performance +most highly. Here, we're creating an iterator, using two adaptors, then +consuming the value. What assembly code would this Rust code compile to? Well, +as of this writing, it compiles down to the same assembly you'd write by hand. +There's no loop at all corresponding to the iteration over the values in +coefficients: Rust knows that there are twelve iterations, so it "unrolls" +the loop. All of the coefficients get stored in registers (which means +accessing the values is very fast). There are no bounds checks on the array +access. It's extremely efficient.

+

Now that you know this, go use iterators and closures without fear! They make +code feel higher-level, but don't impose a runtime performance penalty for +doing so.

+

Summary

+

Closures and iterators are Rust features inspired by functional programming +language ideas. They contribute to Rust's ability to clearly express high-level +ideas. The implementations of closures and iterators, as well as other zero-cost +abstractions in Rust, are such that runtime performance is not affected.

+

Now that we've improved the expressiveness of our I/O project, let's look at +some more features of cargo that would help us get ready to share the project +with the world.

+ +
+ + + + + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + + + diff --git a/ch14-00-more-about-cargo.html b/ch14-00-more-about-cargo.html index c0182272c..c50955693 100644 --- a/ch14-00-more-about-cargo.html +++ b/ch14-00-more-about-cargo.html @@ -47,7 +47,7 @@
@@ -86,7 +86,7 @@ documentation.

- @@ -100,7 +100,7 @@ documentation.

- diff --git a/ch14-01-release-profiles.html b/ch14-01-release-profiles.html index ace9d61f6..953d5fc49 100644 --- a/ch14-01-release-profiles.html +++ b/ch14-01-release-profiles.html @@ -47,7 +47,7 @@
diff --git a/ch14-02-publishing-to-crates-io.html b/ch14-02-publishing-to-crates-io.html index 5d93847c5..8ceef4eea 100644 --- a/ch14-02-publishing-to-crates-io.html +++ b/ch14-02-publishing-to-crates-io.html @@ -47,7 +47,7 @@
diff --git a/ch14-03-cargo-workspaces.html b/ch14-03-cargo-workspaces.html index 484696329..de9595671 100644 --- a/ch14-03-cargo-workspaces.html +++ b/ch14-03-cargo-workspaces.html @@ -47,7 +47,7 @@
diff --git a/ch14-04-installing-binaries.html b/ch14-04-installing-binaries.html index 848897634..8fd32f3cf 100644 --- a/ch14-04-installing-binaries.html +++ b/ch14-04-installing-binaries.html @@ -47,7 +47,7 @@
diff --git a/ch14-05-extending-cargo.html b/ch14-05-extending-cargo.html index 62b5d1173..3009604e0 100644 --- a/ch14-05-extending-cargo.html +++ b/ch14-05-extending-cargo.html @@ -47,7 +47,7 @@
diff --git a/ch15-00-smart-pointers.html b/ch15-00-smart-pointers.html index 8e67a5928..01ffb1b8c 100644 --- a/ch15-00-smart-pointers.html +++ b/ch15-00-smart-pointers.html @@ -47,7 +47,7 @@
diff --git a/ch16-00-concurrency.html b/ch16-00-concurrency.html index 7918291e3..653773f5e 100644 --- a/ch16-00-concurrency.html +++ b/ch16-00-concurrency.html @@ -47,7 +47,7 @@
@@ -92,6 +92,192 @@ 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 +also subject to all of the usual rules around ownership and borrowing. Since +closures attempt to infer the types of their parameters, they also infer how +those parameters are borrowed. Closures make that inference by looking at how +they are used. Consider the example in Listing 13-5 that has functions that +borrow immutably, borrow mutably, and move their parameters, then closures that +reference values from their environment and call each of the functions. We'll +see how this affects inference of when a value is borrowed:

+
+Filename: src/main.rs +
#[derive(Debug)]
+struct Foo;
+
+fn borrows(f: &Foo) {
+    println!("Took {:?} by reference.", f);
+}
+
+fn borrows_mut(f: &mut Foo) {
+    println!("Took {:?} by mutable reference.", f);
+}
+
+fn moves(f: Foo) {
+    println!("Took ownership of {:?}.", f);
+}
+
+fn main() {
+    let f1 = Foo;
+    let closure_that_borrows = |x| borrows(x);
+    closure_that_borrows(&f1);
+
+    let mut f2 = Foo;
+    let closure_that_borrows_mut = |y| borrows_mut(y);
+    closure_that_borrows_mut(&mut f2);
+
+    let f3 = Foo;
+    let closure_that_moves = |z| moves(z);
+    closure_that_moves(f3);
+}
+
+
+

Listing 16-something: Closures that borrow, borrow mutably, and take ownership +of their parameters, which is inferred from how the closure body uses the +parameters

+
+
+

Here, Rust is able to look at how we use the parameters of each closure inside +their bodies. If the closure passes its parameter it to a function that takes +&Foo, then the type of the parameter must be &Foo. If it passes the +parameter to a function that takes &mut Foo, then the type of parameter must +be &mut Foo, and so on. If we try to use f3 after the call to +closure_that_moves in the last line of main, we'll get a compiler error +since ownership of f3 was transferred to closure_that_moves, which +transferred ownership to the function moves.

+

Overriding Inferred Borrowing with the move Keyword

+

Rust will allow you to override the borrowing inference by using the move +keyword. This will cause all of the closure's parameters to be taken by +ownership, instead of whatever they were inferred as. Consider this example:

+
let mut num = 4;
+
+{
+    let mut add_num = |x| num += x;
+
+    add_num(6);
+}
+
+assert_eq!(10, num);
+
+

In this case, the add_num closure took a mutable reference to num, then +when we called add_num, it mutated the underlying value. In the last line, +num contains 10, as we'd expect. We also needed to declare add_num itself +as mut too, because we're mutating its environment.

+

If we change the definition of add_num to a move closure, the behavior is +different:

+
let mut num = 4;
+
+{
+    let mut add_num = move |x| num += x;
+
+    add_num(6);
+}
+
+assert_eq!(4, num);
+
+

In the last line, num now contains 4: add_num took ownership of a copy of +num, rather than mutably borrowing num.

+

One of the most common places you'll see the move keyword used is with +threads, since it's important that one thread is no longer allowed to use a +value once the value has been transferred to another thread through a closure +in order to prevent data races. We'll talk more about that in Chapter XX.

+

Closures and Lifetimes

+

Remember Listing 10-8 from the Lifetime Syntax section of Chapter 10? It looked +like this:

+
{
+    let r;
+
+    {
+        let x = 5;
+        r = &x;
+    }
+
+    println!("r: {}", r);
+}
+
+

This example doesn't compile since x doesn't have a long enough lifetime. +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:

+
+
{
+    let closure;
+
+    {
+        let x = 4;
+
+        closure = || x ; // A closure that takes no arguments and returns x.
+    }
+}
+
+
+

Listing 16-something: A closure that tries to return a borrowed value that does +not live long enough

+
+
+

We get an error because x does not live long enough:

+
error: `x` does not live long enough
+  -->
+   |
+8  |         closure = || x ; // A closure that takes no arguments and returns x.
+   |                   -- ^ does not live long enough
+   |                   |
+   |                   capture occurs here
+9  |     }
+   |     - borrowed value only lives until here
+10 | }
+   | - borrowed value needs to live until here
+
+

To fix the error in the code in Listing 13-6, we can use the move keyword +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:

+
+
{
+    let closure;
+
+    {
+        let mut x = 4;
+
+        closure = move || x ; // A closure that takes no arguments and returns x.
+
+        x = 5;
+
+        assert_eq!(closure(), 4);
+    }
+}
+
+
+

Listing 16-something: Moving a value into the closure to fix the lifetime error

+
+
+

Even though we modified x between the closure definition and assert_eq!, +since closure now has its own version, the changes to x won't change the +version of x that's in the closure.

+

Rust doesn't provide a way to say that some values a closure uses should be +borrowed and some should be moved; it's either all by inference or all moved by +adding the move keyword. However, we can accomplish the goal of borrowing +some values and taking ownership of others by combining move with some extra +bindings. Consider this example where we want to borrow s1 but take ownership +of s2:

+
let s1 = String::from("hello");
+let s2 = String::from("goodbye");
+
+let r = &s1;
+
+let calculation = move || {
+    r;
+    s2;
+};
+
+println!("Can still use s1 here but not s2: {}", s1);
+
+

We've declared calculation to move all the values it references. Before +defining calculation, we declare a new variable r that borrows s1. Then +in the body of the calculation closure, we use r instead of using s1 +directly. The closure takes ownership of r, but r is a reference, so the +closure hasn't taken ownership of s1 even though calculation uses move.

Channels

Look up examples of cases where channels are useful

Can match modeling of certain problems

diff --git a/ch17-00-oop.html b/ch17-00-oop.html index 305a31c79..e4d466cab 100644 --- a/ch17-00-oop.html +++ b/ch17-00-oop.html @@ -47,7 +47,7 @@
diff --git a/ch18-00-patterns.html b/ch18-00-patterns.html index 4237880d4..6b9c62561 100644 --- a/ch18-00-patterns.html +++ b/ch18-00-patterns.html @@ -47,7 +47,7 @@
diff --git a/ch19-00-more-lifetimes.html b/ch19-00-more-lifetimes.html index 17f9da360..b3b6bf952 100644 --- a/ch19-00-more-lifetimes.html +++ b/ch19-00-more-lifetimes.html @@ -47,7 +47,7 @@
diff --git a/ch20-00-advanced-types.html b/ch20-00-advanced-types.html index 0f00cdf00..942352d3b 100644 --- a/ch20-00-advanced-types.html +++ b/ch20-00-advanced-types.html @@ -47,7 +47,7 @@
diff --git a/index.html b/index.html index 34a294898..263d18068 100644 --- a/index.html +++ b/index.html @@ -46,7 +46,7 @@
diff --git a/print.html b/print.html index 9618bab48..d19f29cd4 100644 --- a/print.html +++ b/print.html @@ -47,7 +47,7 @@
@@ -10023,8 +10023,9 @@ method looks like this:

Finally, we need a way to store the lines that contain our search string. For 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:

-

Filename: src/lib.rs

+vector. Listing 12-15 has the full implementation:

+
+Filename: src/lib.rs
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
     let mut results = Vec::new();
 
@@ -10037,6 +10038,10 @@ vector:

results }
+
+

Listing 12-15: Fully functioning implementation of the grep function

+
+

Let's give it a try:

$ cargo test
@@ -10150,8 +10155,9 @@ Trust me.";
 
 

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:

-

Filename: src/lib.rs

+minor changes as shown in Listing 12-16:

+
+Filename: src/lib.rs
fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
     let search = search.to_lowercase();
     let mut results = Vec::new();
@@ -10165,6 +10171,11 @@ minor changes:

results }
+
+

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

+
+

First, we lowercase the search string, and store it in a shadowed variable with the same name. Note that search is now a String rather than a string @@ -10325,7 +10336,7 @@ running we'll see our error message:

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

+change how error messages are printed as shown in Listing 12-17:

Filename: src/main.rs
extern crate greprs;
@@ -10363,7 +10374,7 @@ fn main() {
 }
 
-

Listing 12-15: Writing error messages to stderr instead of stdout

+

Listing 12-17: Writing error messages to stderr instead of stdout

@@ -10402,25 +10413,644 @@ always valid.

Next, let's explore how to make use of some features of Rust that were influenced by functional languages: closures and iterators.

Functional Language features in Rust - Iterators and Closures

+

Rust's design has taken inspiration from a lot of previous work. One of Rust's +influences is functional programming, where functions are values that can be +used as arguments or return values to other functions, assigned to variables, +and so forth. We're going to sidestep the issue of what, exactly, functional +programming is or is not, and instead show off some features of Rust that +are similar to features in many languages referred to as functional.

+

More specifically, we're going to cover:

+
    +
  • Closures, a function-like construct you can store in a variable.
  • +
  • Iterators, a way of processing series of elements.
  • +
  • How to use these features to improve upon the project from the last chapter.
  • +
  • The performance of these features. Spoiler alert: they're faster than you +might think!
  • +
+

This is not a complete list of Rust's influence from the functional style: +pattern matching, enums, and many other features are too. But mastering +closures and iterators are an important part of writing idiomatic, fast Rust +code.

Closures

-

What is a closure

-

How are they diff from fns

-

Fn traits

+

Rust gives you the ability to define closures, which are similar to +functions. Instead of starting with a technical definition, let's see what +closures look like, syntactically, and then we'll return to defining what they +are. Listing 13-1 shows a small closure whose definition is assigned to the +variable add_one, which we can then use to call the closure:

+
+Filename: src/main.rs +
fn main() {
+    let add_one = |x| x + 1;
+
+    let five = add_one(4);
+
+    assert_eq!(5, five);
+}
+
+
+

Listing 13-1: A closure that takes one parameter and adds one to it, assigned to +the variable add_one

+
+
+

The closure definition, on the first line, shows that the closure takes one +parameter named x. Parameters to closures go in between vertical pipes (|).

+

This is a minimal closure with only one expression as its body. Listing 13-2 has +a closure with a bit more complexity:

+
+Filename: src/main.rs +
fn main() {
+    let calculate = |a, b| {
+        let mut result = a * 2;
+
+        result += b;
+
+        result
+    };
+
+    assert_eq!(7, calculate(2, 3)); // 2 * 2 + 3 == 7
+    assert_eq!(13, calculate(4, 5)); // 4 * 2 + 5 == 13
+}
+
+
+

Listing 13-2: A closure with two parameters and multiple expressions in its body

+
+
+

We can use curly brackets to define a closure body with more than one +expression.

+

You'll notice a few things about closures that are different from functions +defined with the fn keyword. The first difference is that we did not need to +annotate the types of the parameters the closure takes or the value it returns. +We can choose to add type annotations if we want; Listing 13-3 shows the +closure from Listing 13-1 with annotations for the parameter's and return +value's types:

+
+Filename: src/main.rs +
fn main() {
+    let add_one = |x: i32| -> i32 { x + 1 };
+
+    assert_eq!(2, add_one(1));
+}
+
+
+

Listing 13-3: A closure definition with optional parameter and return value +type annotations

+
+
+

The syntax of closures and functions looks more similar with type annotations. +Let's compare the different ways we can specify closures with the syntax for +defining a function more directly. We've added some spaces here to line up the +relevant parts:

+
fn  add_one_v1   (x: i32) -> i32 { x + 1 }  // a function
+let add_one_v2 = |x: i32| -> i32 { x + 1 }; // the full syntax for a closure
+let add_one_v3 = |x|             { x + 1 }; // a closure eliding types
+let add_one_v4 = |x|               x + 1  ; // without braces
+
+

The reason type annotations are not required for defining a closure but are +required for defining a function is that functions are part of an explicit +interface exposed to your users, so defining this interface rigidly is +important for ensuring that everyone agrees on what types of values a function +uses and returns. Closures aren't used in an exposed interface like this, +though: they're stored in bindings and called directly. Being forced to +annotate the types would be a significant ergonomic loss for little advantage.

+

Closure definitions do have one type inferred for each of their parameters and +for their return value. For instance, if we call the closure without type +annotations from Listing 13-1 using an i8, we'll get an error if we then try +to call the same closure with an i32:

+

Filename: src/main.rs

+
let add_one = |x| x + 1;
+
+let five = add_one(4i8);
+assert_eq!(5i8, five);
+
+let three = add_one(2i32);
+
+

The compiler gives us this error:

+
error[E0308]: mismatched types
+ -->
+  |
+7 | let three = add_one(2i32);
+  |                     ^^^^ expected i8, found i32
+
+

Since closures' types can be inferred reliably since they're called directly, +it would be tedious if we were required to annotate their types.

+

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

+

Closures Can Reference Their Environment

+

We've learned that functions can only use variables that are in scope, either +by being const or being declared as parameters. Closures can do more: they're +allowed to access variables from their enclosing scope. Listing 13-4 has an +example of a closure in the variable equal_to_x that uses the variable x +from the closure's surrounding environment:

+
+Filename: src/main.rs +
fn main() {
+    let x = 4;
+
+    let equal_to_x = |z| z == x;
+
+    let y = 4;
+
+    assert!(equal_to_x(y));
+}
+
+
+

Listing 13-4: Example of a closure that refers to a variable in its enclosing +scope

+
+
+

Here, even though x is not one of the parameters of equal_to_x, the +equal_to_x closure is allowed to use x, since x is a variable defined in +the scope that equal_to_x is defined. We aren't allowed to do the same thing +that Listing 13-4 does with functions; let's see what happens if we try:

+

Filename: src/main.rs

+
fn main() {
+    let x = 4;
+
+    fn equal_to_x(z: i32) -> bool { z == x }
+
+    let y = 4;
+
+    assert!(equal_to_x(y));
+}
+
+

We get an error:

+
error[E0434]: can't capture dynamic environment in a fn item; use the || { ... }
+closure form instead
+ -->
+  |
+4 |     fn equal_to_x(z: i32) -> bool { z == x }
+  |                                          ^
+
+

The compiler even reminds us that this only works with closures!

+

Creating closures that capture values from their environment is mostly used in +the context of starting new threads. We'll show some more examples and explain +more detail about this feature of closures in Chapter 16 when we talk about +concurrency.

+

Closures as Function Parameters Using the Fn Traits

+

While we can bind closures to variables, that's not the most useful thing we +can do with them. We can also define functions that have closures as parameters +by using the Fn traits. Here's an example of a function named call_with_one +whose signature has a closure as a parameter:

+
fn call_with_one<F>(some_closure: F) -> i32
+    where F: Fn(i32) -> i32 {
+
+    some_closure(1)
+}
+
+let answer = call_with_one(|x| x + 2);
+
+assert_eq!(3, answer);
+
+

We pass the closure |x| x + 2, to call_with_one, and call_with_one calls +that closure with 1 as an argument. The return value of the call to +some_closure is then returned from call_with_one.

+

The signature of call_with_one is using the where syntax discussed in the +Traits section of Chapter 10. The some_closure parameter has the generic type +F, which in the where clause is defined as having the trait bounds +Fn(i32) -> i32. The Fn trait represents a closure, and we can add types to +the Fn trait to represent a specific type of closure. In this case, our +closure has a parameter of type i32 and returns an i32, so the generic bound +we specify is Fn(i32) -> i32.

+

Specifying a function signature that contains a closure requires the use of +generics and trait bounds. Each closure has a unique type, so we can't write +the type of a closure directly, we have to use generics.

+

Fn isn't the only trait bound available for specifying closures, however. +There are three: Fn, FnMut, and FnOnce. This continues the patterns of +threes we've seen elsewhere in Rust: borrowing, borrowing mutably, and +ownership. Using Fn specifies that the closure used may only borrow values in +its environment. To specify a closure that mutates the environment, use +FnMut, and if the closure takes ownership of the environment, FnOnce. Most +of the time, you can start with Fn, and the compiler will tell you if you +need FnMut or FnOnce based on what happens when the function calls the +closure.

+

To illustrate a situation where it's useful for a function to have a parameter +that's a closure, let's move on to our next topic: iterators.

Iterators

-

Iterator & for loop

-

.into_iter()

+

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:

+
+
let v1 = vec![1, 2, 3];
+
+let v2: Vec<i32> = v1.iter().map(|x| x + 1).collect();
+
+assert_eq!(v2, [2, 3, 4]);
+
+
+

Listing 13-5: Using an iterator, map, and collect to add one to each number +in a vector

+
+
+ +

The iter method on vectors allows us to produce an iterator from the +vector. Next, the map method called on the iterator allows us to process each +element: in this case, we've passed a closure to map that specifies for every +element x, add one to it. map is one of the most basic ways of interacting +with an iterator, as processing each element in turn is very useful! Finally, +the collect method consumes the iterator and puts the iterator's elements +into a new data structure. In this case, since we've said that v2 has the +type Vec<i32>, collect will create a new vector out of the i32 values.

+

Methods on iterators like map are sometimes called iterator adaptors +because they take one iterator and produce a new iterator. That is, map +builds on top of our previous iterator and produces another iterator by calling +the closure it's passed to create the new sequence of values.

+

So, to recap, this line of code does the following:

+
    +
  1. Creates an iterator from the vector.
  2. +
  3. Uses the map adaptor with a closure argument to add one to each element.
  4. +
  5. Uses the collect adaptor to consume the iterator and make a new vector.
  6. +
+

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

Iterators are Lazy

-

Difference between adapter and consumer - another iterator or consuming?

-

Implementing the Iterator trait

-

Talk about using Associated Types here, foreshadow to advanced type systems -chapter about why this is a different thing than normal

-

??? How does this improve the I/O project from Chapter 12

-

Does this get woven into the above sections?

-

Summary: Performance

-

Iterators compile down to ASM == for loop

-

Most complicated chain of iterator functions that compile down to the same ASM as a for loop

-

Representation: Closures are a Struct

-

Closures don't have any further performance penalty over regular fn calls

+

In the previous section, you may have noticed a subtle difference in wording: +we said that map adapts an iterator, but collect consumes one. That was +intentional. By themselves, iterators won't do anything; they're lazy. That is, +if we write code like Listing 13-5 except we don't call collect:

+
let v1: Vec<i32> = vec![1, 2, 3];
+
+v1.iter().map(|x| x + 1); // without collect
+
+

It will compile, but it will give us a warning:

+
warning: unused result which must be used: iterator adaptors are lazy and do
+nothing unless consumed, #[warn(unused_must_use)] on by default
+ --> src/main.rs:4:1
+  |
+4 | v1.iter().map(|x| x + 1); // without collect
+  | ^^^^^^^^^^^^^^^^^^^^^^^^^
+
+

We get this warning because iterator adaptors won't start actually doing the +processing on their own. They need some other method that causes the iterator +chain to evaluate. We call those consuming adaptors, and collect is one of +them.

+

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

+

The Iterator trait

+

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

+
trait Iterator {
+    type Item;
+
+    fn next(&mut self) -> Option<Self::Item>;
+}
+
+

There's some new syntax that we haven't covered here yet: type Item and +Self::Item are defining an associated type with this trait, and we'll talk +about associated types in depth in Chapter XX. For now, all you need to know is +that this code says the Iterator trait requires that you also define an +Item type, and this Item type is used in the return type of the next +method. In other words, the Item type will be the type of element that's +returned from the iterator.

+

Let's make an iterator named Counter that will count from 1 to 5, using +the Iterator trait. First, we need to create a struct that holds the current +state of the iterator, which is one field named count that will hold a u32. +We'll also define a new method, which isn't strictly necessary. We want our +Counter to go from one to five, though, so we're always going to have it +holding a zero to start:

+
struct Counter {
+    count: u32,
+}
+
+impl Counter {
+    fn new() -> Counter {
+        Counter { count: 0 }
+    }
+}
+
+

Next, we're going to implement the Iterator trait for our Counter type by +defining the body of the next method. The way we want our iterator to work +is to add one to the state (which is why we initialized count to 0, since we +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:

+
+
# struct Counter {
+#     count: u32,
+# }
+#
+impl Iterator for Counter {
+    // Our iterator will produce u32s
+    type Item = u32;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        // increment our count. This is why we started at zero.
+        self.count += 1;
+
+        // check to see if we've finished counting or not.
+        if self.count < 6 {
+            Some(self.count)
+        } else {
+            None
+        }
+    }
+}
+
+
+

Listing 13-6: Implementing the Iterator trait on our Counter struct

+
+
+ +

The type Item = u32 line is saying that the associated Item type will be +a u32 for our iterator. Again, don't worry about associated types yet, because +we'll be covering them in Chapter XX.

+

The next method is the main interface into an iterator, and it returns an +Option. If the option is Some(value), we have gotten another value from the +iterator. If it's None, iteration is finished. Inside of the next method, +we do whatever kind of calculation our iterator needs to do. In this case, we +add one, then check to see if we're still below six. If we are, we can return +Some(self.count) to produce the next value. If we're at six or more, +iteration is over, so we return None.

+

The iterator trait specifies that when an iterator returns None, that +indicates iteration is finished. The trait does not mandate anything about the +behavior an iterator must have if the next method is called again after +having returned one None value. In this case, every time we call next after +getting the first None value will still return None, but the internal +count field will continue to be incremented by one each time. If we call +next as many times as the maximum value a u32 value can hold, count will +overflow (which will panic! in debug mode and wrap in release mode). Other +iterator implementations choose to start iterating again. If you need to be +sure to have an iterator that will always return None on subsequent calls to +the next method after the first None value is returned, you can use the +fuse method to create an iterator with that characteristic out of any other +iterator.

+

Once we've implemented the Iterator trait, we have an iterator! We can use +the iterator functionality that our Counter struct now has by calling the +next method on it repeatedly:

+
let mut counter = Counter::new();
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+let x = counter.next();
+println!("{:?}", x);
+
+

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

+

All Sorts of Iterator Adaptors

+

In Listing 13-5, we had iterators and we called methods like map and +collect on them. In Listing 13-6, however, we only implemented the next +method on our Counter. How do we get methods like map and collect on our +Counter?

+

Well, when we told you about the definition of Iterator, we committed a small +lie of omission. The Iterator trait has a number of other useful methods +defined on it that come with default implementations that call the next +method. Since next is the only method of the Iterator trait that does not +have a default implementation, once you've done that, you get all of the other +Iterator adaptors for free. There are a lot of them!

+

For example, if for some reason we wanted to take the first five values that +an instance of Counter produces, pair those values with values produced by +another Counter instance after skipping the first value that instance +produces, multiply each pair together, keep only those results that are +divisible by three, and add all the resulting values together, we could do:

+
let sum: u32 = Counter::new().take(5)
+                             .zip(Counter::new().skip(1))
+                             .map(|(a, b)| a * b)
+                             .filter(|x| x % 3 == 0)
+                             .sum();
+assert_eq!(48, sum);
+
+

All of these method calls are possible because we implemented the Iterator +trait by specifying how the next method works. Use the standard library +documentation to find more useful methods that will come in handy when you're +working with iterators.

+

Improving our I/O Project

+

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

+

Removing a clone by Using an Iterator

+

Back in listing 12-8, we had this code that took a slice of String values and +created an instance of the Config struct by checking for the right number of +arguments, indexing into the slice, and cloning the values so that the Config +struct could own those values:

+
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,
+        })
+    }
+}
+
+

At the time, we said not to worry about the clone calls here, and that we +could remove them in the future. Well, that time is now! So, why do we need +clone here? The issue is that we have a slice with String elements in the +parameter args, and the new function does not own args. In order to be +able to return ownership of a Config instance, we need to clone the values +that we put in the search and filename fields of Config, so that the +Config instance can own its values.

+

Now that we know more about iterators, we can change the new function to +instead take ownership of an iterator as its argument. We'll use the iterator +functionality instead of having to check the length of the slice and index into +specific locations. Since we've taken ownership of the iterator, and we won't be +using indexing operations that borrow anymore, we can move the String values +from the iterator into Config instead of calling clone and making a new +allocation.

+

First, let's take main as it was in Listing 12-6, and change it to pass the +return value of env::args to Config::new, instead of calling collect and +passing a slice:

+
fn main() {
+    let config = Config::new(env::args());
+    // ...snip...
+
+ +

If we look in the standard library documentation for the env::args function, +we'll see that its return type is std::env::Args. So next we'll update the +signature of the Config::new function so that the parameter args has the +type std::env::Args instead of &[String]:

+
impl Config {
+    fn new(args: std::env::Args) -> Result<Config, &'static str> {
+        // ...snip...
+
+ +

Next, we'll fix the body of Config::new. As we can also see in the standard +library documentation, std::env::Args implements the Iterator trait, so we +know we can call the next method on it! Here's the new code:

+
# struct Config {
+#     search: String,
+#     filename: String,
+# }
+#
+impl Config {
+    fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
+        args.next();
+
+        let search = match args.next() {
+            Some(arg) => arg,
+            None => return Err("Didn't get a search string"),
+        };
+
+        let filename = match args.next() {
+            Some(arg) => arg,
+            None => return Err("Didn't get a file name"),
+        };
+
+        Ok(Config {
+            search: search,
+            filename: filename,
+        })
+    }
+}
+
+ +

Remember that the first value in the return value of env::args is the name of +the program. We want to ignore that, so first we'll call next and not do +anything with the return value. The second time we call next should be the +value we want to put in the search field of Config. We use a match to +extract the value if next returns a Some, and we return early with an Err +value if there weren't enough arguments (which would cause this call to next +to return None).

+

We do the same thing for the filename value. It's slightly unfortunate that +the match expressions for search and filename are so similar. It would be +nice if we could use ? on the Option returned from next, but ? only +works with Result values currently. Even if we could use ? on Option like +we can on Result, the value we would get would be borrowed, and we want to +move the String from the iterator into Config.

+

Making Code Clearer with Iterator Adaptors

+

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

+ +
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+    let mut results = Vec::new();
+
+    for line in contents.lines() {
+        if line.contains(search) {
+            results.push(line);
+        }
+    }
+
+    results
+}
+
+

We can write this code in a much shorter way, and avoiding having to have a +mutable intermediate results vector, by using iterator adaptor methods like +this instead:

+
fn grep<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+    contents.lines()
+        .filter(|line| line.contains(search))
+        .collect()
+}
+
+

Here, we use the filter adaptor to only keep the lines that +line.contains(search) returns true for. We then collect them up into another +vector with collect. Much simpler!

+

We can use the same technique in the grep_case_insensitive function that we +defined in Listing 12-16 as follows:

+ +
fn grep_case_insensitive<'a>(search: &str, contents: &'a str) -> Vec<&'a str> {
+    contents.lines()
+        .filter(|line| {
+            line.to_lowercase().contains(&search)
+        }).collect()
+}
+
+

Not too bad! So which style should you choose? Most Rust programmers prefer to +use the iterator style. It's a bit tougher to understand at first, but once you +gain an intuition for what the various iterator adaptors do, this is much +easier to understand. Instead of fiddling with the various bits of looping +and building a new vector, the code focuses on the high-level objective of the +loop, abstracting some of the commonplace code so that it's easier to see the +concepts that are unique to this usage of the code, like the condition on which +the code is filtering each element in the iterator.

+

But are they truly equivalent? Surely the more low-level loop will be faster. +Let's talk about performance.

+

Performance

+

Which version of our grep functions is faster: the version with an explicit +for loop or the version with iterators? We ran a benchmark by loading the +entire contents of "The Adventures of Sherlock Holmes" by Sir Arthur Conan +Doyle into a String and looking for the word "the" in the contents. Here were +the results of the benchmark on the version of grep using the for loop and the +version using iterators:

+
test bench_grep_for  ... bench:  19,620,300 ns/iter (+/- 915,700)
+test bench_grep_iter ... bench:  19,234,900 ns/iter (+/- 657,200)
+
+

The iterator version ended up slightly faster! We're not going to go through +the benchmark code here, as the point is not to prove that they're exactly +equivalent, but to get a general sense of how these two implementations +compare. For a real benchmark, you'd want to check various texts of various +sizes, different words, words of different lengths, and all kinds of other +variations. The point is this: iterators, while a high-level abstraction, get +compiled down to roughly the same code as if you'd written the lower-level code +yourself. Iterators are one of Rust's zero-cost abstractions, by which we mean +using the abstraction imposes no additional runtime overhead in the same way +that Bjarne Stroustrup, the original designer and implementer of C++, defines +zero-overhead:

+
+

In general, C++ implementations obey the zero-overhead principle: What you +don’t use, you don’t pay for. And further: What you do use, you couldn’t hand +code any better.

+
    +
  • Bjarne Stroustrup "Foundations of C++"
  • +
+
+

As another example, here is some code taken from an audio decoder. This code +uses an iterator chain to do some math on three variables in scope: a buffer +slice of data, an array of 12 coefficients, and an amount by which to shift +data in qlp_shift. We've declared the variables within this example but not +given them any values; while this code doesn't have much meaning outside of its +context, it's still a concise, real-world example of how Rust translates +high-level ideas to low-level code:

+
let buffer: &mut [i32];
+let coefficients: [i64; 12];
+let qlp_shift: i16;
+
+for i in 12..buffer.len() {
+    let prediction = coefficients.iter()
+                                 .zip(&buffer[i - 12..i])
+                                 .map(|(&c, &s)| c * s as i64)
+                                 .sum::<i64>() >> qlp_shift;
+    let delta = buffer[i];
+    buffer[i] = prediction as i32 + delta;
+}
+
+

In order to calculate the value of prediction, this code iterates through +each of the 12 values in coefficients, uses the zip method to pair the +coefficient values with the previous 12 values in buffer. Then for each pair, +multiply the values together, sum all the results, and shift the bits in the +sum qlp_shift bits to the right

+

Calculations in applications like audio decoders often prioritize performance +most highly. Here, we're creating an iterator, using two adaptors, then +consuming the value. What assembly code would this Rust code compile to? Well, +as of this writing, it compiles down to the same assembly you'd write by hand. +There's no loop at all corresponding to the iteration over the values in +coefficients: Rust knows that there are twelve iterations, so it "unrolls" +the loop. All of the coefficients get stored in registers (which means +accessing the values is very fast). There are no bounds checks on the array +access. It's extremely efficient.

+

Now that you know this, go use iterators and closures without fear! They make +code feel higher-level, but don't impose a runtime performance penalty for +doing so.

+

Summary

+

Closures and iterators are Rust features inspired by functional programming +language ideas. They contribute to Rust's ability to clearly express high-level +ideas. The implementations of closures and iterators, as well as other zero-cost +abstractions in Rust, are such that runtime performance is not affected.

+

Now that we've improved the expressiveness of our I/O project, let's look at +some more features of cargo that would help us get ready to share the project +with the world.

More about Cargo and Crates.io

We've used some features of Cargo in this book so far, but only the most basic ones. We've used Cargo to build, run, and test our code, but it can do a lot @@ -11082,6 +11712,192 @@ 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 +also subject to all of the usual rules around ownership and borrowing. Since +closures attempt to infer the types of their parameters, they also infer how +those parameters are borrowed. Closures make that inference by looking at how +they are used. Consider the example in Listing 13-5 that has functions that +borrow immutably, borrow mutably, and move their parameters, then closures that +reference values from their environment and call each of the functions. We'll +see how this affects inference of when a value is borrowed:

+
+Filename: src/main.rs +
#[derive(Debug)]
+struct Foo;
+
+fn borrows(f: &Foo) {
+    println!("Took {:?} by reference.", f);
+}
+
+fn borrows_mut(f: &mut Foo) {
+    println!("Took {:?} by mutable reference.", f);
+}
+
+fn moves(f: Foo) {
+    println!("Took ownership of {:?}.", f);
+}
+
+fn main() {
+    let f1 = Foo;
+    let closure_that_borrows = |x| borrows(x);
+    closure_that_borrows(&f1);
+
+    let mut f2 = Foo;
+    let closure_that_borrows_mut = |y| borrows_mut(y);
+    closure_that_borrows_mut(&mut f2);
+
+    let f3 = Foo;
+    let closure_that_moves = |z| moves(z);
+    closure_that_moves(f3);
+}
+
+
+

Listing 16-something: Closures that borrow, borrow mutably, and take ownership +of their parameters, which is inferred from how the closure body uses the +parameters

+
+
+

Here, Rust is able to look at how we use the parameters of each closure inside +their bodies. If the closure passes its parameter it to a function that takes +&Foo, then the type of the parameter must be &Foo. If it passes the +parameter to a function that takes &mut Foo, then the type of parameter must +be &mut Foo, and so on. If we try to use f3 after the call to +closure_that_moves in the last line of main, we'll get a compiler error +since ownership of f3 was transferred to closure_that_moves, which +transferred ownership to the function moves.

+

Overriding Inferred Borrowing with the move Keyword

+

Rust will allow you to override the borrowing inference by using the move +keyword. This will cause all of the closure's parameters to be taken by +ownership, instead of whatever they were inferred as. Consider this example:

+
let mut num = 4;
+
+{
+    let mut add_num = |x| num += x;
+
+    add_num(6);
+}
+
+assert_eq!(10, num);
+
+

In this case, the add_num closure took a mutable reference to num, then +when we called add_num, it mutated the underlying value. In the last line, +num contains 10, as we'd expect. We also needed to declare add_num itself +as mut too, because we're mutating its environment.

+

If we change the definition of add_num to a move closure, the behavior is +different:

+
let mut num = 4;
+
+{
+    let mut add_num = move |x| num += x;
+
+    add_num(6);
+}
+
+assert_eq!(4, num);
+
+

In the last line, num now contains 4: add_num took ownership of a copy of +num, rather than mutably borrowing num.

+

One of the most common places you'll see the move keyword used is with +threads, since it's important that one thread is no longer allowed to use a +value once the value has been transferred to another thread through a closure +in order to prevent data races. We'll talk more about that in Chapter XX.

+

Closures and Lifetimes

+

Remember Listing 10-8 from the Lifetime Syntax section of Chapter 10? It looked +like this:

+
{
+    let r;
+
+    {
+        let x = 5;
+        r = &x;
+    }
+
+    println!("r: {}", r);
+}
+
+

This example doesn't compile since x doesn't have a long enough lifetime. +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:

+
+
{
+    let closure;
+
+    {
+        let x = 4;
+
+        closure = || x ; // A closure that takes no arguments and returns x.
+    }
+}
+
+
+

Listing 16-something: A closure that tries to return a borrowed value that does +not live long enough

+
+
+

We get an error because x does not live long enough:

+
error: `x` does not live long enough
+  -->
+   |
+8  |         closure = || x ; // A closure that takes no arguments and returns x.
+   |                   -- ^ does not live long enough
+   |                   |
+   |                   capture occurs here
+9  |     }
+   |     - borrowed value only lives until here
+10 | }
+   | - borrowed value needs to live until here
+
+

To fix the error in the code in Listing 13-6, we can use the move keyword +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:

+
+
{
+    let closure;
+
+    {
+        let mut x = 4;
+
+        closure = move || x ; // A closure that takes no arguments and returns x.
+
+        x = 5;
+
+        assert_eq!(closure(), 4);
+    }
+}
+
+
+

Listing 16-something: Moving a value into the closure to fix the lifetime error

+
+
+

Even though we modified x between the closure definition and assert_eq!, +since closure now has its own version, the changes to x won't change the +version of x that's in the closure.

+

Rust doesn't provide a way to say that some values a closure uses should be +borrowed and some should be moved; it's either all by inference or all moved by +adding the move keyword. However, we can accomplish the goal of borrowing +some values and taking ownership of others by combining move with some extra +bindings. Consider this example where we want to borrow s1 but take ownership +of s2:

+
let s1 = String::from("hello");
+let s2 = String::from("goodbye");
+
+let r = &s1;
+
+let calculation = move || {
+    r;
+    s2;
+};
+
+println!("Can still use s1 here but not s2: {}", s1);
+
+

We've declared calculation to move all the values it references. Before +defining calculation, we declare a new variable r that borrows s1. Then +in the body of the calculation closure, we use r instead of using s1 +directly. The closure takes ownership of r, but r is a reference, so the +closure hasn't taken ownership of s1 even though calculation uses move.

Channels

Look up examples of cases where channels are useful

Can match modeling of certain problems