Rust 1.99 (2024 edition) reference · Iterators

Rust Iterator::collect Method

Turn an iterator into a collection: Vec, String, HashMap, HashSet, or a Result that fails on the first error.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn collect<B: FromIterator<Self::Item>>(self) -> B

Parameters

ParameterDescription
Vec<_> The most common target; annotate the type or use ::<>.
String From chars or &strs.
HashMap<K, V> From (K, V) pairs.
Result<Vec<T>, E> Stops at the first Err.

Examples

Example 1
use std::collections::{BTreeMap, BTreeSet};

fn main() {
    let v: Vec<i32> = (1..=5).collect();
    let s: String = ['r', 'u', 's', 't'].iter().collect();
    let m: BTreeMap<&str, usize> = ["ana", "ben"].iter().map(|n| (*n, n.len())).collect();
    let unique: BTreeSet<char> = "hello".chars().collect();
    println!("{v:?} {s} {m:?} {unique:?}");
}

Output

[1, 2, 3, 4, 5] rust {"ana": 3, "ben": 3} {'e', 'h', 'l', 'o'}

Run this on your computer — see “Get Started” for setup.

Collecting into Result
fn main() {
    let good: Result<Vec<u8>, _> = "1 2 3".split(' ').map(str::parse::<u8>).collect();
    let bad: Result<Vec<u8>, _> = "1 300 3".split(' ').map(str::parse::<u8>).collect();
    println!("{good:?}");
    println!("{bad:?}");
}

Output

Ok([1, 2, 3])
Err(ParseIntError { kind: PosOverflow })

Run this on your computer — see “Get Started” for setup.

Was this page helpful?