Rust Reference ยท Core Traits
The Extend and FromIterator traits
Reference for Rust Extend and FromIterator: how collect() builds collections, implementing FromIterator for custom types, extend() on existing ones, and Result/Option collecting.
FromIterator is the trait behind Iterator::collect(). A type that implements it can be built from any iterator of the right item type. Extend is its in-place sibling: it adds the items of an iterator to a collection that already exists, which is what Vec::extend, String::extend and HashMap::extend use.
Between them they make iterator pipelines end in whatever collection you need: Vec, String, HashMap, HashSet, BTreeMap, Box<[T]>, Result<Vec<T>, E> and your own types.
let squares: Vec<u32> = (1..=4).map(|n| n * n).collect();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait FromIterator<A>: Sized { fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self; } pub trait Extend<A> { fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T); } let c: Collection = iter.collect(); // calls FromIterator::from_iter let c = iter.collect::<Collection>();
| Name | Description |
|---|---|
A |
The item type consumed. A type may implement the trait for several A. |
iter |
Anything that is IntoIterator<Item = A>, so arrays, ranges and collections work directly. |
Returns: from_iter returns the new collection; extend returns ().
Errors / panics / edge cases: collect::<Result<C, E>>() and collect::<Option<C>>() stop at the first Err or None and return it. Collecting key/value pairs into a map keeps the last value for a repeated key.
Usage notes
- Type annotation required.
collect()cannot guess the target, so writelet v: Vec<_> = ...orcollect::<Vec<_>>(). _helps.Vec<_>lets the compiler fill in the item type while you choose the container.- Strings.
StringimplementsFromIterator<char>,<&str>,<String>and<&char>, which is why collecting characters works. - Unit collects.
collect::<()>()runs the iterator for its side effects (rarely better than aforloop). extendreuses allocation.vec.extend(other)can reserve once using the iterator'ssize_hint, which beats pushing in a loop.Extend<&T>forCopytypes.Vec<T>andHashSet<T>accept&Titems whenT: Copy, sov.extend(&other_vec)works.- Related building methods.
Iterator::unzipandpartitionuseDefault + Extend, so any type implementing both can be their target. - Implement both for custom containers. Provide
FromIteratorforcollect()andExtendfor incremental growth; define one in terms of the other as shown.