In Rust, you can loop through collections like Vec
, HashMap
, or arrays using the .iter()
method combined with .for_each()
. The for_each
method takes a closure (anonymous function) and applies it to each element in the collection.
This article shows some common examples of using for_each
in Rust.
1. Basic for_each
with Vec
fn main() {
let names = vec!["Alice", "Bob", "Charlie"];
names.iter().for_each(|name| println!("Hello, {}", name));
}
Output:
Hello, Alice
Hello, Bob
Hello, Charlie
-
.iter()
returns an iterator over the vector. -
.for_each(|name| ...)
applies the closure to each element. -
We use
println!
inside the closure to print each name.