Skip to content

Commit b897e43

Browse files
authored
Small fixes re: closures (#2735)
1 parent 291c2b0 commit b897e43

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/closures/exercise.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
minutes: 10
3+
---
4+
15
# Exercise: Log Filter
26

37
Building on the generic logger from this morning, implement a `Filter` which

src/closures/traits.md

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,16 @@ implement special [`Fn`](https://doc.rust-lang.org/std/ops/trait.Fn.html),
99
[`FnMut`](https://doc.rust-lang.org/std/ops/trait.FnMut.html), and
1010
[`FnOnce`](https://doc.rust-lang.org/std/ops/trait.FnOnce.html) traits:
1111

12-
The special type `fn` refers to function pointers - either the address of a
13-
function, or a closure that captures nothing.
12+
The special types `fn(..) -> T` refer to function pointers - either the address
13+
of a function, or a closure that captures nothing.
1414

1515
```rust,editable
16-
fn apply_and_log(func: impl FnOnce(String) -> String, func_name: &str, input: &str) {
17-
println!("Calling {func_name}({input}): {}", func(input.to_string()))
16+
fn apply_and_log(
17+
func: impl FnOnce(&'static str) -> String,
18+
func_name: &'static str,
19+
input: &'static str,
20+
) {
21+
println!("Calling {func_name}({input}): {}", func(input))
1822
}
1923
2024
fn main() {
@@ -32,9 +36,10 @@ fn main() {
3236
apply_and_log(&mut accumulate, "accumulate", "green");
3337
apply_and_log(&mut accumulate, "accumulate", "blue");
3438
35-
let take_and_reverse = |mut prefix: String| {
36-
prefix.push_str(&v.into_iter().rev().collect::<Vec<_>>().join("/"));
37-
prefix
39+
let take_and_reverse = |prefix| {
40+
let mut acc = String::from(prefix);
41+
acc.push_str(&v.into_iter().rev().collect::<Vec<_>>().join("/"));
42+
acc
3843
};
3944
apply_and_log(take_and_reverse, "take_and_reverse", "reversed: ");
4045
}

0 commit comments

Comments
 (0)