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)
Syntax
fn collect<B: FromIterator<Self::Item>>(self) -> B
Parameters
| Parameter | Description |
|---|---|
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
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.
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.
Related
Iterator::map, filter and filter_map· Transform and select items lazily: map each item, keep matching ones, or do both at once with filter_map.Iterator::sum, fold, any and max_by_key· Reduce an iterator to one value: totals, counts, custom folds, checks, and minimum or maximum items.- Rust Iterators and Closures · tutorial