r/rust•
Meriones

Question about where bounds on traits

I want to write a trait that allows iteration over the type. If we had associated type constructors this would be easy but since we don't I tried to do this

trait Iterable
    where for<'a> &'a Self: IntoIterator 
{}

Unfortunately this fails as soon as I try to use T: Iterable as a bound (playground link).

Is this intended behaviour and is there a better way to express this?

Posted Jul 9, 2017, 11:30 PM UTC · edited

61
kylewlacy•

If you want the T of Foo<T> to be constrained to Iterable, you need to explicitly spell out the additional bounds for the Iterable trait again:

struct Foo<T: Iterable>(T) where for<'a> &'a T: IntoIterator;
//                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here's a playground link which also demonstrates implementing the Iterable trait and using an instance of Foo in a for loop

I think the reasoning for this is explicitness: your T parameter doesn't have any "hidden restrictions" on your type parameter beyond what you specify in-place (although there has been some discussion in the ergonomics initiative to add "implied bounds", which AFAICT would make your original example compile).

2