1. What Are Closures?
A closure is an anonymous function that you can store in a variable or pass to another function.
Unlike regular functions, closures can capture variables from their surrounding environment.
Regular Function
Output:
Closure
Output:
Notice the syntax:
Explanation:
| |contains the parameters.a: i32andb: i32define parameter types.-> i32defines the return type.- The expression inside
{ }is the closure body.
2. Short Closure Syntax
If the closure contains only one expression, you can write it in a shorter form.
Output:
You can also omit parameter and return types when Rust can infer them.
Rust infers that the parameter and result are integers in this example.
Important: Closure parameter types are inferred from their use and generally become fixed after the first call. A closure is not automatically generic like a generic function.
3. Closures Capturing Variables
One important feature of closures is that they can access variables from their surrounding scope.
Example:
Output:
Here, the closure uses the name variable without receiving it as a parameter.
Capturing and Modifying Variables
A closure can also modify a captured variable when it captures it mutably.
Output:
Notice that:
countis declared usingmut.increaseis also declared usingmut.- The closure modifies the captured variable.
4. Passing Closures to Functions
Closures can be passed as arguments to other functions.
Example:
Output:
Here:
Fis a generic type parameter.Fn(i32, i32) -> i32describes a closure that accepts two integers and returns an integer.- We pass different closures to the same function.
5. Understanding Fn, FnMut, and FnOnce
Rust provides three important closure traits.
Trait | Meaning |
|---|---|
| Can be called repeatedly without mutating captured values |
| Can modify captured values |
| Can consume captured values and may only be called once |
Fn Example
The closure only reads the captured variable, so it implements Fn.
FnMut Example
The closure modifies the captured variable, so it implements FnMut.
FnOnce Example
The closure consumes the captured String, so it implements FnOnce.
6. What Are Iterators?
An iterator is a way to process elements one by one.
For example, consider a vector:
You can use an iterator to access its elements.
Output:
Here, iter() creates an iterator that borrows the elements.
7. Understanding iter(), iter_mut(), and into_iter()
Rust provides three commonly used ways to create iterators.
Method | Purpose |
|---|---|
| Borrows elements immutably |
| Borrows elements mutably |
| Takes ownership of elements from the collection |
Using iter()
The original vector remains available because iter() only borrows it.
Using iter_mut()
Output:
The * operator allows us to modify the value through its mutable reference.
Using into_iter()
into_iter() consumes the vector and transfers ownership of its elements to the iterator.
8. Understanding map()
The map() method transforms every element of an iterator.
Example:
Output:
Explanation:
iter()reads each element.map()transforms each element.collect()collects the results into a new vector.
9. Understanding filter()
The filter() method selects elements that satisfy a condition.
Example:
Output:
Here, only numbers greater than 20 are selected.
The predicate receives a reference to an iterator item. Because iter() yields &i32, the closure parameter in filter() is &&i32; that is why the example uses **number.
10. Understanding collect()
The collect() method converts an iterator into a collection.
Example:
Output:
Here, copied() converts the borrowed integer values into copied integers before collecting them.
The collection type is specified as Vec<i32>.
You can also write:
11. Understanding for_each()
The for_each() method performs an operation for every element.
Example:
Output:
Use for_each() when you want to perform an action for every element.
12. Understanding find()
The find() method returns the first element that satisfies a condition.
Example:
Output:
If no matching element exists, find() returns None.
13. Understanding any() and all()
any()
Returns true if at least one element satisfies the condition.
Output:
all()
Returns true only if every element satisfies the condition.
Output:
14. Understanding sum() and count()
sum()
Calculates the total of all elements.
Output:
count()
Counts the number of elements.
Output:
15. Method Chaining
You can combine multiple iterator methods into one expression.
Example:
Output:
Explanation:
iter()reads each number.filter()selects even numbers.map()multiplies each selected number by 10.copied()produces owned integer values.collect()creates a new vector.
16. Difference Between for Loop and Iterator Methods
Feature | For Loop | Iterator Methods |
|---|---|---|
Style | Step-by-step | Expression-based |
Readability | Easy for beginners | Useful for data transformations |
Filtering | Usually uses | Uses |
Transformation | Usually uses assignment | Uses |
Collection | Manual insertion | Uses |
Both approaches are useful. Choose the one that makes your code easiest to understand.
17. Common Mistakes
Mistake | Explanation |
|---|---|
Forgetting | Iterator transformations do not automatically create a new vector |
Using | Mutable iteration requires a mutable collection |
Using a vector after | Ownership has been moved |
Confusing |
|
Expecting lazy iterators to run immediately | Many iterator methods are lazy until consumed |