How to Collect an Iterator into Different Collection Types

Convert Rust iterators into Vec, String, or HashMap using the collect() method with type inference.

Use the collect() method on an iterator to convert it into a Vec, String, HashMap, or other collection types.

let numbers = vec![1, 2, 3];
let vec: Vec<i32> = numbers.iter().collect();
let string: String = "hello".chars().collect();
let map: std::collections::HashMap<i32, i32> = [(1, 2), (3, 4)].iter().cloned().collect();

The compiler infers the target type from the variable annotation or the context where the result is used.