Iterators
The iterator pattern allows you to perform some task on a sequence of items in turn.
Iterators provide a way to traverse, transform, or consume elements efficiently without needing to manually manage indices or loops.
Rust iterators are lazy by default, meaning they don’t perform operations until explicitly consumed.
collect()can take anything iterable, and turn it into a relevant collection.References:
iterators1.rs
// When performing operations on elements within a collection, iterators are
// essential. This module helps you get familiar with the structure of using an
// iterator and how to go through elements within an iterable collection.
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
#[test]
fn iterators() {
let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"];
// Create an iterator over the array.
let mut fav_fruits_iterator = my_fav_fruits.iter();
assert_eq!(fav_fruits_iterator.next(), Some(&"banana"));
assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"avocado"));
assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // Replace `todo!()`
assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry"));
assert_eq!(fav_fruits_iterator.next(), None); // Replace `todo!()`
}
}This exercise is simple we just need to create iterators based on
my_fav_fruitsarray.We can do this by calling
itermethod like this:
iterators2.rs
First task in this exercise is to complete the
capitalize_firstfunction.We already have
matchsyntax for firstcharfor the given input.We just need to uppercase it and combine it with the reset of the chars.
We can do it by using
formator+like this:or
Second and third task is kinda similar, in here we will learn how powerful method
collectis.In the
capitalize_words_vectorfunction we need to iterate givenwordsand capitalize it using function in the first task.We can do it like this:
collect()can take anything iterable, and turn it into a relevant collection.In this case rust will convert the iterator to desired return type which is
Vec<String>.This also means that we can use the same code for our next task in function
capitalize_words_stringand Rust will convert the iterator into desired return type which isString.
iterators3.rs
First task in this exercise is to complete the function
divideto return error in accordance with enumDivisionError.For the overflow checking we can do it by using method
overflowing_div.Second task is to fix function
result_with_list.The return signature that satisfy the desired output should be
Result<Vec<i64>, DivisionError>.And we can use
into_iter().collect()method chain to convert the iterator to the desired output.
Similar like previous task, the last task is to fix function
list_of_results.The return signature that satisfy the desired output should be
Vec<Result<i64, DivisionError>>.And we can use
into_iter().collect()method chain to convert the iterator to the desired output.
iterators4.rs
This exercise is straightforward, we just need to finish the
factorialfunction.We can use
foldmethod to do this.Folds every element into an accumulator by applying an operation, returning the final result.
But then you will see in that rust compiler will suggest to use
productinstead like this:Iterates over the entire iterator, multiplying all the elements
iterators5.rs
This exercise may looks intimidating but its quite simple.
First is we need to complete the function
count_iterator.Basically we need to return count of given hashmap values that match with given Progress.
We can use iterator, map it, then calculate the sum like this:
Second is we need to complete the function
count_collection_iterator.Basically for each hashmap in the given collection we need to count it the matching progress and sum it.
Similar like the first task we can iter, map, then sum it like this:
Last updated