may
may

Reputation: 1185

Understanding Generic FromIterator in Rust

I am new to rust and I found myself lost in this second line. How can I interpreted it? Which one would be the interator that I can use to do the conversion to SimpleLinkedList?

impl<T> FromIterator<T> for SimpleLinkedList<T> {
    fn from_iter<I: IntoIterator<Item = T>>(_iter: I) -> Self {
        unimplemented!()
    }
}

Upvotes: 2

Views: 415

Answers (2)

pretzelhammer
pretzelhammer

Reputation: 15135

It looks intimidating at first but the implementation is very simple.

impl<T> FromIterator<T> for SimpleLinkedList<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let mut list = SimpleLinkedList::new();
        for item in iter {
            list.push(item);
        }
        list
    }
}

The key thing to know is that types which implement the trait IntoIterator can be used in for-in loops. The Item = T just means the iterator returns items of type T. You just iterate over iter and push the items into your SimpleLinkedList struct to do the conversion.

Upvotes: 3

Masklinn
Masklinn

Reputation: 42472

I found myself lost in this second line. How can I interpreted it?

What part? from_iter is defined as a generic function parameterized on a type I. That type is then bounded on (meaning it must implement) IntoIterator<Item=T>.

IntoIterator<Item=T> means the type can be iterated (converted to an Iterator) and yields T. In the lingo of other languages, it's an iterable of Ts.

So from_iter is a generic function whose input is an iterable (IntoIterator) of whatever items the SimpleLinkedList should contain.

Which one would be the interator

_iter.into_iter() would be the input iterator. You can also just iterate on _iter using a for loop, as it implicitly converts its RHS to an iterator using the IntoIterator trait.

Upvotes: 4

Related Questions