feat: improved closure docs and exercises by using into_iter()

This commit is contained in:
jayber 2022-06-07 13:39:54 +01:00
parent 12156a017b
commit 3712439caf
3 changed files with 9 additions and 4 deletions

View File

@ -21,6 +21,9 @@ fn sum_letters(animals: &Vec<&str>) -> usize {
// pay close attention to the where clause in the function signatures
// https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.reduce
// https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.fold
// and the return types of the different ways of getting an iterator
// https://doc.rust-lang.org/stable/std/iter/
// https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#tymethod.into_iter
// TODO: change the next 2 lines to compile and pass the test.
let sum_closure = |x: &usize, y: &usize| &(x + y);
animals.iter().reduce(sum_closure).unwrap().to_owned()

View File

@ -20,7 +20,7 @@ fn main() {
let maybe = Some("yes");
let list = vec![maybe];
list.iter().inspect(|&Some(value)| {
list.into_iter().inspect(|Some(value)| {
println!("maybe {:?}", value);
});
}

View File

@ -178,13 +178,15 @@ path = "exercises/closures/closures5.rs"
mode = "test"
hint = """
Getting the signatures of closures right can be tough. I don't think you can write
any version that fulfills the tests using 'reduce()': you can never return a borrow
any version that fulfills the tests using 'reduce()' with 'iter()': you can never return a borrow
of a value owned by a called function.
You need to replace 'reduce()' with a different function call, update the closure
You can replace 'reduce()' with a different function call. Update the closure
so that it matches the signature of this new call, and change the code to return
the correct type from the sum_letters function. (Using 'sum()' is cheating!)
OR you can change the sort of iterator you get, so that you don't have to return a reference.
Pay close attention to the documentation linked to in the exercise: which type
parameters are the same in the function signatures, and which are different."""
parameters are the same in the function signatures, and which are different. And
how do the return types of the variations of getting an iterator differ from each other?"""
[[exercises]]
name = "closures6"