Search code examples
iteratorrusttraitsgeneric-programminggeneric-collections

How to implement a trait for any iterable type?


I'd like to implement a generic method that's callable on any container or iterator that iterates over a specific type, e.g. &[u32], Vec<u32>, (0..99u32), etc.

The following code does not compile:

trait Foo { fn foo(self); }

impl Foo for std::iter::IntoIterator<Item=u32> {
    fn foo(self) {}
}

error: the value of the associated type IntoIter (from the trait core::iter::IntoIterator) must be specified [E0191]

impl Foo for std::iter::IntoIterator<Item=u32> {

What needs to be specified for the IntoIter associated type? (std::iter::IntoIterator<Item=u32,IntoIter=???>)

so that this would work:

vec![0u32].foo()

Solution

  • The correct syntax here is impl<T> SomeTrait for T where T: OtherTrait. This works:

    trait Foo { fn foo(self); }
    
    impl<T> Foo for T 
        where T: std::iter::IntoIterator<Item=u32> 
    {
        fn foo(self) {}
    }
    
    fn main() {
        vec![0u32].foo()
    }