4

The example implementation of the FromIterator trait in the Rust docs is:

impl FromIterator<i32> for MyCollection {
    fn from_iter<I: IntoIterator<Item=i32>>(iter: I) -> Self {
        let mut c = MyCollection::new();

        for i in iter {
            c.add(i);
        }

        c
    }
}

FromIterator defines how a type will be created from an iterator. The signature of from_iter requires a type that implements IntoIterator, which defines how a type may be converted into an Iterator.

Is from_iter defined this way because IntoIterator is not as strict a requirement as Iterator?

1 Answer 1

3

Is from_iter defined this way because IntoIterator is not as strict a requirement as Iterator?

Yes.

IntoIterator is automatically implemented for Iterator, therefore the set of types implementing IntoIterator is a superset of those implementing Iterator.

When crafting a generic function, it's good to minimize its requirements, i.e., make it as generic as possible.

Of course, there's a trade-off between:

  • ease of use: works with as many types as possible,
  • ease of implementation.

For a lone function in your isolated codebase, it may not be worth optimizing for ease-of-use much; for a trait/function in the standard library, since the number of users far outweigh the number of developers (of this particular piece), the trade-off is strongly in favor of ease-of-use.

And since going from IntoIterator to Iterator is so simple, and thus doesn't weigh much on the implementation, it's an easy call to make.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.