Skip to content

Commit

Permalink
Small correction in ch13-01
Browse files Browse the repository at this point in the history
Fix description: the example tries to count the number of times
`sort_by_key` calls the closure, not how often `sort_by_key` is called.
Also, use a clearer String value in the example code.
  • Loading branch information
stomar committed Nov 18, 2023
1 parent 71352de commit f082dde
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion listings/ch13-functional-features/listing-13-08/output.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ $ cargo run
error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure
--> src/main.rs:18:30
|
15 | let value = String::from("by key called");
15 | let value = String::from("closure called");
| ----- captured outer variable
16 |
17 | list.sort_by_key(|r| {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn main() {
];

let mut sort_operations = vec![];
let value = String::from("by key called");
let value = String::from("closure called");

list.sort_by_key(|r| {
sort_operations.push(value);
Expand Down
4 changes: 2 additions & 2 deletions src/ch13-01-closures.md
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ compiler won’t let us use this closure with `sort_by_key`:
`sort_by_key`</span>

This is a contrived, convoluted way (that doesn’t work) to try and count the
number of times `sort_by_key` gets called when sorting `list`. This code
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`
then moves `value` out of the closure by transferring ownership of `value` to
Expand All @@ -399,7 +399,7 @@ implement `FnMut`:

The error points to the line in the closure body that moves `value` out of the
environment. To fix this, we need to change the closure body so that it doesn’t
move values out of the environment. To count the number of times `sort_by_key`
move values out of the environment. To count the number of times the closure
is called, keeping a counter in the environment and incrementing its value in
the closure body is a more straightforward way to calculate that. The closure
in Listing 13-9 works with `sort_by_key` because it is only capturing a mutable
Expand Down

0 comments on commit f082dde

Please sign in to comment.