1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-08-08 08:22:52 +02:00

Small fixes re: closures (#2735)

This commit is contained in:
Frances Wingerter
2025-05-06 15:54:04 +00:00
committed by GitHub
parent 291c2b08e3
commit b897e43892
2 changed files with 16 additions and 7 deletions

View File

@ -1,3 +1,7 @@
---
minutes: 10
---
# Exercise: Log Filter # Exercise: Log Filter
Building on the generic logger from this morning, implement a `Filter` which Building on the generic logger from this morning, implement a `Filter` which

View File

@ -9,12 +9,16 @@ implement special [`Fn`](https://doc.rust-lang.org/std/ops/trait.Fn.html),
[`FnMut`](https://doc.rust-lang.org/std/ops/trait.FnMut.html), and [`FnMut`](https://doc.rust-lang.org/std/ops/trait.FnMut.html), and
[`FnOnce`](https://doc.rust-lang.org/std/ops/trait.FnOnce.html) traits: [`FnOnce`](https://doc.rust-lang.org/std/ops/trait.FnOnce.html) traits:
The special type `fn` refers to function pointers - either the address of a The special types `fn(..) -> T` refer to function pointers - either the address
function, or a closure that captures nothing. of a function, or a closure that captures nothing.
```rust,editable ```rust,editable
fn apply_and_log(func: impl FnOnce(String) -> String, func_name: &str, input: &str) { fn apply_and_log(
println!("Calling {func_name}({input}): {}", func(input.to_string())) func: impl FnOnce(&'static str) -> String,
func_name: &'static str,
input: &'static str,
) {
println!("Calling {func_name}({input}): {}", func(input))
} }
fn main() { fn main() {
@ -32,9 +36,10 @@ fn main() {
apply_and_log(&mut accumulate, "accumulate", "green"); apply_and_log(&mut accumulate, "accumulate", "green");
apply_and_log(&mut accumulate, "accumulate", "blue"); apply_and_log(&mut accumulate, "accumulate", "blue");
let take_and_reverse = |mut prefix: String| { let take_and_reverse = |prefix| {
prefix.push_str(&v.into_iter().rev().collect::<Vec<_>>().join("/")); let mut acc = String::from(prefix);
prefix acc.push_str(&v.into_iter().rev().collect::<Vec<_>>().join("/"));
acc
}; };
apply_and_log(take_and_reverse, "take_and_reverse", "reversed: "); apply_and_log(take_and_reverse, "take_and_reverse", "reversed: ");
} }