Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 362
Kornel Avatar asked Oct 27 '25 07:10

Kornel


1 Answers

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()
}
like image 78
Lukas Kalbertodt Avatar answered Oct 30 '25 03:10

Lukas Kalbertodt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!