Conversion from an Iterator. By implementing FromIterator for a type, you define how it will be created from an iterator. This is common for types which describe a collection of some kind. If you want to create a collection from the contents of an iterator, the Iterator::collect() method is preferred. However, when you need to specify the container type, FromIterator::from_iter() can be more readable than using a turbofish (e.g. ::>()). See the Iterator::collect() documentation for more examples of its use. See also: IntoIterator.

Signature

pub trait FromIterator

Examples

Basic usage:
let v = FromIterator::from_iter(0..5_u32);

assert_eq!(v, array![0, 1, 2, 3, 4]);
Implementing FromIterator for your type:
use core::metaprogramming::TypeEqual;

// A sample collection, that's just a wrapper over Array
#[derive(Drop, Debug)]
struct MyCollection {
    arr: Array,
}

// Let's give it some methods so we can create one and add things
// to it.
#[generate_trait]
impl MyCollectionImpl of MyCollectionTrait {
    fn new() -> MyCollection {
        MyCollection { arr: ArrayTrait::new() }
    }

    fn add(ref self: MyCollection, elem: u32) {
        self.arr.append(elem);
    }
}

// and we'll implement FromIterator
impl MyCollectionFromIterator of FromIterator {
    fn from_iter,
            +TypeEqual,
            +Destruct,
            +Destruct,
        >(
            iter: I
        ) -> MyCollection {
        let mut c = MyCollectionTrait::new();
        for i in iter {
            c.add(i);
        };
        c
    }
}

// Now we can make a new iterator...
let iter = (0..5_u32).into_iter();

// ... and make a MyCollection out of it
let c = FromIterator::::from_iter(iter);

assert_eq!(c.arr, array![0, 1, 2, 3, 4]);

Trait functions

from_iter

Creates a value from an iterator. See the module-level documentation for more.

Signature

fn from_iter,
    +TypeEqual,
    +Destruct,
    +Destruct,
>(
    iter: I,
) -> T

Examples

let iter = (0..5_u32).into_iter();

let v = FromIterator::from_iter(iter);

assert_eq!(v, array![0, 1, 2, 3, 4]);