diff --git a/ci/dictionary.txt b/ci/dictionary.txt
index d8aeaa8a43..c83a6268d0 100644
--- a/ci/dictionary.txt
+++ b/ci/dictionary.txt
@@ -168,6 +168,7 @@ eprintln
Erlang
ErrorKind
Español
+ETAPS
eval
executables
ExitCode
@@ -624,6 +625,7 @@ wasi
wasn
weakt
WeatherForecast
+webpage
WebSocket
whitespace
wildcard
diff --git a/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs
index 06b1a03e1f..87db05b619 100644
--- a/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs
+++ b/listings/ch11-writing-automated-tests/no-listing-10-result-in-tests/src/lib.rs
@@ -2,11 +2,11 @@ pub fn add(left: u64, right: u64) -> u64 {
left + right
}
+// ANCHOR: here
#[cfg(test)]
mod tests {
use super::*;
- // ANCHOR: here
#[test]
fn it_works() -> Result<(), String> {
let result = add(2, 2);
@@ -17,5 +17,5 @@ mod tests {
Err(String::from("two plus two does not equal four"))
}
}
- // ANCHOR_END: here
}
+// ANCHOR_END: here
diff --git a/listings/ch15-smart-pointers/listing-15-14/output.txt b/listings/ch15-smart-pointers/listing-15-14/output.txt
index 1393d44b33..939bc7f458 100644
--- a/listings/ch15-smart-pointers/listing-15-14/output.txt
+++ b/listings/ch15-smart-pointers/listing-15-14/output.txt
@@ -2,6 +2,6 @@ $ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/drop-example`
-CustomSmartPointers created.
+CustomSmartPointers created
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
diff --git a/listings/ch15-smart-pointers/listing-15-14/src/main.rs b/listings/ch15-smart-pointers/listing-15-14/src/main.rs
index 231612ae62..bcf95160f6 100644
--- a/listings/ch15-smart-pointers/listing-15-14/src/main.rs
+++ b/listings/ch15-smart-pointers/listing-15-14/src/main.rs
@@ -15,5 +15,5 @@ fn main() {
let d = CustomSmartPointer {
data: String::from("other stuff"),
};
- println!("CustomSmartPointers created.");
+ println!("CustomSmartPointers created");
}
diff --git a/listings/ch15-smart-pointers/listing-15-15/src/main.rs b/listings/ch15-smart-pointers/listing-15-15/src/main.rs
index ff3b391a91..5fddbac967 100644
--- a/listings/ch15-smart-pointers/listing-15-15/src/main.rs
+++ b/listings/ch15-smart-pointers/listing-15-15/src/main.rs
@@ -13,8 +13,8 @@ fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
- println!("CustomSmartPointer created.");
+ println!("CustomSmartPointer created");
c.drop();
- println!("CustomSmartPointer dropped before the end of main.");
+ println!("CustomSmartPointer dropped before the end of main");
}
// ANCHOR_END: here
diff --git a/listings/ch15-smart-pointers/listing-15-16/output.txt b/listings/ch15-smart-pointers/listing-15-16/output.txt
index f032d84b6b..ae2ed04d08 100644
--- a/listings/ch15-smart-pointers/listing-15-16/output.txt
+++ b/listings/ch15-smart-pointers/listing-15-16/output.txt
@@ -2,6 +2,6 @@ $ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s
Running `target/debug/drop-example`
-CustomSmartPointer created.
+CustomSmartPointer created
Dropping CustomSmartPointer with data `some data`!
-CustomSmartPointer dropped before the end of main.
+CustomSmartPointer dropped before the end of main
diff --git a/listings/ch15-smart-pointers/listing-15-16/src/main.rs b/listings/ch15-smart-pointers/listing-15-16/src/main.rs
index f11715c45e..af62879976 100644
--- a/listings/ch15-smart-pointers/listing-15-16/src/main.rs
+++ b/listings/ch15-smart-pointers/listing-15-16/src/main.rs
@@ -13,8 +13,8 @@ fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
- println!("CustomSmartPointer created.");
+ println!("CustomSmartPointer created");
drop(c);
- println!("CustomSmartPointer dropped before the end of main.");
+ println!("CustomSmartPointer dropped before the end of main");
}
// ANCHOR_END: here
diff --git a/listings/ch15-smart-pointers/listing-15-25/src/main.rs b/listings/ch15-smart-pointers/listing-15-25/src/main.rs
index f36c7fd06d..6051014de7 100644
--- a/listings/ch15-smart-pointers/listing-15-25/src/main.rs
+++ b/listings/ch15-smart-pointers/listing-15-25/src/main.rs
@@ -1,3 +1,4 @@
+// ANCHOR: here
use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;
@@ -16,5 +17,6 @@ impl List {
}
}
}
+// ANCHOR_END: here
fn main() {}
diff --git a/nostarch/appendix.md b/nostarch/appendix.md
index 7a2a964f3a..53b7739821 100644
--- a/nostarch/appendix.md
+++ b/nostarch/appendix.md
@@ -13,10 +13,10 @@ Rust journey.
## Appendix A: Keywords
-The following list contains keywords that are reserved for current or future
+The following lists contain keywords that are reserved for current or future
use by the Rust language. As such, they cannot be used as identifiers (except
-as raw identifiers as we’ll discuss in the “Raw
-Identifiers” section). Identifiers are names
+as raw identifiers, as we discuss in the “Raw
+Identifiers” section). *Identifiers* are names
of functions, variables, parameters, struct fields, modules, crates, constants,
macros, static values, attributes, types, traits, or lifetimes.
@@ -25,54 +25,55 @@ macros, static values, attributes, types, traits, or lifetimes.
The following is a list of keywords currently in use, with their functionality
described.
-* `as` - perform primitive casting, disambiguate the specific trait containing
- an item, or rename items in `use` statements
-* `async` - return a `Future` instead of blocking the current thread
-* `await` - suspend execution until the result of a `Future` is ready
-* `break` - exit a loop immediately
-* `const` - define constant items or constant raw pointers
-* `continue` - continue to the next loop iteration
-* `crate` - in a module path, refers to the crate root
-* `dyn` - dynamic dispatch to a trait object
-* `else` - fallback for `if` and `if let` control flow constructs
-* `enum` - define an enumeration
-* `extern` - link an external function or variable
-* `false` - Boolean false literal
-* `fn` - define a function or the function pointer type
-* `for` - loop over items from an iterator, implement a trait, or specify a
- higher-ranked lifetime
-* `if` - branch based on the result of a conditional expression
-* `impl` - implement inherent or trait functionality
-* `in` - part of `for` loop syntax
-* `let` - bind a variable
-* `loop` - loop unconditionally
-* `match` - match a value to patterns
-* `mod` - define a module
-* `move` - make a closure take ownership of all its captures
-* `mut` - denote mutability in references, raw pointers, or pattern bindings
-* `pub` - denote public visibility in struct fields, `impl` blocks, or modules
-* `ref` - bind by reference
-* `return` - return from function
-* `Self` - a type alias for the type we are defining or implementing
-* `self` - method subject or current module
-* `static` - global variable or lifetime lasting the entire program execution
-* `struct` - define a structure
-* `super` - parent module of the current module
-* `trait` - define a trait
-* `true` - Boolean true literal
-* `type` - define a type alias or associated type
-* `union` - define a union; is only a keyword when used
- in a union declaration
-* `unsafe` - denote unsafe code, functions, traits, or implementations
-* `use` - bring symbols into scope; specify precise captures for generic and
- lifetime bounds
-* `where` - denote clauses that constrain a type
-* `while` - loop conditionally based on the result of an expression
+* **`as`**: Perform primitive casting, disambiguate the specific trait
+ containing an item, or rename items in `use` statements.
+* **`async`**: Return a `Future` instead of blocking the current thread.
+* **`await`**: Suspend execution until the result of a `Future` is ready.
+* **`break`**: Exit a loop immediately.
+* **`const`**: Define constant items or constant raw pointers.
+* **`continue`**: Continue to the next loop iteration.
+* **`crate`**: In a module path, refers to the crate root.
+* **`dyn`**: Dynamic dispatch to a trait object.
+* **`else`**: Fallback for `if` and `if let` control flow constructs.
+* **`enum`**: Define an enumeration.
+* **`extern`**: Link an external function or variable.
+* **`false`**: Boolean false literal.
+* **`fn`**: Define a function or the function pointer type.
+* **`for`**: Loop over items from an iterator, implement a trait, or specify a
+ higher ranked lifetime.
+* **`if`**: Branch based on the result of a conditional expression.
+* **`impl`**: Implement inherent or trait functionality.
+* **`in`**: Part of `for` loop syntax.
+* **`let`**: Bind a variable.
+* **`loop`**: Loop unconditionally.
+* **`match`**: Match a value to patterns.
+* **`mod`**: Define a module.
+* **`move`**: Make a closure take ownership of all its captures.
+* **`mut`**: Denote mutability in references, raw pointers, or pattern bindings.
+* **`pub`**: Denote public visibility in struct fields, `impl` blocks, or
+ modules.
+* **`ref`**: Bind by reference.
+* **`return`**: Return from function.
+* **`Self`**: A type alias for the type we are defining or implementing.
+* **`self`**: Method subject or current module.
+* **`static`**: Global variable or lifetime lasting the entire program
+ execution.
+* **`struct`**: Define a structure.
+* **`super`**: Parent module of the current module.
+* **`trait`**: Define a trait.
+* **`true`**: Boolean true literal.
+* **`type`**: Define a type alias or associated type.
+* **`union`**: Define a union; is a keyword only when
+ used in a union declaration.
+* **`unsafe`**: Denote unsafe code, functions, traits, or implementations.
+* **`use`**: Bring symbols into scope.
+* **`where`**: Denote clauses that constrain a type.
+* **`while`**: Loop conditionally based on the result of an expression.
### Keywords Reserved for Future Use
The following keywords do not yet have any functionality but are reserved by
-Rust for potential future use.
+Rust for potential future use:
* `abstract`
* `become`
@@ -140,10 +141,10 @@ identifier names, as well as lets us integrate with programs written in a
language where these words aren’t keywords. In addition, raw identifiers allow
you to use libraries written in a different Rust edition than your crate uses.
For example, `try` isn’t a keyword in the 2015 edition but is in the 2018, 2021,
-and 2024 editions. If you depend on a library that’s written using the 2015
+and 2024 editions. If you depend on a library that is written using the 2015
edition and has a `try` function, you’ll need to use the raw identifier syntax,
-`r#try` in this case, to call that function from your 2018 edition code. See
-Appendix E for more information on editions.
+`r#try` in this case, to call that function from your code on later editions.
+See Appendix E for more information on editions.
## Appendix B: Operators and Symbols
@@ -186,7 +187,7 @@ Table B-1: Operators
|`->`|`fn(...) -> type`, \|...\| -> type
|Function and closure return type||
|`.`|`expr.ident`|Field access||
|`.`|`expr.ident(expr, ...)`|Method call||
-|`.`|`expr.0`, `expr.1`, etc.|Tuple indexing||
+|`.`|`expr.0`, `expr.1`, and so on|Tuple indexing||
|`..`|`..`, `expr..`, `..expr`, `expr..expr`|Right-exclusive range literal|`PartialOrd`|
|`..=`|`..=expr`, `expr..=expr`|Right-inclusive range literal|`PartialOrd`|
|`..`|`..expr`|Struct literal update syntax||
@@ -221,26 +222,26 @@ Table B-1: Operators
### Non-operator Symbols
-The following list contains all symbols that don’t function as operators; that
+The following tables contain all symbols that don’t function as operators; that
is, they don’t behave like a function or method call.
Table B-2 shows symbols that appear on their own and are valid in a variety of
locations.
-Table B-2: Stand-Alone Syntax
+Table B-2: Stand-alone Syntax
|Symbol|Explanation|
|------|-----------|
|`'ident`|Named lifetime or loop label|
-|Digits immediately followed by `u8`, `i32`, `f64`, `usize`, and so on|Numeric literal of specific type|
+|Digits immediately followed by `u8`, `i32`, `f64`, `usize`, and so on|Numeric literal of specific type|
|`"..."`|String literal|
-|`r"..."`, `r#"..."#`, `r##"..."##`, etc.|Raw string literal, escape characters not processed|
+|`r"..."`, `r#"..."#`, `r##"..."##`, and so on|Raw string literal; escape characters not processed|
|`b"..."`|Byte string literal; constructs an array of bytes instead of a string|
-|`br"..."`, `br#"..."#`, `br##"..."##`, etc.|Raw byte string literal, combination of raw and byte string literal|
+|`br"..."`, `br#"..."#`, `br##"..."##`, and so on|Raw byte string literal; combination of raw and byte string literal|
|`'...'`|Character literal|
|`b'...'`|ASCII byte literal|
|\|...\| expr
|Closure|
-|`!`|Always empty bottom type for diverging functions|
+|`!`|Always-empty bottom type for diverging functions|
|`_`|“Ignored” pattern binding; also used to make integer literals readable|
Table B-3 shows symbols that appear in the context of a path through the module
@@ -251,11 +252,11 @@ Table B-3: Path-Related Syntax
|Symbol|Explanation|
|------|-----------|
|`ident::ident`|Namespace path|
-|`::path`|Path relative to the extern prelude, where all other crates are rooted (i.e., an explicitly absolute path including crate name)|
-|`self::path`|Path relative to the current module (i.e., an explicitly relative path).|
+|`::path`|Path relative to the crate root (that is, an explicitly absolute path)|
+|`self::path`|Path relative to the current module (that is, an explicitly relative path)|
|`super::path`|Path relative to the parent of the current module|
|`type::ident`, `::ident`|Associated constants, functions, and types|
-|`::...`|Associated item for a type that cannot be directly named (e.g., `<&T>::...`, `<[T]>::...`, etc.)|
+|`::...`|Associated item for a type that cannot be directly named (for example, `<&T>::...`, `<[T]>::...`, and so on)|
|`trait::method(...)`|Disambiguating a method call by naming the trait that defines it|
|`type::method(...)`|Disambiguating a method call by naming the type for which it’s defined|
|`::method(...)`|Disambiguating a method call by naming the trait and type|
@@ -267,14 +268,14 @@ Table B-4: Generics
|Symbol|Explanation|
|------|-----------|
-|`path<...>`|Specifies parameters to generic type in a type (e.g., `Vec`)|
-|`path::<...>`, `method::<...>`|Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., `"42".parse::()`)|
+|`path<...>`|Specifies parameters to a generic type in a type (for example, `Vec`)|
+|`path::<...>`, `method::<...>`|Specifies parameters to a generic type, function, or method in an expression; often referred to as *turbofish* (for example, `"42".parse::()`)|
|`fn ident<...> ...`|Define generic function|
|`struct ident<...> ...`|Define generic structure|
|`enum ident<...> ...`|Define generic enumeration|
|`impl<...> ...`|Define generic implementation|
-|`for<...> type`|Higher-ranked lifetime bounds|
-|`type`|A generic type where one or more associated types have specific assignments (e.g., `Iterator- `)|
+|`for<...> type`|Higher ranked lifetime bounds|
+|`type`|A generic type where one or more associated types have specific assignments (for example, `Iterator
- `)|
Table B-5 shows symbols that appear in the context of constraining generic type
parameters with trait bounds.
@@ -331,7 +332,7 @@ Table B-8: Parentheses
|`(type, ...)`|Tuple type|
|`expr(expr, ...)`|Function call expression; also used to initialize tuple `struct`s and tuple `enum` variants|
-Table B-9 shows the contexts in which curly braces are used.
+Table B-9 shows the contexts in which curly brackets are used.
Table B-9: Curly Brackets
@@ -349,7 +350,7 @@ Table B-10: Square Brackets
|`[...]`|Array literal|
|`[expr; len]`|Array literal containing `len` copies of `expr`|
|`[type; len]`|Array type containing `len` instances of `type`|
-|`expr[expr]`|Collection indexing. Overloadable (`Index`, `IndexMut`)|
+|`expr[expr]`|Collection indexing; overloadable (`Index`, `IndexMut`)|
|`expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]`|Collection indexing pretending to be collection slicing, using `Range`, `RangeFrom`, `RangeTo`, or `RangeFull` as the “index”|
## Appendix C: Derivable Traits
@@ -370,9 +371,9 @@ library that you can use with `derive`. Each section covers:
If you want different behavior from that provided by the `derive` attribute,
consult the standard library documentation
-for each trait for details of how to manually implement them.
+for each trait for details on how to manually implement them.
-These traits listed here are the only ones defined by the standard library that
+The traits listed here are the only ones defined by the standard library that
can be implemented on your types using `derive`. Other traits defined in the
standard library don’t have sensible default behavior, so it’s up to you to
implement them in the way that makes sense for what you’re trying to accomplish.
@@ -385,10 +386,10 @@ would be most relevant to them? The Rust compiler doesn’t have this insight, s
it can’t provide appropriate default behavior for you.
The list of derivable traits provided in this appendix is not comprehensive:
-libraries can implement `derive` for their own traits, making the list of
-traits you can use `derive` with truly open-ended. Implementing `derive`
-involves using a procedural macro, which is covered in the
-“Macros” section of Chapter 20.
+Libraries can implement `derive` for their own traits, making the list of
+traits you can use `derive` with truly open ended. Implementing `derive`
+involves using a procedural macro, which is covered in the “Custom `derive`
+Macros” section in Chapter 20.
### Debug for Programmer Output
@@ -399,9 +400,10 @@ The `Debug` trait allows you to print instances of a type for debugging
purposes, so you and other programmers using your type can inspect an instance
at a particular point in a program’s execution.
-The `Debug` trait is required, for example, in using the `assert_eq!` macro.
-This macro prints the values of instances given as arguments if the equality
-assertion fails so programmers can see why the two instances weren’t equal.
+The `Debug` trait is required, for example, in the use of the `assert_eq!`
+macro. This macro prints the values of instances given as arguments if the
+equality assertion fails so that programmers can see why the two instances
+weren’t equal.
### PartialEq and Eq for Equality Comparisons
@@ -410,7 +412,7 @@ equality and enables use of the `==` and `!=` operators.
Deriving `PartialEq` implements the `eq` method. When `PartialEq` is derived on
structs, two instances are equal only if *all* fields are equal, and the
-instances are not equal if any fields are not equal. When derived on enums,
+instances are not equal if *any* fields are not equal. When derived on enums,
each variant is equal to itself and not equal to the other variants.
The `PartialEq` trait is required, for example, with the use of the
@@ -420,12 +422,12 @@ for equality.
The `Eq` trait has no methods. Its purpose is to signal that for every value of
the annotated type, the value is equal to itself. The `Eq` trait can only be
applied to types that also implement `PartialEq`, although not all types that
-implement `PartialEq` can implement `Eq`. One example of this is floating point
-number types: the implementation of floating point numbers states that two
+implement `PartialEq` can implement `Eq`. One example of this is floating-point
+number types: The implementation of floating-point numbers states that two
instances of the not-a-number (`NaN`) value are not equal to each other.
-An example of when `Eq` is required is for keys in a `HashMap` so the
-`HashMap` can tell whether two keys are the same.
+An example of when `Eq` is required is for keys in a `HashMap` so that
+the `HashMap` can tell whether two keys are the same.
### PartialOrd and Ord for Ordering Comparisons
@@ -438,8 +440,8 @@ Deriving `PartialOrd` implements the `partial_cmp` method, which returns an
`Option` that will be `None` when the values given don’t produce an
ordering. An example of a value that doesn’t produce an ordering, even though
most values of that type can be compared, is the `NaN` floating point value.
-Calling `partial_cmp` with any floating point number and the `NaN` floating
-point value will return `None`.
+Calling `partial_cmp` with any floating-point number and the `NaN`
+floating-point value will return `None`.
When derived on structs, `PartialOrd` compares two instances by comparing the
value in each field in the order in which the fields appear in the struct
@@ -465,9 +467,9 @@ a data structure that stores data based on the sort order of the values.
The `Clone` trait allows you to explicitly create a deep copy of a value, and
the duplication process might involve running arbitrary code and copying heap
-data. See Variables and Data Interacting with
-Clone” in Chapter 4
-for more information on `Clone`.
+data. See the “Variables and Data Interacting with
+Clone” section in
+Chapter 4 for more information on `Clone`.
Deriving `Clone` implements the `clone` method, which when implemented for the
whole type, calls `clone` on each of the parts of the type. This means all the
@@ -479,9 +481,9 @@ returned from `to_vec` will need to own its instances, so `to_vec` calls
`clone` on each item. Thus, the type stored in the slice must implement `Clone`.
The `Copy` trait allows you to duplicate a value by only copying bits stored on
-the stack; no arbitrary code is necessary. See “Stack-Only Data:
-Copy” in Chapter 4 for more information on
-`Copy`.
+the stack; no arbitrary code is necessary. See the “Stack-Only Data:
+Copy” section in Chapter 4 for more
+information on `Copy`.
The `Copy` trait doesn’t define any methods to prevent programmers from
overloading those methods and violating the assumption that no arbitrary code
@@ -489,7 +491,7 @@ is being run. That way, all programmers can assume that copying a value will be
very fast.
You can derive `Copy` on any type whose parts all implement `Copy`. A type that
-implements `Copy` must also implement `Clone`, because a type that implements
+implements `Copy` must also implement `Clone` because a type that implements
`Copy` has a trivial implementation of `Clone` that performs the same task as
`Copy`.
@@ -520,10 +522,10 @@ meaning all fields or values in the type must also implement `Default` to
derive `Default`.
The `Default::default` function is commonly used in combination with the struct
-update syntax discussed in “Creating Instances From Other Instances With Struct
-Update
-Syntax” in Chapter 5. You can customize a few fields of a struct and then set
-and use a default value for the rest of the fields by using
+update syntax discussed in the “Creating Instances from Other Instances with
+Struct Update
+Syntax” section in Chapter 5. You can customize a few fields of a struct and
+then set and use a default value for the rest of the fields by using
`..Default::default()`.
The `Default` trait is required when you use the method `unwrap_or_default` on
@@ -531,7 +533,7 @@ The `Default` trait is required when you use the method `unwrap_or_default` on
`unwrap_or_default` will return the result of `Default::default` for the type
`T` stored in the `Option`.
-## Appendix D - Useful Development Tools
+## Appendix D: Useful Development Tools
In this appendix, we talk about some useful development tools that the Rust
project provides. We’ll look at automatic formatting, quick ways to apply
@@ -541,11 +543,11 @@ warning fixes, a linter, and integrating with IDEs.
The `rustfmt` tool reformats your code according to the community code style.
Many collaborative projects use `rustfmt` to prevent arguments about which
-style to use when writing Rust: everyone formats their code using the tool.
+style to use when writing Rust: Everyone formats their code using the tool.
Rust installations include `rustfmt` by default, so you should already have the
programs `rustfmt` and `cargo-fmt` on your system. These two commands are
-analogous to `rustc` and `cargo` in that `rustfmt` allows finer-grained control
+analogous to `rustc` and `cargo` in that `rustfmt` allows finer grained control
and `cargo-fmt` understands conventions of a project that uses Cargo. To format
any Cargo project, enter the following:
@@ -559,10 +561,10 @@ on `rustfmt`, see its documentation at *https://github.com/rust-lang/rustfmt*.
### Fix Your Code with rustfix
-The `rustfix` tool is included with Rust installations and can automatically fix
-compiler warnings that have a clear way to correct the problem that’s likely
-what you want. You’ve probably seen compiler warnings before. For example,
-consider this code:
+The `rustfix` tool is included with Rust installations and can automatically
+fix compiler warnings that have a clear way to correct the problem that’s
+likely what you want. You’ve probably seen compiler warnings before. For
+example, consider this code:
Filename: src/main.rs
@@ -615,13 +617,13 @@ fn main() {
The variable `x` is now immutable, and the warning no longer appears.
You can also use the `cargo fix` command to transition your code between
-different Rust editions. Editions are covered in Appendix E at *appendix-05-editions.md*.
+different Rust editions. Editions are covered in Appendix E.
### More Lints with Clippy
-The Clippy tool is a collection of lints to analyze your code so you can catch
-common mistakes and improve your Rust code. Clippy is included with standard
-Rust installations.
+The Clippy tool is a collection of lints to analyze your code so that you can
+catch common mistakes and improve your Rust code. Clippy is included with
+standard Rust installations.
To run Clippy’s lints on any Cargo project, enter the following:
@@ -691,7 +693,7 @@ for installation instructions, then install the language server support in your
particular IDE. Your IDE will gain capabilities such as autocompletion, jump to
definition, and inline errors.
-## Appendix E - Editions
+## Appendix E: Editions
In Chapter 1, you saw that `cargo new` adds a bit of metadata to your
*Cargo.toml* file about an edition. This appendix talks about what that means!
@@ -703,7 +705,7 @@ while, all of these tiny changes add up. But from release to release, it can be
difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has
changed a lot!”
-Every two or three years, the Rust team produces a new Rust *edition*. Each
+Every three years or so, the Rust team produces a new Rust *edition*. Each
edition brings together the features that have landed into a clear package with
fully updated documentation and tooling. New editions ship as part of the usual
six-week release process.
@@ -739,15 +741,15 @@ Rust 2018, your project will compile and be able to use that dependency. The
opposite situation, where your project uses Rust 2018 and a dependency uses
Rust 2015, works as well.
-To be clear: most features will be available on all editions. Developers using
+To be clear: Most features will be available on all editions. Developers using
any Rust edition will continue to see improvements as new stable releases are
made. However, in some cases, mainly when new keywords are added, some new
features might only be available in later editions. You will need to switch
editions if you want to take advantage of such features.
-For more details, the *Edition Guide* at *https://doc.rust-lang.org/stable/edition-guide/* is a complete book
-about editions that enumerates the differences between editions and explains
-how to automatically upgrade your code to a new edition via `cargo fix`.
+For more details, see *The Rust Edition Guide* at *https://doc.rust-lang.org/stable/edition-guide*. This is a
+complete book that enumerates the differences between editions and explains how
+to automatically upgrade your code to a new edition via `cargo fix`.
## Appendix F: Translations of the Book
diff --git a/nostarch/appendix_a.md b/nostarch/appendix_a.md
index 26791b66ec..92b3c83393 100644
--- a/nostarch/appendix_a.md
+++ b/nostarch/appendix_a.md
@@ -10,62 +10,62 @@ directory, so all fixes need to be made in `/src/`.
The following lists contain keywords that are reserved for current or future
use by the Rust language. As such, they cannot be used as identifiers (except
-as raw identifiers, as we’ll discuss in “Raw Identifiers” on page XX).
-*Identifiers* are names of functions, variables, parameters, struct fields,
-modules, crates, constants, macros, static values, attributes, types, traits,
-or lifetimes.
+as raw identifiers, as we discuss in the “Raw
+Identifiers” section). *Identifiers* are names
+of functions, variables, parameters, struct fields, modules, crates, constants,
+macros, static values, attributes, types, traits, or lifetimes.
-## Keywords Currently in Use
+### Keywords Currently in Use
The following is a list of keywords currently in use, with their functionality
described.
-* **`as` **: perform primitive casting, disambiguate the specific trait
-containing an item, or rename items in `use` statements
-* **`async` **: return a `Future` instead of blocking the current thread
-* **`await` **: suspend execution until the result of a `Future` is ready
-* **`break` **: exit a loop immediately
-* **`const` **: define constant items or constant raw pointers
-* **`continue` **: continue to the next loop iteration
-* **`crate` **: in a module path, refers to the crate root
-* **`dyn` **: dynamic dispatch to a trait object
-* **`else` **: fallback for `if` and `if let` control flow constructs
-* **`enum` **: define an enumeration
-* **`extern` **: link an external function or variable
-* **`false` **: Boolean false literal
-* **`fn` **: define a function or the function pointer type
-* **`for` **: loop over items from an iterator, implement a trait, or specify a
-higher-ranked lifetime
-* **`if` **: branch based on the result of a conditional expression
-* **`impl` **: implement inherent or trait functionality
-* **`in` **: part of `for` loop syntax
-* **`let` **: bind a variable
-* **`loop` **: loop unconditionally
-* **`match` **: match a value to patterns
-* **`mod` **: define a module
-* **`move` **: make a closure take ownership of all its captures
-* **`mut` **: denote mutability in references, raw pointers, or pattern bindings
-* **`pub` **: denote public visibility in struct fields, `impl` blocks, or
-modules
-* **`ref` **: bind by reference
-* **`return` **: return from function
-* **`Self` **: a type alias for the type we are defining or implementing
-* **`self` **: method subject or current module
-* **`static` **: global variable or lifetime lasting the entire program
-execution
-* **`struct` **: define a structure
-* **`super` **: parent module of the current module
-* **`trait` **: define a trait
-* **`true` **: Boolean true literal
-* **`type` **: define a type alias or associated type
-* **`union` **: define a union; is a keyword only when used in a union
-declaration
-* **`unsafe` **: denote unsafe code, functions, traits, or implementations
-* **`use` **: bring symbols into scope
-* **`where` **: denote clauses that constrain a type
-* **`while` **: loop conditionally based on the result of an expression
-
-## Keywords Reserved for Future Use
+* **`as`**: Perform primitive casting, disambiguate the specific trait
+ containing an item, or rename items in `use` statements.
+* **`async`**: Return a `Future` instead of blocking the current thread.
+* **`await`**: Suspend execution until the result of a `Future` is ready.
+* **`break`**: Exit a loop immediately.
+* **`const`**: Define constant items or constant raw pointers.
+* **`continue`**: Continue to the next loop iteration.
+* **`crate`**: In a module path, refers to the crate root.
+* **`dyn`**: Dynamic dispatch to a trait object.
+* **`else`**: Fallback for `if` and `if let` control flow constructs.
+* **`enum`**: Define an enumeration.
+* **`extern`**: Link an external function or variable.
+* **`false`**: Boolean false literal.
+* **`fn`**: Define a function or the function pointer type.
+* **`for`**: Loop over items from an iterator, implement a trait, or specify a
+ higher ranked lifetime.
+* **`if`**: Branch based on the result of a conditional expression.
+* **`impl`**: Implement inherent or trait functionality.
+* **`in`**: Part of `for` loop syntax.
+* **`let`**: Bind a variable.
+* **`loop`**: Loop unconditionally.
+* **`match`**: Match a value to patterns.
+* **`mod`**: Define a module.
+* **`move`**: Make a closure take ownership of all its captures.
+* **`mut`**: Denote mutability in references, raw pointers, or pattern bindings.
+* **`pub`**: Denote public visibility in struct fields, `impl` blocks, or
+ modules.
+* **`ref`**: Bind by reference.
+* **`return`**: Return from function.
+* **`Self`**: A type alias for the type we are defining or implementing.
+* **`self`**: Method subject or current module.
+* **`static`**: Global variable or lifetime lasting the entire program
+ execution.
+* **`struct`**: Define a structure.
+* **`super`**: Parent module of the current module.
+* **`trait`**: Define a trait.
+* **`true`**: Boolean true literal.
+* **`type`**: Define a type alias or associated type.
+* **`union`**: Define a union; is a keyword only when
+ used in a union declaration.
+* **`unsafe`**: Denote unsafe code, functions, traits, or implementations.
+* **`use`**: Bring symbols into scope.
+* **`where`**: Denote clauses that constrain a type.
+* **`while`**: Loop conditionally based on the result of an expression.
+
+### Keywords Reserved for Future Use
The following keywords do not yet have any functionality but are reserved by
Rust for potential future use:
@@ -75,6 +75,7 @@ Rust for potential future use:
* `box`
* `do`
* `final`
+* `gen`
* `macro`
* `override`
* `priv`
@@ -84,7 +85,7 @@ Rust for potential future use:
* `virtual`
* `yield`
-## Raw Identifiers
+### Raw Identifiers
*Raw identifiers* are the syntax that lets you use keywords where they wouldn’t
normally be allowed. You use a raw identifier by prefixing a keyword with `r#`.
diff --git a/nostarch/appendix_b.md b/nostarch/appendix_b.md
index dceca86623..4d894dd51e 100644
--- a/nostarch/appendix_b.md
+++ b/nostarch/appendix_b.md
@@ -49,7 +49,7 @@ type | |
| `->` | `fn(...) -> type`, `|...| -> type` | Function and closure return type | |
| `.` | `expr.ident` | Field access | |
| `.` | `expr.ident(expr, ...)` | Method call | |
-| `.` | `expr.0`, `expr.1`, etc. | Tuple indexing | |
+| `.` | `expr.0`, `expr.1`, and so on | Tuple indexing | |
| `..` | `..`, `expr..`, `..expr`, `expr..expr` | Right-exclusive range literal
| `PartialOrd` |
| `..=` | `..=expr`, `expr..=expr` | Right-inclusive range literal |
@@ -61,7 +61,7 @@ binding | |
inclusive range pattern | |
| `/` | `expr / expr` | Arithmetic division | `Div` |
| `/=` | `var /= expr` | Arithmetic division and assignment | `DivAssign` |
-| `: | `pat: type`, `ident: type` | Constraints | |
+| `:` | `pat: type`, `ident: type` | Constraints | |
| `:` | `ident: expr` | Struct field initializer | |
| `:` | `'a: loop {...}` | Loop label | |
| `;` | `expr;` | Statement and item terminator | |
@@ -94,12 +94,12 @@ is, they don’t behave like a function or method call.
Table B-2 shows symbols that appear on their own and are valid in a variety of
locations.
-Table B-2: Stand-Alone Syntax
+Table B-2: Stand-alone Syntax
| Symbol | Explanation |
|---|---|
| `'ident` | Named lifetime or loop label |
-| Digits immediately followed by `u8`, `i32`, `f64`, `usize`, and so on |
+| Digits immediately followed by `u8`, `i32`, `f64`, `usize`, and so on |
Numeric literal of specific type |
| `"..."` | String literal |
| `r"..."`, `r#"..."#`, `r##"..."##`, and so on | Raw string literal; escape
@@ -147,14 +147,14 @@ Table B-4: Generics
|---|---|
| `path<...>` | Specifies parameters to a generic type in a type (for example,
`Vec`) |
-| `path::<...>, method::<...>` | Specifies parameters to a generic type,
-function, or method in an expression; often referred to as turbofish (for
+| `path::<...>`, `method::<...>` | Specifies parameters to a generic type,
+function, or method in an expression; often referred to as *turbofish* (for
example, `"42".parse::()`) |
| `fn ident<...> ...` | Define generic function |
| `struct ident<...> ...` | Define generic structure |
| `enum ident<...> ...` | Define generic enumeration |
| `impl<...> ...` | Define generic implementation |
-| `for<...> type` | Higher-ranked lifetime bounds |
+| `for<...> type` | Higher ranked lifetime bounds |
| `type` | A generic type where one or more associated types have
specific assignments (for example, `Iterator
- `) |
diff --git a/nostarch/appendix_c.md b/nostarch/appendix_c.md
index 53131eb5fa..4023b12fa7 100644
--- a/nostarch/appendix_c.md
+++ b/nostarch/appendix_c.md
@@ -39,9 +39,10 @@ would be most relevant to them? The Rust compiler doesn’t have this insight, s
it can’t provide appropriate default behavior for you.
The list of derivable traits provided in this appendix is not comprehensive:
-libraries can implement `derive` for their own traits, making the list of
+Libraries can implement `derive` for their own traits, making the list of
traits you can use `derive` with truly open ended. Implementing `derive`
-involves using a procedural macro, which is covered in “Macros” on page XX.
+involves using a procedural macro, which is covered in the “Custom `derive`
+Macros” section in Chapter 20.
## Debug for Programmer Output
@@ -54,8 +55,8 @@ at a particular point in a program’s execution.
The `Debug` trait is required, for example, in the use of the `assert_eq!`
macro. This macro prints the values of instances given as arguments if the
-equality assertion fails so programmers can see why the two instances weren’t
-equal.
+equality assertion fails so that programmers can see why the two instances
+weren’t equal.
## PartialEq and Eq for Equality Comparisons
@@ -64,7 +65,7 @@ equality and enables use of the `==` and `!=` operators.
Deriving `PartialEq` implements the `eq` method. When `PartialEq` is derived on
structs, two instances are equal only if *all* fields are equal, and the
-instances are not equal if any fields are not equal. When derived on enums,
+instances are not equal if *any* fields are not equal. When derived on enums,
each variant is equal to itself and not equal to the other variants.
The `PartialEq` trait is required, for example, with the use of the
@@ -75,7 +76,7 @@ The `Eq` trait has no methods. Its purpose is to signal that for every value of
the annotated type, the value is equal to itself. The `Eq` trait can only be
applied to types that also implement `PartialEq`, although not all types that
implement `PartialEq` can implement `Eq`. One example of this is floating-point
-number types: the implementation of floating-point numbers states that two
+number types: The implementation of floating-point numbers states that two
instances of the not-a-number (`NaN`) value are not equal to each other.
An example of when `Eq` is required is for keys in a `HashMap` so that
@@ -91,8 +92,8 @@ that also implement `PartialEq`.
Deriving `PartialOrd` implements the `partial_cmp` method, which returns an
`Option` that will be `None` when the values given don’t produce an
ordering. An example of a value that doesn’t produce an ordering, even though
-most values of that type can be compared, is the not-a-number (`NaN`) floating
-point value. Calling `partial_cmp` with any floating-point number and the `NaN`
+most values of that type can be compared, is the `NaN` floating point value.
+Calling `partial_cmp` with any floating-point number and the `NaN`
floating-point value will return `None`.
When derived on structs, `PartialOrd` compares two instances by comparing the
@@ -119,8 +120,8 @@ a data structure that stores data based on the sort order of the values.
The `Clone` trait allows you to explicitly create a deep copy of a value, and
the duplication process might involve running arbitrary code and copying heap
-data. See “Variables and Data Interacting with Clone” on page XX for more
-information on `Clone`.
+data. See the “Variables and Data Interacting with Clone” section in Chapter 4
+for more information on `Clone`.
Deriving `Clone` implements the `clone` method, which when implemented for the
whole type, calls `clone` on each of the parts of the type. This means all the
@@ -129,11 +130,11 @@ fields or values in the type must also implement `Clone` to derive `Clone`.
An example of when `Clone` is required is when calling the `to_vec` method on a
slice. The slice doesn’t own the type instances it contains, but the vector
returned from `to_vec` will need to own its instances, so `to_vec` calls
-`clone` on each item. Thus the type stored in the slice must implement `Clone`.
+`clone` on each item. Thus, the type stored in the slice must implement `Clone`.
The `Copy` trait allows you to duplicate a value by only copying bits stored on
-the stack; no arbitrary code is necessary. See “Stack-Only Data: Copy” on page
-XX for more information on `Copy`.
+the stack; no arbitrary code is necessary. See the “Stack-Only Data: Copy”
+section in Chapter 4 for more information on `Copy`.
The `Copy` trait doesn’t define any methods to prevent programmers from
overloading those methods and violating the assumption that no arbitrary code
@@ -172,9 +173,9 @@ meaning all fields or values in the type must also implement `Default` to
derive `Default`.
The `Default::default` function is commonly used in combination with the struct
-update syntax discussed in “Creating Instances from Other Instances with Struct
-Update Syntax” on page XX. You can customize a few fields of a struct and then
-set and use a default value for the rest of the fields by using
+update syntax discussed in the “Creating Instances with Struct Update Syntax”
+section in Chapter 5. You can customize a few fields of a struct and then set
+and use a default value for the rest of the fields by using
`..Default::default()`.
The `Default` trait is required when you use the method `unwrap_or_default` on
diff --git a/nostarch/appendix_d.md b/nostarch/appendix_d.md
index 18e6094cb8..48a5fa33d0 100644
--- a/nostarch/appendix_d.md
+++ b/nostarch/appendix_d.md
@@ -16,11 +16,11 @@ warning fixes, a linter, and integrating with IDEs.
The `rustfmt` tool reformats your code according to the community code style.
Many collaborative projects use `rustfmt` to prevent arguments about which
-style to use when writing Rust: everyone formats their code using the tool.
+style to use when writing Rust: Everyone formats their code using the tool.
Rust installations include `rustfmt` by default, so you should already have the
programs `rustfmt` and `cargo-fmt` on your system. These two commands are
-analogous to `rustc` and `cargo` in that `rustfmt` allows finer-grained control
+analogous to `rustc` and `cargo` in that `rustfmt` allows finer grained control
and `cargo-fmt` understands conventions of a project that uses Cargo. To format
any Cargo project, enter the following:
@@ -95,9 +95,9 @@ different Rust editions. Editions are covered in Appendix E.
## More Lints with Clippy
-The Clippy tool is a collection of lints to analyze your code so you can catch
-common mistakes and improve your Rust code. Clippy is included with standard
-Rust installations.
+The Clippy tool is a collection of lints to analyze your code so that you can
+catch common mistakes and improve your Rust code. Clippy is included with
+standard Rust installations.
To run Clippy’s lints on any Cargo project, enter the following:
diff --git a/nostarch/appendix_e.md b/nostarch/appendix_e.md
index ddb12b782b..f7244328cf 100644
--- a/nostarch/appendix_e.md
+++ b/nostarch/appendix_e.md
@@ -18,7 +18,7 @@ while, all of these tiny changes add up. But from release to release, it can be
difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has
changed a lot!”
-Every two or three years, the Rust team produces a new Rust *edition*. Each
+Every three years or so, the Rust team produces a new Rust *edition*. Each
edition brings together the features that have landed into a clear package with
fully updated documentation and tooling. New editions ship as part of the usual
six-week release process.
@@ -32,8 +32,9 @@ landed, which might make Rust worth another look.
* For those developing Rust, a new edition provides a rallying point for the
project as a whole.
-At the time of this writing, three Rust editions are available: Rust 2015, Rust
-2018, and Rust 2021. This book is written using Rust 2021 edition idioms.
+At the time of this writing, four Rust editions are available: Rust 2015, Rust
+2018, Rust 2021, and Rust 2024. This book is written using Rust 2024 edition
+idioms.
The `edition` key in *Cargo.toml* indicates which edition the compiler should
use for your code. If the key doesn’t exist, Rust uses `2015` as the edition
@@ -53,14 +54,14 @@ Rust 2018, your project will compile and be able to use that dependency. The
opposite situation, where your project uses Rust 2018 and a dependency uses
Rust 2015, works as well.
-To be clear: most features will be available on all editions. Developers using
+To be clear: Most features will be available on all editions. Developers using
any Rust edition will continue to see improvements as new stable releases are
made. However, in some cases, mainly when new keywords are added, some new
features might only be available in later editions. You will need to switch
editions if you want to take advantage of such features.
-For more details, *The* *Edition Guide* at
-*https://doc.rust-lang.org/stable/edition-guide* is a complete book about
-editions that enumerates the differences between editions and explains how to
-automatically upgrade your code to a new edition via `cargo fix`.
+For more details, see *The Rust Edition Guide* at
+*https://doc.rust-lang.org/stable/edition-guide*. This is a complete book that
+enumerates the differences between editions and explains how to automatically
+upgrade your code to a new edition via `cargo fix`.
diff --git a/nostarch/chapter10.md b/nostarch/chapter10.md
index ba8a9e03bf..29860d9148 100644
--- a/nostarch/chapter10.md
+++ b/nostarch/chapter10.md
@@ -16,25 +16,25 @@ when compiling and running the code.
Functions can take parameters of some generic type, instead of a concrete type
like `i32` or `String`, in the same way they take parameters with unknown
-values to run the same code on multiple concrete values. In fact, we’ve already
+values to run the same code on multiple concrete values. In fact, we already
used generics in Chapter 6 with `Option`, in Chapter 8 with `Vec` and
`HashMap`, and in Chapter 9 with `Result`. In this chapter, you’ll
explore how to define your own types, functions, and methods with generics!
-First we’ll review how to extract a function to reduce code duplication. We’ll
+First, we’ll review how to extract a function to reduce code duplication. We’ll
then use the same technique to make a generic function from two functions that
differ only in the types of their parameters. We’ll also explain how to use
generic types in struct and enum definitions.
-Then you’ll learn how to use *traits* to define behavior in a generic way. You
+Then, you’ll learn how to use traits to define behavior in a generic way. You
can combine traits with generic types to constrain a generic type to accept
only those types that have a particular behavior, as opposed to just any type.
Finally, we’ll discuss *lifetimes*: a variety of generics that give the
compiler information about how references relate to each other. Lifetimes allow
us to give the compiler enough information about borrowed values so that it can
-ensure references will be valid in more situations than it could without our
-help.
+ensure that references will be valid in more situations than it could without
+our help.
## Removing Duplication by Extracting a Function
@@ -42,7 +42,7 @@ Generics allow us to replace specific types with a placeholder that represents
multiple types to remove code duplication. Before diving into generics syntax,
let’s first look at how to remove duplication in a way that doesn’t involve
generic types by extracting a function that replaces specific values with a
-placeholder that represents multiple values. Then we’ll apply the same
+placeholder that represents multiple values. Then, we’ll apply the same
technique to extract a generic function! By looking at how to recognize
duplicated code you can extract into a function, you’ll start to recognize
duplicated code that can use generics.
@@ -115,7 +115,7 @@ fn main() {
Listing 10-2: Code to find the largest number in *two* lists of numbers
-Although this code works, duplicating code is tedious and error prone. We also
+Although this code works, duplicating code is tedious and error-prone. We also
have to remember to update the code in multiple places when we want to change
it.
@@ -125,7 +125,7 @@ solution makes our code clearer and lets us express the concept of finding the
largest number in a list abstractly.
In Listing 10-3, we extract the code that finds the largest number into a
-function named `largest`. Then we call the function to find the largest number
+function named `largest`. Then, we call the function to find the largest number
in the two lists from Listing 10-2. We could also use the function on any other
list of `i32` values we might have in the future.
@@ -185,7 +185,7 @@ values. How would we eliminate that duplication? Let’s find out!
We use generics to create definitions for items like function signatures or
structs, which we can then use with many different concrete data types. Let’s
first look at how to define functions, structs, enums, and methods using
-generics. Then we’ll discuss how generics affect code performance.
+generics. Then, we’ll discuss how generics affect code performance.
### In Function Definitions
@@ -249,13 +249,13 @@ To parameterize the types in a new single function, we need to name the type
parameter, just as we do for the value parameters to a function. You can use
any identifier as a type parameter name. But we’ll use `T` because, by
convention, type parameter names in Rust are short, often just one letter, and
-Rust’s type-naming convention is CamelCase. Short for *type*, `T` is the default
-choice of most Rust programmers.
+Rust’s type-naming convention is UpperCamelCase. Short for *type*, `T` is the
+default choice of most Rust programmers.
When we use a parameter in the body of the function, we have to declare the
-parameter name in the signature so the compiler knows what that name means.
-Similarly, when we use a type parameter name in a function signature, we have
-to declare the type parameter name before we use it. To define the generic
+parameter name in the signature so that the compiler knows what that name
+means. Similarly, when we use a type parameter name in a function signature, we
+have to declare the type parameter name before we use it. To define the generic
`largest` function, we place type name declarations inside angle brackets,
`<>`, between the name of the function and the parameter list, like this:
@@ -263,8 +263,8 @@ to declare the type parameter name before we use it. To define the generic
fn largest(list: &[T]) -> &T {
```
-We read this definition as: the function `largest` is generic over some type
-`T`. This function has one parameter named `list`, which is a slice of values
+We read this definition as “The function `largest` is generic over some type
+`T`.” This function has one parameter named `list`, which is a slice of values
of type `T`. The `largest` function will return a reference to a value of the
same type `T`.
@@ -325,7 +325,7 @@ For more information about this error, try `rustc --explain E0369`.
error: could not compile `chapter10` (bin "chapter10") due to 1 previous error
```
-The help text mentions `std::cmp::PartialOrd`, which is a *trait*, and we’re
+The help text mentions `std::cmp::PartialOrd`, which is a trait, and we’re
going to talk about traits in the next section. For now, know that this error
states that the body of `largest` won’t work for all possible types that `T`
could be. Because we want to compare values of type `T` in the body, we can
@@ -359,10 +359,9 @@ fn main() {
Listing 10-6: A `Point` struct that holds `x` and `y` values of type `T`
The syntax for using generics in struct definitions is similar to that used in
-function definitions. First we declare the name of the type parameter inside
-angle brackets just after the name of the struct. Then we use the generic
-type in the struct definition where we would otherwise specify concrete data
-types.
+function definitions. First, we declare the name of the type parameter inside
+angle brackets just after the name of the struct. Then, we use the generic type
+in the struct definition where we would otherwise specify concrete data types.
Note that because we’ve used only one generic type to define `Point`, this
definition says that the `Point` struct is generic over some type `T`, and
@@ -387,8 +386,8 @@ Listing 10-7: The fields `x` and `y` must be the same type because both have the
In this example, when we assign the integer value `5` to `x`, we let the
compiler know that the generic type `T` will be an integer for this instance of
-`Point`. Then when we specify `4.0` for `y`, which we’ve defined to have the
-same type as `x`, we’ll get a type mismatch error like this:
+`Point`. Then, when we specify `4.0` for `y`, which we’ve defined to have
+the same type as `x`, we’ll get a type mismatch error like this:
```
$ cargo run
@@ -506,11 +505,11 @@ Listing 10-9: Implementing a method named `x` on the `Point` struct that will
Here, we’ve defined a method named `x` on `Point` that returns a reference
to the data in the field `x`.
-Note that we have to declare `T` just after `impl` so we can use `T` to specify
-that we’re implementing methods on the type `Point`. By declaring `T` as a
-generic type after `impl`, Rust can identify that the type in the angle
-brackets in `Point` is a generic type rather than a concrete type. We could
-have chosen a different name for this generic parameter than the generic
+Note that we have to declare `T` just after `impl` so that we can use `T` to
+specify that we’re implementing methods on the type `Point`. By declaring
+`T` as a generic type after `impl`, Rust can identify that the type in the
+angle brackets in `Point` is a generic type rather than a concrete type. We
+could have chosen a different name for this generic parameter than the generic
parameter declared in the struct definition, but using the same name is
conventional. If you write a method within an `impl` that declares a generic
type, that method will be defined on any instance of the type, no matter what
@@ -518,7 +517,7 @@ concrete type ends up substituting for the generic type.
We can also specify constraints on generic types when defining methods on the
type. We could, for example, implement methods only on `Point` instances
-rather than on `Point` instances with any generic type. In Listing 10-10 we
+rather than on `Point` instances with any generic type. In Listing 10-10, we
use the concrete type `f32`, meaning we don’t declare any types after `impl`.
src/main.rs
@@ -541,8 +540,8 @@ available only for floating-point types.
Generic type parameters in a struct definition aren’t always the same as those
you use in that same struct’s method signatures. Listing 10-11 uses the generic
-types `X1` and `Y1` for the `Point` struct and `X2` `Y2` for the `mixup` method
-signature to make the example clearer. The method creates a new `Point`
+types `X1` and `Y1` for the `Point` struct and `X2` and `Y2` for the `mixup`
+method signature to make the example clearer. The method creates a new `Point`
instance with the `x` value from the `self` `Point` (of type `X1`) and the `y`
value from the passed-in `Point` (of type `Y2`).
@@ -573,7 +572,7 @@ fn main() {
}
```
-Listing 10-11: A method that uses generic types different from its struct’s definition
+Listing 10-11: A method that uses generic types that are different from its struct’s definition
In `main`, we’ve defined a `Point` that has an `i32` for `x` (with value `5`)
and an `f64` for `y` (with value `10.4`). The `p2` variable is a `Point` struct
@@ -600,7 +599,7 @@ Rust accomplishes this by performing monomorphization of the code using
generics at compile time. *Monomorphization* is the process of turning generic
code into specific code by filling in the concrete types that are used when
compiled. In this process, the compiler does the opposite of the steps we used
-to create the generic function in Listing 10-5: the compiler looks at all the
+to create the generic function in Listing 10-5: The compiler looks at all the
places where generic code is called and generates code for the concrete types
the generic code is called with.
@@ -614,7 +613,7 @@ let float = Some(5.0);
When Rust compiles this code, it performs monomorphization. During that
process, the compiler reads the values that have been used in `Option`
-instances and identifies two kinds of `Option`: one is `i32` and the other
+instances and identifies two kinds of `Option`: One is `i32` and the other
is `f64`. As such, it expands the generic definition of `Option` into two
definitions specialized to `i32` and `f64`, thereby replacing the generic
definition with the specific ones.
@@ -650,7 +649,11 @@ runs, it performs just as it would if we had duplicated each definition by
hand. The process of monomorphization makes Rust’s generics extremely efficient
at runtime.
-## Traits: Defining Shared Behavior
+
+
+
+
+## Defining Shared Behavior with Traits
A *trait* defines the functionality a particular type has and can share with
other types. We can use traits to define shared behavior in an abstract way. We
@@ -703,7 +706,7 @@ its own custom behavior for the body of the method. The compiler will enforce
that any type that has the `Summary` trait will have the method `summarize`
defined with this signature exactly.
-A trait can have multiple methods in its body: the method signatures are listed
+A trait can have multiple methods in its body: The method signatures are listed
one per line, and each line ends in a semicolon.
### Implementing a Trait on a Type
@@ -793,16 +796,20 @@ library traits like `Display` on a custom type like `SocialPost` as part of our
crate.
But we can’t implement external traits on external types. For example, we can’t
-implement the `Display` trait on `Vec` within our `aggregator` crate because
-`Display` and `Vec` are both defined in the standard library and aren’t
-local to our `aggregator` crate. This restriction is part of a property called
-*coherence*, and more specifically the *orphan rule*, so named because the
-parent type is not present. This rule ensures that other people’s code can’t
-break your code and vice versa. Without the rule, two crates could implement
-the same trait for the same type, and Rust wouldn’t know which implementation
-to use.
+implement the `Display` trait on `Vec` within our `aggregator` crate,
+because `Display` and `Vec` are both defined in the standard library and
+aren’t local to our `aggregator` crate. This restriction is part of a property
+called *coherence*, and more specifically the *orphan rule*, so named because
+the parent type is not present. This rule ensures that other people’s code
+can’t break your code and vice versa. Without the rule, two crates could
+implement the same trait for the same type, and Rust wouldn’t know which
+implementation to use.
+
+
+
+
-### Default Implementations
+### Using Default Implementations
Sometimes it’s useful to have default behavior for some or all of the methods
in a trait instead of requiring implementations for all methods on every type.
@@ -909,7 +916,11 @@ This code prints `1 new post: (Read more from @horse_ebooks...)`.
Note that it isn’t possible to call the default implementation from an
overriding implementation of that same method.
-### Traits as Parameters
+
+
+
+
+### Using Traits as Parameters
Now that you know how to define and implement traits, we can explore how to use
traits to define functions that accept many different types. We’ll use the
@@ -929,7 +940,7 @@ keyword and the trait name. This parameter accepts any type that implements the
specified trait. In the body of `notify`, we can call any methods on `item`
that come from the `Summary` trait, such as `summarize`. We can call `notify`
and pass in any instance of `NewsArticle` or `SocialPost`. Code that calls the
-function with any other type, such as a `String` or an `i32`, won’t compile
+function with any other type, such as a `String` or an `i32`, won’t compile,
because those types don’t implement `Summary`.
@@ -973,10 +984,14 @@ The generic type `T` specified as the type of the `item1` and `item2`
parameters constrains the function such that the concrete type of the value
passed as an argument for `item1` and `item2` must be the same.
-#### Specifying Multiple Trait Bounds with the + Syntax
+
+
+
+
+#### Multiple Trait Bounds with the + Syntax
We can also specify more than one trait bound. Say we wanted `notify` to use
-display formatting as well as `summarize` on `item`: we specify in the `notify`
+display formatting as well as `summarize` on `item`: We specify in the `notify`
definition that `item` must implement both `Display` and `Summary`. We can do
so using the `+` syntax:
@@ -1016,7 +1031,7 @@ where
{
```
-This function’s signature is less cluttered: the function name, parameter list,
+This function’s signature is less cluttered: The function name, parameter list,
and return type are close together, similar to a function without lots of trait
bounds.
@@ -1085,20 +1100,20 @@ fn returns_summarizable(switch: bool) -> impl Summary {
Returning either a `NewsArticle` or a `SocialPost` isn’t allowed due to
restrictions around how the `impl Trait` syntax is implemented in the compiler.
We’ll cover how to write a function with this behavior in the “Using Trait
-Objects That Allow for Values of Different
-Types” section of Chapter 18.
+Objects to Abstract over Shared Behavior”
+section of Chapter 18.
### Using Trait Bounds to Conditionally Implement Methods
By using a trait bound with an `impl` block that uses generic type parameters,
we can implement methods conditionally for types that implement the specified
traits. For example, the type `Pair` in Listing 10-15 always implements the
-`new` function to return a new instance of `Pair` (recall from the
-“Defining Methods” section of Chapter 5 that `Self`
-is a type alias for the type of the `impl` block, which in this case is
-`Pair`). But in the next `impl` block, `Pair` only implements the
-`cmp_display` method if its inner type `T` implements the `PartialOrd` trait
-that enables comparison *and* the `Display` trait that enables printing.
+`new` function to return a new instance of `Pair` (recall from the “Method
+Syntax” section of Chapter 5 that `Self` is a type
+alias for the type of the `impl` block, which in this case is `Pair`). But
+in the next `impl` block, `Pair` only implements the `cmp_display` method if
+its inner type `T` implements the `PartialOrd` trait that enables comparison
+*and* the `Display` trait that enables printing.
src/lib.rs
@@ -1159,10 +1174,10 @@ reduce duplication but also specify to the compiler that we want the generic
type to have particular behavior. The compiler can then use the trait bound
information to check that all the concrete types used with our code provide the
correct behavior. In dynamically typed languages, we would get an error at
-runtime if we called a method on a type which didn’t define the method. But
-Rust moves these errors to compile time so we’re forced to fix the problems
+runtime if we called a method on a type that didn’t define the method. But Rust
+moves these errors to compile time so that we’re forced to fix the problems
before our code is even able to run. Additionally, we don’t have to write code
-that checks for behavior at runtime because we’ve already checked at compile
+that checks for behavior at runtime, because we’ve already checked at compile
time. Doing so improves performance without having to give up the flexibility
of generics.
@@ -1174,26 +1189,30 @@ references are valid as long as we need them to be.
One detail we didn’t discuss in the “References and
Borrowing” section in Chapter 4 is
-that every reference in Rust has a *lifetime*, which is the scope for which
+that every reference in Rust has a lifetime, which is the scope for which
that reference is valid. Most of the time, lifetimes are implicit and inferred,
just like most of the time, types are inferred. We are only required to
-annotate types when multiple types are possible. In a similar way, we have to
+annotate types when multiple types are possible. In a similar way, we must
annotate lifetimes when the lifetimes of references could be related in a few
different ways. Rust requires us to annotate the relationships using generic
-lifetime parameters to ensure the actual references used at runtime will
+lifetime parameters to ensure that the actual references used at runtime will
definitely be valid.
Annotating lifetimes is not even a concept most other programming languages
have, so this is going to feel unfamiliar. Although we won’t cover lifetimes in
their entirety in this chapter, we’ll discuss common ways you might encounter
-lifetime syntax so you can get comfortable with the concept.
+lifetime syntax so that you can get comfortable with the concept.
-### Preventing Dangling References with Lifetimes
+
+
+
-The main aim of lifetimes is to prevent *dangling references*, which cause a
-program to reference data other than the data it’s intended to reference.
-Consider the program in Listing 10-16, which has an outer scope and an inner
-scope.
+### Dangling References
+
+The main aim of lifetimes is to prevent dangling references, which, if they
+were allowed to exist, would cause a program to reference data other than the
+data it’s intended to reference. Consider the program in Listing 10-16, which
+has an outer scope and an inner scope.
```
@@ -1213,17 +1232,17 @@ Listing 10-16: An attempt to use a reference whose value has gone out of scope
> Note: The examples in Listings 10-16, 10-17, and 10-23 declare variables
> without giving them an initial value, so the variable name exists in the outer
-> scope. At first glance, this might appear to be in conflict with Rust’s having
+> scope. At first glance, this might appear to be in conflict with Rust having
> no null values. However, if we try to use a variable before giving it a value,
-> we’ll get a compile-time error, which shows that Rust indeed does not allow
+> we’ll get a compile-time error, which shows that indeed Rust does not allow
> null values.
The outer scope declares a variable named `r` with no initial value, and the
inner scope declares a variable named `x` with the initial value of `5`. Inside
-the inner scope, we attempt to set the value of `r` as a reference to `x`. Then
-the inner scope ends, and we attempt to print the value in `r`. This code won’t
-compile because the value that `r` is referring to has gone out of scope before
-we try to use it. Here is the error message:
+the inner scope, we attempt to set the value of `r` as a reference to `x`.
+Then, the inner scope ends, and we attempt to print the value in `r`. This code
+won’t compile, because the value that `r` is referring to has gone out of scope
+before we try to use it. Here is the error message:
```
$ cargo run
@@ -1250,7 +1269,7 @@ reason is that `x` will be out of scope when the inner scope ends on line 7.
But `r` is still valid for the outer scope; because its scope is larger, we say
that it “lives longer.” If Rust allowed this code to work, `r` would be
referencing memory that was deallocated when `x` went out of scope, and
-anything we tried to do with `r` wouldn’t work correctly. So how does Rust
+anything we tried to do with `r` wouldn’t work correctly. So, how does Rust
determine that this code is invalid? It uses a borrow checker.
### The Borrow Checker
@@ -1280,10 +1299,10 @@ with `'b`. As you can see, the inner `'b` block is much smaller than the outer
`'a` lifetime block. At compile time, Rust compares the size of the two
lifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory
with a lifetime of `'b`. The program is rejected because `'b` is shorter than
-`'a`: the subject of the reference doesn’t live as long as the reference.
+`'a`: The subject of the reference doesn’t live as long as the reference.
-Listing 10-18 fixes the code so it doesn’t have a dangling reference and it
-compiles without any errors.
+Listing 10-18 fixes the code so that it doesn’t have a dangling reference and
+it compiles without any errors.
```
@@ -1304,8 +1323,8 @@ means `r` can reference `x` because Rust knows that the reference in `r` will
always be valid while `x` is valid.
Now that you know where the lifetimes of references are and how Rust analyzes
-lifetimes to ensure references will always be valid, let’s explore generic
-lifetimes of parameters and return values in the context of functions.
+lifetimes to ensure that references will always be valid, let’s explore generic
+lifetimes in function parameters and return values.
### Generic Lifetimes in Functions
@@ -1383,7 +1402,7 @@ Listings 10-17 and 10-18 to determine whether the reference we return will
always be valid. The borrow checker can’t determine this either, because it
doesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the
return value. To fix this error, we’ll add generic lifetime parameters that
-define the relationship between the references so the borrow checker can
+define the relationship between the references so that the borrow checker can
perform its analysis.
### Lifetime Annotation Syntax
@@ -1394,15 +1413,15 @@ other without affecting the lifetimes. Just as functions can accept any type
when the signature specifies a generic type parameter, functions can accept
references with any lifetime by specifying a generic lifetime parameter.
-Lifetime annotations have a slightly unusual syntax: the names of lifetime
+Lifetime annotations have a slightly unusual syntax: The names of lifetime
parameters must start with an apostrophe (`'`) and are usually all lowercase
and very short, like generic types. Most people use the name `'a` for the first
lifetime annotation. We place lifetime parameter annotations after the `&` of a
reference, using a space to separate the annotation from the reference’s type.
-Here are some examples: a reference to an `i32` without a lifetime parameter, a
+Here are some examples—a reference to an `i32` without a lifetime parameter, a
reference to an `i32` that has a lifetime parameter named `'a`, and a mutable
-reference to an `i32` that also has the lifetime `'a`.
+reference to an `i32` that also has the lifetime `'a`:
```
&i32 // a reference
@@ -1410,22 +1429,26 @@ reference to an `i32` that also has the lifetime `'a`.
&'a mut i32 // a mutable reference with an explicit lifetime
```
-One lifetime annotation by itself doesn’t have much meaning because the
+One lifetime annotation by itself doesn’t have much meaning, because the
annotations are meant to tell Rust how generic lifetime parameters of multiple
references relate to each other. Let’s examine how the lifetime annotations
relate to each other in the context of the `longest` function.
-### Lifetime Annotations in Function Signatures
+
+
+
+
+### In Function Signatures
To use lifetime annotations in function signatures, we need to declare the
-generic *lifetime* parameters inside angle brackets between the function name
-and the parameter list, just as we did with generic *type* parameters.
+generic lifetime parameters inside angle brackets between the function name and
+the parameter list, just as we did with generic type parameters.
-We want the signature to express the following constraint: the returned
-reference will be valid as long as both the parameters are valid. This is the
-relationship between lifetimes of the parameters and the return value. We’ll
-name the lifetime `'a` and then add it to each reference, as shown in Listing
-10-21.
+We want the signature to express the following constraint: The returned
+reference will be valid as long as both of the parameters are valid. This is
+the relationship between lifetimes of the parameters and the return value.
+We’ll name the lifetime `'a` and then add it to each reference, as shown in
+Listing 10-21.
src/main.rs
@@ -1504,7 +1527,7 @@ Next, let’s try an example that shows that the lifetime of the reference in
`result` must be the smaller lifetime of the two arguments. We’ll move the
declaration of the `result` variable outside the inner scope but leave the
assignment of the value to the `result` variable inside the scope with
-`string2`. Then we’ll move the `println!` that uses `result` to outside the
+`string2`. Then, we’ll move the `println!` that uses `result` to outside the
inner scope, after the inner scope has ended. The code in Listing 10-23 will
not compile.
@@ -1562,9 +1585,13 @@ disallows the code in Listing 10-23 as possibly having an invalid reference.
Try designing more experiments that vary the values and lifetimes of the
references passed in to the `longest` function and how the returned reference
is used. Make hypotheses about whether or not your experiments will pass the
-borrow checker before you compile; then check to see if you’re right!
+borrow checker before you compile; then, check to see if you’re right!
+
+
-### Thinking in Terms of Lifetimes
+
+
+### Relationships
The way in which you need to specify lifetime parameters depends on what your
function is doing. For example, if we changed the implementation of the
@@ -1631,7 +1658,7 @@ of the `longest` function. We’re also trying to return a reference to `result`
from the function. There is no way we can specify lifetime parameters that
would change the dangling reference, and Rust won’t let us create a dangling
reference. In this case, the best fix would be to return an owned data type
-rather than a reference so the calling function is then responsible for
+rather than a reference so that the calling function is then responsible for
cleaning up the value.
Ultimately, lifetime syntax is about connecting the lifetimes of various
@@ -1639,12 +1666,16 @@ parameters and return values of functions. Once they’re connected, Rust has
enough information to allow memory-safe operations and disallow operations that
would create dangling pointers or otherwise violate memory safety.
-### Lifetime Annotations in Struct Definitions
+
+
+
+
+### In Struct Definitions
So far, the structs we’ve defined all hold owned types. We can define structs
-to hold references, but in that case we would need to add a lifetime annotation
-on every reference in the struct’s definition. Listing 10-24 has a struct named
-`ImportantExcerpt` that holds a string slice.
+to hold references, but in that case, we would need to add a lifetime
+annotation on every reference in the struct’s definition. Listing 10-24 has a
+struct named `ImportantExcerpt` that holds a string slice.
src/main.rs
@@ -1666,8 +1697,8 @@ Listing 10-24: A struct that holds a reference, requiring a lifetime annotation
This struct has the single field `part` that holds a string slice, which is a
reference. As with generic data types, we declare the name of the generic
-lifetime parameter inside angle brackets after the name of the struct so we can
-use the lifetime parameter in the body of the struct definition. This
+lifetime parameter inside angle brackets after the name of the struct so that
+we can use the lifetime parameter in the body of the struct definition. This
annotation means an instance of `ImportantExcerpt` can’t outlive the reference
it holds in its `part` field.
@@ -1704,7 +1735,7 @@ fn first_word(s: &str) -> &str {
Listing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references
The reason this function compiles without lifetime annotations is historical:
-in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because
+In early versions (pre-1.0) of Rust, this code wouldn’t have compiled, because
every reference needed an explicit lifetime. At that time, the function
signature would have been written like this:
@@ -1716,8 +1747,8 @@ After writing a lot of Rust code, the Rust team found that Rust programmers
were entering the same lifetime annotations over and over in particular
situations. These situations were predictable and followed a few deterministic
patterns. The developers programmed these patterns into the compiler’s code so
-the borrow checker could infer the lifetimes in these situations and wouldn’t
-need explicit annotations.
+that the borrow checker could infer the lifetimes in these situations and
+wouldn’t need explicit annotations.
This piece of Rust history is relevant because it’s possible that more
deterministic patterns will emerge and be added to the compiler. In the future,
@@ -1731,8 +1762,8 @@ fits these cases, you don’t need to write the lifetimes explicitly.
The elision rules don’t provide full inference. If there is still ambiguity
about what lifetimes the references have after Rust applies the rules, the
compiler won’t guess what the lifetime of the remaining references should be.
-Instead of guessing, the compiler will give you an error that you can resolve by
-adding the lifetime annotations.
+Instead of guessing, the compiler will give you an error that you can resolve
+by adding the lifetime annotations.
Lifetimes on function or method parameters are called *input lifetimes*, and
lifetimes on return values are called *output lifetimes*.
@@ -1766,7 +1797,7 @@ references:
fn first_word(s: &str) -> &str {
```
-Then the compiler applies the first rule, which specifies that each parameter
+Then, the compiler applies the first rule, which specifies that each parameter
gets its own lifetime. We’ll call it `'a` as usual, so now the signature is
this:
@@ -1793,31 +1824,35 @@ no lifetime parameters when we started working with it in Listing 10-20:
fn longest(x: &str, y: &str) -> &str {
```
-Let’s apply the first rule: each parameter gets its own lifetime. This time we
+Let’s apply the first rule: Each parameter gets its own lifetime. This time we
have two parameters instead of one, so we have two lifetimes:
```
fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {
```
-You can see that the second rule doesn’t apply because there is more than one
+You can see that the second rule doesn’t apply, because there is more than one
input lifetime. The third rule doesn’t apply either, because `longest` is a
function rather than a method, so none of the parameters are `self`. After
working through all three rules, we still haven’t figured out what the return
type’s lifetime is. This is why we got an error trying to compile the code in
-Listing 10-20: the compiler worked through the lifetime elision rules but still
+Listing 10-20: The compiler worked through the lifetime elision rules but still
couldn’t figure out all the lifetimes of the references in the signature.
Because the third rule really only applies in method signatures, we’ll look at
lifetimes in that context next to see why the third rule means we don’t have to
annotate lifetimes in method signatures very often.
-### Lifetime Annotations in Method Definitions
+
+
+
+
+### In Method Definitions
When we implement methods on a struct with lifetimes, we use the same syntax as
-that of generic type parameters, as shown in Listing 10-11. Where we declare and
-use the lifetime parameters depends on whether they’re related to the struct
-fields or the method parameters and return values.
+that of generic type parameters, as shown in Listing 10-11. Where we declare
+and use the lifetime parameters depends on whether they’re related to the
+struct fields or the method parameters and return values.
Lifetime names for struct fields always need to be declared after the `impl`
keyword and then used after the struct’s name because those lifetimes are part
@@ -1829,7 +1864,7 @@ addition, the lifetime elision rules often make it so that lifetime annotations
aren’t necessary in method signatures. Let’s look at some examples using the
struct named `ImportantExcerpt` that we defined in Listing 10-24.
-First we’ll use a method named `level` whose only parameter is a reference to
+First, we’ll use a method named `level` whose only parameter is a reference to
`self` and whose return value is an `i32`, which is not a reference to anything:
```
@@ -1841,8 +1876,8 @@ impl<'a> ImportantExcerpt<'a> {
```
The lifetime parameter declaration after `impl` and its use after the type name
-are required, but we’re not required to annotate the lifetime of the reference
-to `self` because of the first elision rule.
+are required, but because of the first elision rule, we’re not required to
+annotate the lifetime of the reference to `self`.
Here is an example where the third lifetime elision rule applies:
@@ -1875,13 +1910,17 @@ always available. Therefore, the lifetime of all string literals is `'static`.
You might see suggestions in error messages to use the `'static` lifetime. But
before specifying `'static` as the lifetime for a reference, think about
-whether the reference you have actually lives the entire lifetime of your
-program or not, and whether you want it to. Most of the time, an error message
+whether or not the reference you have actually lives the entire lifetime of
+your program, and whether you want it to. Most of the time, an error message
suggesting the `'static` lifetime results from attempting to create a dangling
reference or a mismatch of the available lifetimes. In such cases, the solution
is to fix those problems, not to specify the `'static` lifetime.
-## Generic Type Parameters, Trait Bounds, and Lifetimes Together
+
+
+
+
+## Generic Type Parameters, Trait Bounds, and Lifetimes
Let’s briefly look at the syntax of specifying generic type parameters, trait
bounds, and lifetimes all in one function!
@@ -1926,5 +1965,5 @@ Believe it or not, there is much more to learn on the topics we discussed in
this chapter: Chapter 18 discusses trait objects, which are another way to use
traits. There are also more complex scenarios involving lifetime annotations
that you will only need in very advanced scenarios; for those, you should read
-the Rust Reference at *../reference/index.html*. But next, you’ll learn how to write tests in
-Rust so you can make sure your code is working the way it should.
+the Rust Reference at *../reference/trait-bounds.html*. But next, you’ll learn how to write tests in
+Rust so that you can make sure your code is working the way it should.
diff --git a/nostarch/chapter11.md b/nostarch/chapter11.md
index 6363cfddc7..f90efc3fe1 100644
--- a/nostarch/chapter11.md
+++ b/nostarch/chapter11.md
@@ -13,11 +13,12 @@ testing can be a very effective way to show the presence of bugs, but it is
hopelessly inadequate for showing their absence.” That doesn’t mean we shouldn’t
try to test as much as we can!
-Correctness in our programs is the extent to which our code does what we intend
-it to do. Rust is designed with a high degree of concern about the correctness
-of programs, but correctness is complex and not easy to prove. Rust’s type
-system shoulders a huge part of this burden, but the type system cannot catch
-everything. As such, Rust includes support for writing automated software tests.
+*Correctness* in our programs is the extent to which our code does what we
+intend it to do. Rust is designed with a high degree of concern about the
+correctness of programs, but correctness is complex and not easy to prove.
+Rust’s type system shoulders a huge part of this burden, but the type system
+cannot catch everything. As such, Rust includes support for writing automated
+software tests.
Say we write a function `add_two` that adds 2 to whatever number is passed to
it. This function’s signature accepts an integer as a parameter and returns an
@@ -33,7 +34,7 @@ We can write tests that assert, for example, that when we pass `3` to the
we make changes to our code to make sure any existing correct behavior has not
changed.
-Testing is a complex skill: although we can’t cover in one chapter every detail
+Testing is a complex skill: Although we can’t cover in one chapter every detail
about how to write good tests, in this chapter we will discuss the mechanics of
Rust’s testing facilities. We’ll talk about the annotations and macros
available to you when writing your tests, the default behavior and options
@@ -42,7 +43,7 @@ integration tests.
## How to Write Tests
-Tests are Rust functions that verify that the non-test code is functioning in
+*Tests* are Rust functions that verify that the non-test code is functioning in
the expected manner. The bodies of test functions typically perform these three
actions:
@@ -54,7 +55,11 @@ Let’s look at the features Rust provides specifically for writing tests that
take these actions, which include the `test` attribute, a few macros, and the
`should_panic` attribute.
-### The Anatomy of a Test Function
+
+
+
+
+### Structuring Test Functions
At its simplest, a test in Rust is a function that’s annotated with the `test`
attribute. Attributes are metadata about pieces of Rust code; one example is
@@ -66,12 +71,12 @@ fails.
Whenever we make a new library project with Cargo, a test module with a test
function in it is automatically generated for us. This module gives you a
-template for writing your tests so you don’t have to look up the exact
+template for writing your tests so that you don’t have to look up the exact
structure and syntax every time you start a new project. You can add as many
additional test functions and as many test modules as you want!
We’ll explore some aspects of how tests work by experimenting with the template
-test before we actually test any code. Then we’ll write some real-world tests
+test before we actually test any code. Then, we’ll write some real-world tests
that call some code that we’ve written and assert that its behavior is correct.
Let’s create a new library project called `adder` that will add two numbers:
@@ -117,11 +122,11 @@ mod tests {
Listing 11-1: The code generated automatically by `cargo new`
-The file starts with an example `add` function, so that we have something
-to test.
+The file starts with an example `add` function so that we have something to
+test.
For now, let’s focus solely on the `it_works` function. Note the `#[test]`
-annotation: this attribute indicates this is a test function, so the test
+annotation: This attribute indicates this is a test function, so the test
runner knows to treat this function as a test. We might also have non-test
functions in the `tests` module to help set up common scenarios or perform
common operations, so we always need to indicate which functions are tests.
@@ -160,13 +165,13 @@ Cargo compiled and ran the test. We see the line `running 1 test`. The next
line shows the name of the generated test function, called `tests::it_works`,
and that the result of running that test is `ok`. The overall summary `test result: ok.` means that all the tests passed, and the portion that reads `1 passed; 0 failed` totals the number of tests that passed or failed.
-It’s possible to mark a test as ignored so it doesn’t run in a particular
-instance; we’ll cover that in the “Ignoring Some Tests Unless Specifically
+It’s possible to mark a test as ignored so that it doesn’t run in a particular
+instance; we’ll cover that in the “Ignoring Tests Unless Specifically
Requested” section later in this chapter. Because we
haven’t done that here, the summary shows `0 ignored`. We can also pass an
argument to the `cargo test` command to run only tests whose name matches a
-string; this is called *filtering* and we’ll cover it in the “Running a
-Subset of Tests by Name” section. Here we haven’t
+string; this is called *filtering*, and we’ll cover it in the “Running a
+Subset of Tests by Name” section. Here, we haven’t
filtered the tests being run, so the end of the summary shows `0 filtered out`.
The `0 measured` statistic is for benchmark tests that measure performance.
@@ -203,7 +208,7 @@ mod tests {
}
```
-Then run `cargo test` again. The output now shows `exploration` instead of
+Then, run `cargo test` again. The output now shows `exploration` instead of
`it_works`:
```
@@ -297,22 +302,26 @@ check the line number of the panic matches the line number in the following para
-->
Instead of `ok`, the line `test tests::another` shows `FAILED`. Two new
-sections appear between the individual results and the summary: the first
+sections appear between the individual results and the summary: The first
displays the detailed reason for each test failure. In this case, we get the
details that `tests::another` failed because it panicked with the message `Make this test fail` on line 17 in the *src/lib.rs* file. The next section lists
just the names of all the failing tests, which is useful when there are lots of
tests and lots of detailed failing test output. We can use the name of a
-failing test to run just that test to more easily debug it; we’ll talk more
+failing test to run just that test to debug it more easily; we’ll talk more
about ways to run tests in the “Controlling How Tests Are
Run” section.
-The summary line displays at the end: overall, our test result is `FAILED`. We
+The summary line displays at the end: Overall, our test result is `FAILED`. We
had one test pass and one test fail.
Now that you’ve seen what the test results look like in different scenarios,
let’s look at some macros other than `panic!` that are useful in tests.
-### Checking Results with the assert! Macro
+
+
+
+
+### Checking Results with assert!
The `assert!` macro, provided by the standard library, is useful when you want
to ensure that some condition in a test evaluates to `true`. We give the
@@ -384,7 +393,7 @@ a glob here, so anything we define in the outer module is available to this
`tests` module.
We’ve named our test `larger_can_hold_smaller`, and we’ve created the two
-`Rectangle` instances that we need. Then we called the `assert!` macro and
+`Rectangle` instances that we need. Then, we called the `assert!` macro and
passed it the result of calling `larger.can_hold(&smaller)`. This expression is
supposed to return `true`, so our test should pass. Let’s find out!
@@ -464,8 +473,8 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
Two tests that pass! Now let’s see what happens to our test results when we
introduce a bug in our code. We’ll change the implementation of the `can_hold`
-method by replacing the greater-than sign with a less-than sign when it
-compares the widths:
+method by replacing the greater-than sign (`>`) with a less-than sign (`<`)
+when it compares the widths:
```
// --snip--
@@ -509,7 +518,11 @@ Our tests caught the bug! Because `larger.width` is `8` and `smaller.width` is
`5`, the comparison of the widths in `can_hold` now returns `false`: 8 is not
less than 5.
-### Testing Equality with the assert_eq! and assert_ne! Macros
+
+
+
+
+### Testing Equality with assert_eq! and assert_ne!
A common way to verify functionality is to test for equality between the result
of the code under test and the value you expect the code to return. You could
@@ -523,7 +536,7 @@ fails, which makes it easier to see *why* the test failed; conversely, the
expression, without printing the values that led to the `false` value.
In Listing 11-7, we write a function named `add_two` that adds `2` to its
-parameter, then we test this function using the `assert_eq!` macro.
+parameter, and then we test this function using the `assert_eq!` macro.
src/lib.rs
@@ -568,7 +581,7 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
```
We create a variable named `result` that holds the result of calling
-`add_two(2)`. Then we pass `result` and `4` as the arguments to the
+`add_two(2)`. Then, we pass `result` and `4` as the arguments to the
`assert_eq!` macro. The output line for this test is `test tests::it_adds_two ... ok`, and the `ok` text indicates that our test passed!
Let’s introduce a bug into our code to see what `assert_eq!` looks like when it
@@ -612,8 +625,8 @@ error: test failed, to rerun pass `--lib`
Our test caught the bug! The `tests::it_adds_two` test failed, and the message
tells us that the assertion that failed was `left == right` and what the `left`
-and `right` values are. This message helps us start debugging: the `left`
-argument, where we had the result of calling `add_two(2)`, was `5` but the
+and `right` values are. This message helps us start debugging: The `left`
+argument, where we had the result of calling `add_two(2)`, was `5`, but the
`right` argument was `4`. You can imagine that this would be especially helpful
when we have a lot of tests going on.
@@ -623,14 +636,14 @@ we specify the arguments matters. However, in Rust, they’re called `left` and
`right`, and the order in which we specify the value we expect and the value
the code produces doesn’t matter. We could write the assertion in this test as
`assert_eq!(4, result)`, which would result in the same failure message that
-displays `` assertion `left == right` failed``.
+displays ``assertion `left == right` failed``.
The `assert_ne!` macro will pass if the two values we give it are not equal and
-fail if they’re equal. This macro is most useful for cases when we’re not sure
-what a value *will* be, but we know what the value definitely *shouldn’t* be.
-For example, if we’re testing a function that is guaranteed to change its input
-in some way, but the way in which the input is changed depends on the day of
-the week that we run our tests, the best thing to assert might be that the
+will fail if they are equal. This macro is most useful for cases when we’re not
+sure what a value *will* be, but we know what the value definitely *shouldn’t*
+be. For example, if we’re testing a function that is guaranteed to change its
+input in some way, but the way in which the input is changed depends on the day
+of the week that we run our tests, the best thing to assert might be that the
output of the function is not equal to the input.
Under the surface, the `assert_eq!` and `assert_ne!` macros use the operators
@@ -651,8 +664,8 @@ details about these and other derivable traits.
You can also add a custom message to be printed with the failure message as
optional arguments to the `assert!`, `assert_eq!`, and `assert_ne!` macros. Any
arguments specified after the required arguments are passed along to the
-`format!` macro (discussed in “Concatenation with the `+` Operator or the
-`format!` Macro” in Chapter 8), so you can pass a format string that contains `{}`
+`format!` macro (discussed in “Concatenating with `+` or
+`format!`” in Chapter 8), so you can pass a format string that contains `{}`
placeholders and values to go in those placeholders. Custom messages are useful
for documenting what an assertion means; when a test fails, you’ll have a better
idea of what the problem is with the code.
@@ -984,15 +997,19 @@ error: test failed, to rerun pass `--lib`
```
The failure message indicates that this test did indeed panic as we expected,
-but the panic message did not include the expected string `less than or equal to 100`. The panic message that we did get in this case was `Guess value must be greater than or equal to 1, got 200.` Now we can start figuring out where
+but the panic message did not include the expected string `less than or equal to 100`. The panic message that we did get in this case was `Guess value must be greater than or equal to 1, got 200`. Now we can start figuring out where
our bug is!
### Using Result in Tests
-Our tests so far all panic when they fail. We can also write tests that use
+All of our tests so far panic when they fail. We can also write tests that use
`Result`! Here’s the test from Listing 11-1, rewritten to use `Result` and return an `Err` instead of panicking:
```
+#[cfg(test)]
+mod tests {
+ use super::*;
+
#[test]
fn it_works() -> Result<(), String> {
let result = add(2, 2);
@@ -1003,6 +1020,7 @@ Our tests so far all panic when they fail. We can also write tests that use
Err(String::from("two plus two does not equal four"))
}
}
+}
```
The `it_works` function now has the `Result<(), String>` return type. In the
@@ -1010,9 +1028,10 @@ body of the function, rather than calling the `assert_eq!` macro, we return
`Ok(())` when the test passes and an `Err` with a `String` inside when the test
fails.
-Writing tests so they return a `Result` enables you to use the question
-mark operator in the body of tests, which can be a convenient way to write
-tests that should fail if any operation within them returns an `Err` variant.
+Writing tests so that they return a `Result` enables you to use the
+question mark operator in the body of tests, which can be a convenient way to
+write tests that should fail if any operation within them returns an `Err`
+variant.
You can’t use the `#[should_panic]` annotation on tests that use `Result`. To assert that an operation returns an `Err` variant, *don’t* use the
question mark operator on the `Result` value. Instead, use
@@ -1036,26 +1055,26 @@ binary. To separate these two types of arguments, you list the arguments that
go to `cargo test` followed by the separator `--` and then the ones that go to
the test binary. Running `cargo test --help` displays the options you can use
with `cargo test`, and running `cargo test -- --help` displays the options you
-can use after the separator. Those options are also documented in the “Tests”
-section at *https://doc.rust-lang.org/rustc/tests/index.html* of the the rustc book at *https://doc.rust-lang.org/rustc/index.html*.
+can use after the separator. These options are also documented in the “Tests”
+section of *The `rustc` Book* at *https://doc.rust-lang.org/rustc/tests/index.html*.
### Running Tests in Parallel or Consecutively
When you run multiple tests, by default they run in parallel using threads,
-meaning they finish running faster and you get feedback quicker. Because the
-tests are running at the same time, you must make sure your tests don’t depend
-on each other or on any shared state, including a shared environment, such as
-the current working directory or environment variables.
+meaning they finish running more quickly and you get feedback sooner. Because
+the tests are running at the same time, you must make sure your tests don’t
+depend on each other or on any shared state, including a shared environment,
+such as the current working directory or environment variables.
For example, say each of your tests runs some code that creates a file on disk
-named *test-output.txt* and writes some data to that file. Then each test reads
-the data in that file and asserts that the file contains a particular value,
-which is different in each test. Because the tests run at the same time, one
-test might overwrite the file in the time between another test writing and
-reading the file. The second test will then fail, not because the code is
-incorrect but because the tests have interfered with each other while running
-in parallel. One solution is to make sure each test writes to a different file;
-another solution is to run the tests one at a time.
+named *test-output.txt* and writes some data to that file. Then, each test
+reads the data in that file and asserts that the file contains a particular
+value, which is different in each test. Because the tests run at the same time,
+one test might overwrite the file in the time between when another test is
+writing and reading the file. The second test will then fail, not because the
+code is incorrect but because the tests have interfered with each other while
+running in parallel. One solution is to make sure each test writes to a
+different file; another solution is to run the tests one at a time.
If you don’t want to run the tests in parallel or if you want more fine-grained
control over the number of threads used, you can send the `--test-threads` flag
@@ -1198,7 +1217,7 @@ error: test failed, to rerun pass `--lib`
### Running a Subset of Tests by Name
-Sometimes, running a full test suite can take a long time. If you’re working on
+Running a full test suite can sometimes take a long time. If you’re working on
code in a particular area, you might want to run only the tests pertaining to
that code. You can choose which tests to run by passing `cargo test` the name
or names of the test(s) you want to run as an argument.
@@ -1312,7 +1331,11 @@ named `one_hundred`. Also note that the module in which a test appears becomes
part of the test’s name, so we can run all the tests in a module by filtering
on the module’s name.
-### Ignoring Some Tests Unless Specifically Requested
+
+
+
+
+### Ignoring Tests Unless Specifically Requested
Sometimes a few specific tests can be very time-consuming to execute, so you
might want to exclude them during most runs of `cargo test`. Rather than
@@ -1415,7 +1438,7 @@ code that they’re testing. The convention is to create a module named `tests`
in each file to contain the test functions and to annotate the module with
`cfg(test)`.
-#### The Tests Module and \#[cfg(test)]
+#### The tests Module and \#[cfg(test)]
The `#[cfg(test)]` annotation on the `tests` module tells Rust to compile and
run the test code only when you run `cargo test`, not when you run `cargo build`. This saves compile time when you only want to build the library and
@@ -1455,7 +1478,11 @@ given a certain configuration option. In this case, the configuration option is
with `cargo test`. This includes any helper functions that might be within this
module, in addition to the functions annotated with `#[test]`.
-#### Testing Private Functions
+
+
+
+
+#### Private Function Tests
There’s debate within the testing community about whether or not private
functions should be tested directly, and other languages make it difficult or
@@ -1492,9 +1519,10 @@ Note that the `internal_adder` function is not marked as `pub`. Tests are just
Rust code, and the `tests` module is just another module. As we discussed in
“Paths for Referring to an Item in the Module Tree”,
items in child modules can use the items in their ancestor modules. In this
-test, we bring all of the `tests` module’s parent’s items into scope with `use super::*`, and then the test can call `internal_adder`. If you don’t think
-private functions should be tested, there’s nothing in Rust that will compel you
-to do so.
+test, we bring all of the items belonging to the `tests` module’s parent into
+scope with `use super::*`, and then the test can call `internal_adder`. If you
+don’t think private functions should be tested, there’s nothing in Rust that
+will compel you to do so.
### Integration Tests
@@ -1544,7 +1572,7 @@ fn it_adds_two() {
Listing 11-13: An integration test of a function in the `adder` crate
Each file in the *tests* directory is a separate crate, so we need to bring our
-library into each test crate’s scope. For that reason we add `use adder::add_two;` at the top of the code, which we didn’t need in the unit tests.
+library into each test crate’s scope. For that reason, we add `use adder::add_two;` at the top of the code, which we didn’t need in the unit tests.
We don’t need to annotate any code in *tests/integration_test.rs* with
`#[cfg(test)]`. Cargo treats the *tests* directory specially and compiles files
@@ -1579,7 +1607,7 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
The three sections of output include the unit tests, the integration test, and
the doc tests. Note that if any test in a section fails, the following sections
will not be run. For example, if a unit test fails, there won’t be any output
-for integration and doc tests because those tests will only be run if all unit
+for integration and doc tests, because those tests will only be run if all unit
tests are passing.
The first section for the unit tests is the same as we’ve been seeing: one line
@@ -1625,7 +1653,7 @@ share the same behavior as files in *src* do, as you learned in Chapter 7
regarding how to separate code into modules and files.
The different behavior of *tests* directory files is most noticeable when you
-have a set of helper functions to use in multiple integration test files and
+have a set of helper functions to use in multiple integration test files, and
you try to follow the steps in the “Separating Modules into Different
Files” section of Chapter 7 to
extract them into a common module. For example, if we create *tests/common.rs*
@@ -1743,8 +1771,8 @@ file will work as well, and that small amount of code doesn’t need to be teste
## Summary
Rust’s testing features provide a way to specify how code should function to
-ensure it continues to work as you expect, even as you make changes. Unit tests
-exercise different parts of a library separately and can test private
+ensure that it continues to work as you expect, even as you make changes. Unit
+tests exercise different parts of a library separately and can test private
implementation details. Integration tests check that many parts of the library
work together correctly, and they use the library’s public API to test the code
in the same way external code will use it. Even though Rust’s type system and
diff --git a/nostarch/chapter12.md b/nostarch/chapter12.md
index dbb7242d83..7b22854400 100644
--- a/nostarch/chapter12.md
+++ b/nostarch/chapter12.md
@@ -18,7 +18,7 @@ an ideal language for creating command line tools, so for our project, we’ll
make our own version of the classic command line search tool `grep`
(**g**lobally search a **r**egular **e**xpression and **p**rint). In the
simplest use case, `grep` searches a specified file for a specified string. To
-do so, `grep` takes as its arguments a file path and a string. Then it reads
+do so, `grep` takes as its arguments a file path and a string. Then, it reads
the file, finds lines in that file that contain the string argument, and prints
those lines.
@@ -51,7 +51,7 @@ cover in detail.
Let’s create a new project with, as always, `cargo new`. We’ll call our project
`minigrep` to distinguish it from the `grep` tool that you might already have
-on your system.
+on your system:
```
$ cargo new minigrep
@@ -79,13 +79,13 @@ just learning this concept, let’s implement this capability ourselves.
To enable `minigrep` to read the values of command line arguments we pass to
it, we’ll need the `std::env::args` function provided in Rust’s standard
library. This function returns an iterator of the command line arguments passed
-to `minigrep`. We’ll cover iterators fully in Chapter 13. For now, you only need to know two details about iterators: iterators
+to `minigrep`. We’ll cover iterators fully in Chapter 13. For now, you only need to know two details about iterators: Iterators
produce a series of values, and we can call the `collect` method on an iterator
-to turn it into a collection, such as a vector, that contains all the elements
+to turn it into a collection, such as a vector, which contains all the elements
the iterator produces.
The code in Listing 12-1 allows your `minigrep` program to read any command
-line arguments passed to it, and then collect the values into a vector.
+line arguments passed to it and then collect the values into a vector.
src/main.rs
@@ -100,8 +100,8 @@ fn main() {
Listing 12-1: Collecting the command line arguments into a vector and printing them
-First we bring the `std::env` module into scope with a `use` statement so we
-can use its `args` function. Notice that the `std::env::args` function is
+First, we bring the `std::env` module into scope with a `use` statement so that
+we can use its `args` function. Notice that the `std::env::args` function is
nested in two levels of modules. As we discussed in Chapter
7, in cases where the desired function is
nested in more than one module, we’ve chosen to bring the parent module into
@@ -164,8 +164,8 @@ chapter, we’ll ignore it and save only the two arguments we need.
The program is currently able to access the values specified as command line
arguments. Now we need to save the values of the two arguments in variables so
-we can use the values throughout the rest of the program. We do that in Listing
-12-2.
+that we can use the values throughout the rest of the program. We do that in
+Listing 12-2.
src/main.rs
@@ -214,7 +214,7 @@ capabilities instead.
## Reading a File
Now we’ll add functionality to read the file specified in the `file_path`
-argument. First we need a sample file to test it with: we’ll use a file with a
+argument. First, we need a sample file to test it with: We’ll use a file with a
small amount of text over multiple lines with some repeated words. Listing 12-3
has an Emily Dickinson poem that will work well! Create a file called
*poem.txt* at the root level of your project, and enter the poem “I’m Nobody!
@@ -258,15 +258,15 @@ fn main() {
Listing 12-4: Reading the contents of the file specified by the second argument
-First we bring in a relevant part of the standard library with a `use`
-statement: we need `std::fs` to handle files.
+First, we bring in a relevant part of the standard library with a `use`
+statement: We need `std::fs` to handle files.
In `main`, the new statement `fs::read_to_string` takes the `file_path`, opens
that file, and returns a value of type `std::io::Result` that contains
the file’s contents.
After that, we again add a temporary `println!` statement that prints the value
-of `contents` after the file is read, so we can check that the program is
+of `contents` after the file is read so that we can check that the program is
working so far.
Let’s run this code with any string as the first command line argument (because
@@ -295,7 +295,7 @@ To an admiring bog!
Great! The code read and then printed the contents of the file. But the code
has a few flaws. At the moment, the `main` function has multiple
-responsibilities: generally, functions are clearer and easier to maintain if
+responsibilities: Generally, functions are clearer and easier to maintain if
each function is responsible for only one idea. The other problem is that we’re
not handling errors as well as we could. The program is still small, so these
flaws aren’t a big problem, but as the program grows, it will be harder to fix
@@ -307,14 +307,14 @@ code. We’ll do that next.
To improve our program, we’ll fix four problems that have to do with the
program’s structure and how it’s handling potential errors. First, our `main`
-function now performs two tasks: it parses arguments and reads files. As our
+function now performs two tasks: It parses arguments and reads files. As our
program grows, the number of separate tasks the `main` function handles will
increase. As a function gains responsibilities, it becomes more difficult to
reason about, harder to test, and harder to change without breaking one of its
-parts. It’s best to separate functionality so each function is responsible for
-one task.
+parts. It’s best to separate functionality so that each function is responsible
+for one task.
-This issue also ties into the second problem: although `query` and `file_path`
+This issue also ties into the second problem: Although `query` and `file_path`
are configuration variables to our program, variables like `contents` are used
to perform the program’s logic. The longer `main` becomes, the more variables
we’ll need to bring into scope; the more variables we have in scope, the harder
@@ -322,7 +322,7 @@ it will be to keep track of the purpose of each. It’s best to group the
configuration variables into one structure to make their purpose clear.
The third problem is that we’ve used `expect` to print an error message when
-reading the file fails, but the error message just prints `Should have been able to read the file`. Reading a file can fail in a number of ways: for
+reading the file fails, but the error message just prints `Should have been able to read the file`. Reading a file can fail in a number of ways: For
example, the file could be missing, or we might not have permission to open it.
Right now, regardless of the situation, we’d print the same error message for
everything, which wouldn’t give the user any information!
@@ -330,14 +330,18 @@ everything, which wouldn’t give the user any information!
Fourth, we use `expect` to handle an error, and if the user runs our program
without specifying enough arguments, they’ll get an `index out of bounds` error
from Rust that doesn’t clearly explain the problem. It would be best if all the
-error-handling code were in one place so future maintainers had only one place
-to consult the code if the error-handling logic needed to change. Having all the
-error-handling code in one place will also ensure that we’re printing messages
-that will be meaningful to our end users.
+error-handling code were in one place so that future maintainers had only one
+place to consult the code if the error-handling logic needed to change. Having
+all the error-handling code in one place will also ensure that we’re printing
+messages that will be meaningful to our end users.
Let’s address these four problems by refactoring our project.
-### Separation of Concerns for Binary Projects
+
+
+
+
+### Separating Concerns in Binary Projects
The organizational problem of allocating responsibility for multiple tasks to
the `main` function is common to many binary projects. As a result, many Rust
@@ -489,10 +493,10 @@ giving up a little performance to gain simplicity is a worthwhile trade-off.
> easier to start with the most efficient solution, but for now, it’s
> perfectly acceptable to call `clone`.
-We’ve updated `main` so it places the instance of `Config` returned by
+We’ve updated `main` so that it places the instance of `Config` returned by
`parse_config` into a variable named `config`, and we updated the code that
-previously used the separate `query` and `file_path` variables so it now uses
-the fields on the `Config` struct instead.
+previously used the separate `query` and `file_path` variables so that it now
+uses the fields on the `Config` struct instead.
Now our code more clearly conveys that `query` and `file_path` are related and
that their purpose is to configure how the program will work. Any code that
@@ -508,7 +512,7 @@ relationship should be conveyed in our code. We then added a `Config` struct to
name the related purpose of `query` and `file_path` and to be able to return the
values’ names as struct field names from the `parse_config` function.
-So now that the purpose of the `parse_config` function is to create a `Config`
+So, now that the purpose of the `parse_config` function is to create a `Config`
instance, we can change `parse_config` from a plain function to a function
named `new` that is associated with the `Config` struct. Making this change
will make the code more idiomatic. We can create instances of types in the
@@ -610,9 +614,9 @@ not enough arguments
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```
-This output is better: we now have a reasonable error message. However, we also
+This output is better: We now have a reasonable error message. However, we also
have extraneous information we don’t want to give to our users. Perhaps the
-technique we used in Listing 9-13 isn’t the best one to use here: a call to
+technique we used in Listing 9-13 isn’t the best one to use here: A call to
`panic!` is more appropriate for a programming problem than a usage problem,
as discussed in Chapter 9. Instead,
we’ll use the other technique you learned about in Chapter 9—returning a
@@ -629,7 +633,7 @@ the successful case and will describe the problem in the error case. We’re als
going to change the function name from `new` to `build` because many
programmers expect `new` functions to never fail. When `Config::build` is
communicating to `main`, we can use the `Result` type to signal there was a
-problem. Then we can change `main` to convert an `Err` variant into a more
+problem. Then, we can change `main` to convert an `Err` variant into a more
practical error for our users without the surrounding text about `thread 'main'` and `RUST_BACKTRACE` that a call to `panic!` causes.
Listing 12-9 shows the changes we need to make to the return value of the
@@ -660,7 +664,7 @@ Our `build` function returns a `Result` with a `Config` instance in the success
case and a string literal in the error case. Our error values will always be
string literals that have the `'static` lifetime.
-We’ve made two changes in the body of the function: instead of calling `panic!`
+We’ve made two changes in the body of the function: Instead of calling `panic!`
when the user doesn’t pass enough arguments, we now return an `Err` value, and
we’ve wrapped the `Config` return value in an `Ok`. These changes make the
function conform to its new type signature.
@@ -704,8 +708,8 @@ In this listing, we’ve used a method we haven’t covered in detail yet:
`unwrap_or_else`, which is defined on `Result` by the standard library.
Using `unwrap_or_else` allows us to define some custom, non-`panic!` error
handling. If the `Result` is an `Ok` value, this method’s behavior is similar
-to `unwrap`: it returns the inner value that `Ok` is wrapping. However, if the
-value is an `Err` value, this method calls the code in the *closure*, which is
+to `unwrap`: It returns the inner value that `Ok` is wrapping. However, if the
+value is an `Err` value, this method calls the code in the closure, which is
an anonymous function we define and pass as an argument to `unwrap_or_else`.
We’ll cover closures in more detail in Chapter 13. For
now, you just need to know that `unwrap_or_else` will pass the inner value of
@@ -716,7 +720,7 @@ appears between the vertical pipes. The code in the closure can then use the
We’ve added a new `use` line to bring `process` from the standard library into
scope. The code in the closure that will be run in the error case is only two
-lines: we print the `err` value and then call `process::exit`. The
+lines: We print the `err` value and then call `process::exit`. The
`process::exit` function will stop the program immediately and return the
number that was passed as the exit status code. This is similar to the
`panic!`-based handling we used in Listing 12-8, but we no longer get all the
@@ -734,12 +738,12 @@ Great! This output is much friendlier for our users.
-
+
-### Extracting Logic from the main Function
+### Extracting Logic from main
Now that we’ve finished refactoring the configuration parsing, let’s turn to
-the program’s logic. As we stated in “Separation of Concerns for Binary
+the program’s logic. As we stated in “Separating Concerns in Binary
Projects”, we’ll
extract a function named `run` that will hold all the logic currently in the
`main` function that isn’t involved with setting up configuration or handling
@@ -777,7 +781,11 @@ The `run` function now contains all the remaining logic from `main`, starting
from reading the file. The `run` function takes the `Config` instance as an
argument.
-#### Returning Errors from the run Function
+
+
+
+
+#### Returning Errors from run
With the remaining program logic separated into the `run` function, we can
improve the error handling, as we did with `Config::build` in Listing 12-9.
@@ -810,14 +818,14 @@ the `run` function to `Result<(), Box>`. This function previously
returned the unit type, `()`, and we keep that as the value returned in the
`Ok` case.
-For the error type, we used the *trait object* `Box` (and we’ve
-brought `std::error::Error` into scope with a `use` statement at the top).
-We’ll cover trait objects in Chapter 18. For now, just
-know that `Box` means the function will return a type that
-implements the `Error` trait, but we don’t have to specify what particular type
-the return value will be. This gives us flexibility to return error values that
-may be of different types in different error cases. The `dyn` keyword is short
-for *dynamic*.
+For the error type, we used the trait object `Box` (and we brought
+`std::error::Error` into scope with a `use` statement at the top). We’ll cover
+trait objects in Chapter 18. For now, just know that
+`Box` means the function will return a type that implements the
+`Error` trait, but we don’t have to specify what particular type the return
+value will be. This gives us flexibility to return error values that may be of
+different types in different error cases. The `dyn` keyword is short for
+*dynamic*.
Second, we’ve removed the call to `expect` in favor of the `?` operator, as we
talked about in Chapter 9. Rather than
@@ -827,7 +835,7 @@ for the caller to handle.
Third, the `run` function now returns an `Ok` value in the success case.
We’ve declared the `run` function’s success type as `()` in the signature,
which means we need to wrap the unit type value in the `Ok` value. This
-`Ok(())` syntax might look a bit strange at first, but using `()` like this is
+`Ok(())` syntax might look a bit strange at first. But using `()` like this is
the idiomatic way to indicate that we’re calling `run` for its side effects
only; it doesn’t return a value we need.
@@ -901,7 +909,7 @@ the success case, we only care about detecting an error, so we don’t need
`unwrap_or_else` to return the unwrapped value, which would only be `()`.
The bodies of the `if let` and the `unwrap_or_else` functions are the same in
-both cases: we print the error and exit.
+both cases: We print the error and exit.
### Splitting Code into a Library Crate
@@ -921,9 +929,12 @@ the signature in more detail when we fill in the implementation.
src/lib.rs
```
+pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
+ unimplemented!();
+}
```
-Listing 12-13: Defining the `search` function in *src/lib.rs*
+Listing 12-13: Defining the `search` function in *src/lib.rs*
We’ve used the `pub` keyword on the function definition to designate `search`
as part of our library crate’s public API. We now have a library crate that we
@@ -943,6 +954,7 @@ fn main() {
}
// --snip--
+
fn run(config: Config) -> Result<(), Box> {
let contents = fs::read_to_string(config.file_path)?;
@@ -959,7 +971,7 @@ Listing 12-14: Using the `minigrep` library crate’s `search` function in *src/
We add a `use minigrep::search` line to bring the `search` function from
the library crate into the binary crate’s scope. Then, in the `run` function,
rather than printing out the contents of the file, we call the `search`
-function and pass the `config.query` value and `contents` as arguments. Then
+function and pass the `config.query` value and `contents` as arguments. Then,
`run` will use a `for` loop to print each line returned from `search` that
matched the query. This is also a good time to remove the `println!` calls in
the `main` function that displayed the query and the file path so that our
@@ -967,7 +979,7 @@ program only prints the search results (if no errors occur).
Note that the search function will be collecting all the results into a vector
it returns before any printing happens. This implementation could be slow to
-display results when searching large files because results aren’t printed as
+display results when searching large files, because results aren’t printed as
they’re found; we’ll discuss a possible way to fix this using iterators in
Chapter 13.
@@ -976,10 +988,14 @@ future. Now it’s much easier to handle errors, and we’ve made the code more
modular. Almost all of our work will be done in *src/lib.rs* from here on out.
Let’s take advantage of this newfound modularity by doing something that would
-have been difficult with the old code but is easy with the new code: we’ll
+have been difficult with the old code but is easy with the new code: We’ll
write some tests!
-## Developing the Library’s Functionality with Test-Driven Development
+
+
+
+
+## Adding Functionality with Test-Driven Development
Now that we have the search logic in *src/lib.rs* separate from the `main`
function, it’s much easier to write tests for the core functionality of our
@@ -998,7 +1014,7 @@ the test-driven development (TDD) process with the following steps:
Though it’s just one of many ways to write software, TDD can help drive code
design. Writing the test before you write the code that makes the test pass
-helps to maintain high test coverage throughout the process.
+helps maintain high test coverage throughout the process.
We’ll test-drive the implementation of the functionality that will actually do
the searching for the query string in the file contents and produce a list of
@@ -1009,7 +1025,7 @@ lines that match the query. We’ll add this functionality in a function called
In *src/lib.rs*, we’ll add a `tests` module with a test function, as we did in
Chapter 11. The test function specifies the
-behavior we want the `search` function to have: it will take a query and the
+behavior we want the `search` function to have: It will take a query and the
text to search, and it will return only the lines from the text that contain
the query. Listing 12-15 shows this test.
@@ -1047,8 +1063,8 @@ If we run this test, it will currently fail because the `unimplemented!` macro
panics with the message “not implemented”. In accordance with TDD principles,
we’ll take a small step of adding just enough code to get the test to not panic
when calling the function by defining the `search` function to always return an
-empty vector, as shown in Listing 12-16. Then the test should compile and fail
-because an empty vector doesn’t match a vector containing the line `"safe, fast, productive."`
+empty vector, as shown in Listing 12-16. Then, the test should compile and fail
+because an empty vector doesn’t match a vector containing the line `"safe, fast, productive."`.
src/lib.rs
@@ -1058,7 +1074,7 @@ pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
}
```
-Listing 12-16: Defining just enough of the `search` function so calling it won’t panic
+Listing 12-16: Defining just enough of the `search` function so that calling it won’t panic
Now let’s discuss why we need to define an explicit lifetime `'a` in the
signature of `search` and use that lifetime with the `contents` argument and
@@ -1143,7 +1159,7 @@ pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
Listing 12-17: Iterating through each line in `contents`
The `lines` method returns an iterator. We’ll talk about iterators in depth in
-Chapter 13, but recall that you saw this way
+Chapter 13. But recall that you saw this way
of using an iterator in Listing 3-5, where we used a
`for` loop with an iterator to run some code on each item in a collection.
@@ -1195,7 +1211,7 @@ pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
}
```
-Listing 12-19: Storing the lines that match so we can return them
+Listing 12-19: Storing the lines that match so that we can return them
Now the `search` function should return only the lines that contain `query`,
and our test should pass. Let’s run the test:
@@ -1284,7 +1300,11 @@ users enter it each time they want it to apply, but by instead making it an
environment variable, we allow our users to set the environment variable once
and have all their searches be case insensitive in that terminal session.
-### Writing a Failing Test for the Case-Insensitive search Function
+
+
+
+
+### Writing a Failing Test for Case-Insensitive Search
We first add a new `search_case_insensitive` function to the `minigrep` library
that will be called when the environment variable has a value. We’ll continue
@@ -1376,10 +1396,10 @@ pub fn search_case_insensitive<'a>(
Listing 12-21: Defining the `search_case_insensitive` function to lowercase the query and the line before comparing them
-First we lowercase the `query` string and store it in a new variable with the
+First, we lowercase the `query` string and store it in a new variable with the
same name, shadowing the original `query`. Calling `to_lowercase` on the query
is necessary so that no matter whether the user’s query is `"rust"`, `"RUST"`,
-`"Rust"`, or ```"``rUsT``"```, we’ll treat the query as if it were `"rust"` and be
+`"Rust"`, or `"rUsT"`, we’ll treat the query as if it were `"rust"` and be
insensitive to the case. While `to_lowercase` will handle basic Unicode, it
won’t be 100 percent accurate. If we were writing a real application, we’d want
to do a bit more work here, but this section is about environment variables,
@@ -1387,7 +1407,7 @@ not Unicode, so we’ll leave it at that here.
Note that `query` is now a `String` rather than a string slice because calling
`to_lowercase` creates new data rather than referencing existing data. Say the
-query is `"rUsT"`, as an example: that string slice doesn’t contain a lowercase
+query is `"rUsT"`, as an example: That string slice doesn’t contain a lowercase
`u` or `t` for us to use, so we have to allocate a new `String` containing
`"rust"`. When we pass `query` as an argument to the `contains` method now, we
need to add an ampersand because the signature of `contains` is defined to take
@@ -1425,8 +1445,8 @@ test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fini
```
-Great! They passed. Now, let’s call the new `search_case_insensitive` function
-from the `run` function. First we’ll add a configuration option to the `Config`
+Great! They passed. Now let’s call the new `search_case_insensitive` function
+from the `run` function. First, we’ll add a configuration option to the `Config`
struct to switch between case-sensitive and case-insensitive search. Adding
this field will cause compiler errors because we aren’t initializing this field
anywhere yet:
@@ -1518,11 +1538,11 @@ care about the *value* of the environment variable, just whether it’s set or
unset, so we’re checking `is_ok` rather than using `unwrap`, `expect`, or any
of the other methods we’ve seen on `Result`.
-We pass the value in the `ignore_case` variable to the `Config` instance so the
-`run` function can read that value and decide whether to call
+We pass the value in the `ignore_case` variable to the `Config` instance so
+that the `run` function can read that value and decide whether to call
`search_case_insensitive` or `search`, as we implemented in Listing 12-22.
-Let’s give it a try! First we’ll run our program without the environment
+Let’s give it a try! First, we’ll run our program without the environment
variable set and with the query `to`, which should match any line that contains
the word *to* in all lowercase:
@@ -1536,7 +1556,7 @@ How dreary to be somebody!
```
Looks like that still works! Now let’s run the program with `IGNORE_CASE` set
-to `1` but with the same query *to*:
+to `1` but with the same query `to`:
```
$ IGNORE_CASE=1 cargo run -- to poem.txt
@@ -1585,9 +1605,13 @@ precedence if the program is run with one set to case sensitive and one set to
ignore case.
The `std::env` module contains many more useful features for dealing with
-environment variables: check out its documentation to see what is available.
+environment variables: Check out its documentation to see what is available.
+
+
+
+
-## Writing Error Messages to Standard Error Instead of Standard Output
+## Redirecting Errors to Standard Error
At the moment, we’re writing all of our output to the terminal using the
`println!` macro. In most terminals, there are two kinds of output: *standard
@@ -1601,7 +1625,7 @@ to use something else to print to standard error.
### Checking Where Errors Are Written
-First let’s observe how the content printed by `minigrep` is currently being
+First, let’s observe how the content printed by `minigrep` is currently being
written to standard output, including any error messages we want to write to
standard error instead. We’ll do that by redirecting the standard output stream
to a file while intentionally causing an error. We won’t redirect the standard
@@ -1609,9 +1633,10 @@ error stream, so any content sent to standard error will continue to display on
the screen.
Command line programs are expected to send error messages to the standard error
-stream so we can still see error messages on the screen even if we redirect the
-standard output stream to a file. Our program is not currently well behaved:
-we’re about to see that it saves the error message output to a file instead!
+stream so that we can still see error messages on the screen even if we
+redirect the standard output stream to a file. Our program is not currently
+well behaved: We’re about to see that it saves the error message output to a
+file instead!
To demonstrate this behavior, we’ll run the program with `>` and the file path,
*output.txt*, that we want to redirect the standard output stream to. We won’t
@@ -1631,8 +1656,8 @@ Problem parsing arguments: not enough arguments
```
Yup, our error message is being printed to standard output. It’s much more
-useful for error messages like this to be printed to standard error so only
-data from a successful run ends up in the file. We’ll change that.
+useful for error messages like this to be printed to standard error so that
+only data from a successful run ends up in the file. We’ll change that.
### Printing Errors to Standard Error
diff --git a/nostarch/chapter13.md b/nostarch/chapter13.md
index 73fede40be..e22c6baa14 100644
--- a/nostarch/chapter13.md
+++ b/nostarch/chapter13.md
@@ -23,19 +23,20 @@ More specifically, we’ll cover:
* *Closures*, a function-like construct you can store in a variable
* *Iterators*, a way of processing a series of elements
* How to use closures and iterators to improve the I/O project in Chapter 12
-* The performance of closures and iterators (spoiler alert: they’re faster than
+* The performance of closures and iterators (spoiler alert: They’re faster than
you might think!)
We’ve already covered some other Rust features, such as pattern matching and
enums, that are also influenced by the functional style. Because mastering
-closures and iterators is an important part of writing idiomatic, fast Rust
+closures and iterators is an important part of writing fast, idiomatic, Rust
code, we’ll devote this entire chapter to them.
-
+
+
-## Closures: Anonymous Functions That Capture Their Environment
+## Closures
Rust’s closures are anonymous functions you can save in a variable or pass as
arguments to other functions. You can create the closure in one place and then
@@ -49,11 +50,12 @@ customization.
+
-### Capturing the Environment with Closures
+### Capturing the Environment
We’ll first examine how we can use closures to capture values from the
-environment they’re defined in for later use. Here’s the scenario: every so
+environment they’re defined in for later use. Here’s the scenario: Every so
often, our T-shirt company gives away an exclusive, limited-edition shirt to
someone on our mailing list as a promotion. People on the mailing list can
optionally add their favorite color to their profile. If the person chosen for
@@ -66,8 +68,8 @@ enum called `ShirtColor` that has the variants `Red` and `Blue` (limiting the
number of colors available for simplicity). We represent the company’s
inventory with an `Inventory` struct that has a field named `shirts` that
contains a `Vec` representing the shirt colors currently in stock.
-The method `giveaway` defined on `Inventory` gets the optional shirt
-color preference of the free-shirt winner, and returns the shirt color the
+The method `giveaway` defined on `Inventory` gets the optional shirt color
+preference of the free-shirt winner, and it returns the shirt color the
person will get. This setup is shown in Listing 13-1.
src/main.rs
@@ -172,7 +174,11 @@ immutable reference to the `self` `Inventory` instance and passes it with the
code we specify to the `unwrap_or_else` method. Functions, on the other hand,
are not able to capture their environment in this way.
-### Closure Type Inference and Annotation
+
+
+
+
+### Inferring and Annotating Closure Types
There are more differences between functions and closures. Closures don’t
usually require you to annotate the types of the parameters or the return value
@@ -180,8 +186,8 @@ like `fn` functions do. Type annotations are required on functions because the
types are part of an explicit interface exposed to your users. Defining this
interface rigidly is important for ensuring that everyone agrees on what types
of values a function uses and returns. Closures, on the other hand, aren’t used
-in an exposed interface like this: they’re stored in variables and used without
-naming them and exposing them to users of our library.
+in an exposed interface like this: They’re stored in variables, and they’re
+used without naming them and exposing them to users of our library.
Closures are typically short and relevant only within a narrow context rather
than in any arbitrary scenario. Within these limited contexts, the compiler can
@@ -368,10 +374,10 @@ After calling closure: [1, 2, 3, 7]
```
Note that there’s no longer a `println!` between the definition and the call of
-the `borrows_mutably` closure: when `borrows_mutably` is defined, it captures a
+the `borrows_mutably` closure: When `borrows_mutably` is defined, it captures a
mutable reference to `list`. We don’t use the closure again after the closure
is called, so the mutable borrow ends. Between the closure definition and the
-closure call, an immutable borrow to print isn’t allowed because no other
+closure call, an immutable borrow to print isn’t allowed, because no other
borrows are allowed when there’s a mutable borrow. Try adding a `println!`
there to see what error message you get!
@@ -415,17 +421,18 @@ main thread finishes, or the main thread might finish first. If the main thread
maintained ownership of `list` but ended before the new thread and drops
`list`, the immutable reference in the thread would be invalid. Therefore, the
compiler requires that `list` be moved into the closure given to the new thread
-so the reference will be valid. Try removing the `move` keyword or using `list`
-in the main thread after the closure is defined to see what compiler errors you
-get!
+so that the reference will be valid. Try removing the `move` keyword or using
+`list` in the main thread after the closure is defined to see what compiler
+errors you get!
+
-### Moving Captured Values Out of Closures and the Fn Traits
+### Moving Captured Values Out of Closures
Once a closure has captured a reference or captured ownership of a value from
the environment where the closure is defined (thus affecting what, if anything,
@@ -433,7 +440,7 @@ is moved *into* the closure), the code in the body of the closure defines what
happens to the references or values when the closure is evaluated later (thus
affecting what, if anything, is moved *out of* the closure).
-A closure body can do any of the following: move a captured value out of the
+A closure body can do any of the following: Move a captured value out of the
closure, mutate the captured value, neither move nor mutate the value, or
capture nothing from the environment to begin with.
@@ -447,14 +454,13 @@ depending on how the closure’s body handles the values:
at least this trait because all closures can be called. A closure that moves
captured values out of its body will only implement `FnOnce` and none of the
other `Fn` traits because it can only be called once.
-* `FnMut` applies to closures that don’t move captured values out of their
- body, but that might mutate the captured values. These closures can be
- called more than once.
+* `FnMut` applies to closures that don’t move captured values out of their body
+ but might mutate the captured values. These closures can be called more than
+ once.
* `Fn` applies to closures that don’t move captured values out of their body
- and that don’t mutate captured values, as well as closures that capture
- nothing from their environment. These closures can be called more than once
- without mutating their environment, which is important in cases such as
- calling a closure multiple times concurrently.
+ and don’t mutate captured values, as well as closures that capture nothing
+ from their environment. These closures can be called more than once without
+ mutating their environment, which is important in cases such as calling a closure multiple times concurrently.
Let’s look at the definition of the `unwrap_or_else` method on `Option` that
we used in Listing 13-1:
@@ -475,7 +481,7 @@ impl Option {
Recall that `T` is the generic type representing the type of the value in the
`Some` variant of an `Option`. That type `T` is also the return type of the
-`unwrap_or_else` function: code that calls `unwrap_or_else` on an
+`unwrap_or_else` function: Code that calls `unwrap_or_else` on an
`Option`, for example, will get a `String`.
Next, notice that the `unwrap_or_else` function has the additional generic type
@@ -485,7 +491,7 @@ the closure we provide when calling `unwrap_or_else`.
The trait bound specified on the generic type `F` is `FnOnce() -> T`, which
means `F` must be able to be called once, take no arguments, and return a `T`.
Using `FnOnce` in the trait bound expresses the constraint that
-`unwrap_or_else` is only going to call `f` at most one time. In the body of
+`unwrap_or_else` will not call `f` more than once. In the body of
`unwrap_or_else`, we can see that if the `Option` is `Some`, `f` won’t be
called. If the `Option` is `None`, `f` will be called once. Because all
closures implement `FnOnce`, `unwrap_or_else` accepts all three kinds of
@@ -503,9 +509,9 @@ Now let’s look at the standard library method `sort_by_key`, defined on slices
to see how that differs from `unwrap_or_else` and why `sort_by_key` uses
`FnMut` instead of `FnOnce` for the trait bound. The closure gets one argument
in the form of a reference to the current item in the slice being considered,
-and returns a value of type `K` that can be ordered. This function is useful
+and it returns a value of type `K` that can be ordered. This function is useful
when you want to sort a slice by a particular attribute of each item. In
-Listing 13-7, we have a list of `Rectangle` instances and we use `sort_by_key`
+Listing 13-7, we have a list of `Rectangle` instances, and we use `sort_by_key`
to order them by their `width` attribute from low to high.
src/main.rs
@@ -591,13 +597,13 @@ fn main() {
Listing 13-8: Attempting to use an `FnOnce` closure with `sort_by_key`
-This is a contrived, convoluted way (that doesn’t work) to try and count the
+This is a contrived, convoluted way (that doesn’t work) to try to count the
number of times `sort_by_key` calls the closure when sorting `list`. This code
attempts to do this counting by pushing `value`—a `String` from the closure’s
environment—into the `sort_operations` vector. The closure captures `value` and
then moves `value` out of the closure by transferring ownership of `value` to
the `sort_operations` vector. This closure can be called once; trying to call
-it a second time wouldn’t work because `value` would no longer be in the
+it a second time wouldn’t work, because `value` would no longer be in the
environment to be pushed into `sort_operations` again! Therefore, this closure
only implements `FnOnce`. When we try to compile this code, we get this error
that `value` can’t be moved out of the closure because the closure must
@@ -632,7 +638,7 @@ move values out of the environment. Keeping a counter in the environment and
incrementing its value in the closure body is a more straightforward way to
count the number of times the closure is called. The closure in Listing 13-9
works with `sort_by_key` because it is only capturing a mutable reference to the
-`num_sort_operations` counter and can therefore be called more than once:
+`num_sort_operations` counter and can therefore be called more than once.
src/main.rs
@@ -659,7 +665,7 @@ fn main() {
}
```
-Listing 13-9: Using an `FnMut` closure with `sort_by_key` is allowed
+Listing 13-9: Using an `FnMut` closure with `sort_by_key` is allowed.
The `Fn` traits are important when defining or using functions or types that
make use of closures. In the next section, we’ll discuss iterators. Many
@@ -774,11 +780,11 @@ src/lib.rs
Listing 13-12: Calling the `next` method on an iterator
-Note that we needed to make `v1_iter` mutable: calling the `next` method on an
+Note that we needed to make `v1_iter` mutable: Calling the `next` method on an
iterator changes internal state that the iterator uses to keep track of where
it is in the sequence. In other words, this code *consumes*, or uses up, the
iterator. Each call to `next` eats up an item from the iterator. We didn’t need
-to make `v1_iter` mutable when we used a `for` loop because the loop took
+to make `v1_iter` mutable when we used a `for` loop, because the loop took
ownership of `v1_iter` and made it mutable behind the scenes.
Also note that the values we get from the calls to `next` are immutable
@@ -797,7 +803,7 @@ trait. Some of these methods call the `next` method in their definition, which
is why you’re required to implement the `next` method when implementing the
`Iterator` trait.
-Methods that call `next` are called *consuming adapters*, because calling them
+Methods that call `next` are called *consuming adapters* because calling them
uses up the iterator. One example is the `sum` method, which takes ownership of
the iterator and iterates through the items by repeatedly calling `next`, thus
consuming the iterator. As it iterates through, it adds each item to a running
@@ -821,7 +827,7 @@ src/lib.rs
Listing 13-13: Calling the `sum` method to get the total of all items in the iterator
-We aren’t allowed to use `v1_iter` after the call to `sum` because `sum` takes
+We aren’t allowed to use `v1_iter` after the call to `sum`, because `sum` takes
ownership of the iterator we call it on.
### Methods That Produce Other Iterators
@@ -870,7 +876,7 @@ warning: `iterators` (bin "iterators") generated 1 warning
```
The code in Listing 13-14 doesn’t do anything; the closure we’ve specified
-never gets called. The warning reminds us why: iterator adapters are lazy, and
+never gets called. The warning reminds us why: Iterator adapters are lazy, and
we need to consume the iterator here.
To fix this warning and consume the iterator, we’ll use the `collect` method,
@@ -902,7 +908,11 @@ You can chain multiple calls to iterator adapters to perform complex actions in
a readable way. But because all iterators are lazy, you have to call one of the
consuming adapter methods to get results from calls to iterator adapters.
-### Using Closures That Capture Their Environment
+
+
+
+
+### Closures That Capture Their Environment
Many iterator adapters take closures as arguments, and commonly the closures
we’ll specify as arguments to iterator adapters will be closures that capture
@@ -976,18 +986,18 @@ The `shoes_in_size` function takes ownership of a vector of shoes and a shoe
size as parameters. It returns a vector containing only shoes of the specified
size.
-In the body of `shoes_in_size`, we call `into_iter` to create an iterator
-that takes ownership of the vector. Then we call `filter` to adapt that
-iterator into a new iterator that only contains elements for which the closure
-returns `true`.
+In the body of `shoes_in_size`, we call `into_iter` to create an iterator that
+takes ownership of the vector. Then, we call `filter` to adapt that iterator
+into a new iterator that only contains elements for which the closure returns
+`true`.
The closure captures the `shoe_size` parameter from the environment and
compares the value with each shoe’s size, keeping only shoes of the size
specified. Finally, calling `collect` gathers the values returned by the
adapted iterator into a vector that’s returned by the function.
-The test shows that when we call `shoes_in_size`, we get back only shoes
-that have the same size as the value we specified.
+The test shows that when we call `shoes_in_size`, we get back only shoes that
+have the same size as the value we specified.
## Improving Our I/O Project
@@ -1035,7 +1045,8 @@ we would remove them in the future. Well, that time is now!
We needed `clone` here because we have a slice with `String` elements in the
parameter `args`, but the `build` function doesn’t own `args`. To return
ownership of a `Config` instance, we had to clone the values from the `query`
-and `file_path` fields of `Config` so the `Config` instance can own its values.
+and `file_path` fields of `Config` so that the `Config` instance can own its
+values.
With our new knowledge about iterators, we can change the `build` function to
take ownership of an iterator as its argument instead of borrowing a slice.
@@ -1110,18 +1121,21 @@ The standard library documentation for the `env::args` function shows that the
type of the iterator it returns is `std::env::Args`, and that type implements
the `Iterator` trait and returns `String` values.
-We’ve updated the signature of the `Config::build` function so the parameter
-`args` has a generic type with the trait bounds `impl Iterator
- `
-instead of `&[String]`. This usage of the `impl Trait` syntax we discussed in
-the “Traits as Parameters” section of Chapter 10
-means that `args` can be any type that implements the `Iterator` trait and
-returns `String` items.
+We’ve updated the signature of the `Config::build` function so that the
+parameter `args` has a generic type with the trait bounds `impl Iterator
- ` instead of `&[String]`. This usage of the `impl Trait` syntax we
+discussed in the “Using Traits as Parameters”
+section of Chapter 10 means that `args` can be any type that implements the
+`Iterator` trait and returns `String` items.
Because we’re taking ownership of `args` and we’ll be mutating `args` by
iterating over it, we can add the `mut` keyword into the specification of the
`args` parameter to make it mutable.
-#### Using Iterator Trait Methods Instead of Indexing
+
+
+
+
+#### Using Iterator Trait Methods
Next, we’ll fix the body of `Config::build`. Because `args` implements the
`Iterator` trait, we know we can call the `next` method on it! Listing 13-20
@@ -1161,13 +1175,17 @@ Listing 13-20: Changing the body of `Config::build` to use iterator methods
Remember that the first value in the return value of `env::args` is the name of
the program. We want to ignore that and get to the next value, so first we call
-`next` and do nothing with the return value. Then we call `next` to get the
-value we want to put in the `query` field of `Config`. If `next` returns `Some`,
-we use a `match` to extract the value. If it returns `None`, it means not enough
-arguments were given and we return early with an `Err` value. We do the same
-thing for the `file_path` value.
+`next` and do nothing with the return value. Then, we call `next` to get the
+value we want to put in the `query` field of `Config`. If `next` returns
+`Some`, we use a `match` to extract the value. If it returns `None`, it means
+not enough arguments were given, and we return early with an `Err` value. We do
+the same thing for the `file_path` value.
+
+
+
+
-### Making Code Clearer with Iterator Adapters
+### Clarifying Code with Iterator Adapters
We can also take advantage of iterators in the `search` function in our I/O
project, which is reproduced here in Listing 13-21 as it was in Listing 12-19.
@@ -1226,7 +1244,7 @@ until it has collected all of the results, but after the change, the results
will be printed as each matching line is found because the `for` loop in the
`run` function is able to take advantage of the laziness of the iterator.
-
+
@@ -1240,14 +1258,18 @@ prefer to use the iterator style. It’s a bit tougher to get the hang of at
first, but once you get a feel for the various iterator adapters and what they
do, iterators can be easier to understand. Instead of fiddling with the various
bits of looping and building new vectors, the code focuses on the high-level
-objective of the loop. This abstracts away some of the commonplace code so it’s
-easier to see the concepts that are unique to this code, such as the filtering
-condition each element in the iterator must pass.
+objective of the loop. This abstracts away some of the commonplace code so that
+it’s easier to see the concepts that are unique to this code, such as the
+filtering condition each element in the iterator must pass.
But are the two implementations truly equivalent? The intuitive assumption
might be that the lower-level loop will be faster. Let’s talk about performance.
-## Comparing Performance: Loops vs. Iterators
+
+
+
+
+## Performance in Loops vs. Iterators
To determine whether to use loops or iterators, you need to know which
implementation is faster: the version of the `search` function with an explicit
@@ -1271,12 +1293,12 @@ compare performance-wise.
For a more comprehensive benchmark, you should check using various texts of
various sizes as the `contents`, different words and words of different lengths
as the `query`, and all kinds of other variations. The point is this:
-iterators, although a high-level abstraction, get compiled down to roughly the
+Iterators, although 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 that using the abstraction
imposes no additional runtime overhead. This is analogous to how Bjarne
Stroustrup, the original designer and implementor of C++, defines
-*zero-overhead* in “Foundations of C++” (2012):
+zero-overhead in his 2012 ETAPS keynote presentation “Foundations of C++”:
> 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
diff --git a/nostarch/chapter14.md b/nostarch/chapter14.md
index fb2491d04f..e376fe0109 100644
--- a/nostarch/chapter14.md
+++ b/nostarch/chapter14.md
@@ -12,18 +12,18 @@ So far, we’ve used only the most basic features of Cargo to build, run, and
test our code, but it can do a lot more. In this chapter, we’ll discuss some of
its other, more advanced features to show you how to do the following:
-* Customize your build through release profiles
-* Publish libraries on crates.io
-* Organize large projects with workspaces
-* Install binaries from crates.io
-* Extend Cargo using custom commands
+* Customize your build through release profiles.
+* Publish libraries on crates.io.
+* Organize large projects with workspaces.
+* Install binaries from crates.io.
+* Extend Cargo using custom commands.
Cargo can do even more than the functionality we cover in this chapter, so for
a full explanation of all its features, see its documentation at *https://doc.rust-lang.org/cargo/*.
## Customizing Builds with Release Profiles
-In Rust, *release profiles* are predefined and customizable profiles with
+In Rust, *release profiles* are predefined, customizable profiles with
different configurations that allow a programmer to have more control over
various options for compiling code. Each profile is configured independently of
the others.
@@ -158,7 +158,7 @@ rendered, as shown in Figure 14-1.
-Figure 14-1: HTML documentation for the `add_one`
+Figure 14-1: The HTML documentation for the `add_one`
function
#### Commonly Used Sections
@@ -167,12 +167,12 @@ We used the `# Examples` Markdown heading in Listing 14-1 to create a section
in the HTML with the title “Examples.” Here are some other sections that crate
authors commonly use in their documentation:
-* **Panics**: The scenarios in which the function being documented could
- panic. Callers of the function who don’t want their programs to panic should
- make sure they don’t call the function in these situations.
+* **Panics**: These are the scenarios in which the function being documented
+ could panic. Callers of the function who don’t want their programs to panic
+ should make sure they don’t call the function in these situations.
* **Errors**: If the function returns a `Result`, describing the kinds of
errors that might occur and what conditions might cause those errors to be
- returned can be helpful to callers so they can write code to handle the
+ returned can be helpful to callers so that they can write code to handle the
different kinds of errors in different ways.
* **Safety**: If the function is `unsafe` to call (we discuss unsafety in
Chapter 20), there should be a section explaining why the function is unsafe
@@ -185,12 +185,12 @@ interested in knowing about.
#### Documentation Comments as Tests
Adding example code blocks in your documentation comments can help demonstrate
-how to use your library, and doing so has an additional bonus: running `cargo test` will run the code examples in your documentation as tests! Nothing is
-better than documentation with examples. But nothing is worse than examples
-that don’t work because the code has changed since the documentation was
-written. If we run `cargo test` with the documentation for the `add_one`
-function from Listing 14-1, we will see a section in the test results that looks
-like this:
+how to use your library and has an additional bonus: Running `cargo test` will
+run the code examples in your documentation as tests! Nothing is better than
+documentation with examples. But nothing is worse than examples that don’t work
+because the code has changed since the documentation was written. If we run
+`cargo test` with the documentation for the `add_one` function from Listing
+14-1, we will see a section in the test results that looks like this:
+
+
+
+#### Contained Item Comments
The style of doc comment `//!` adds documentation to the item that *contains*
-the comments rather than to the items *following* the comments. We typically use
-these doc comments inside the crate root file (*src/lib.rs* by convention) or
-inside a module to document the crate or the module as a whole.
+the comments rather than to the items *following* the comments. We typically
+use these doc comments inside the crate root file (*src/lib.rs* by convention)
+or inside a module to document the crate or the module as a whole.
For example, to add documentation that describes the purpose of the `my_crate`
crate that contains the `add_one` function, we add documentation comments that
@@ -235,7 +239,7 @@ src/lib.rs
// --snip--
```
-Listing 14-2: Documentation for the `my_crate` crate as a whole
+Listing 14-2: The documentation for the `my_crate` crate as a whole
Notice there isn’t any code after the last line that begins with `//!`. Because
we started the comments with `//!` instead of `///`, we’re documenting the item
@@ -243,20 +247,24 @@ that contains this comment rather than an item that follows this comment. In
this case, that item is the *src/lib.rs* file, which is the crate root. These
comments describe the entire crate.
-When we run `cargo doc --open`, these comments will display on the front
-page of the documentation for `my_crate` above the list of public items in the
+When we run `cargo doc --open`, these comments will display on the front page
+of the documentation for `my_crate` above the list of public items in the
crate, as shown in Figure 14-2.
+Documentation comments within items are useful for describing crates and
+modules especially. Use them to explain the overall purpose of the container to
+help your users understand the crate’s organization.
+
-Figure 14-2: Rendered documentation for `my_crate`,
+Figure 14-2: The rendered documentation for `my_crate`,
including the comment describing the crate as a whole
-Documentation comments within items are useful for describing crates and
-modules especially. Use them to explain the overall purpose of the container to
-help your users understand the crate’s organization.
+
-### Exporting a Convenient Public API with pub use
+
+
+### Exporting a Convenient Public API
The structure of your public API is a major consideration when publishing a
crate. People who use your crate are less familiar with the structure than you
@@ -273,7 +281,7 @@ exists. They might also be annoyed at having to enter `use my_crate::some_module
The good news is that if the structure *isn’t* convenient for others to use
from another library, you don’t have to rearrange your internal organization:
-instead, you can re-export items to make a public structure that’s different
+Instead, you can re-export items to make a public structure that’s different
from your private structure by using `pub use`. *Re-exporting* takes a public
item in one location and makes it public in another location, as if it were
defined in the other location instead.
@@ -324,7 +332,7 @@ generated by `cargo doc` would look like.
-Figure 14-3: Front page of the documentation for `art`
+Figure 14-3: The front page of the documentation for `art`
that lists the `kinds` and `utils` modules
Note that the `PrimaryColor` and `SecondaryColor` types aren’t listed on the
@@ -418,11 +426,12 @@ people who use the crate. Another common use of `pub use` is to re-export
definitions of a dependency in the current crate to make that crate’s
definitions part of your crate’s public API.
-Creating a useful public API structure is more of an art than a science, and
-you can iterate to find the API that works best for your users. Choosing `pub use` gives you flexibility in how you structure your crate internally and
-decouples that internal structure from what you present to your users. Look at
-some of the code of crates you’ve installed to see if their internal structure
-differs from their public API.
+Creating a useful public API structure is more an art than a science, and you
+can iterate to find the API that works best for your users. Choosing `pub use`
+gives you flexibility in how you structure your crate internally and decouples
+that internal structure from what you present to your users. Look at some of
+the code of crates you’ve installed to see if their internal structure differs
+from their public API.
### Setting Up a Crates.io Account
@@ -433,7 +442,7 @@ in via a GitHub account. (The GitHub account is currently a requirement, but
the site might support other ways of creating an account in the future.) Once
you’re logged in, visit your account settings at
https://crates.io/me/ and retrieve your
-API key. Then run the `cargo login` command and paste your API key when prompted, like this:
+API key. Then, run the `cargo login` command and paste your API key when prompted, like this:
```
$ cargo login
@@ -441,7 +450,7 @@ abcdefghijklmnopqrstuvwxyz012345
```
This command will inform Cargo of your API token and store it locally in
-*~/.cargo/credentials.toml*. Note that this token is a *secret*: do not share
+*~/.cargo/credentials.toml*. Note that this token is a secret: Do not share
it with anyone else. If you do share it with anyone for any reason, you should
revoke it and generate a new token on crates.io.
@@ -489,14 +498,14 @@ Caused by:
the remote server responded with an error (status 400 Bad Request): missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for more information on configuring these fields
```
-This results in an error because you’re missing some crucial information: a
-description and license are required so people will know what your crate does
-and under what terms they can use it. In *Cargo.toml*, add a description that’s
-just a sentence or two, because it will appear with your crate in search
-results. For the `license` field, you need to give a *license identifier value*.
-The Linux Foundation’s Software Package Data Exchange (SPDX) at *https://spdx.org/licenses/* lists the
-identifiers you can use for this value. For example, to specify that you’ve
-licensed your crate using the MIT License, add the `MIT` identifier:
+This results in an error because you’re missing some crucial information: A
+description and license are required so that people will know what your crate
+does and under what terms they can use it. In *Cargo.toml*, add a description
+that’s just a sentence or two, because it will appear with your crate in search
+results. For the `license` field, you need to give a *license identifier
+value*. The Linux Foundation’s Software Package Data Exchange (SPDX) at *https://spdx.org/licenses/*
+lists the identifiers you can use for this value. For example, to specify that
+you’ve licensed your crate using the MIT License, add the `MIT` identifier:
Filename: Cargo.toml
@@ -586,13 +595,14 @@ When you’ve made changes to your crate and are ready to release a new version,
you change the `version` value specified in your *Cargo.toml* file and
republish. Use the Semantic Versioning rules at *https://semver.org/* to decide what an
appropriate next version number is, based on the kinds of changes you’ve made.
-Then run `cargo publish` to upload the new version.
+Then, run `cargo publish` to upload the new version.
-
+
+
-### Deprecating Versions from Crates.io with cargo yank
+### Deprecating Versions from Crates.io
Although you can’t remove previous versions of a crate, you can prevent any
future projects from adding them as a new dependency. This is useful when a
@@ -607,8 +617,8 @@ yank means that all projects with a *Cargo.lock* will not break, and any future
To yank a version of a crate, in the directory of the crate that you’ve
previously published, run `cargo yank` and specify which version you want to
yank. For example, if we’ve published a crate named `guessing_game` version
-1.0.1 and we want to yank it, in the project directory for `guessing_game` we’d
-run:
+1.0.1 and we want to yank it, then we’d run the following in the project
+directory for `guessing_game`:
+
+
+
+### Depending on an External Package
Notice that the workspace has only one *Cargo.lock* file at the top level,
rather than having a *Cargo.lock* in each crate’s directory. This ensures that
@@ -853,7 +867,7 @@ resolve both of those to one version of `rand` and record that in the one
*Cargo.lock*. Making all crates in the workspace use the same dependencies
means the crates will always be compatible with each other. Let’s add the
`rand` crate to the `[dependencies]` section in the *add_one/Cargo.toml* file
-so we can use the `rand` crate in the `add_one` crate:
+so that we can use the `rand` crate in the `add_one` crate:
+
@@ -1057,14 +1071,14 @@ packages that have binary targets. A *binary target* is the runnable program
that is created if the crate has a *src/main.rs* file or another file specified
as a binary, as opposed to a library target that isn’t runnable on its own but
is suitable for including within other programs. Usually, crates have
-information in the *README* file about whether a crate is a library, has a
+information in the README file about whether a crate is a library, has a
binary target, or both.
All binaries installed with `cargo install` are stored in the installation
root’s *bin* folder. If you installed Rust using *rustup.rs* and don’t have any
custom configurations, this directory will be *$HOME/.cargo/bin*. Ensure that
-directory is in your `$PATH` to be able to run programs you’ve installed with
-`cargo install`.
+this directory is in your `$PATH` to be able to run programs you’ve installed
+with `cargo install`.
For example, in Chapter 12 we mentioned that there’s a Rust implementation of
the `grep` tool called `ripgrep` for searching files. To install `ripgrep`, we
@@ -1094,9 +1108,9 @@ then run `rg --help` and start using a faster, Rustier tool for searching files!
## Extending Cargo with Custom Commands
-Cargo is designed so you can extend it with new subcommands without having to
-modify it. If a binary in your `$PATH` is named `cargo-something`, you can run
-it as if it were a Cargo subcommand by running `cargo something`. Custom
+Cargo is designed so that you can extend it with new subcommands without having
+to modify it. If a binary in your `$PATH` is named `cargo-something`, you can
+run it as if it were a Cargo subcommand by running `cargo something`. Custom
commands like this are also listed when you run `cargo --list`. Being able to
use `cargo install` to install extensions and then run them just like the
built-in Cargo tools is a super-convenient benefit of Cargo’s design!
diff --git a/nostarch/chapter15.md b/nostarch/chapter15.md
index 4403925cb2..a3e5c900a4 100644
--- a/nostarch/chapter15.md
+++ b/nostarch/chapter15.md
@@ -8,7 +8,7 @@ directory, so all fixes need to be made in `/src/`.
# Smart Pointers
-A *pointer* is a general concept for a variable that contains an address in
+A pointer is a general concept for a variable that contains an address in
memory. This address refers to, or “points at,” some other data. The most
common kind of pointer in Rust is a reference, which you learned about in
Chapter 4. References are indicated by the `&` symbol and borrow the value they
@@ -17,7 +17,7 @@ data, and they have no overhead.
*Smart pointers*, on the other hand, are data structures that act like a
pointer but also have additional metadata and capabilities. The concept of
-smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist
+smart pointers isn’t unique to Rust: Smart pointers originated in C++ and exist
in other languages as well. Rust has a variety of smart pointers defined in the
standard library that provide functionality beyond that provided by references.
To explore the general concept, we’ll look at a couple of different examples of
@@ -25,17 +25,17 @@ smart pointers, including a *reference counting* smart pointer type. This
pointer enables you to allow data to have multiple owners by keeping track of
the number of owners and, when no owners remain, cleaning up the data.
-Rust, with its concept of ownership and borrowing, has an additional difference
-between references and smart pointers: while references only borrow data, in
-many cases smart pointers *own* the data they point to.
+In Rust, with its concept of ownership and borrowing, there is an additional
+difference between references and smart pointers: While references only borrow
+data, in many cases smart pointers *own* the data they point to.
Smart pointers are usually implemented using structs. Unlike an ordinary
struct, smart pointers implement the `Deref` and `Drop` traits. The `Deref`
trait allows an instance of the smart pointer struct to behave like a reference
-so you can write your code to work with either references or smart pointers.
-The `Drop` trait allows you to customize the code that’s run when an instance
-of the smart pointer goes out of scope. In this chapter, we’ll discuss both of
-these traits and demonstrate why they’re important to smart pointers.
+so that you can write your code to work with either references or smart
+pointers. The `Drop` trait allows you to customize the code that’s run when an
+instance of the smart pointer goes out of scope. In this chapter, we’ll discuss
+both of these traits and demonstrate why they’re important to smart pointers.
Given that the smart pointer pattern is a general design pattern used
frequently in Rust, this chapter won’t cover every existing smart pointer. Many
@@ -64,11 +64,11 @@ Boxes don’t have performance overhead, other than storing their data on the
heap instead of on the stack. But they don’t have many extra capabilities
either. You’ll use them most often in these situations:
-* When you have a type whose size can’t be known at compile time and you want
+* When you have a type whose size can’t be known at compile time, and you want
to use a value of that type in a context that requires an exact size
-* When you have a large amount of data and you want to transfer ownership but
- ensure the data won’t be copied when you do so
-* When you want to own a value and you care only that it’s a type that
+* When you have a large amount of data, and you want to transfer ownership but
+ ensure that the data won’t be copied when you do so
+* When you want to own a value, and you care only that it’s a type that
implements a particular trait rather than being of a specific type
We’ll demonstrate the first situation in “Enabling Recursive Types with
@@ -78,11 +78,15 @@ because the data is copied around on the stack. To improve performance in this
situation, we can store the large amount of data on the heap in a box. Then,
only the small amount of pointer data is copied around on the stack, while the
data it references stays in one place on the heap. The third case is known as a
-*trait object*, and “Using Trait Objects That Allow for Values of Different
-Types,” in Chapter 18 is devoted to that topic.
-So what you learn here you’ll apply again in that section!
+*trait object*, and “Using Trait Objects to Abstract over Shared
+Behavior” in Chapter 18 is devoted to that
+topic. So, what you learn here you’ll apply again in that section!
-### Using Box to Store Data on the Heap
+
+
+
+
+### Storing Data on the Heap
Before we discuss the heap storage use case for `Box`, we’ll cover the
syntax and how to interact with values stored within a `Box`.
@@ -123,13 +127,17 @@ types could theoretically continue infinitely, so Rust can’t know how much spa
the value needs. Because boxes have a known size, we can enable recursive types
by inserting a box in the recursive type definition.
-As an example of a recursive type, let’s explore the *cons list*. This is a data
+As an example of a recursive type, let’s explore the cons list. This is a data
type commonly found in functional programming languages. The cons list type
we’ll define is straightforward except for the recursion; therefore, the
-concepts in the example we’ll work with will be useful any time you get into
+concepts in the example we’ll work with will be useful anytime you get into
more complex situations involving recursive types.
-#### More Information About the Cons List
+
+
+
+
+#### Understanding the Cons List
A *cons list* is a data structure that comes from the Lisp programming language
and its dialects, is made up of nested pairs, and is the Lisp version of a
@@ -146,11 +154,11 @@ list `1, 2, 3` with each pair in parentheses:
```
Each item in a cons list contains two elements: the value of the current item
-and the next item. The last item in the list contains only a value called `Nil`
-without a next item. A cons list is produced by recursively calling the `cons`
-function. The canonical name to denote the base case of the recursion is `Nil`.
-Note that this is not the same as the “null” or “nil” concept discussed in
-Chapter 6, which is an invalid or absent value.
+and of the next item. The last item in the list contains only a value called
+`Nil` without a next item. A cons list is produced by recursively calling the
+`cons` function. The canonical name to denote the base case of the recursion is
+`Nil`. Note that this is not the same as the “null” or “nil” concept discussed
+in Chapter 6, which is an invalid or absent value.
The cons list isn’t a commonly used data structure in Rust. Most of the time
when you have a list of items in Rust, `Vec` is a better choice to use.
@@ -159,7 +167,7 @@ but by starting with the cons list in this chapter, we can explore how boxes
let us define a recursive data type without much distraction.
Listing 15-2 contains an enum definition for a cons list. Note that this code
-won’t compile yet because the `List` type doesn’t have a known size, which
+won’t compile yet, because the `List` type doesn’t have a known size, which
we’ll demonstrate.
src/main.rs
@@ -238,9 +246,9 @@ error: could not compile `cons-list` (bin "cons-list") due to 2 previous errors
Listing 15-4: The error we get when attempting to define a recursive enum
The error shows this type “has infinite size.” The reason is that we’ve defined
-`List` with a variant that is recursive: it holds another value of itself
+`List` with a variant that is recursive: It holds another value of itself
directly. As a result, Rust can’t figure out how much space it needs to store a
-`List` value. Let’s break down why we get this error. First we’ll look at how
+`List` value. Let’s break down why we get this error. First, we’ll look at how
Rust decides how much space it needs to store a value of a non-recursive type.
#### Computing the Size of a Non-Recursive Type
@@ -273,12 +281,16 @@ type needs, the compiler looks at the variants, starting with the `Cons`
variant. The `Cons` variant holds a value of type `i32` and a value of type
`List`, and this process continues infinitely, as shown in Figure 15-1.
-
+
Figure 15-1: An infinite `List` consisting of infinite
`Cons` variants
-#### Using Box to Get a Recursive Type with a Known Size
+
+
+
+
+#### Getting a Recursive Type with a Known Size
Because Rust can’t figure out how much space to allocate for recursively
defined types, the compiler gives an error with this helpful suggestion:
@@ -299,7 +311,7 @@ directly, we should change the data structure to store the value indirectly by
storing a pointer to the value instead.
Because a `Box` is a pointer, Rust always knows how much space a `Box`
-needs: a pointer’s size doesn’t change based on the amount of data it’s
+needs: A pointer’s size doesn’t change based on the amount of data it’s
pointing to. This means we can put a `Box` inside the `Cons` variant instead
of another `List` value directly. The `Box` will point to the next `List`
value that will be on the heap rather than inside the `Cons` variant.
@@ -325,19 +337,19 @@ fn main() {
}
```
-Listing 15-5: Definition of `List` that uses `Box` in order to have a known size
+Listing 15-5: The definition of `List` that uses `Box` in order to have a known size
-The `Cons` variant needs the size of an `i32` plus the space to store the
-box’s pointer data. The `Nil` variant stores no values, so it needs less space
-on the stack than the `Cons` variant. We now know that any `List` value will
-take up the size of an `i32` plus the size of a box’s pointer data. By using a
-box, we’ve broken the infinite, recursive chain, so the compiler can figure out
-the size it needs to store a `List` value. Figure 15-2 shows what the `Cons`
+The `Cons` variant needs the size of an `i32` plus the space to store the box’s
+pointer data. The `Nil` variant stores no values, so it needs less space on the
+stack than the `Cons` variant. We now know that any `List` value will take up
+the size of an `i32` plus the size of a box’s pointer data. By using a box,
+we’ve broken the infinite, recursive chain, so the compiler can figure out the
+size it needs to store a `List` value. Figure 15-2 shows what the `Cons`
variant looks like now.
-
+
-Figure 15-2: A `List` that is not infinitely sized
+Figure 15-2: A `List` that is not infinitely sized,
because `Cons` holds a `Box`
Boxes provide only the indirection and heap allocation; they don’t have any
@@ -355,11 +367,12 @@ even more important to the functionality provided by the other smart pointer
types we’ll discuss in the rest of this chapter. Let’s explore these two traits
in more detail.
-## Treating Smart Pointers Like Regular References with Deref
-
-
+
+
+
+## Treating Smart Pointers Like Regular References
Implementing the `Deref` trait allows you to customize the behavior of the
*dereference operator* `*` (not to be confused with the multiplication or glob
@@ -368,14 +381,14 @@ treated like a regular reference, you can write code that operates on
references and use that code with smart pointers too.
Let’s first look at how the dereference operator works with regular references.
-Then we’ll try to define a custom type that behaves like `Box`, and see why
+Then, we’ll try to define a custom type that behaves like `Box` and see why
the dereference operator doesn’t work like a reference on our newly defined
type. We’ll explore how implementing the `Deref` trait makes it possible for
-smart pointers to work in ways similar to references. Then we’ll look at
-Rust’s *deref coercion* feature and how it lets us work with either references
-or smart pointers.
+smart pointers to work in ways similar to references. Then, we’ll look at
+Rust’s deref coercion feature and how it lets us work with either references or
+smart pointers.
-
+
@@ -404,9 +417,9 @@ Listing 15-6: Using the dereference operator to follow a reference to an `i32` v
The variable `x` holds an `i32` value `5`. We set `y` equal to a reference to
`x`. We can assert that `x` is equal to `5`. However, if we want to make an
assertion about the value in `y`, we have to use `*y` to follow the reference
-to the value it’s pointing to (hence *dereference*) so the compiler can compare
-the actual value. Once we dereference `y`, we have access to the integer value
-`y` is pointing to that we can compare with `5`.
+to the value it’s pointing to (hence, *dereference*) so that the compiler can
+compare the actual value. Once we dereference `y`, we have access to the
+integer value `y` is pointing to that we can compare with `5`.
If we tried to write `assert_eq!(5, y);` instead, we would get this compilation
error:
@@ -463,11 +476,11 @@ that enables us to use the dereference operator by defining our own box type.
Let’s build a wrapper type similar to the `Box` type provided by the
standard library to experience how smart pointer types behave differently from
-references by default. Then we’ll look at how to add the ability to use the
+references by default. Then, we’ll look at how to add the ability to use the
dereference operator.
> Note: There’s one big difference between the `MyBox` type we’re about to
-> build and the real `Box`: our version will not store its data on the heap.
+> build and the real `Box`: Our version will not store its data on the heap.
> We are focusing this example on `Deref`, so where the data is actually stored
> is less important than the pointer-like behavior.
@@ -489,15 +502,15 @@ impl MyBox {
Listing 15-8: Defining a `MyBox` type
-We define a struct named `MyBox` and declare a generic parameter `T` because
-we want our type to hold values of any type. The `MyBox` type is a tuple struct
+We define a struct named `MyBox` and declare a generic parameter `T` because we
+want our type to hold values of any type. The `MyBox` type is a tuple struct
with one element of type `T`. The `MyBox::new` function takes one parameter of
type `T` and returns a `MyBox` instance that holds the value passed in.
Let’s try adding the `main` function in Listing 15-7 to Listing 15-8 and
changing it to use the `MyBox` type we’ve defined instead of `Box`. The
-code in Listing 15-9 won’t compile because Rust doesn’t know how to dereference
-`MyBox`.
+code in Listing 15-9 won’t compile, because Rust doesn’t know how to
+dereference `MyBox`.
src/main.rs
@@ -532,7 +545,7 @@ Our `MyBox` type can’t be dereferenced because we haven’t implemented tha
ability on our type. To enable dereferencing with the `*` operator, we
implement the `Deref` trait.
-
+
@@ -561,21 +574,20 @@ impl Deref for MyBox {
Listing 15-10: Implementing `Deref` on `MyBox`
-The `type Target = T;` syntax defines an associated type for the `Deref`
-trait to use. Associated types are a slightly different way of declaring a
-generic parameter, but you don’t need to worry about them for now; we’ll cover
-them in more detail in Chapter 20.
+The `type Target = T;` syntax defines an associated type for the `Deref` trait
+to use. Associated types are a slightly different way of declaring a generic
+parameter, but you don’t need to worry about them for now; we’ll cover them in
+more detail in Chapter 20.
-We fill in the body of the `deref` method with `&self.0` so `deref` returns a
-reference to the value we want to access with the `*` operator; recall from
-“Using Tuple Structs Without Named Fields to Create Different
-Types” in Chapter 5 that `.0` accesses the first
-value in a tuple struct. The `main` function in Listing 15-9 that calls `*` on
-the `MyBox` value now compiles, and the assertions pass!
+We fill in the body of the `deref` method with `&self.0` so that `deref`
+returns a reference to the value we want to access with the `*` operator;
+recall from “Creating Different Types with Tuple Structs” in Chapter 5 that `.0` accesses the first value in a tuple struct.
+The `main` function in Listing 15-9 that calls `*` on the `MyBox` value now
+compiles, and the assertions pass!
Without the `Deref` trait, the compiler can only dereference `&` references.
The `deref` method gives the compiler the ability to take a value of any type
-that implements `Deref` and call the `deref` method to get an `&` reference that
+that implements `Deref` and call the `deref` method to get a reference that
it knows how to dereference.
When we entered `*y` in Listing 15-9, behind the scenes Rust actually ran this
@@ -586,8 +598,8 @@ code:
```
Rust substitutes the `*` operator with a call to the `deref` method and then a
-plain dereference so we don’t have to think about whether or not we need to
-call the `deref` method. This Rust feature lets us write code that functions
+plain dereference so that we don’t have to think about whether or not we need
+to call the `deref` method. This Rust feature lets us write code that functions
identically whether we have a regular reference or a type that implements
`Deref`.
@@ -604,13 +616,18 @@ Because the substitution of the `*` operator does not recurse infinitely, we
end up with data of type `i32`, which matches the `5` in `assert_eq!` in
Listing 15-9.
-### Implicit Deref Coercions with Functions and Methods
+
+
+
+
+
+### Using Deref Coercion in Functions and Methods
*Deref coercion* converts a reference to a type that implements the `Deref`
trait into a reference to another type. For example, deref coercion can convert
`&String` to `&str` because `String` implements the `Deref` trait such that it
returns `&str`. Deref coercion is a convenience Rust performs on arguments to
-functions and methods, and works only on types that implement the `Deref`
+functions and methods, and it works only on types that implement the `Deref`
trait. It happens automatically when we pass a reference to a particular type’s
value as an argument to a function or method that doesn’t match the parameter
type in the function or method definition. A sequence of calls to the `deref`
@@ -674,7 +691,7 @@ fn main() {
Listing 15-13: The code we would have to write if Rust didn’t have deref coercion
-The `(*m)` dereferences the `MyBox` into a `String`. Then the `&` and
+The `(*m)` dereferences the `MyBox` into a `String`. Then, the `&` and
`[..]` take a string slice of the `String` that is equal to the whole string to
match the signature of `hello`. This code without deref coercions is harder to
read, write, and understand with all of these symbols involved. Deref coercion
@@ -686,7 +703,11 @@ match the parameter’s type. The number of times that `Deref::deref` needs to b
inserted is resolved at compile time, so there is no runtime penalty for taking
advantage of deref coercion!
-### How Deref Coercion Interacts with Mutability
+
+
+
+
+### Handling Deref Coercion with Mutable References
Similar to how you use the `Deref` trait to override the `*` operator on
immutable references, you can use the `DerefMut` trait to override the `*`
@@ -701,11 +722,11 @@ cases:
The first two cases are the same except that the second implements mutability.
The first case states that if you have a `&T`, and `T` implements `Deref` to
-some type `U`, you can get a `&U` transparently. The second case states that the
-same deref coercion happens for mutable references.
+some type `U`, you can get a `&U` transparently. The second case states that
+the same deref coercion happens for mutable references.
The third case is trickier: Rust will also coerce a mutable reference to an
-immutable one. But the reverse is *not* possible: immutable references will
+immutable one. But the reverse is *not* possible: Immutable references will
never coerce to mutable references. Because of the borrowing rules, if you have
a mutable reference, that mutable reference must be the only reference to that
data (otherwise, the program wouldn’t compile). Converting one mutable
@@ -725,15 +746,15 @@ be used to release resources like files or network connections.
We’re introducing `Drop` in the context of smart pointers because the
functionality of the `Drop` trait is almost always used when implementing a
-smart pointer. For example, when a `Box` is dropped it will deallocate the
+smart pointer. For example, when a `Box` is dropped, it will deallocate the
space on the heap that the box points to.
In some languages, for some types, the programmer must call code to free memory
or resources every time they finish using an instance of those types. Examples
-include file handles, sockets, and locks. If they forget, the system might
-become overloaded and crash. In Rust, you can specify that a particular bit of
-code be run whenever a value goes out of scope, and the compiler will insert
-this code automatically. As a result, you don’t need to be careful about
+include file handles, sockets, and locks. If the programmer forgets, the system
+might become overloaded and crash. In Rust, you can specify that a particular
+bit of code be run whenever a value goes out of scope, and the compiler will
+insert this code automatically. As a result, you don’t need to be careful about
placing cleanup code everywhere in a program that an instance of a particular
type is finished with—you still won’t leak resources!
@@ -766,7 +787,7 @@ fn main() {
let d = CustomSmartPointer {
data: String::from("other stuff"),
};
- println!("CustomSmartPointers created.");
+ println!("CustomSmartPointers created");
}
```
@@ -792,7 +813,7 @@ $ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/drop-example`
-CustomSmartPointers created.
+CustomSmartPointers created
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
```
@@ -804,7 +825,7 @@ give you a visual guide to how the `drop` method works; usually you would
specify the cleanup code that your type needs to run rather than a print
message.
-
+
@@ -812,15 +833,14 @@ Unfortunately, it’s not straightforward to disable the automatic `drop`
functionality. Disabling `drop` isn’t usually necessary; the whole point of the
`Drop` trait is that it’s taken care of automatically. Occasionally, however,
you might want to clean up a value early. One example is when using smart
-pointers that manage locks: you might want to force the `drop` method that
+pointers that manage locks: You might want to force the `drop` method that
releases the lock so that other code in the same scope can acquire the lock.
Rust doesn’t let you call the `Drop` trait’s `drop` method manually; instead,
you have to call the `std::mem::drop` function provided by the standard library
if you want to force a value to be dropped before the end of its scope.
-If we try to call the `Drop` trait’s `drop` method manually by modifying the
-`main` function from Listing 15-14, as shown in Listing 15-15, we’ll get a
-compiler error.
+Trying to call the `Drop` trait’s `drop` method manually by modifying the
+`main` function from Listing 15-14 won’t work, as shown in Listing 15-15.
src/main.rs
@@ -829,9 +849,9 @@ fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
- println!("CustomSmartPointer created.");
+ println!("CustomSmartPointer created");
c.drop();
- println!("CustomSmartPointer dropped before the end of main.");
+ println!("CustomSmartPointer dropped before the end of main");
}
```
@@ -863,10 +883,9 @@ for a function that cleans up an instance. A *destructor* is analogous to a
*constructor*, which creates an instance. The `drop` function in Rust is one
particular destructor.
-Rust doesn’t let us call `drop` explicitly because Rust would still
+Rust doesn’t let us call `drop` explicitly, because Rust would still
automatically call `drop` on the value at the end of `main`. This would cause a
-*double free* error because Rust would be trying to clean up the same value
-twice.
+double free error because Rust would be trying to clean up the same value twice.
We can’t disable the automatic insertion of `drop` when a value goes out of
scope, and we can’t call the `drop` method explicitly. So, if we need to force
@@ -884,9 +903,9 @@ fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
- println!("CustomSmartPointer created.");
+ println!("CustomSmartPointer created");
drop(c);
- println!("CustomSmartPointer dropped before the end of main.");
+ println!("CustomSmartPointer dropped before the end of main");
}
```
@@ -899,22 +918,22 @@ $ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.73s
Running `target/debug/drop-example`
-CustomSmartPointer created.
+CustomSmartPointer created
Dropping CustomSmartPointer with data `some data`!
-CustomSmartPointer dropped before the end of main.
+CustomSmartPointer dropped before the end of main
```
The text ``Dropping CustomSmartPointer with data `some data`!`` is printed
-between the `CustomSmartPointer created.` and `CustomSmartPointer dropped before the end of main.` text, showing that the `drop` method code is called to
-drop `c` at that point.
+between the `CustomSmartPointer created` and `CustomSmartPointer dropped before the end of main` text, showing that the `drop` method code is called to drop
+`c` at that point.
You can use code specified in a `Drop` trait implementation in many ways to
-make cleanup convenient and safe: for instance, you could use it to create your
+make cleanup convenient and safe: For instance, you could use it to create your
own memory allocator! With the `Drop` trait and Rust’s ownership system, you
-don’t have to remember to clean up because Rust does it automatically.
+don’t have to remember to clean up, because Rust does it automatically.
You also don’t have to worry about problems resulting from accidentally
-cleaning up values still in use: the ownership system that makes sure
+cleaning up values still in use: The ownership system that makes sure
references are always valid also ensures that `drop` gets called only once when
the value is no longer being used.
@@ -922,9 +941,9 @@ Now that we’ve examined `Box` and some of the characteristics of smart
pointers, let’s look at a few other smart pointers defined in the standard
library.
-## Rc, the Reference Counted Smart Pointer
+## Rc, the Reference-Counted Smart Pointer
-In the majority of cases, ownership is clear: you know exactly which variable
+In the majority of cases, ownership is clear: You know exactly which variable
owns a given value. However, there are cases when a single value might have
multiple owners. For example, in graph data structures, multiple edges might
point to the same node, and that node is conceptually owned by all of the edges
@@ -953,21 +972,30 @@ Note that `Rc` is only for use in single-threaded scenarios. When we discuss
concurrency in Chapter 16, we’ll cover how to do reference counting in
multithreaded programs.
-### Using Rc to Share Data
+
+
+
+
+### Sharing Data
Let’s return to our cons list example in Listing 15-5. Recall that we defined
it using `Box`. This time, we’ll create two lists that both share ownership
of a third list. Conceptually, this looks similar to Figure 15-3.
-
+
Figure 15-3: Two lists, `b` and `c`, sharing ownership of
a third list, `a`
-We’ll create list `a` that contains `5` and then `10`. Then we’ll make two more
-lists: `b` that starts with `3` and `c` that starts with `4`. Both `b` and `c`
-lists will then continue on to the first `a` list containing `5` and `10`. In
-other words, both lists will share the first list containing `5` and `10`.
+We’ll create list `a` that contains `5` and then `10`. Then, we’ll make two
+more lists: `b` that starts with `3` and `c` that starts with `4`. Both the `b`
+and `c` lists will then continue on to the first `a` list containing `5` and
+`10`. In other words, both lists will share the first list containing `5` and
+`10`.
Trying to implement this scenario using our definition of `List` with `Box`
won’t work, as shown in Listing 15-17.
@@ -1068,13 +1096,19 @@ increase the reference count. When looking for performance problems in the
code, we only need to consider the deep-copy clones and can disregard calls to
`Rc::clone`.
-### Cloning an Rc Increases the Reference Count
+
+
+
-Let’s change our working example in Listing 15-18 so we can see the reference
-counts changing as we create and drop references to the `Rc` in `a`.
+### Cloning to Increase the Reference Count
-In Listing 15-19, we’ll change `main` so it has an inner scope around list `c`;
-then we can see how the reference count changes when `c` goes out of scope.
+Let’s change our working example in Listing 15-18 so that we can see the
+reference counts changing as we create and drop references to the `Rc` in
+`a`.
+
+In Listing 15-19, we’ll change `main` so that it has an inner scope around list
+`c`; then, we can see how the reference count changes when `c` goes out of
+scope.
src/main.rs
@@ -1115,15 +1149,15 @@ count after creating c = 3
count after c goes out of scope = 2
```
-We can see that the `Rc` in `a` has an initial reference count of 1; then
-each time we call `clone`, the count goes up by 1. When `c` goes out of scope,
-the count goes down by 1. We don’t have to call a function to decrease the
-reference count like we have to call `Rc::clone` to increase the reference
-count: the implementation of the `Drop` trait decreases the reference count
+We can see that the `Rc` in `a` has an initial reference count of 1;
+then, each time we call `clone`, the count goes up by 1. When `c` goes out of
+scope, the count goes down by 1. We don’t have to call a function to decrease
+the reference count like we have to call `Rc::clone` to increase the reference
+count: The implementation of the `Drop` trait decreases the reference count
automatically when an `Rc` value goes out of scope.
What we can’t see in this example is that when `b` and then `a` go out of scope
-at the end of `main`, the count is then 0, and the `Rc` is cleaned up
+at the end of `main`, the count is 0, and the `Rc` is cleaned up
completely. Using `Rc` allows a single value to have multiple owners, and
the count ensures that the value remains valid as long as any of the owners
still exist.
@@ -1131,7 +1165,7 @@ still exist.
Via immutable references, `Rc` allows you to share data between multiple
parts of your program for reading only. If `Rc` allowed you to have multiple
mutable references too, you might violate one of the borrowing rules discussed
-in Chapter 4: multiple mutable borrows to the same place can cause data races
+in Chapter 4: Multiple mutable borrows to the same place can cause data races
and inconsistencies. But being able to mutate data is very useful! In the next
section, we’ll discuss the interior mutability pattern and the `RefCell`
type that you can use in conjunction with an `Rc` to work with this
@@ -1155,10 +1189,14 @@ safe API, and the outer type is still immutable.
Let’s explore this concept by looking at the `RefCell` type that follows the
interior mutability pattern.
-### Enforcing Borrowing Rules at Runtime with RefCell
+
+
+
+
+### Enforcing Borrowing Rules at Runtime
Unlike `Rc`, the `RefCell` type represents single ownership over the data
-it holds. So what makes `RefCell` different from a type like `Box`?
+it holds. So, what makes `RefCell` different from a type like `Box`?
Recall the borrowing rules you learned in Chapter 4:
* At any given time, you can have *either* one mutable reference or any number
@@ -1180,7 +1218,7 @@ The advantage of checking the borrowing rules at runtime instead is that
certain memory-safe scenarios are then allowed, where they would’ve been
disallowed by the compile-time checks. Static analysis, like the Rust compiler,
is inherently conservative. Some properties of code are impossible to detect by
-analyzing the code: the most famous example is the Halting Problem, which is
+analyzing the code: The most famous example is the Halting Problem, which is
beyond the scope of this book but is an interesting topic to research.
Because some analysis is impossible, if the Rust compiler can’t be sure the
@@ -1208,11 +1246,15 @@ Here is a recap of the reasons to choose `Box`, `Rc`, or `RefCell`:
mutate the value inside the `RefCell` even when the `RefCell` is
immutable.
-Mutating the value inside an immutable value is the *interior mutability*
+Mutating the value inside an immutable value is the interior mutability
pattern. Let’s look at a situation in which interior mutability is useful and
examine how it’s possible.
-### Interior Mutability: A Mutable Borrow to an Immutable Value
+
+
+
+
+### Using Interior Mutability
A consequence of the borrowing rules is that when you have an immutable value,
you can’t borrow it mutably. For example, this code won’t compile:
@@ -1248,7 +1290,7 @@ However, there are situations in which it would be useful for a value to mutate
itself in its methods but appear immutable to other code. Code outside the
value’s methods would not be able to mutate the value. Using `RefCell` is
one way to get the ability to have interior mutability, but `RefCell`
-doesn’t get around the borrowing rules completely: the borrow checker in the
+doesn’t get around the borrowing rules completely: The borrow checker in the
compiler allows this interior mutability, and the borrowing rules are checked
at runtime instead. If you violate the rules, you’ll get a `panic!` instead of
a compiler error.
@@ -1256,7 +1298,11 @@ a compiler error.
Let’s work through a practical example where we can use `RefCell` to mutate
an immutable value and see why that is useful.
-#### A Use Case for Interior Mutability: Mock Objects
+
+
+
+
+#### Testing with Mock Objects
Sometimes during testing a programmer will use a type in place of another type,
in order to observe particular behavior and assert that it’s implemented
@@ -1264,7 +1310,7 @@ correctly. This placeholder type is called a *test double*. Think of it in the
sense of a stunt double in filmmaking, where a person steps in and substitutes
for an actor to do a particularly tricky scene. Test doubles stand in for other
types when we’re running tests. *Mock objects* are specific types of test
-doubles that record what happens during a test so you can assert that the
+doubles that record what happens during a test so that you can assert that the
correct actions took place.
Rust doesn’t have objects in the same sense as other languages have objects,
@@ -1272,7 +1318,7 @@ and Rust doesn’t have mock object functionality built into the standard librar
as some other languages do. However, you can definitely create a struct that
will serve the same purposes as a mock object.
-Here’s the scenario we’ll test: we’ll create a library that tracks a value
+Here’s the scenario we’ll test: We’ll create a library that tracks a value
against a maximum value and sends messages based on how close to the maximum
value the current value is. This library could be used to keep track of a
user’s quota for the number of API calls they’re allowed to make, for example.
@@ -1280,10 +1326,10 @@ user’s quota for the number of API calls they’re allowed to make, for exampl
Our library will only provide the functionality of tracking how close to the
maximum a value is and what the messages should be at what times. Applications
that use our library will be expected to provide the mechanism for sending the
-messages: the application could put a message in the application, send an email,
-send a text message, or do something else. The library doesn’t need to know that
-detail. All it needs is something that implements a trait we’ll provide called
-`Messenger`. Listing 15-20 shows the library code.
+messages: The application could show the message to the user directly, send an
+email, send a text message, or do something else. The library doesn’t need to
+know that detail. All it needs is something that implements a trait we’ll
+provide, called `Messenger`. Listing 15-20 shows the library code.
src/lib.rs
@@ -1338,8 +1384,8 @@ is that we want to test the behavior of the `set_value` method on the
`LimitTracker`. We can change what we pass in for the `value` parameter, but
`set_value` doesn’t return anything for us to make assertions on. We want to be
able to say that if we create a `LimitTracker` with something that implements
-the `Messenger` trait and a particular value for `max`, when we pass different
-numbers for `value` the messenger is told to send the appropriate messages.
+the `Messenger` trait and a particular value for `max`, the messenger is told
+to send the appropriate messages when we pass different numbers for `value`.
We need a mock object that, instead of sending an email or text message when we
call `send`, will only keep track of the messages it’s told to send. We can
@@ -1391,18 +1437,18 @@ This test code defines a `MockMessenger` struct that has a `sent_messages`
field with a `Vec` of `String` values to keep track of the messages it’s told
to send. We also define an associated function `new` to make it convenient to
create new `MockMessenger` values that start with an empty list of messages. We
-then implement the `Messenger` trait for `MockMessenger` so we can give a
+then implement the `Messenger` trait for `MockMessenger` so that we can give a
`MockMessenger` to a `LimitTracker`. In the definition of the `send` method, we
take the message passed in as a parameter and store it in the `MockMessenger`
list of `sent_messages`.
In the test, we’re testing what happens when the `LimitTracker` is told to set
-`value` to something that is more than 75 percent of the `max` value. First we
+`value` to something that is more than 75 percent of the `max` value. First, we
create a new `MockMessenger`, which will start with an empty list of messages.
-Then we create a new `LimitTracker` and give it a reference to the new
+Then, we create a new `LimitTracker` and give it a reference to the new
`MockMessenger` and a `max` value of `100`. We call the `set_value` method on
the `LimitTracker` with a value of `80`, which is more than 75 percent of 100.
-Then we assert that the list of messages that the `MockMessenger` is keeping
+Then, we assert that the list of messages that the `MockMessenger` is keeping
track of should now have one message in it.
However, there’s one problem with this test, as shown here:
@@ -1429,7 +1475,7 @@ For more information about this error, try `rustc --explain E0596`.
error: could not compile `limit-tracker` (lib test) due to 1 previous error
```
-We can’t modify the `MockMessenger` to keep track of the messages because the
+We can’t modify the `MockMessenger` to keep track of the messages, because the
`send` method takes an immutable reference to `self`. We also can’t take the
suggestion from the error text to use `&mut self` in both the `impl` method and
the trait definition. We do not want to change the `Messenger` trait solely for
@@ -1437,9 +1483,9 @@ the sake of testing. Instead, we need to find a way to make our test code work
correctly with our existing design.
This is a situation in which interior mutability can help! We’ll store the
-`sent_messages` within a `RefCell`, and then the `send` method will be
-able to modify `sent_messages` to store the messages we’ve seen. Listing 15-22
-shows what that looks like.
+`sent_messages` within a `RefCell`, and then the `send` method will be able
+to modify `sent_messages` to store the messages we’ve seen. Listing 15-22 shows
+what that looks like.
src/lib.rs
@@ -1486,16 +1532,20 @@ For the implementation of the `send` method, the first parameter is still an
immutable borrow of `self`, which matches the trait definition. We call
`borrow_mut` on the `RefCell>` in `self.sent_messages` to get a
mutable reference to the value inside the `RefCell>`, which is the
-vector. Then we can call `push` on the mutable reference to the vector to keep
+vector. Then, we can call `push` on the mutable reference to the vector to keep
track of the messages sent during the test.
-The last change we have to make is in the assertion: to see how many items are
+The last change we have to make is in the assertion: To see how many items are
in the inner vector, we call `borrow` on the `RefCell>` to get an
immutable reference to the vector.
Now that you’ve seen how to use `RefCell`, let’s dig into how it works!
-#### Keeping Track of Borrows at Runtime with RefCell
+
+
+
+
+#### Tracking Borrows at Runtime
When creating immutable and mutable references, we use the `&` and `&mut`
syntax, respectively. With `RefCell`, we use the `borrow` and `borrow_mut`
@@ -1535,8 +1585,8 @@ src/lib.rs
Listing 15-23: Creating two mutable references in the same scope to see that `RefCell` will panic
We create a variable `one_borrow` for the `RefMut` smart pointer returned
-from `borrow_mut`. Then we create another mutable borrow in the same way in the
-variable `two_borrow`. This makes two mutable references in the same scope,
+from `borrow_mut`. Then, we create another mutable borrow in the same way in
+the variable `two_borrow`. This makes two mutable references in the same scope,
which isn’t allowed. When we run the tests for our library, the code in Listing
15-23 will compile without any errors, but the test will fail:
@@ -1580,23 +1630,25 @@ in a context where only immutable values are allowed. You can use `RefCell`
despite its trade-offs to get more functionality than regular references
provide.
-
+
+
-### Allowing Multiple Owners of Mutable Data with Rc and RefCell
+### Allowing Multiple Owners of Mutable Data
A common way to use `RefCell` is in combination with `Rc`. Recall that
`Rc` lets you have multiple owners of some data, but it only gives immutable
access to that data. If you have an `Rc` that holds a `RefCell`, you can
get a value that can have multiple owners *and* that you can mutate!
-For example, recall the cons list example in Listing 15-18 where we used `Rc`
-to allow multiple lists to share ownership of another list. Because `Rc`
-holds only immutable values, we can’t change any of the values in the list once
-we’ve created them. Let’s add in `RefCell` for its ability to change the
-values in the lists. Listing 15-24 shows that by using a `RefCell` in the
-`Cons` definition, we can modify the value stored in all the lists.
+For example, recall the cons list example in Listing 15-18 where we used
+`Rc` to allow multiple lists to share ownership of another list. Because
+`Rc` holds only immutable values, we can’t change any of the values in the
+list once we’ve created them. Let’s add in `RefCell` for its ability to
+change the values in the lists. Listing 15-24 shows that by using a
+`RefCell` in the `Cons` definition, we can modify the value stored in all
+the lists.
src/main.rs
@@ -1630,11 +1682,11 @@ fn main() {
Listing 15-24: Using `Rc>` to create a `List` that we can mutate
We create a value that is an instance of `Rc>` and store it in a
-variable named `value` so we can access it directly later. Then we create a
-`List` in `a` with a `Cons` variant that holds `value`. We need to clone
-`value` so both `a` and `value` have ownership of the inner `5` value rather
-than transferring ownership from `value` to `a` or having `a` borrow from
-`value`.
+variable named `value` so that we can access it directly later. Then, we create
+a `List` in `a` with a `Cons` variant that holds `value`. We need to clone
+`value` so that both `a` and `value` have ownership of the inner `5` value
+rather than transferring ownership from `value` to `a` or having `a` borrow
+from `value`.
We wrap the list `a` in an `Rc` so that when we create lists `b` and `c`,
they can both refer to `a`, which is what we did in Listing 15-18.
@@ -1642,7 +1694,7 @@ they can both refer to `a`, which is what we did in Listing 15-18.
After we’ve created the lists in `a`, `b`, and `c`, we want to add 10 to the
value in `value`. We do this by calling `borrow_mut` on `value`, which uses the
automatic dereferencing feature we discussed in “Where’s the `->`
-Operator?”) in Chapter 5 to dereference
+Operator?” in Chapter 5 to dereference
the `Rc` to the inner `RefCell` value. The `borrow_mut` method returns a
`RefMut` smart pointer, and we use the dereference operator on it and change
the inner value.
@@ -1662,9 +1714,9 @@ c after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil))
This technique is pretty neat! By using `RefCell`, we have an outwardly
immutable `List` value. But we can use the methods on `RefCell` that provide
-access to its interior mutability so we can modify our data when we need to.
-The runtime checks of the borrowing rules protect us from data races, and it’s
-sometimes worth trading a bit of speed for this flexibility in our data
+access to its interior mutability so that we can modify our data when we need
+to. The runtime checks of the borrowing rules protect us from data races, and
+it’s sometimes worth trading a bit of speed for this flexibility in our data
structures. Note that `RefCell` does not work for multithreaded code!
`Mutex` is the thread-safe version of `RefCell`, and we’ll discuss
`Mutex` in Chapter 16.
@@ -1675,7 +1727,7 @@ Rust’s memory safety guarantees make it difficult, but not impossible, to
accidentally create memory that is never cleaned up (known as a *memory leak*).
Preventing memory leaks entirely is not one of Rust’s guarantees, meaning
memory leaks are memory safe in Rust. We can see that Rust allows memory leaks
-by using `Rc` and `RefCell`: it’s possible to create references where
+by using `Rc` and `RefCell`: It’s possible to create references where
items refer to each other in a cycle. This creates memory leaks because the
reference count of each item in the cycle will never reach 0, and the values
will never be dropped.
@@ -1707,11 +1759,9 @@ impl List {
}
}
}
-
-fn main() {}
```
-Listing 15-25: A cons list definition that holds a `RefCell` so we can modify what a `Cons` variant is referring to
+Listing 15-25: A cons list definition that holds a `RefCell` so that we can modify what a `Cons` variant is referring to
We’re using another variation of the `List` definition from Listing 15-5. The
second element in the `Cons` variant is now `RefCell>`, meaning that
@@ -1722,7 +1772,7 @@ second item if we have a `Cons` variant.
In Listing 15-26, we’re adding a `main` function that uses the definitions in
Listing 15-25. This code creates a list in `a` and a list in `b` that points to
-the list in `a`. Then it modifies the list in `a` to point to `b`, creating a
+the list in `a`. Then, it modifies the list in `a` to point to `b`, creating a
reference cycle. There are `println!` statements along the way to show what the
reference counts are at various points in this process.
@@ -1758,14 +1808,14 @@ Listing 15-26: Creating a reference cycle of two `List` values pointing to each
We create an `Rc` instance holding a `List` value in the variable `a`
with an initial list of `5, Nil`. We then create an `Rc` instance holding
-another `List` value in the variable `b` that contains the value `10` and points
-to the list in `a`.
+another `List` value in the variable `b` that contains the value `10` and
+points to the list in `a`.
-We modify `a` so it points to `b` instead of `Nil`, creating a cycle. We do
-that by using the `tail` method to get a reference to the `RefCell>`
-in `a`, which we put in the variable `link`. Then we use the `borrow_mut`
-method on the `RefCell>` to change the value inside from an `Rc`
-that holds a `Nil` value to the `Rc` in `b`.
+We modify `a` so that it points to `b` instead of `Nil`, creating a cycle. We
+do that by using the `tail` method to get a reference to the
+`RefCell>` in `a`, which we put in the variable `link`. Then, we use
+the `borrow_mut` method on the `RefCell>` to change the value inside
+from an `Rc` that holds a `Nil` value to the `Rc` in `b`.
When we run this code, keeping the last `println!` commented out for the
moment, we’ll get this output:
@@ -1786,29 +1836,29 @@ a rc count after changing a = 2
The reference count of the `Rc` instances in both `a` and `b` is 2 after
we change the list in `a` to point to `b`. At the end of `main`, Rust drops the
-variable `b`, which decreases the reference count of the `b` `Rc` instance
-from 2 to 1. The memory that `Rc` has on the heap won’t be dropped at
-this point because its reference count is 1, not 0. Then Rust drops `a`, which
-decreases the reference count of the `a` `Rc` instance from 2 to 1 as
-well. This instance’s memory can’t be dropped either, because the other
+variable `b`, which decreases the reference count of the `b` `Rc`
+instance from 2 to 1. The memory that `Rc` has on the heap won’t be
+dropped at this point because its reference count is 1, not 0. Then, Rust drops
+`a`, which decreases the reference count of the `a` `Rc` instance from 2
+to 1 as well. This instance’s memory can’t be dropped either, because the other
`Rc` instance still refers to it. The memory allocated to the list will
-remain uncollected forever. To visualize this reference cycle, we’ve created the
-diagram in Figure 15-4.
+remain uncollected forever. To visualize this reference cycle, we’ve created
+the diagram in Figure 15-4.
-
+
Figure 15-4: A reference cycle of lists `a` and `b`
pointing to each other
-If you uncomment the last `println!` and run the program, Rust will try to print
-this cycle with `a` pointing to `b` pointing to `a` and so forth until it
+If you uncomment the last `println!` and run the program, Rust will try to
+print this cycle with `a` pointing to `b` pointing to `a` and so forth until it
overflows the stack.
-Compared to a real-world program, the consequences of creating a reference cycle
-in this example aren’t very dire: right after we create the reference cycle,
-the program ends. However, if a more complex program allocated lots of memory
-in a cycle and held onto it for a long time, the program would use more memory
-than it needed and might overwhelm the system, causing it to run out of
+Compared to a real-world program, the consequences of creating a reference
+cycle in this example aren’t very dire: Right after we create the reference
+cycle, the program ends. However, if a more complex program allocated lots of
+memory in a cycle and held onto it for a long time, the program would use more
+memory than it needed and might overwhelm the system, causing it to run out of
available memory.
Creating reference cycles is not easily done, but it’s not impossible either.
@@ -1829,21 +1879,22 @@ Let’s look at an example using graphs made up of parent nodes and child nodes
to see when non-ownership relationships are an appropriate way to prevent
reference cycles.
-
+
### Preventing Reference Cycles Using Weak
-So far, we’ve demonstrated that calling `Rc::clone` increases the `strong_count`
-of an `Rc` instance, and an `Rc` instance is only cleaned up if its
-`strong_count` is 0. You can also create a weak reference to the value within
-an `Rc` instance by calling `Rc::downgrade` and passing a reference to the
-`Rc`. *Strong references* are how you can share ownership of an `Rc`
-instance. *Weak references* don’t express an ownership relationship, and their
-count doesn’t affect when an `Rc` instance is cleaned up. They won’t cause a
-reference cycle because any cycle involving some weak references will be broken
-once the strong reference count of values involved is 0.
+So far, we’ve demonstrated that calling `Rc::clone` increases the
+`strong_count` of an `Rc` instance, and an `Rc` instance is only cleaned
+up if its `strong_count` is 0. You can also create a weak reference to the
+value within an `Rc` instance by calling `Rc::downgrade` and passing a
+reference to the `Rc`. *Strong references* are how you can share ownership
+of an `Rc` instance. *Weak references* don’t express an ownership
+relationship, and their count doesn’t affect when an `Rc` instance is
+cleaned up. They won’t cause a reference cycle, because any cycle involving
+some weak references will be broken once the strong reference count of values
+involved is 0.
When you call `Rc::downgrade`, you get a smart pointer of type `Weak`.
Instead of increasing the `strong_count` in the `Rc` instance by 1, calling
@@ -1862,14 +1913,18 @@ Rust will ensure that the `Some` case and the `None` case are handled, and
there won’t be an invalid pointer.
As an example, rather than using a list whose items know only about the next
-item, we’ll create a tree whose items know about their children items *and*
-their parent items.
+item, we’ll create a tree whose items know about their child items *and* their
+parent items.
+
+
+
+
-#### Creating a Tree Data Structure: A Node with Child Nodes
+#### Creating a Tree Data Structure
To start, we’ll build a tree with nodes that know about their child nodes.
We’ll create a struct named `Node` that holds its own `i32` value as well as
-references to its children `Node` values:
+references to its child `Node` values:
Filename: src/main.rs
@@ -1885,8 +1940,8 @@ struct Node {
```
We want a `Node` to own its children, and we want to share that ownership with
-variables so we can access each `Node` in the tree directly. To do this, we
-define the `Vec` items to be values of type `Rc`. We also want to
+variables so that we can access each `Node` in the tree directly. To do this,
+we define the `Vec` items to be values of type `Rc`. We also want to
modify which nodes are children of another node, so we have a `RefCell` in
`children` around the `Vec>`.
@@ -1929,11 +1984,11 @@ create a reference cycle with `leaf.parent` pointing to `branch` and
values to never be 0.
Thinking about the relationships another way, a parent node should own its
-children: if a parent node is dropped, its child nodes should be dropped as
-well. However, a child should not own its parent: if we drop a child node, the
+children: If a parent node is dropped, its child nodes should be dropped as
+well. However, a child should not own its parent: If we drop a child node, the
parent should still exist. This is a case for weak references!
-So instead of `Rc`, we’ll make the type of `parent` use `Weak`,
+So, instead of `Rc`, we’ll make the type of `parent` use `Weak`,
specifically a `RefCell>`. Now our `Node` struct definition looks
like this:
@@ -1951,8 +2006,8 @@ struct Node {
}
```
-A node will be able to refer to its parent node but doesn’t own its parent.
-In Listing 15-28, we update `main` to use this new definition so the `leaf`
+A node will be able to refer to its parent node but doesn’t own its parent. In
+Listing 15-28, we update `main` to use this new definition so that the `leaf`
node will have a way to refer to its parent, `branch`.
src/main.rs
@@ -1994,16 +2049,15 @@ leaf parent = None
```
When we create the `branch` node, it will also have a new `Weak`
-reference in the `parent` field because `branch` doesn’t have a parent node.
-We still have `leaf` as one of the children of `branch`. Once we have the
-`Node` instance in `branch`, we can modify `leaf` to give it a `Weak`
-reference to its parent. We use the `borrow_mut` method on the
-`RefCell>` in the `parent` field of `leaf`, and then we use the
-`Rc::downgrade` function to create a `Weak` reference to `branch` from
-the `Rc` in `branch`.
+reference in the `parent` field because `branch` doesn’t have a parent node. We
+still have `leaf` as one of the children of `branch`. Once we have the `Node`
+instance in `branch`, we can modify `leaf` to give it a `Weak` reference
+to its parent. We use the `borrow_mut` method on the `RefCell>` in
+the `parent` field of `leaf`, and then we use the `Rc::downgrade` function to
+create a `Weak` reference to `branch` from the `Rc` in `branch`.
When we print the parent of `leaf` again, this time we’ll get a `Some` variant
-holding `branch`: now `leaf` can access its parent! When we print `leaf`, we
+holding `branch`: Now `leaf` can access its parent! When we print `leaf`, we
also avoid the cycle that eventually ended in a stack overflow like we had in
Listing 15-26; the `Weak` references are printed as `(Weak)`:
@@ -2080,7 +2134,7 @@ count of 0. In the inner scope, we create `branch` and associate it with
will have a strong count of 1 and a weak count of 1 (for `leaf.parent` pointing
to `branch` with a `Weak`). When we print the counts in `leaf`, we’ll see
it will have a strong count of 2 because `branch` now has a clone of the
-`Rc` of `leaf` stored in `branch.children`, but will still have a weak
+`Rc` of `leaf` stored in `branch.children` but will still have a weak
count of 0.
When the inner scope ends, `branch` goes out of scope and the strong count of
@@ -2106,7 +2160,7 @@ This chapter covered how to use smart pointers to make different guarantees and
trade-offs from those Rust makes by default with regular references. The
`Box` type has a known size and points to data allocated on the heap. The
`Rc` type keeps track of the number of references to data on the heap so
-that data can have multiple owners. The `RefCell` type with its interior
+that the data can have multiple owners. The `RefCell` type with its interior
mutability gives us a type that we can use when we need an immutable type but
need to change an inner value of that type; it also enforces the borrowing
rules at runtime instead of at compile time.
diff --git a/nostarch/chapter16.md b/nostarch/chapter16.md
index c34a258c9c..1877883b2f 100644
--- a/nostarch/chapter16.md
+++ b/nostarch/chapter16.md
@@ -13,7 +13,7 @@ major goals. *Concurrent programming*, in which different parts of a program
execute independently, and *parallel programming*, in which different parts of
a program execute at the same time, are becoming increasingly important as more
computers take advantage of their multiple processors. Historically,
-programming in these contexts has been difficult and error prone. Rust hopes to
+programming in these contexts has been difficult and error-prone. Rust hopes to
change that.
Initially, the Rust team thought that ensuring memory safety and preventing
@@ -144,7 +144,7 @@ hi number 5 from the spawned thread!
The calls to `thread::sleep` force a thread to stop its execution for a short
duration, allowing a different thread to run. The threads will probably take
-turns, but that isn’t guaranteed: it depends on how your operating system
+turns, but that isn’t guaranteed: It depends on how your operating system
schedules the threads. In this run, the main thread printed first, even though
the print statement from the spawned thread appears first in the code. And even
though we told the spawned thread to print until `i` is `9`, it only got to `5`
@@ -154,7 +154,11 @@ If you run this code and only see output from the main thread, or don’t see an
overlap, try increasing the numbers in the ranges to create more opportunities
for the operating system to switch between the threads.
-### Waiting for All Threads to Finish Using join Handles
+
+
+
+
+### Waiting for All Threads to Finish
The code in Listing 16-1 not only stops the spawned thread prematurely most of
the time due to the main thread ending, but because there is no guarantee on
@@ -286,7 +290,7 @@ another. In “Capturing References or Moving Ownership” in Chapter 13, we dis
concentrate more on the interaction between `move` and `thread::spawn`.
Notice in Listing 16-1 that the closure we pass to `thread::spawn` takes no
-arguments: we’re not using any data from the main thread in the spawned
+arguments: We’re not using any data from the main thread in the spawned
thread’s code. To use data from the main thread in the spawned thread, the
spawned thread’s closure must capture the values it needs. Listing 16-3 shows
an attempt to create a vector in the main thread and use it in the spawned
@@ -456,10 +460,14 @@ ownership rules.
Now that we’ve covered what threads are and the methods supplied by the thread
API, let’s look at some situations in which we can use threads.
-## Using Message Passing to Transfer Data Between Threads
+
+
+
-One increasingly popular approach to ensuring safe concurrency is *message
-passing*, where threads or actors communicate by sending each other messages
+## Transfer Data Between Threads with Message Passing
+
+One increasingly popular approach to ensuring safe concurrency is message
+passing, where threads or actors communicate by sending each other messages
containing data. Here’s the idea in a slogan from the Go language documentation at *https://golang.org/doc/effective_go.html#concurrency*:
“Do not communicate by sharing memory; instead, share memory by communicating.”
@@ -506,7 +514,7 @@ We create a new channel using the `mpsc::channel` function; `mpsc` stands for
*multiple producer, single consumer*. In short, the way Rust’s standard library
implements channels means a channel can have multiple *sending* ends that
produce values but only one *receiving* end that consumes those values. Imagine
-multiple streams flowing together into one big river: everything sent down any
+multiple streams flowing together into one big river: Everything sent down any
of the streams will end up in one river at the end. We’ll start with a single
producer for now, but we’ll add multiple producers when we get this example
working.
@@ -522,9 +530,9 @@ pattern that destructures the tuples; we’ll discuss the use of patterns in
the tuple returned by `mpsc::channel`.
Let’s move the transmitting end into a spawned thread and have it send one
-string so the spawned thread is communicating with the main thread, as shown in
-Listing 16-7. This is like putting a rubber duck in the river upstream or
-sending a chat message from one thread to another.
+string so that the spawned thread is communicating with the main thread, as
+shown in Listing 16-7. This is like putting a rubber duck in the river upstream
+or sending a chat message from one thread to another.
src/main.rs
@@ -545,7 +553,7 @@ fn main() {
Listing 16-7: Moving `tx` to a spawned thread and sending `"hi"`
Again, we’re using `thread::spawn` to create a new thread and then using `move`
-to move `tx` into the closure so the spawned thread owns `tx`. The spawned
+to move `tx` into the closure so that the spawned thread owns `tx`. The spawned
thread needs to own the transmitter to be able to send messages through the
channel.
@@ -553,7 +561,7 @@ The transmitter has a `send` method that takes the value we want to send. The
`send` method returns a `Result` type, so if the receiver has already
been dropped and there’s nowhere to send a value, the send operation will
return an error. In this example, we’re calling `unwrap` to panic in case of an
-error. But in a real application, we would handle it properly: return to
+error. But in a real application, we would handle it properly: Return to
Chapter 9 to review strategies for proper error handling.
In Listing 16-8, we’ll get the value from the receiver in the main thread. This
@@ -590,7 +598,7 @@ an error to signal that no more values will be coming.
The `try_recv` method doesn’t block, but will instead return a `Result`
immediately: an `Ok` value holding a message if one is available and an `Err`
value if there aren’t any messages this time. Using `try_recv` is useful if
-this thread has other work to do while waiting for messages: we could write a
+this thread has other work to do while waiting for messages: We could write a
loop that calls `try_recv` every so often, handles a message if one is
available, and otherwise does other work for a little while until checking
again.
@@ -612,13 +620,17 @@ Got: hi
Perfect!
-### Channels and Ownership Transference
+
+
+