std-method

Iterator::collect

Drive the iterator to construct a chosen destination. Provide a type annotation or turbofish when inference lacks enough context. Some destination implementations can short-circuit. Expected stdout (not executed): ["A", "B"] Common mistake: Assuming collect always returns Vec.

Formal Syntax & Structure

rust syntaxrust
fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized

Working Example

Example Snippetrust
fn main() {    let codes: Vec<_> = ["a", "b"].into_iter().map(str::to_uppercase).collect();    println!("{codes:?}");}
Rust Reference