0

I'm trying to define a trait that extends IntoIterator, to achieve something similar to the code bellow, but "associated type defaults are unstable" (https://github.com/rust-lang/rust/issues/29661).

Is there another way to achieve it?

pub trait MyTrait : IntoIterator{
    type Item = i32;
    fn foo(&self);
}

pub fn run<M: MyTrait>(my : M){
    my.foo();
    for a in my {
        println!("{}", a);
    }
}
Guy Korland
  • 8,355
  • 13
  • 55
  • 102

1 Answers1

4

I think what you want is this:

trait MyTrait: IntoIterator<Item = i32> {
    fn foo(&self);
}

This means: everything that implements your trait also implements IntoIterator where the Item is i32. Or put differently: all implementors of MyTrait can also be turned into an iterator over i32s.

Lukas Kalbertodt
  • 66,297
  • 20
  • 206
  • 264
  • It worked nicely in the simple example but I got another error when tried to set it in an enum https://stackoverflow.com/questions/66919186/error-requirements-on-the-impl-of-intoiterator-but-already-implemeted-intoit – Guy Korland Apr 02 '21 at 12:16