`IntoIterator`
IntoIterator converts a value into an iterator. for uses it, and so does anything that takes impl IntoIterator, which is why a function can accept both a Vec and a slice.
Detailed Explanation
IntoIterator has one method, into_iter(self) -> Self::IntoIter, and an associated type Item. Implementing it is what makes for x in value compile. The for loop desugars to let mut iter = IntoIterator::into_iter(value); while let Some(x) = iter.next() { ... }.
The standard library implements IntoIterator for collections, for references to collections, and for iterators themselves (so into_iter on an iterator is the identity). Vec<T>'s into_iter yields T and takes ownership of the buffer. &Vec<T> and &[T] yield &T. &mut Vec<T> yields &mut T. The same type, three implementations, three item types. That is why for x in &names and for x in names are different operations.
APIs that want "any sequence" should take impl IntoIterator<Item = T> rather than Vec<T>. Callers can pass a Vec, an array, a range, an iterator that is already running, or a slice via .iter().copied(). Taking Vec<T> forces an allocation at the call site even when the caller had a slice. Taking &[T] cannot accept a consuming iterator of owned values. IntoIterator is the bound that covers both.
Iterator implements IntoIterator<Item = Self::Item, IntoIter = Self>. That is why you can pass vec.iter().map(...) to a function that takes IntoIterator. You do not have to collect first.
Implement IntoIterator for your own collection when for should work. The owned impl usually consumes the collection and yields owned items. Add &MyType and &mut MyType impls if borrowing should also work. The iter() and iter_mut() methods on standard collections are convenience wrappers that call those impls.
When you take IntoIterator: a function that will walk the data once. When you take &[T]: you need random access or multiple passes. When you take Vec<T>: you must store the data and need ownership.
Code Examples
fn sum_all(items: impl IntoIterator<Item = u32>) -> u32 {
items.into_iter().sum()
}
fn main() {
println!("{}", sum_all([1, 2, 3])); // prints: 6
println!("{}", sum_all(vec![4, 5])); // prints: 9
println!("{}", sum_all(0..4)); // prints: 6
}Common Gotchas
`into_iter()` on a `Vec` is a move
The vector cannot be used after. `iter()` borrows. The names are easy to swap when you are reading quickly.
A function taking `Vec<T>` is a stricter API than it looks
Callers with a slice must allocate. Prefer `impl IntoIterator<Item = T>` or `impl AsRef<[T]>` depending on whether you need ownership.
Iterators are already `IntoIterator`
Do not `collect` only to pass a `Vec` into a function that would have accepted the iterator.
`for x in &vec` vs `for x in vec`
The first yields `&T`. The second yields `T`. Method calls that need `T` will start cloning if you picked the wrong one.