From b897e43892bbb32bbdaee73c1e48dc3f7fe5cbcb Mon Sep 17 00:00:00 2001 From: Frances Wingerter <91758128+fw-immunant@users.noreply.github.com> Date: Tue, 6 May 2025 15:54:04 +0000 Subject: [PATCH] Small fixes re: closures (#2735) --- src/closures/exercise.md | 4 ++++ src/closures/traits.md | 19 ++++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/closures/exercise.md b/src/closures/exercise.md index 6b064cb7..efb210b5 100644 --- a/src/closures/exercise.md +++ b/src/closures/exercise.md @@ -1,3 +1,7 @@ +--- +minutes: 10 +--- + # Exercise: Log Filter Building on the generic logger from this morning, implement a `Filter` which diff --git a/src/closures/traits.md b/src/closures/traits.md index 4eb29b6f..c8a92acf 100644 --- a/src/closures/traits.md +++ b/src/closures/traits.md @@ -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 [`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 -function, or a closure that captures nothing. +The special types `fn(..) -> T` refer to function pointers - either the address +of a function, or a closure that captures nothing. ```rust,editable -fn apply_and_log(func: impl FnOnce(String) -> String, func_name: &str, input: &str) { - println!("Calling {func_name}({input}): {}", func(input.to_string())) +fn apply_and_log( + func: impl FnOnce(&'static str) -> String, + func_name: &'static str, + input: &'static str, +) { + println!("Calling {func_name}({input}): {}", func(input)) } fn main() { @@ -32,9 +36,10 @@ fn main() { apply_and_log(&mut accumulate, "accumulate", "green"); apply_and_log(&mut accumulate, "accumulate", "blue"); - let take_and_reverse = |mut prefix: String| { - prefix.push_str(&v.into_iter().rev().collect::>().join("/")); - prefix + let take_and_reverse = |prefix| { + let mut acc = String::from(prefix); + acc.push_str(&v.into_iter().rev().collect::>().join("/")); + acc }; apply_and_log(take_and_reverse, "take_and_reverse", "reversed: "); }