Why is the associated type not allowed in this case?

Viewed 116
trait Envs {
    type Item;
    type Iter: Iterator;
    fn get_envs(&self) -> Self::Iter<Item=Self::Item>;
}

I am trying to implement the method that returns the environment variables but I couldn't figure out why the associated type is not allowed in the trait.

2 Answers
trait Envs {
    type Item;
    type Iter: Iterator<Item = Self::Item>;
    fn get_envs(&self) -> Self::Iter;
}

Playground link

If you do like above, it would restrict the implementer of the trait to specify an Iterator which has an associated type same as Envs::Item. So, Envs::Item needs to be same as <Envs::Iter as Iterator>::Item.


If you do like:

trait Envs {
    type Item;
    type Iter: Iterator;
    fn get_envs(&self) -> Self::Iter;
}

This would allow the implementer to specify an Iter which doesn't return elements same as Envs::Item. So, in this case it could be possible that Envs::Item was i32 but the Envs::Iter is an Iterator over String.

You can have the trait method return a boxed Iterator trait object like below if you meant to have the associated type of the iterator to be the Item associated type of your trait.

trait Envs {
    type Item;
    fn get_envs(&self) -> Box<dyn Iterator<Item=&Self::Item>>;
}
Related