RS.CLIPPY.FROM_ITER_INSTEAD_OF_COLLECT
Use `.collect()` instead of `::from_iter()`
This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: from_iter_instead_of_collect. Copyright ©2025 The Rust Team. All rights reserved.
What it does
Checks for from_iter() function calls on types that implement the FromIterator
trait.
Why is this bad?
If it's needed to create a collection from the contents of an iterator, the Iterator::collect(_)
method is preferred. However, when it's needed to specify the container type,
Vec::from_iter(_) can be more readable than using a turbofish (e.g. _.collect::<Vec<_>>()). See
FromIterator documentation
Example
let five_fives = std::iter::repeat(5).take(5);
let v = Vec::from_iter(five_fives);
assert_eq!(v, vec![5, 5, 5, 5, 5]);
Use instead:
let five_fives = std::iter::repeat(5).take(5);
let v: Vec<i32> = five_fives.collect();
assert_eq!(v, vec![5, 5, 5, 5, 5]);
but prefer to use
let numbers: Vec<i32> = FromIterator::from_iter(1..=5);
instead of
let numbers = (1..=5).collect::<Vec<_>>();