RS.CLIPPY.NEEDLESS_FOR_EACH

Using `for_each` where a `for` loop would be simpler

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: needless_for_each. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for usage of for_each that would be more simply written as a for loop.

Why is this bad?

for_each may be used after applying iterator transformers like filter for better readability and performance. It may also be used to fit a simple operation on one line. But when none of these apply, a simple for loop is more idiomatic.

Example

let v = vec![0, 1, 2];
v.iter().for_each(|elem| {
    println!("{elem}");
})

Use instead:

let v = vec![0, 1, 2];
for elem in &v {
    println!("{elem}");
}

Known Problems

When doing things such as:

let v = vec![0, 1, 2];
v.iter().for_each(|elem| unsafe {
    libc::printf(c"%d\
".as_ptr(), elem);
});

This lint will not trigger.