Re:Fear Not the Association of Types
by Someone on Monday August 19, 2024 @12:46PM
(#41292582)
Does that matter for Iterator? You can have
It would matter for Iterable. You cannot have this:
, but there, there’s a second problem: in Java, you can’t have overloads that only differ in their return type.
[ Parent
| on HN ]
It's not useful to have a type implement Iterator for multiple element types. But in Rust, if Iterator took the element type as a generic parameter, it would be possible. The fact that it's not useful is precisely why Rust makes the element type an associated type instead.
The benefits of using an associated type (compared to using a generic parameter in Rust, not compared to Java) include clarity, possibly improving type inference, and avoiding issues with crate coherence by requiring that the Iterator impl live in the crate that defines the input type, rather than the one that defines the output type.