rieux
rieux

Reputation: 829

How to constrain the element type of an iterator?

I’m converting some older Rust code to work on 1.0.0. I need to convert a function that takes an iterator over characters, which used to be written like this:

 fn f<I: Iterator<char>>(char_iter: I)

Now that Iterator doesn’t take a parameter, the constraint on I can only be I: Iterator. The element type is then I::Item. Is there a way to express the constraint that I::Item = char? (Or should I be doing this another way entirely?)

Upvotes: 4

Views: 1328

Answers (3)

Francis Gagn&#233;
Francis Gagn&#233;

Reputation: 65937

fn f<I: Iterator<Item = char>>(char_iter: I)

Associated types were recently added to the language, and many library types were updated to take advantage of them. For example, Iterator defines one associated type, named Item. You can add a constraint on the associated type by writing the name of the associated type, an equals sign, and the type you need.

Upvotes: 6

rieux
rieux

Reputation: 829

Okay, I was able to figure this out from reading some RFC discussions, and the answer is that you can instantiate associated types in the trait (like signature fibration in ML):

fn f<I: Iterator<Item = char>>(char_iter: I)

Soon it should be possible to use equality constraints in where clauses, but this doesn’t work in 1.0.0-alpha:

fn f<I: Iterator>(char_iter: I) where I::Item == char

Upvotes: 3

huon
huon

Reputation: 102276

You can write I: Iterator<Item = char>. At some point in the future, a where clause like where I::Item == char may work too, but not now.

Upvotes: 1

Related Questions