Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let squares: Vec<u32> = (1..=4).map(|n| n * n).collect();

Try it

Rust collect into different collections

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.

Rust Custom FromIterator and Extend

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

Rust
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 write let v: Vec<_> = ... or collect::<Vec<_>>().
  • _ helps. Vec<_> lets the compiler fill in the item type while you choose the container.
  • Strings. String implements FromIterator<char>, <&str>, <String> and <&char>, which is why collecting characters works.
  • Unit collects. collect::<()>() runs the iterator for its side effects (rarely better than a for loop).
  • extend reuses allocation. vec.extend(other) can reserve once using the iterator's size_hint, which beats pushing in a loop.
  • Extend<&T> for Copy types. Vec<T> and HashSet<T> accept &T items when T: Copy, so v.extend(&other_vec) works.
  • Related building methods. Iterator::unzip and partition use Default + Extend, so any type implementing both can be their target.
  • Implement both for custom containers. Provide FromIterator for collect() and Extend for incremental growth; define one in terms of the other as shown.