Introduction
The for_each
function in Rust is a method provided by the Iterator
trait that allows you to apply a closure or function to each item in the iterator. This function is particularly useful for performing side effects, such as printing or modifying external state, for each element in a collection.
Syntax
The basic syntax of the for_each
function is as follows:
iterator.for_each(|item| {
// perform some action with item
});
Here, iterator
is any type that implements the Iterator
trait, and |item|
is a closure that defines the action to be performed on each element.
Example Usage
Example 1: Printing Each Element
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
numbers.iter().for_each(|&x| println!("{}", x));
// Output:
// 1
// 2
// 3
// 4
// 5
}
Example 2: Modifying External State
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let mut sum = 0;
numbers.iter().for_each(|&x| sum += x);
println!("Sum: {}", sum); // Output: Sum: 15
}
Example 3: Using a Custom Function
fn print_double(x: &i32) {
println!("{}", x * 2);
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
numbers.iter().for_each(print_double);
// Output:
// 2
// 4
// 6
// 8
// 10
}
Example 4: Working with Enumerations
fn main() {
let names = vec!["Alice", "Bob", "Carol"];
names.iter().enumerate().for_each(|(index, &name)| {
println!("{}: {}", index, name);
});
// Output:
// 0: Alice
// 1: Bob
// 2: Carol
}
Example 5: Conditional Actions
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
numbers.iter().for_each(|&x| {
if x % 2 == 0 {
println!("Even: {}", x);
} else {
println!("Odd: {}", x);
}
});
// Output:
// Odd: 1
// Even: 2
// Odd: 3
// Even: 4
// Odd: 5
}
Considerations
- The
for_each
method consumes the iterator, meaning that the iterator cannot be used afterfor_each
has been called. - Since
for_each
is primarily used for side effects, it returns()
(the unit type) rather than a collection or value.
See Also
- map - Transforms each element of an iterator and returns a new iterator with the transformed elements.
- filter - Creates an iterator that only yields elements that satisfy a predicate.
- collect - Transforms an iterator into a collection such as a vector or hash map.
- fold - Reduces an iterator to a single value by applying a function.
- enumerate - Adds a counter to an iterator, returning an iterator of pairs where the first element is the counter and the second is the item.